1 # $Id: Utils.pm,v 1.35 2007-06-28 13:59:31 sondberg 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';
32 # Utility functions follow, exported for use of web UI
34 my($r, $key, $value) = @_;
35 die "utf8param() called with value '$value'" if defined $value;
37 my $raw = $r->param($key);
38 return undef if !defined $raw;
39 my $cooked = decode_utf8($raw);
40 warn "converted '$raw' to '", $cooked, "'\n" if $cooked ne $raw;
48 my($sec, $min, $hour, $mday, $mon, $year) = localtime($time);
49 return sprintf("%04d-%02d-%02dT%02d:%02d:%02d",
50 $year+1900, $mon+1, $mday, $hour, $min, $sec);
54 # I can't -- just can't, can't, can't -- believe that this function
55 # isn't provided by one of the core XML modules. But the evidence all
56 # says that it's not: among other things, XML::Generator and
57 # Template::Plugin both roll their own. So I will do likewise. D'oh!
60 my($text, $fallback, $opts) = @_;
61 if (!defined $opts && ref $fallback) {
62 # The second and third arguments are both optional
66 $opts = {} if !defined $opts;
68 $text = $fallback if !defined $text;
70 confess "xml_encode(): text and fallback both undefined"
76 # Internet Explorer can't display ' (!) so don't create it
77 #$text =~ s/['']/'/g;
78 $text =~ s/[""]/"/g;
79 $text =~ s/ / /g if $opts->{nbsp};
85 # Quotes a term for use in a CQL query
89 $term =~ s/([""\\*?])/\\$1/g;
90 $term = qq["$term"] if $term =~ /[\s""\/]/;
95 # Makes a CQL query that finds a specified target. Arguments may be
96 # either an ID alone, or a (host, port, db) triple.
98 my($protocol, $host, $port, $db) = @_;
102 $id = irspy_make_identifier($protocol, $host, $port, $db);
107 return "rec.id=" . cql_quote($id);
111 # PRIVATE to irspy_namespace() and irspy_xpath_context()
113 e => 'http://explain.z3950.org/dtd/2.0/',
118 sub irspy_namespace {
122 confess "irspy_namespace(undef)" if !defined $prefix;
123 my $uri = $_namespaces{$prefix};
124 die "irspy_namespace(): no URI for namespace prefix '$prefix'"
131 sub irspy_xpath_context {
134 if (ref $record && $record->isa("ZOOM::Record")) {
135 $record = $record->render();
142 my $parser = new XML::LibXML();
143 my $doc = $parser->parse_string($record);
144 $root = $doc->getDocumentElement();
147 my $xc = XML::LibXML::XPathContext->new($root);
148 foreach my $prefix (keys %_namespaces) {
149 $xc->registerNs($prefix, $_namespaces{$prefix});
155 # Construct an opaque identifier from its components. Although it's
156 # trivial, this is needed in so many places that it really needs to be
159 # This is the converse of _parse_target_string() in IRSpy.pm, which
160 # should be renamed and moved into this package.
162 sub irspy_make_identifier {
163 my($protocol, $host, $port, $dbname) = @_;
165 die "irspy_make_identifier(" . join(", ", map { "'$_'" } @_).
166 "): wrong number of arguments" if @_ != 4;
168 die "irspy_make_identifier(): protocol undefined" if !defined $protocol;
169 die "irspy_make_identifier(): host undefined" if !defined $host;
170 die "irspy_make_identifier(): port undefined" if !defined $port;
171 die "irspy_make_identifier(): dbname undefined" if !defined $dbname;
173 return "$protocol:$host:$port/$dbname";
177 # Returns the opaque identifier of an IRSpy record based on the
178 # XPathContext'ed DOM object, as returned by irspy_xpath_context().
179 # This is doing the same thing as irspy_make_identifier() but from a
180 # record rather than a set of parameters.
182 sub irspy_record2identifier {
185 ### Must be kept the same as is used in ../../../zebra/*.xsl
186 return $xc->find("concat(e:serverInfo/\@protocol, ':',
187 e:serverInfo/e:host, ':',
188 e:serverInfo/e:port, '/',
189 e:serverInfo/e:database)");
193 # Transforms an IRSpy opqaue identifier, as returned from
194 # irspy_make_identifier() or irspy_record2identifier(), into a YAZ
195 # target-string suitable for feeding to ZOOM. Before we introduced
196 # the protocol element at the start of the identifier string, this was
197 # a null transform; now we have to be a bit cleverer.
199 sub irspy_identifier2target {
200 my $res = _irspy_identifier2target(@_);
201 #carp "converted ID '@_' to target '$res'";
205 sub _irspy_identifier2target {
208 my($protocol, $target) = ($id =~ /(.*?):(.*)/);
209 if (uc($protocol) eq "Z39.50") {
210 return "tcp:$target";
211 } elsif (uc($protocol) eq "SRU") {
212 return "sru=get,http:$target";
213 } elsif (uc($protocol) eq "SRW") {
214 return "sru=srw,http:$target";
217 warn "unrecognised protocol '$protocol' in ID $id";
222 sub modify_xml_document {
223 my($xc, $fieldsByKey, $data) = @_;
226 foreach my $key (keys %$data) {
227 my $value = $data->{$key};
228 my $ref = $fieldsByKey->{$key} or die "no field '$key'";
229 my($name, $nlines, $caption, $xpath, @addAfter) = @$ref;
230 #print "Considering $key='$value' ($xpath)<br/>\n";
231 my @nodes = $xc->findnodes($xpath);
233 warn scalar(@nodes), " nodes match '$xpath'" if @nodes > 1;
234 my $node = $nodes[0];
236 if ($node->isa("XML::LibXML::Attr")) {
237 if ($value ne $node->getValue()) {
238 $node->setValue($value);
240 #print "Attr $key: '", $node->getValue(), "' -> '$value' ($xpath)<br/>\n";
242 } elsif ($node->isa("XML::LibXML::Element")) {
243 # The contents could be any mixture of text and
244 # comments and maybe even other crud such as processing
245 # instructions. The simplest thing is just to throw it all
246 # away and start again, making a single Text node the
247 # canonical representation. But before we do that,
248 # we'll check whether the element is already
249 # canonical, to determine whether our change is a
252 my @children = $node->childNodes();
253 if (@children == 1) {
254 my $child = $node->firstChild();
255 if (ref $child && ref $child eq "XML::LibXML::Text") {
256 $old = $child->getData();
257 #print STDERR "child='$child', old=", _renderchars($old), "\n" if $key eq "title";
260 next if $value eq $old;
262 $node->removeChildNodes();
263 my $child = new XML::LibXML::Text($value);
264 $node->appendChild($child);
266 #print STDERR "Elem $key ($xpath): ", _renderchars($old), " -> '", _renderchars($value), "\n";
268 warn "unexpected node type $node";
272 next if !$value; # No need to create a new empty node
273 my($ppath, $selector) = $xpath =~ /(.*)\/(.*)/;
274 dom_add_node($xc, $ppath, $selector, $value, @addAfter);
275 #print "New $key ($xpath) = '$value'<br/>\n";
287 return "'" . $text . "'", " (", join(" ", map {ord($_)} split //, $text), "), is_utf8=" , is_utf8($text);
292 my($xc, $ppath, $selector, $value, @addAfter) = @_;
294 #print "Adding $selector='$value' at '$ppath' after (", join(", ", map { "'$_'" } @addAfter), ")<br/>\n";
295 my $node = find_or_make_node($xc, $ppath, 0);
296 die "couldn't find or make node '$node'" if !defined $node;
298 my $is_attr = ($selector =~ s/^@//);
299 my(undef, $prefix, $simpleSel) = $selector =~ /((.*?):)?(.*)/;
300 #warn "selector='$selector', prefix='$prefix', simpleSel='$simpleSel'";
302 if (defined $prefix) {
303 ### This seems to no-op (thank, DOM!) but I have have no
304 # idea, and it's not needed for IRSpy, so I am not going
306 $node->setAttributeNS(irspy_namespace($prefix),
309 $node->setAttribute($simpleSel, $value);
314 my $new = new XML::LibXML::Element($simpleSel);
315 $new->setNamespace(irspy_namespace($prefix), $prefix)
318 $new->appendText($value);
319 foreach my $predecessor (reverse @addAfter) {
320 my($child) = $xc->findnodes($predecessor, $node);
321 if (defined $child) {
322 $node->insertAfter($new, $child);
323 #warn "Added after '$predecessor'";
328 # Didn't find any of the nodes that are supposed to precede the
329 # new one, so we need to insert the new node as the first of the
330 # parent's children. However *sigh* there is no prependChild()
331 # analogous to appendChild(), so we have to go the long way round.
332 my @children = $node->childNodes();
334 $node->insertBefore($new, $children[0]);
335 #warn "Added new first child";
337 $node->appendChild($new);
338 #warn "Added new only child";
342 my $text = xml_encode(inheritance_tree($xc));
343 $text =~ s/\n/<br\/>$&/sg;
344 print "<pre>$text</pre>\n";
349 sub find_or_make_node {
350 my($xc, $path, $recursion_level) = @_;
352 die "deep recursion in find_or_make_node($path)"
353 if $recursion_level == 10;
354 $path = "." if $path eq "";
356 my @nodes = $xc->findnodes($path);
358 # Oh dear, the parent node doesn't exist. We could make it,
359 my(undef, $ppath, $element) = $path =~ /((.*)\/)?(.*)/;
360 $ppath = "" if !defined $ppath;
361 #warn "path='$path', ppath='$ppath', element='$element'";
362 #warn "no node '$path': making it";
363 my $parent = find_or_make_node($xc, $ppath, $recursion_level-1);
365 my(undef, $prefix, $nsElem) = $element =~ /((.*?):)?(.*)/;
366 #warn "element='$element', prefix='$prefix', nsElem='$nsElem'";
367 my $new = new XML::LibXML::Element($nsElem);
368 if (defined $prefix) {
369 #warn "setNamespace($prefix)";
370 $new->setNamespace(irspy_namespace($prefix), $prefix);
373 $parent->appendChild($new);
376 warn scalar(@nodes), " nodes match parent '$path'" if @nodes > 1;
381 sub inheritance_tree {
382 my($type, $level) = @_;
383 $level = 0 if !defined $level;
384 return "Woah! Too deep, man!\n" if $level > 20;
386 $type = ref $type if ref $type;
388 $text = "--> " if $level == 0;
389 $text .= ("\t" x $level) . "$type\n";
390 my @ISA = eval "\@${type}::ISA";
391 foreach my $superclass (@ISA) {
392 $text .= inheritance_tree($superclass, $level+1);
399 # This function is made available in xslt using the register_function call
401 my ($arg1, $arg2) = @_;
402 return "$arg1" cmp "$arg2";
406 ### It feels like this should be in YAZ, exported via ZOOM-Perl.
407 my %_bib1_access_point = (
408 1 => "Personal name",
409 2 => "Corporate name",
410 3 => "Conference name",
413 6 => "Title uniform",
416 9 => "LC card number",
417 10 => "BNB card no.",
419 12 => "Local number",
420 13 => "Dewey classification",
421 14 => "UDC classification",
422 15 => "Bliss classification",
423 16 => "LC call number",
424 17 => "NLM call number",
425 18 => "NAL call number",
426 19 => "MOS call number",
427 20 => "Local classification",
428 21 => "Subject heading",
429 22 => "Subject Rameau",
430 23 => "BDI index subject",
431 24 => "INSPEC subject",
432 25 => "MESH subject",
434 27 => "LC subject heading",
435 28 => "RVM subject heading",
436 29 => "Local subject index",
438 31 => "Date of publication",
439 32 => "Date of acquisition",
441 34 => "Title collective",
442 35 => "Title parallel",
444 37 => "Title added title page",
445 38 => "Title caption",
446 39 => "Title running",
448 41 => "Title other variant",
449 42 => "Title former",
450 43 => "Title abbreviated",
451 44 => "Title expanded",
452 45 => "Subject precis",
453 46 => "Subject rswk",
454 47 => "Subject subdivision",
455 48 => "No. nat'l biblio.",
456 49 => "No. legal deposit",
457 50 => "No. govt pub.",
458 51 => "No. music publisher",
460 53 => "Number local call",
461 54 => "Code--language",
462 55 => "Code--geographic area",
463 56 => "Code--institution",
464 57 => "Name and title *",
465 58 => "Name geographic",
466 59 => "Place publication",
468 61 => "Microform generation",
471 1000 => "Author-title",
472 1001 => "Record type",
475 1004 => "Author-name personal",
476 1005 => "Author-name corporate",
477 1006 => "Author-name conference",
478 1007 => "Identifier--standard",
479 1008 => "Subject--LC children's",
480 1009 => "Subject name -- personal",
481 1010 => "Body of text",
482 1011 => "Date/time added to db",
483 1012 => "Date/time last modified",
484 1013 => "Authority/format id",
485 1014 => "Concept-text",
486 1015 => "Concept-reference",
488 1017 => "Server-choice",
490 1019 => "Record-source",
493 1022 => "Geographic-class",
494 1023 => "Indexed-by",
497 1026 => "Related-periodical",
498 1027 => "Report-number",
499 1028 => "Stock-number",
500 1030 => "Thematic-number",
501 1031 => "Material-type",
504 1034 => "Content-type",
506 1036 => "Author-Title-Subject",
507 1032 => "Doc-id (semantic definition change)",
509 1038 => "Abstract-language",
510 1039 => "Application-kind",
511 1040 => "Classification",
512 1041 => "Classification-basic",
513 1042 => "Classification-local-record",
515 1044 => "Possessing-institution",
516 1045 => "Record-linking",
517 1046 => "Record-status",
519 1048 => "Control-number-GKD",
520 1049 => "Control-number-linking",
521 1050 => "Control-number-PND",
522 1051 => "Control-number-SWD",
523 1052 => "Control-number-ZDB",
524 1053 => "Country-publication (country of Publication)",
525 1054 => "Date-conference (meeting date)",
526 1055 => "Date-record-status",
527 1056 => "Dissertation-information",
528 1057 => "Meeting-organizer",
529 1058 => "Note-availability",
530 1059 => "Number-CAS-registry (CAS registry number)",
531 1060 => "Number-document (document number)",
532 1061 => "Number-local-accounting",
533 1062 => "Number-local-acquisition",
534 1063 => "Number-local-call-copy-specific",
535 1064 => "Number-of-reference (reference count)",
536 1065 => "Number-norm",
537 1066 => "Number-volume",
538 1067 => "Place-conference (meeting location)",
539 1068 => "Reference (references and footnotes)",
540 1069 => "Referenced-journal (reference work)",
541 1070 => "Section-code",
542 1071 => "Section-heading",
543 1072 => "Subject-GOO",
544 1073 => "Subject-name-conference",
545 1074 => "Subject-name-corporate",
546 1075 => "Subject-genre/form",
547 1076 => "Subject-name-geographical",
548 1077 => "Subject--chronological",
549 1078 => "Subject--title",
550 1079 => "Subject--topical",
551 1080 => "Subject-uncontrolled",
552 1081 => "Terminology-chemical (chemical name)",
553 1082 => "Title-translated",
554 1083 => "Year-of-beginning",
555 1084 => "Year-of-ending",
556 1085 => "Subject-AGROVOC",
557 1086 => "Subject-COMPASS",
558 1087 => "Subject-EPT",
559 1088 => "Subject-NAL",
560 1089 => "Classification-BCM",
561 1090 => "Classification-DB",
562 1091 => "Identifier-ISRC",
563 1092 => "Identifier-ISMN",
564 1093 => "Identifier-ISRN",
565 1094 => "Identifier-DOI",
566 1095 => "Code-language-original",
567 1096 => "Title-later",
569 1098 => "DC-Creator",
570 1099 => "DC-Subject",
571 1100 => "DC-Description",
572 1101 => "DC-Publisher",
574 1103 => "DC-ResourceType",
575 1104 => "DC-ResourceIdentifier",
576 1105 => "DC-Language",
577 1106 => "DC-OtherContributor",
580 1109 => "DC-Relation",
581 1110 => "DC-Coverage",
582 1111 => "DC-RightsManagement",
583 1112 => "Controlled Subject Index",
584 1113 => "Subject Thesaurus",
585 1114 => "Index Terms -- Controlled",
586 1115 => "Controlled Term",
587 1116 => "Spatial Domain",
588 1117 => "Bounding Coordinates",
589 1118 => "West Bounding Coordinate",
590 1119 => "East Bounding Coordinate",
591 1120 => "North Bounding Coordinate",
592 1121 => "South Bounding Coordinate",
594 1123 => "Place Keyword Thesaurus",
595 1124 => "Place Keyword",
596 1125 => "Time Period",
597 1126 => "Time Period Textual",
598 1127 => "Time Period Structured",
599 1128 => "Beginning Date",
600 1129 => "Ending Date",
601 1130 => "Availability",
602 1131 => "Distributor",
603 1132 => "Distributor Name",
604 1133 => "Distributor Organization",
605 1134 => "Distributor Street Address",
606 1135 => "Distributor City",
607 1136 => "Distributor State or Province",
608 1137 => "Distributor Zip or Postal Code",
609 1138 => "Distributor Country",
610 1139 => "Distributor Network Address",
611 1140 => "Distributor Hours of Service",
612 1141 => "Distributor Telephone",
613 1142 => "Distributor Fax",
614 1143 => "Resource Description",
615 1144 => "Order Process",
616 1145 => "Order Information",
618 1147 => "Cost Information",
619 1148 => "Technical Prerequisites",
620 1149 => "Available Time Period",
621 1150 => "Available Time Textual",
622 1151 => "Available Time Structured",
623 1152 => "Available Linkage",
624 1153 => "Linkage Type",
626 1155 => "Sources of Data",
627 1156 => "Methodology",
628 1157 => "Access Constraints",
629 1158 => "General Access Constraints",
630 1159 => "Originator Dissemination Control",
631 1160 => "Security Classification Control",
632 1161 => "Use Constraints",
633 1162 => "Point of Contact",
634 1163 => "Contact Name",
635 1164 => "Contact Organization",
636 1165 => "Contact Street Address",
637 1166 => "Contact City",
638 1167 => "Contact State or Province",
639 1168 => "Contact Zip or Postal Code",
640 1169 => "Contact Country",
641 1170 => "Contact Network Address",
642 1171 => "Contact Hours of Service",
643 1172 => "Contact Telephone",
644 1173 => "Contact Fax",
645 1174 => "Supplemental Information",
647 1176 => "Agency Program",
648 1177 => "Cross Reference",
649 1178 => "Cross Reference Title",
650 1179 => "Cross Reference Relationship",
651 1180 => "Cross Reference Linkage",
652 1181 => "Schedule Number",
653 1182 => "Original Control Identifier",
654 1183 => "Language of Record",
655 1184 => "Record Review Date",
657 1186 => "Performer-Individual",
658 1187 => "Performer-Group",
659 1188 => "Instrumentation",
660 1189 => "Instrumentation-Original",
661 1190 => "Instrumentation-Current",
662 1191 => "Arrangement",
663 1192 => "Arrangement-Original",
664 1193 => "Arrangement-Current",
665 1194 => "Musical Key-Original",
666 1195 => "Musical Key-Current",
667 1196 => "Date-Composition",
668 1197 => "Date-Recording",
669 1198 => "Place-Recording",
670 1199 => "Country-Recording",
671 1200 => "Number-ISWC",
672 1201 => "Number-Matrix",
673 1202 => "Number-Plate",
674 1203 => "Classification-McColvin",
676 1205 => "Number-Copies",
677 1206 => "Musical Theme",
678 1207 => "Instruments - total number",
679 1208 => "Instruments - distinct number",
680 1209 => "Identifier - URN",
681 1210 => "Sears Subject Heading",
682 1211 => "OCLC Number",
683 1212 => "Composition",
684 1213 => "Intellectual level",
688 1217 => "Nationality",
690 1219 => "Compression",
692 1221 => "Subject - occupation",
693 1222 => "Subject - function",
697 sub bib1_access_point {
700 return $_bib1_access_point{$ap} ||
701 "unknown BIB-1 attribute '$ap'";
706 my($rs, $which, $elementSetName) = @_;
708 # There is a slight race condition here on the element-set name,
709 # but it shouldn't be a problem as this is (currently) only called
710 # from parts of the program that run single-threaded.
711 my $old = $rs->option(elementSetName => $elementSetName);
712 my $rec = $rs->record($which);
713 $rs->option(elementSetName => $old);
715 return $rec->render();