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