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