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