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