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