1 # $Id: Utils.pm,v 1.27 2007-04-27 14:04:40 mike Exp $
3 package ZOOM::IRSpy::Utils;
10 our @EXPORT_OK = qw(isodate
16 irspy_record2identifier
17 irspy_identifier2target
23 use XML::LibXML::XPathContext;
25 our $IRSPY_NS = 'http://indexdata.com/irspy/1.0';
28 # Utility functions follow, exported for use of web UI
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);
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!
44 my($text, $fallback, $opts) = @_;
45 if (!defined $opts && ref $fallback) {
46 # The second and third arguments are both optional
50 $opts = {} if !defined $opts;
52 $text = $fallback if !defined $text;
54 confess "xml_encode(): text and fallback both undefined"
60 # Internet Explorer can't display ' (!) so don't create it
61 #$text =~ s/['']/'/g;
62 $text =~ s/[""]/"/g;
63 $text =~ s/ / /g if $opts->{nbsp};
69 # Quotes a term for use in a CQL query
73 $term =~ s/([""\\])/\\$1/g;
74 $term = qq["$term"] if $term =~ /[\s""\/]/;
79 # Makes a CQL query that finds a specified target. Arguments may be
80 # either an ID alone, or a (host, port, db) triple.
82 my($protocol, $host, $port, $db) = @_;
86 $id = irspy_make_identifier($protocol, $host, $port, $db);
91 return "rec.id=" . cql_quote($id);
95 # PRIVATE to irspy_namespace() and irspy_xpath_context()
97 e => 'http://explain.z3950.org/dtd/2.0/',
102 sub irspy_namespace {
106 confess "irspy_namespace(undef)" if !defined $prefix;
107 my $uri = $_namespaces{$prefix};
108 die "irspy_namespace(): no URI for namespace prefix '$prefix'"
115 sub irspy_xpath_context {
118 if (ref $record && $record->isa("ZOOM::Record")) {
119 $record = $record->render();
126 my $parser = new XML::LibXML();
127 my $doc = $parser->parse_string($record);
128 $root = $doc->getDocumentElement();
131 my $xc = XML::LibXML::XPathContext->new($root);
132 foreach my $prefix (keys %_namespaces) {
133 $xc->registerNs($prefix, $_namespaces{$prefix});
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
143 # This is the converse of _parse_target_string() in IRSpy.pm, which
144 # should be renamed and moved into this package.
146 sub irspy_make_identifier {
147 my($protocol, $host, $port, $dbname) = @_;
149 die "irspy_make_identifier(" . join(", ", map { "'$_'" } @_).
150 "): wrong number of arguments" if @_ != 4;
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;
157 return "$protocol:$host:$port/$dbname";
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.
166 sub irspy_record2identifier {
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)");
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.
183 sub irspy_identifier2target {
186 my($protocol, $target) = ($id =~ /(.*?):(.*)/);
187 print STDERR "protocol='$protocol', target='$target'\n";
188 ### This assumes everything is Z39.50
193 sub modify_xml_document {
194 my($xc, $fieldsByKey, $data) = @_;
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);
204 warn scalar(@nodes), " nodes match '$xpath'" if @nodes > 1;
205 my $node = $nodes[0];
207 if ($node->isa("XML::LibXML::Attr")) {
208 if ($value ne $node->getValue()) {
209 $node->setValue($value);
211 #print "Attr $key: '", $node->getValue(), "' -> '$value' ($xpath)<br/>\n";
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
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;
232 $node->removeChildNodes();
233 my $child = new XML::LibXML::Text($value);
234 $node->appendChild($child);
236 #print "Elem $key: '$old' -> '$value' ($xpath)<br/>\n";
238 warn "unexpected node type $node";
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";
255 my($xc, $ppath, $selector, $value, @addAfter) = @_;
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;
261 my $is_attr = ($selector =~ s/^@//);
262 my(undef, $prefix, $simpleSel) = $selector =~ /((.*?):)?(.*)/;
263 #warn "selector='$selector', prefix='$prefix', simpleSel='$simpleSel'";
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
269 $node->setAttributeNS(irspy_namespace($prefix),
272 $node->setAttribute($simpleSel, $value);
277 my $new = new XML::LibXML::Element($simpleSel);
278 $new->setNamespace(irspy_namespace($prefix), $prefix)
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'";
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();
297 $node->insertBefore($new, $children[0]);
298 #warn "Added new first child";
300 $node->appendChild($new);
301 #warn "Added new only child";
305 my $text = xml_encode(inheritance_tree($xc));
306 $text =~ s/\n/<br\/>$&/sg;
307 print "<pre>$text</pre>\n";
312 sub find_or_make_node {
313 my($xc, $path, $recursion_level) = @_;
315 die "deep recursion in find_or_make_node($path)"
316 if $recursion_level == 10;
317 $path = "." if $path eq "";
319 my @nodes = $xc->findnodes($path);
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);
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);
336 $parent->appendChild($new);
339 warn scalar(@nodes), " nodes match parent '$path'" if @nodes > 1;
344 sub inheritance_tree {
345 my($type, $level) = @_;
346 $level = 0 if !defined $level;
347 return "Woah! Too deep, man!\n" if $level > 20;
349 $type = ref $type if ref $type;
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);
362 # This function is made available in xslt using the register_function call
364 my ($arg1, $arg2) = @_;
365 return ($arg1->to_literal()) cmp ($arg2->to_literal());
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",
376 6 => "Title uniform",
379 9 => "LC card number",
380 10 => "BNB card no.",
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",
397 27 => "LC subject heading",
398 28 => "RVM subject heading",
399 29 => "Local subject index",
401 31 => "Date of publication",
402 32 => "Date of acquisition",
404 34 => "Title collective",
405 35 => "Title parallel",
407 37 => "Title added title page",
408 38 => "Title caption",
409 39 => "Title running",
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",
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",
431 61 => "Microform generation",
434 1000 => "Author-title",
435 1001 => "Record type",
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",
451 1017 => "Server-choice",
453 1019 => "Record-source",
456 1022 => "Geographic-class",
457 1023 => "Indexed-by",
460 1026 => "Related-periodical",
461 1027 => "Report-number",
462 1028 => "Stock-number",
463 1030 => "Thematic-number",
464 1031 => "Material-type",
467 1034 => "Content-type",
469 1036 => "Author-Title-Subject",
470 1032 => "Doc-id (semantic definition change)",
472 1038 => "Abstract-language",
473 1039 => "Application-kind",
474 1040 => "Classification",
475 1041 => "Classification-basic",
476 1042 => "Classification-local-record",
478 1044 => "Possessing-institution",
479 1045 => "Record-linking",
480 1046 => "Record-status",
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",
532 1098 => "DC-Creator",
533 1099 => "DC-Subject",
534 1100 => "DC-Description",
535 1101 => "DC-Publisher",
537 1103 => "DC-ResourceType",
538 1104 => "DC-ResourceIdentifier",
539 1105 => "DC-Language",
540 1106 => "DC-OtherContributor",
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",
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",
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",
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",
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",
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",
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",
651 1217 => "Nationality",
653 1219 => "Compression",
655 1221 => "Subject - occupation",
656 1222 => "Subject - function",
660 sub bib1_access_point {
663 return $_bib1_access_point{$ap} ||
664 "unknown BIB-1 attribute '$ap'";
669 my($rs, $which, $elementSetName) = @_;
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);
678 return $rec->render();