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