1 # $Id: Utils.pm,v 1.38 2009-04-15 18:16:45 wosch Exp $
3 package ZOOM::IRSpy::Utils;
10 our @EXPORT_OK = qw(utf8param
17 irspy_record2identifier
18 irspy_identifier2target
24 use XML::LibXML::XPathContext;
26 use Encode qw(is_utf8);
29 our $IRSPY_NS = 'http://indexdata.com/irspy/1.0';
31 # Under Apache 2/mod_perl 2, the ubiquitous $r is no longer and
32 # Apache::Request object, nor even an Apache2::Request, but an
33 # Apache2::RequestReq ... which, astonishingly, doesn't have the
34 # param() method. So if we're given one of these things, we need to
35 # make an Apache::Request out of, which at least isn't too hard.
36 # However *sigh* this may not be a cheap operation, so we keep a cache
37 # of already-made Request objects.
40 my %_paramsbyrequest; # Used for Apache2 only
42 my($r, $key, $value) = @_;
44 if ($r->isa('Apache2::RequestRec')) {
45 # Running under Apache2
46 if (defined $_apache2request{$r}) {
47 #warn "using existing Apache2::RequestReq for '$r'";
48 $r = $_apache2request{$r};
50 require Apache2::Request;
51 #warn "making new Apache2::RequestReq for '$r'";
52 $r = $_apache2request{$r} = new Apache2::Request($r);
57 return map { decode_utf8($_) } $r->param();
61 $raw = $_paramsbyrequest{$r}->{$key} if $r->isa('Apache2::Request');
62 $raw = $r->param($key) if !defined $raw;
65 # Argh! Simply writing through to the underlying method
66 # param() won't work in Apache2, where param() is readonly.
67 # So we have to keep a hash of additional values, which we
68 # consult (above) before the actual parameters. Ouch ouch.
69 if ($r->isa('Apache2::Request')) {
70 $_paramsbyrequest{$r}->{$key} = encode_utf8($value);
72 $r->param($key, encode_utf8($value));
76 return undef if !defined $raw;
77 my $cooked = decode_utf8($raw);
78 warn "converted '$raw' to '", $cooked, "'\n" if $cooked ne $raw;
83 # Utility functions follow, exported for use of web UI
84 sub utf8param_apache1 {
85 my($r, $key, $value) = @_;
86 die "utf8param() called with value '$value'" if defined $value;
88 my $raw = $r->param($key);
89 return undef if !defined $raw;
90 my $cooked = decode_utf8($raw);
91 warn "converted '$raw' to '", $cooked, "'\n" if $cooked ne $raw;
99 my($sec, $min, $hour, $mday, $mon, $year) = localtime($time);
100 return sprintf("%04d-%02d-%02dT%02d:%02d:%02d",
101 $year+1900, $mon+1, $mday, $hour, $min, $sec);
105 # I can't -- just can't, can't, can't -- believe that this function
106 # isn't provided by one of the core XML modules. But the evidence all
107 # says that it's not: among other things, XML::Generator and
108 # Template::Plugin both roll their own. So I will do likewise. D'oh!
111 my($text, $fallback, $opts) = @_;
112 if (!defined $opts && ref $fallback) {
113 # The second and third arguments are both optional
117 $opts = {} if !defined $opts;
119 $text = $fallback if !defined $text;
121 confess "xml_encode(): text and fallback both undefined"
124 $text =~ s/&/&/g;
127 # Internet Explorer can't display ' (!) so don't create it
128 #$text =~ s/['']/'/g;
129 $text =~ s/[""]/"/g;
130 $text =~ s/ / /g if $opts->{nbsp};
136 # Quotes a term for use in a CQL query
140 $term =~ s/([""\\*?])/\\$1/g;
141 $term = qq["$term"] if $term =~ /[\s""\/]/;
146 # Makes a CQL query that finds a specified target. Arguments may be
147 # either an ID alone, or a (host, port, db) triple.
149 my($protocol, $host, $port, $db) = @_;
153 $id = irspy_make_identifier($protocol, $host, $port, $db);
158 return "rec.id=" . cql_quote($id);
162 # PRIVATE to irspy_namespace() and irspy_xpath_context()
164 e => 'http://explain.z3950.org/dtd/2.0/',
169 sub irspy_namespace {
173 confess "irspy_namespace(undef)" if !defined $prefix;
174 my $uri = $_namespaces{$prefix};
175 die "irspy_namespace(): no URI for namespace prefix '$prefix'"
182 sub irspy_xpath_context {
185 if (ref $record && $record->isa("ZOOM::Record")) {
186 $record = $record->render();
193 my $parser = new XML::LibXML();
194 my $doc = $parser->parse_string($record);
195 $root = $doc->getDocumentElement();
198 my $xc = XML::LibXML::XPathContext->new($root);
199 foreach my $prefix (keys %_namespaces) {
200 $xc->registerNs($prefix, $_namespaces{$prefix});
206 # Construct an opaque identifier from its components. Although it's
207 # trivial, this is needed in so many places that it really needs to be
210 # This is the converse of _parse_target_string() in IRSpy.pm, which
211 # should be renamed and moved into this package.
213 sub irspy_make_identifier {
214 my($protocol, $host, $port, $dbname) = @_;
216 die "irspy_make_identifier(" . join(", ", map { "'$_'" } @_).
217 "): wrong number of arguments" if @_ != 4;
219 die "irspy_make_identifier(): protocol undefined" if !defined $protocol;
220 die "irspy_make_identifier(): host undefined" if !defined $host;
221 die "irspy_make_identifier(): port undefined" if !defined $port;
222 die "irspy_make_identifier(): dbname undefined" if !defined $dbname;
224 return "$protocol:$host:$port/$dbname";
228 # Returns the opaque identifier of an IRSpy record based on the
229 # XPathContext'ed DOM object, as returned by irspy_xpath_context().
230 # This is doing the same thing as irspy_make_identifier() but from a
231 # record rather than a set of parameters.
233 sub irspy_record2identifier {
236 ### Must be kept the same as is used in ../../../zebra/*.xsl
237 return $xc->find("concat(e:serverInfo/\@protocol, ':',
238 e:serverInfo/e:host, ':',
239 e:serverInfo/e:port, '/',
240 e:serverInfo/e:database)");
244 # Transforms an IRSpy opqaue identifier, as returned from
245 # irspy_make_identifier() or irspy_record2identifier(), into a YAZ
246 # target-string suitable for feeding to ZOOM. Before we introduced
247 # the protocol element at the start of the identifier string, this was
248 # a null transform; now we have to be a bit cleverer.
250 sub irspy_identifier2target {
251 my $res = _irspy_identifier2target(@_);
252 #carp "converted ID '@_' to target '$res'";
256 sub _irspy_identifier2target {
259 confess "_irspy_identifier2target(): id is undefined"
262 my($protocol, $target) = ($id =~ /(.*?):(.*)/);
263 if (uc($protocol) eq "Z39.50" || uc($protocol) eq "TCP") {
264 return "tcp:$target";
265 } elsif (uc($protocol) eq "SRU") {
266 return "sru=get,http:$target";
267 } elsif (uc($protocol) eq "SRW") {
268 return "sru=srw,http:$target";
271 warn "_irspy_identifier2target($id): unrecognised protocol '$protocol'";
276 sub modify_xml_document {
277 my($xc, $fieldsByKey, $data) = @_;
280 foreach my $key (keys %$data) {
281 my $value = $data->{$key};
282 my $ref = $fieldsByKey->{$key} or die "no field '$key'";
283 my($name, $nlines, $caption, $xpath, @addAfter) = @$ref;
284 #print "Considering $key='$value' ($xpath)<br/>\n";
285 my @nodes = $xc->findnodes($xpath);
287 warn scalar(@nodes), " nodes match '$xpath'" if @nodes > 1;
288 my $node = $nodes[0];
290 if ($node->isa("XML::LibXML::Attr")) {
291 if ($value ne $node->getValue()) {
292 $node->setValue($value);
294 #print "Attr $key: '", $node->getValue(), "' -> '$value' ($xpath)<br/>\n";
296 } elsif ($node->isa("XML::LibXML::Element")) {
297 # The contents could be any mixture of text and
298 # comments and maybe even other crud such as processing
299 # instructions. The simplest thing is just to throw it all
300 # away and start again, making a single Text node the
301 # canonical representation. But before we do that,
302 # we'll check whether the element is already
303 # canonical, to determine whether our change is a
306 my @children = $node->childNodes();
307 if (@children == 1) {
308 my $child = $node->firstChild();
309 if (ref $child && ref $child eq "XML::LibXML::Text") {
310 $old = $child->getData();
311 #print STDERR "child='$child', old=", _renderchars($old), "\n" if $key eq "title";
314 next if $value eq $old;
316 $node->removeChildNodes();
317 my $child = new XML::LibXML::Text($value);
318 $node->appendChild($child);
320 #print STDERR "Elem $key ($xpath): ", _renderchars($old), " -> '", _renderchars($value), "\n";
322 warn "unexpected node type $node";
326 next if !$value; # No need to create a new empty node
327 my($ppath, $selector) = $xpath =~ /(.*)\/(.*)/;
328 dom_add_node($xc, $ppath, $selector, $value, @addAfter);
329 #print "New $key ($xpath) = '$value'<br/>\n";
341 return "'" . $text . "'", " (", join(" ", map {ord($_)} split //, $text), "), is_utf8=" , is_utf8($text);
346 my($xc, $ppath, $selector, $value, @addAfter) = @_;
348 #print "Adding $selector='$value' at '$ppath' after (", join(", ", map { "'$_'" } @addAfter), ")<br/>\n";
349 my $node = find_or_make_node($xc, $ppath, 0);
350 die "couldn't find or make node '$node'" if !defined $node;
352 my $is_attr = ($selector =~ s/^@//);
353 my(undef, $prefix, $simpleSel) = $selector =~ /((.*?):)?(.*)/;
354 #warn "selector='$selector', prefix='$prefix', simpleSel='$simpleSel'";
356 if (defined $prefix) {
357 ### This seems to no-op (thank, DOM!) but I have have no
358 # idea, and it's not needed for IRSpy, so I am not going
360 $node->setAttributeNS(irspy_namespace($prefix),
363 $node->setAttribute($simpleSel, $value);
368 my $new = new XML::LibXML::Element($simpleSel);
369 $new->setNamespace(irspy_namespace($prefix), $prefix)
372 $new->appendText($value);
373 foreach my $predecessor (reverse @addAfter) {
374 my($child) = $xc->findnodes($predecessor, $node);
375 if (defined $child) {
376 $node->insertAfter($new, $child);
377 #warn "Added after '$predecessor'";
382 # Didn't find any of the nodes that are supposed to precede the
383 # new one, so we need to insert the new node as the first of the
384 # parent's children. However *sigh* there is no prependChild()
385 # analogous to appendChild(), so we have to go the long way round.
386 my @children = $node->childNodes();
388 $node->insertBefore($new, $children[0]);
389 #warn "Added new first child";
391 $node->appendChild($new);
392 #warn "Added new only child";
396 my $text = xml_encode(inheritance_tree($xc));
397 $text =~ s/\n/<br\/>$&/sg;
398 print "<pre>$text</pre>\n";
403 sub find_or_make_node {
404 my($xc, $path, $recursion_level) = @_;
406 die "deep recursion in find_or_make_node($path)"
407 if $recursion_level == 10;
408 $path = "." if $path eq "";
410 my @nodes = $xc->findnodes($path);
412 # Oh dear, the parent node doesn't exist. We could make it,
413 my(undef, $ppath, $element) = $path =~ /((.*)\/)?(.*)/;
414 $ppath = "" if !defined $ppath;
415 #warn "path='$path', ppath='$ppath', element='$element'";
416 #warn "no node '$path': making it";
417 my $parent = find_or_make_node($xc, $ppath, $recursion_level-1);
419 my(undef, $prefix, $nsElem) = $element =~ /((.*?):)?(.*)/;
420 #warn "element='$element', prefix='$prefix', nsElem='$nsElem'";
421 my $new = new XML::LibXML::Element($nsElem);
422 if (defined $prefix) {
423 #warn "setNamespace($prefix)";
424 $new->setNamespace(irspy_namespace($prefix), $prefix);
427 $parent->appendChild($new);
430 warn scalar(@nodes), " nodes match parent '$path'" if @nodes > 1;
435 sub inheritance_tree {
436 my($type, $level) = @_;
437 $level = 0 if !defined $level;
438 return "Woah! Too deep, man!\n" if $level > 20;
440 $type = ref $type if ref $type;
442 $text = "--> " if $level == 0;
443 $text .= ("\t" x $level) . "$type\n";
444 my @ISA = eval "\@${type}::ISA";
445 foreach my $superclass (@ISA) {
446 $text .= inheritance_tree($superclass, $level+1);
453 # This function is made available in xslt using the register_function call
455 my ($arg1, $arg2) = @_;
456 return "$arg1" cmp "$arg2";
460 ### It feels like this should be in YAZ, exported via ZOOM-Perl.
461 my %_bib1_access_point = (
462 1 => "Personal name",
463 2 => "Corporate name",
464 3 => "Conference name",
467 6 => "Title uniform",
470 9 => "LC card number",
471 10 => "BNB card no.",
473 12 => "Local number",
474 13 => "Dewey classification",
475 14 => "UDC classification",
476 15 => "Bliss classification",
477 16 => "LC call number",
478 17 => "NLM call number",
479 18 => "NAL call number",
480 19 => "MOS call number",
481 20 => "Local classification",
482 21 => "Subject heading",
483 22 => "Subject Rameau",
484 23 => "BDI index subject",
485 24 => "INSPEC subject",
486 25 => "MESH subject",
488 27 => "LC subject heading",
489 28 => "RVM subject heading",
490 29 => "Local subject index",
492 31 => "Date of publication",
493 32 => "Date of acquisition",
495 34 => "Title collective",
496 35 => "Title parallel",
498 37 => "Title added title page",
499 38 => "Title caption",
500 39 => "Title running",
502 41 => "Title other variant",
503 42 => "Title former",
504 43 => "Title abbreviated",
505 44 => "Title expanded",
506 45 => "Subject precis",
507 46 => "Subject rswk",
508 47 => "Subject subdivision",
509 48 => "No. nat'l biblio.",
510 49 => "No. legal deposit",
511 50 => "No. govt pub.",
512 51 => "No. music publisher",
514 53 => "Number local call",
515 54 => "Code--language",
516 55 => "Code--geographic area",
517 56 => "Code--institution",
518 57 => "Name and title *",
519 58 => "Name geographic",
520 59 => "Place publication",
522 61 => "Microform generation",
525 1000 => "Author-title",
526 1001 => "Record type",
529 1004 => "Author-name personal",
530 1005 => "Author-name corporate",
531 1006 => "Author-name conference",
532 1007 => "Identifier--standard",
533 1008 => "Subject--LC children's",
534 1009 => "Subject name -- personal",
535 1010 => "Body of text",
536 1011 => "Date/time added to db",
537 1012 => "Date/time last modified",
538 1013 => "Authority/format id",
539 1014 => "Concept-text",
540 1015 => "Concept-reference",
542 1017 => "Server-choice",
544 1019 => "Record-source",
547 1022 => "Geographic-class",
548 1023 => "Indexed-by",
551 1026 => "Related-periodical",
552 1027 => "Report-number",
553 1028 => "Stock-number",
554 1030 => "Thematic-number",
555 1031 => "Material-type",
558 1034 => "Content-type",
560 1036 => "Author-Title-Subject",
561 1032 => "Doc-id (semantic definition change)",
563 1038 => "Abstract-language",
564 1039 => "Application-kind",
565 1040 => "Classification",
566 1041 => "Classification-basic",
567 1042 => "Classification-local-record",
569 1044 => "Possessing-institution",
570 1045 => "Record-linking",
571 1046 => "Record-status",
573 1048 => "Control-number-GKD",
574 1049 => "Control-number-linking",
575 1050 => "Control-number-PND",
576 1051 => "Control-number-SWD",
577 1052 => "Control-number-ZDB",
578 1053 => "Country-publication (country of Publication)",
579 1054 => "Date-conference (meeting date)",
580 1055 => "Date-record-status",
581 1056 => "Dissertation-information",
582 1057 => "Meeting-organizer",
583 1058 => "Note-availability",
584 1059 => "Number-CAS-registry (CAS registry number)",
585 1060 => "Number-document (document number)",
586 1061 => "Number-local-accounting",
587 1062 => "Number-local-acquisition",
588 1063 => "Number-local-call-copy-specific",
589 1064 => "Number-of-reference (reference count)",
590 1065 => "Number-norm",
591 1066 => "Number-volume",
592 1067 => "Place-conference (meeting location)",
593 1068 => "Reference (references and footnotes)",
594 1069 => "Referenced-journal (reference work)",
595 1070 => "Section-code",
596 1071 => "Section-heading",
597 1072 => "Subject-GOO",
598 1073 => "Subject-name-conference",
599 1074 => "Subject-name-corporate",
600 1075 => "Subject-genre/form",
601 1076 => "Subject-name-geographical",
602 1077 => "Subject--chronological",
603 1078 => "Subject--title",
604 1079 => "Subject--topical",
605 1080 => "Subject-uncontrolled",
606 1081 => "Terminology-chemical (chemical name)",
607 1082 => "Title-translated",
608 1083 => "Year-of-beginning",
609 1084 => "Year-of-ending",
610 1085 => "Subject-AGROVOC",
611 1086 => "Subject-COMPASS",
612 1087 => "Subject-EPT",
613 1088 => "Subject-NAL",
614 1089 => "Classification-BCM",
615 1090 => "Classification-DB",
616 1091 => "Identifier-ISRC",
617 1092 => "Identifier-ISMN",
618 1093 => "Identifier-ISRN",
619 1094 => "Identifier-DOI",
620 1095 => "Code-language-original",
621 1096 => "Title-later",
623 1098 => "DC-Creator",
624 1099 => "DC-Subject",
625 1100 => "DC-Description",
626 1101 => "DC-Publisher",
628 1103 => "DC-ResourceType",
629 1104 => "DC-ResourceIdentifier",
630 1105 => "DC-Language",
631 1106 => "DC-OtherContributor",
634 1109 => "DC-Relation",
635 1110 => "DC-Coverage",
636 1111 => "DC-RightsManagement",
637 1112 => "Controlled Subject Index",
638 1113 => "Subject Thesaurus",
639 1114 => "Index Terms -- Controlled",
640 1115 => "Controlled Term",
641 1116 => "Spatial Domain",
642 1117 => "Bounding Coordinates",
643 1118 => "West Bounding Coordinate",
644 1119 => "East Bounding Coordinate",
645 1120 => "North Bounding Coordinate",
646 1121 => "South Bounding Coordinate",
648 1123 => "Place Keyword Thesaurus",
649 1124 => "Place Keyword",
650 1125 => "Time Period",
651 1126 => "Time Period Textual",
652 1127 => "Time Period Structured",
653 1128 => "Beginning Date",
654 1129 => "Ending Date",
655 1130 => "Availability",
656 1131 => "Distributor",
657 1132 => "Distributor Name",
658 1133 => "Distributor Organization",
659 1134 => "Distributor Street Address",
660 1135 => "Distributor City",
661 1136 => "Distributor State or Province",
662 1137 => "Distributor Zip or Postal Code",
663 1138 => "Distributor Country",
664 1139 => "Distributor Network Address",
665 1140 => "Distributor Hours of Service",
666 1141 => "Distributor Telephone",
667 1142 => "Distributor Fax",
668 1143 => "Resource Description",
669 1144 => "Order Process",
670 1145 => "Order Information",
672 1147 => "Cost Information",
673 1148 => "Technical Prerequisites",
674 1149 => "Available Time Period",
675 1150 => "Available Time Textual",
676 1151 => "Available Time Structured",
677 1152 => "Available Linkage",
678 1153 => "Linkage Type",
680 1155 => "Sources of Data",
681 1156 => "Methodology",
682 1157 => "Access Constraints",
683 1158 => "General Access Constraints",
684 1159 => "Originator Dissemination Control",
685 1160 => "Security Classification Control",
686 1161 => "Use Constraints",
687 1162 => "Point of Contact",
688 1163 => "Contact Name",
689 1164 => "Contact Organization",
690 1165 => "Contact Street Address",
691 1166 => "Contact City",
692 1167 => "Contact State or Province",
693 1168 => "Contact Zip or Postal Code",
694 1169 => "Contact Country",
695 1170 => "Contact Network Address",
696 1171 => "Contact Hours of Service",
697 1172 => "Contact Telephone",
698 1173 => "Contact Fax",
699 1174 => "Supplemental Information",
701 1176 => "Agency Program",
702 1177 => "Cross Reference",
703 1178 => "Cross Reference Title",
704 1179 => "Cross Reference Relationship",
705 1180 => "Cross Reference Linkage",
706 1181 => "Schedule Number",
707 1182 => "Original Control Identifier",
708 1183 => "Language of Record",
709 1184 => "Record Review Date",
711 1186 => "Performer-Individual",
712 1187 => "Performer-Group",
713 1188 => "Instrumentation",
714 1189 => "Instrumentation-Original",
715 1190 => "Instrumentation-Current",
716 1191 => "Arrangement",
717 1192 => "Arrangement-Original",
718 1193 => "Arrangement-Current",
719 1194 => "Musical Key-Original",
720 1195 => "Musical Key-Current",
721 1196 => "Date-Composition",
722 1197 => "Date-Recording",
723 1198 => "Place-Recording",
724 1199 => "Country-Recording",
725 1200 => "Number-ISWC",
726 1201 => "Number-Matrix",
727 1202 => "Number-Plate",
728 1203 => "Classification-McColvin",
730 1205 => "Number-Copies",
731 1206 => "Musical Theme",
732 1207 => "Instruments - total number",
733 1208 => "Instruments - distinct number",
734 1209 => "Identifier - URN",
735 1210 => "Sears Subject Heading",
736 1211 => "OCLC Number",
737 1212 => "Composition",
738 1213 => "Intellectual level",
742 1217 => "Nationality",
744 1219 => "Compression",
746 1221 => "Subject - occupation",
747 1222 => "Subject - function",
751 sub bib1_access_point {
754 return $_bib1_access_point{$ap} ||
755 "unknown BIB-1 attribute '$ap'";
760 my($rs, $which, $elementSetName) = @_;
762 # There is a slight race condition here on the element-set name,
763 # but it shouldn't be a problem as this is (currently) only called
764 # from parts of the program that run single-threaded.
765 my $old = $rs->option(elementSetName => $elementSetName);
766 my $rec = $rs->record($which);
767 $rs->option(elementSetName => $old);
769 return $rec->render();