c31d188ef6f757ad7f8e88501cdb0a0eacd21e6b
[irspy-moved-to-github.git] / lib / ZOOM / IRSpy / Utils.pm
1 # $Id: Utils.pm,v 1.22 2007-03-01 13:51:18 mike Exp $
2
3 package ZOOM::IRSpy::Utils;
4
5 use 5.008;
6 use strict;
7 use warnings;
8
9 use Exporter 'import';
10 our @EXPORT_OK = qw(isodate
11                     xml_encode 
12                     cql_quote
13                     irspy_xpath_context
14                     modify_xml_document
15                     bib1_access_point);
16
17 use XML::LibXML;
18 use XML::LibXML::XPathContext;
19
20 our $IRSPY_NS = 'http://indexdata.com/irspy/1.0';
21
22
23 # Utility functions follow, exported for use of web UI
24 sub isodate {
25     my($time) = @_;
26
27     my($sec, $min, $hour, $mday, $mon, $year) = localtime($time);
28     return sprintf("%04d-%02d-%02dT%02d:%02d:%02d",
29                    $year+1900, $mon+1, $mday, $hour, $min, $sec);
30 }
31
32
33 # I can't -- just can't, can't, can't -- believe that this function
34 # isn't provided by one of the core XML modules.  But the evidence all
35 # says that it's not: among other things, XML::Generator and
36 # Template::Plugin both roll their own.  So I will do likewise.  D'oh!
37 #
38 sub xml_encode {
39     my($text, $fallback, $opts) = @_;
40     if (!defined $opts && ref $fallback) {
41         # The second and third arguments are both optional
42         $opts = $fallback;
43         $fallback = undef;
44     }
45     $opts = {} if !defined $opts;
46
47     $text = $fallback if !defined $text;
48     use Carp;
49     confess "xml_encode(): text and fallback both undefined"
50         if !defined $text;
51
52     $text =~ s/&/&/g;
53     $text =~ s/</&lt;/g;
54     $text =~ s/>/&gt;/g;
55     # Internet Explorer can't display &apos; (!) so don't create it
56     #$text =~ s/['']/&apos;/g;
57     $text =~ s/[""]/&quot;/g;
58     $text =~ s/ /&nbsp;/g if $opts->{nbsp};
59
60     return $text;
61 }
62
63
64 # Quotes a term for use in a CQL query
65 sub cql_quote {
66     my($term) = @_;
67
68     $term =~ s/([""\\])/\\$1/g;
69     $term = qq["$term"] if $term =~ /\s/;
70     return $term;
71 }
72
73
74 # PRIVATE to irspy_namespace() and irspy_xpath_context()
75 my %_namespaces = (
76                    e => 'http://explain.z3950.org/dtd/2.0/',
77                    i => $IRSPY_NS,
78                    );
79
80
81 sub irspy_namespace {
82     my($prefix) = @_;
83
84     use Carp;
85     confess "irspy_namespace(undef)" if !defined $prefix;
86     my $uri = $_namespaces{$prefix};
87     die "irspy_namespace(): no URI for namespace prefix '$prefix'"
88         if !defined $uri;
89
90     return $uri;
91 }
92
93
94 sub irspy_xpath_context {
95     my($record) = @_;
96
97     my $xml = ref $record ? $record->render() : $record;
98     my $parser = new XML::LibXML();
99     my $doc = $parser->parse_string($xml);
100     my $root = $doc->getDocumentElement();
101     my $xc = XML::LibXML::XPathContext->new($root);
102     foreach my $prefix (keys %_namespaces) {
103         $xc->registerNs($prefix, $_namespaces{$prefix});
104     }
105     return $xc;
106 }
107
108
109 sub modify_xml_document {
110     my($xc, $fieldsByKey, $data) = @_;
111
112     my @changes = ();
113     foreach my $key (keys %$data) {
114         my $value = $data->{$key};
115         my $ref = $fieldsByKey->{$key} or die "no field '$key'";
116         my($name, $nlines, $caption, $xpath, @addAfter) = @$ref;
117         #print "Considering $key='$value' ($xpath)<br/>\n";
118         my @nodes = $xc->findnodes($xpath);
119         if (@nodes) {
120             warn scalar(@nodes), " nodes match '$xpath'" if @nodes > 1;
121             my $node = $nodes[0];
122
123             if ($node->isa("XML::LibXML::Attr")) {
124                 if ($value ne $node->getValue()) {
125                     $node->setValue($value);
126                     push @changes, $ref;
127                     #print "Attr $key: '", $node->getValue(), "' -> '$value' ($xpath)<br/>\n";
128                 }
129             } elsif ($node->isa("XML::LibXML::Element")) {
130                 # The contents could be any mixture of text and
131                 # comments and maybe even other crud such as processing
132                 # instructions.  The simplest thing is just to throw it all
133                 # away and start again, making a single Text node the
134                 # canonical representation.  But before we do that,
135                 # we'll check whether the element is already
136                 # canonical, to determine whether our change is a
137                 # no-op.
138                 my $old = "???";
139                 my @children = $node->childNodes();
140                 if (@children == 1) {
141                     my $child = $node->firstChild();
142                     if (ref $child && ref $child eq "XML::LibXML::Text") {
143                         $old = $child->getData();
144                         next if $value eq $old;
145                     }
146                 }
147
148                 $node->removeChildNodes();
149                 my $child = new XML::LibXML::Text($value);
150                 $node->appendChild($child);
151                 push @changes, $ref;
152                 #print "Elem $key: '$old' -> '$value' ($xpath)<br/>\n";
153             } else {
154                 warn "unexpected node type $node";
155             }
156
157         } else {
158             next if !$value; # No need to create a new empty node
159             my($ppath, $selector) = $xpath =~ /(.*)\/(.*)/;
160             dom_add_node($xc, $ppath, $selector, $value, @addAfter);
161             #print "New $key ($xpath) = '$value'<br/>\n";
162             push @changes, $ref;
163         }
164     }
165
166     return @changes;
167 }
168
169
170 sub dom_add_node {
171     my($xc, $ppath, $selector, $value, @addAfter) = @_;
172
173     #print "Adding $selector='$value' at '$ppath' after (", join(", ", map { "'$_'" } @addAfter), ")<br/>\n";
174     my $node = find_or_make_node($xc, $ppath, 0);
175     die "couldn't find or make node '$node'" if !defined $node;
176
177     my $is_attr = ($selector =~ s/^@//);
178     my(undef, $prefix, $simpleSel) = $selector =~ /((.*?):)?(.*)/;
179     #warn "selector='$selector', prefix='$prefix', simpleSel='$simpleSel'";
180     if ($is_attr) {
181         if (defined $prefix) {
182             ### This seems to no-op (thank, DOM!) but I have have no
183             # idea, and it's not needed for IRSpy, so I am not going
184             # to debug it now.
185             $node->setAttributeNS(irspy_namespace($prefix),
186                                   $simpleSel, $value);
187         } else {
188             $node->setAttribute($simpleSel, $value);
189         }
190         return;
191     }
192
193     my $new = new XML::LibXML::Element($simpleSel);
194     $new->setNamespace(irspy_namespace($prefix), $prefix)
195         if defined $prefix;
196
197     $new->appendText($value);
198     foreach my $predecessor (reverse @addAfter) {
199         my($child) = $xc->findnodes($predecessor, $node);
200         if (defined $child) {
201             $node->insertAfter($new, $child);
202             #warn "Added after '$predecessor'";
203             return;
204         }
205     }
206
207     # Didn't find any of the nodes that are supposed to precede the
208     # new one, so we need to insert the new node as the first of the
209     # parent's children.  However *sigh* there is no prependChild()
210     # analogous to appendChild(), so we have to go the long way round.
211     my @children = $node->childNodes();
212     if (@children) {
213         $node->insertBefore($new, $children[0]);
214         #warn "Added new first child";
215     } else {
216         $node->appendChild($new);
217         #warn "Added new only child";
218     }
219
220     if (0) {
221         my $text = xml_encode(inheritance_tree($xc));
222         $text =~ s/\n/<br\/>$&/sg;
223         print "<pre>$text</pre>\n";
224     }
225 }
226
227
228 sub find_or_make_node {
229     my($xc, $path, $recursion_level) = @_;
230
231     die "deep recursion in find_or_make_node($path)"
232         if $recursion_level == 10;
233     $path = "." if $path eq "";
234
235     my @nodes = $xc->findnodes($path);
236     if (@nodes == 0) {
237         # Oh dear, the parent node doesn't exist.  We could make it,
238         my(undef, $ppath, $element) = $path =~ /((.*)\/)?(.*)/;
239         $ppath = "" if !defined $ppath;
240         #warn "path='$path', ppath='$ppath', element='$element'";
241         #warn "no node '$path': making it";
242         my $parent = find_or_make_node($xc, $ppath, $recursion_level-1);
243
244         my(undef, $prefix, $nsElem) = $element =~ /((.*?):)?(.*)/;
245         #warn "element='$element', prefix='$prefix', nsElem='$nsElem'";
246         my $new = new XML::LibXML::Element($nsElem);
247         if (defined $prefix) {
248             #warn "setNamespace($prefix)";
249             $new->setNamespace(irspy_namespace($prefix), $prefix);
250         }
251
252         $parent->appendChild($new);
253         return $new;
254     }
255     warn scalar(@nodes), " nodes match parent '$path'" if @nodes > 1;
256     return $nodes[0];
257 }
258
259
260 sub inheritance_tree {
261     my($type, $level) = @_;
262     $level = 0 if !defined $level;
263     return "Woah!  Too deep, man!\n" if $level > 20;
264
265     $type = ref $type if ref $type;
266     my $text = "";
267     $text = "--> " if $level == 0;
268     $text .= ("\t" x $level) . "$type\n";
269     my @ISA = eval "\@${type}::ISA";
270     foreach my $superclass (@ISA) {
271         $text .= inheritance_tree($superclass, $level+1);
272     }
273
274     return $text;
275 }
276
277
278 # This function is made available in xslt using the register_function call
279 sub xslt_strcmp {
280     my ($arg1, $arg2) = @_;
281     return ($arg1->to_literal()) cmp ($arg2->to_literal());
282 }
283
284
285 ### It feels like this should be in YAZ, exported via ZOOM-Perl.
286 my %_bib1_access_point = (
287         1 =>    "Personal name",
288         2 =>    "Corporate name",
289         3 =>    "Conference name",
290         4 =>    "Title",
291         5 =>    "Title series",
292         6 =>    "Title uniform",
293         7 =>    "ISBN",
294         8 =>    "ISSN",
295         9 =>    "LC card number",
296         10 =>   "BNB card no.",
297         11 =>   "BGF number",
298         12 =>   "Local number",
299         13 =>   "Dewey classification",
300         14 =>   "UDC classification",
301         15 =>   "Bliss classification",
302         16 =>   "LC call number",
303         17 =>   "NLM call number",
304         18 =>   "NAL call number",
305         19 =>   "MOS call number",
306         20 =>   "Local classification",
307         21 =>   "Subject heading",
308         22 =>   "Subject Rameau",
309         23 =>   "BDI index subject",
310         24 =>   "INSPEC subject",
311         25 =>   "MESH subject",
312         26 =>   "PA subject",
313         27 =>   "LC subject heading",
314         28 =>   "RVM subject heading",
315         29 =>   "Local subject index",
316         30 =>   "Date",
317         31 =>   "Date of publication",
318         32 =>   "Date of acquisition",
319         33 =>   "Title key",
320         34 =>   "Title collective",
321         35 =>   "Title parallel",
322         36 =>   "Title cover",
323         37 =>   "Title added title page",
324         38 =>   "Title caption",
325         39 =>   "Title running",
326         40 =>   "Title spine",
327         41 =>   "Title other variant",
328         42 =>   "Title former",
329         43 =>   "Title abbreviated",
330         44 =>   "Title expanded",
331         45 =>   "Subject precis",
332         46 =>   "Subject rswk",
333         47 =>   "Subject subdivision",
334         48 =>   "No. nat'l biblio.",
335         49 =>   "No. legal deposit",
336         50 =>   "No. govt pub.",
337         51 =>   "No. music publisher",
338         52 =>   "Number db",
339         53 =>   "Number local call",
340         54 =>   "Code--language",
341         55 =>   "Code--geographic area",
342         56 =>   "Code--institution",
343         57 =>   "Name and title *",
344         58 =>   "Name geographic",
345         59 =>   "Place publication",
346         60 =>   "CODEN",
347         61 =>   "Microform generation",
348         62 =>   "Abstract",
349         63 =>   "Note",
350         1000 => "Author-title",
351         1001 => "Record type",
352         1002 => "Name",
353         1003 => "Author",
354         1004 => "Author-name personal",
355         1005 => "Author-name corporate",
356         1006 => "Author-name conference",
357         1007 => "Identifier--standard",
358         1008 => "Subject--LC children's",
359         1009 => "Subject name -- personal",
360         1010 => "Body of text",
361         1011 => "Date/time added to db",
362         1012 => "Date/time last modified",
363         1013 => "Authority/format id",
364         1014 => "Concept-text",
365         1015 => "Concept-reference",
366         1016 => "Any",
367         1017 => "Server-choice",
368         1018 => "Publisher",
369         1019 => "Record-source",
370         1020 => "Editor",
371         1021 => "Bib-level",
372         1022 => "Geographic-class",
373         1023 => "Indexed-by",
374         1024 => "Map-scale",
375         1025 => "Music-key",
376         1026 => "Related-periodical",
377         1027 => "Report-number",
378         1028 => "Stock-number",
379         1030 => "Thematic-number",
380         1031 => "Material-type",
381         1032 => "Doc-id",
382         1033 => "Host-item",
383         1034 => "Content-type",
384         1035 => "Anywhere",
385         1036 => "Author-Title-Subject",
386         1032 => "Doc-id (semantic definition change)",
387         1037 => "SICI",
388         1038 => "Abstract-language",
389         1039 => "Application-kind",
390         1040 => "Classification",
391         1041 => "Classification-basic",
392         1042 => "Classification-local-record",
393         1043 => "Enzyme",
394         1044 => "Possessing-institution",
395         1045 => "Record-linking",
396         1046 => "Record-status",
397         1047 => "Treatment",
398         1048 => "Control-number-GKD",
399         1049 => "Control-number-linking",
400         1050 => "Control-number-PND",
401         1051 => "Control-number-SWD",
402         1052 => "Control-number-ZDB",
403         1053 => "Country-publication (country of Publication)",
404         1054 => "Date-conference (meeting date)",
405         1055 => "Date-record-status",
406         1056 => "Dissertation-information",
407         1057 => "Meeting-organizer",
408         1058 => "Note-availability",
409         1059 => "Number-CAS-registry (CAS registry number)",
410         1060 => "Number-document (document number)",
411         1061 => "Number-local-accounting",
412         1062 => "Number-local-acquisition",
413         1063 => "Number-local-call-copy-specific",
414         1064 => "Number-of-reference (reference count)",
415         1065 => "Number-norm",
416         1066 => "Number-volume",
417         1067 => "Place-conference (meeting location)",
418         1068 => "Reference (references and footnotes)",
419         1069 => "Referenced-journal (reference work)",
420         1070 => "Section-code",
421         1071 => "Section-heading",
422         1072 => "Subject-GOO",
423         1073 => "Subject-name-conference",
424         1074 => "Subject-name-corporate",
425         1075 => "Subject-genre/form",
426         1076 => "Subject-name-geographical",
427         1077 => "Subject--chronological",
428         1078 => "Subject--title",
429         1079 => "Subject--topical",
430         1080 => "Subject-uncontrolled",
431         1081 => "Terminology-chemical (chemical name)",
432         1082 => "Title-translated",
433         1083 => "Year-of-beginning",
434         1084 => "Year-of-ending",
435         1085 => "Subject-AGROVOC",
436         1086 => "Subject-COMPASS",
437         1087 => "Subject-EPT",
438         1088 => "Subject-NAL",
439         1089 => "Classification-BCM",
440         1090 => "Classification-DB",
441         1091 => "Identifier-ISRC",
442         1092 => "Identifier-ISMN",
443         1093 => "Identifier-ISRN",
444         1094 => "Identifier-DOI",
445         1095 => "Code-language-original",
446         1096 => "Title-later",
447         1097 => "DC-Title",
448         1098 => "DC-Creator",
449         1099 => "DC-Subject",
450         1100 => "DC-Description",
451         1101 => "DC-Publisher",
452         1102 => "DC-Date",
453         1103 => "DC-ResourceType",
454         1104 => "DC-ResourceIdentifier",
455         1105 => "DC-Language",
456         1106 => "DC-OtherContributor",
457         1107 => "DC-Format",
458         1108 => "DC-Source",
459         1109 => "DC-Relation",
460         1110 => "DC-Coverage",
461         1111 => "DC-RightsManagement",
462         1112 => "Controlled Subject Index",
463         1113 => "Subject Thesaurus",
464         1114 => "Index Terms -- Controlled",
465         1115 => "Controlled Term",
466         1116 => "Spatial Domain",
467         1117 => "Bounding Coordinates",
468         1118 => "West Bounding Coordinate",
469         1119 => "East Bounding Coordinate",
470         1120 => "North Bounding Coordinate",
471         1121 => "South Bounding Coordinate",
472         1122 => "Place",
473         1123 => "Place Keyword Thesaurus",
474         1124 => "Place Keyword",
475         1125 => "Time Period",
476         1126 => "Time Period Textual",
477         1127 => "Time Period Structured",
478         1128 => "Beginning Date",
479         1129 => "Ending Date",
480         1130 => "Availability",
481         1131 => "Distributor",
482         1132 => "Distributor Name",
483         1133 => "Distributor Organization",
484         1134 => "Distributor Street Address",
485         1135 => "Distributor City",
486         1136 => "Distributor State or Province",
487         1137 => "Distributor Zip or Postal Code",
488         1138 => "Distributor Country",
489         1139 => "Distributor Network Address",
490         1140 => "Distributor Hours of Service",
491         1141 => "Distributor Telephone",
492         1142 => "Distributor Fax",
493         1143 => "Resource Description",
494         1144 => "Order Process",
495         1145 => "Order Information",
496         1146 => "Cost",
497         1147 => "Cost Information",
498         1148 => "Technical Prerequisites",
499         1149 => "Available Time Period",
500         1150 => "Available Time Textual",
501         1151 => "Available Time Structured",
502         1152 => "Available Linkage",
503         1153 => "Linkage Type",
504         1154 => "Linkage",
505         1155 => "Sources of Data",
506         1156 => "Methodology",
507         1157 => "Access Constraints",
508         1158 => "General Access Constraints",
509         1159 => "Originator Dissemination Control",
510         1160 => "Security Classification Control",
511         1161 => "Use Constraints",
512         1162 => "Point of Contact",
513         1163 => "Contact Name",
514         1164 => "Contact Organization",
515         1165 => "Contact Street Address",
516         1166 => "Contact City",
517         1167 => "Contact State or Province",
518         1168 => "Contact Zip or Postal Code",
519         1169 => "Contact Country",
520         1170 => "Contact Network Address",
521         1171 => "Contact Hours of Service",
522         1172 => "Contact Telephone",
523         1173 => "Contact Fax",
524         1174 => "Supplemental Information",
525         1175 => "Purpose",
526         1176 => "Agency Program",
527         1177 => "Cross Reference",
528         1178 => "Cross Reference Title",
529         1179 => "Cross Reference Relationship",
530         1180 => "Cross Reference Linkage",
531         1181 => "Schedule Number",
532         1182 => "Original Control Identifier",
533         1183 => "Language of Record",
534         1184 => "Record Review Date",
535         1185 => "Performer",
536         1186 => "Performer-Individual",
537         1187 => "Performer-Group",
538         1188 => "Instrumentation",
539         1189 => "Instrumentation-Original",
540         1190 => "Instrumentation-Current",
541         1191 => "Arrangement",
542         1192 => "Arrangement-Original",
543         1193 => "Arrangement-Current",
544         1194 => "Musical Key-Original",
545         1195 => "Musical Key-Current",
546         1196 => "Date-Composition",
547         1197 => "Date-Recording",
548         1198 => "Place-Recording",
549         1199 => "Country-Recording",
550         1200 => "Number-ISWC",
551         1201 => "Number-Matrix",
552         1202 => "Number-Plate",
553         1203 => "Classification-McColvin",
554         1204 => "Duration",
555         1205 => "Number-Copies",
556         1206 => "Musical Theme",
557         1207 => "Instruments - total number",
558         1208 => "Instruments - distinct number",
559         1209 => "Identifier - URN",
560         1210 => "Sears Subject Heading",
561         1211 => "OCLC Number",
562         1212 => "Composition",
563         1213 => "Intellectual level",
564         1214 => "EAN",
565         1215 => "NLC",
566         1216 => "CRCS",
567         1217 => "Nationality",
568         1218 => "Equinox",
569         1219 => "Compression",
570         1220 => "Format",
571         1221 => "Subject - occupation",
572         1222 => "Subject - function",
573         1223 => "Edition",
574 );
575
576 sub bib1_access_point {
577     my($ap) = @_;
578
579     return $_bib1_access_point{$ap} ||
580         "unknown BIB-1 attribute '$ap'";
581 }
582
583
584 1;