rename function trimFields to trimField
[irspy-moved-to-github.git] / lib / ZOOM / IRSpy / Utils.pm
1
2 package ZOOM::IRSpy::Utils;
3
4 use 5.008;
5 use strict;
6 use warnings;
7
8 use Scalar::Util;
9
10 use Exporter 'import';
11 our @EXPORT_OK = qw(utf8param
12                     isodate
13                     xml_encode 
14                     cql_quote
15                     cql_target
16                     irspy_xpath_context
17                     irspy_make_identifier
18                     irspy_record2identifier
19                     irspy_identifier2target
20                     modify_xml_document
21                     bib1_access_point
22                     render_record
23                     calc_reliability_string
24                     calc_reliability_stats);
25
26 use XML::LibXML;
27 use XML::LibXML::XPathContext;
28 use Encode;
29 use Encode qw(is_utf8);
30
31
32 our $IRSPY_NS = 'http://indexdata.com/irspy/1.0';
33
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.
41 #
42 my %_apache2request;
43 my %_paramsbyrequest;           # Used for Apache2 only
44 sub utf8param {
45     my($r, $key, $value) = @_;
46
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};
52         } else {
53             require Apache2::Request;
54             #warn "making new Apache2::RequestReq for '$r'";
55             $r = $_apache2request{$r} = new Apache2::Request($r);
56         }
57     }
58
59     if (!defined $key) {
60         return map { decode_utf8($_) } $r->param();
61     }
62
63     my $raw = undef;
64     $raw = $_paramsbyrequest{$r}->{$key} if $r->isa('Apache2::Request');
65     $raw = $r->param($key) if !defined $raw;
66
67     if (defined $value) {
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);
74         } else {
75             $r->param($key, encode_utf8($value));
76         }
77     }
78
79     return undef if !defined $raw;
80     my $cooked = decode_utf8($raw);
81     warn "converted '$raw' to '", $cooked, "'\n" if $cooked ne $raw;
82     return $cooked;
83 }
84
85
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;
90
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;
95     return $cooked;
96 }
97
98
99 sub isodate {
100     my($time) = @_;
101
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);
105 }
106
107 # strips whitespaces and start and ends of a field
108 sub trimField {
109     my $field  = shift;
110
111     $field =~ s/^\s+//;
112     $field =~ s/\s+$//;
113
114     return $field;
115 }
116
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!
121 #
122 sub xml_encode {
123     my($text, $fallback, $opts) = @_;
124     if (!defined $opts && ref $fallback) {
125         # The second and third arguments are both optional
126         $opts = $fallback;
127         $fallback = undef;
128     }
129     $opts = {} if !defined $opts;
130
131     $text = $fallback if !defined $text;
132     use Carp;
133     confess "xml_encode(): text and fallback both undefined"
134         if !defined $text;
135
136     $text =~ s/&/&/g;
137     $text =~ s/</&lt;/g;
138     $text =~ s/>/&gt;/g;
139     # Internet Explorer can't display &apos; (!) so don't create it
140     #$text =~ s/['']/&apos;/g;
141     $text =~ s/[""]/&quot;/g;
142     $text =~ s/ /&nbsp;/g if $opts->{nbsp};
143
144     return $text;
145 }
146
147
148 # Quotes a term for use in a CQL query
149 sub cql_quote {
150     my($term) = @_;
151
152     $term =~ s/([""\\*?])/\\$1/g;
153     $term = qq["$term"] if $term =~ /[\s""\/]/;
154     return $term;
155 }
156
157
158 # Makes a CQL query that finds a specified target.  Arguments may be
159 # either an ID alone, or a (host, port, db) triple.
160 sub cql_target {
161     my($protocol, $host, $port, $db) = @_;
162
163     my $id;
164     if (defined $host) {
165         $id = irspy_make_identifier($protocol, $host, $port, $db);
166     } else {
167         $id = $protocol;
168     }
169
170     return "rec.id=" . cql_quote($id);
171 }
172
173
174 # PRIVATE to irspy_namespace() and irspy_xpath_context()
175 my %_namespaces = (
176                    e => 'http://explain.z3950.org/dtd/2.0/',
177                    i => $IRSPY_NS,
178                    );
179
180
181 sub irspy_namespace {
182     my($prefix) = @_;
183
184     use Carp;
185     confess "irspy_namespace(undef)" if !defined $prefix;
186     my $uri = $_namespaces{$prefix};
187     die "irspy_namespace(): no URI for namespace prefix '$prefix'"
188         if !defined $uri;
189
190     return $uri;
191 }
192
193
194 sub irspy_xpath_context {
195     my($record) = @_;
196
197     if (ref $record && $record->isa("ZOOM::Record")) {
198         $record = $record->render();
199     }
200
201     my $root;
202     if (ref $record) {
203         $root = $record;
204     } else {
205         my $parser = new XML::LibXML();
206         my $doc = $parser->parse_string($record);
207         $root = $doc->getDocumentElement();
208     }
209
210     my $xc = XML::LibXML::XPathContext->new($root);
211     foreach my $prefix (keys %_namespaces) {
212         $xc->registerNs($prefix, $_namespaces{$prefix});
213     }
214     return $xc;
215 }
216
217
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
220 # factored out.
221 #
222 # This is the converse of _parse_target_string() in IRSpy.pm, which
223 # should be renamed and moved into this package.
224 #
225 sub irspy_make_identifier {
226     my($protocol, $host, $port, $dbname) = @_;
227
228     die "irspy_make_identifier(" . join(", ", map { "'$_'" } @_).
229         "): wrong number of arguments" if @_ != 4;
230
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;
235
236     return "$protocol:$host:$port/$dbname";
237 }
238
239
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.
244 #
245 sub irspy_record2identifier {
246     my($xc) = @_;
247
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)");
253 }
254
255
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.
261 #
262 sub irspy_identifier2target {
263     my $res = _irspy_identifier2target(@_);
264     #carp "converted ID '@_' to target '$res'";
265     return $res;
266 }
267
268 sub _irspy_identifier2target {
269     my($id) = @_;
270
271     confess "_irspy_identifier2target(): id is undefined"
272         if !defined $id;
273
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";
281     }
282
283     warn "_irspy_identifier2target($id): unrecognised protocol '$protocol'";
284     return $target;
285 }
286
287
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.
292
293 sub modify_xml_document {
294     my($xc, $fieldsByKey, $data) = @_;
295
296     my @changes = ();
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);
303         if (@nodes) {
304             warn scalar(@nodes), " nodes match '$xpath'" if @nodes > 1;
305             my $node = $nodes[0];
306
307             if ($node->isa("XML::LibXML::Attr")) {
308                 if ($value ne $node->getValue()) {
309                     $node->setValue($value);
310                     push @changes, $ref;
311                     #print "Attr $key: '", $node->getValue(), "' -> '$value' ($xpath)<br/>\n";
312                 }
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
321                 # no-op.
322                 my $old = "";
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";
329                     }
330                 }
331                 next if $value eq $old;
332
333                 $node->removeChildNodes();
334                 my $child = new XML::LibXML::Text($value);
335                 $node->appendChild($child);
336                 push @changes, $ref;
337                 #print STDERR "Elem $key ($xpath): ", _renderchars($old), " -> '", _renderchars($value), "\n";
338             } else {
339                 warn "unexpected node type $node";
340             }
341
342         } else {
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";
347             push @changes, $ref;
348         }
349     }
350
351     return @changes;
352 }
353
354
355 sub _renderchars {
356     my($text) = @_;
357
358     return "'" . $text . "'", " (", join(" ", map {ord($_)} split //, $text), "), is_utf8=" , is_utf8($text);
359 }
360
361
362 sub dom_add_node {
363     my($xc, $ppath, $selector, $value, @addAfter) = @_;
364
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;
368
369     my $is_attr = ($selector =~ s/^@//);
370     my(undef, $prefix, $simpleSel) = $selector =~ /((.*?):)?(.*)/;
371     #warn "selector='$selector', prefix='$prefix', simpleSel='$simpleSel'";
372     if ($is_attr) {
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
376             # to debug it now.
377             $node->setAttributeNS(irspy_namespace($prefix),
378                                   $simpleSel, $value);
379         } else {
380             $node->setAttribute($simpleSel, $value);
381         }
382         return;
383     }
384
385     my $new = new XML::LibXML::Element($simpleSel);
386     $new->setNamespace(irspy_namespace($prefix), $prefix)
387         if defined $prefix;
388
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'";
395             return;
396         }
397     }
398
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();
404     if (@children) {
405         $node->insertBefore($new, $children[0]);
406         #warn "Added new first child";
407     } else {
408         $node->appendChild($new);
409         #warn "Added new only child";
410     }
411
412     if (0) {
413         my $text = xml_encode(inheritance_tree($xc));
414         $text =~ s/\n/<br\/>$&/sg;
415         print "<pre>$text</pre>\n";
416     }
417 }
418
419
420 sub find_or_make_node {
421     my($xc, $path, $recursion_level) = @_;
422
423     die "deep recursion in find_or_make_node($path)"
424         if $recursion_level == 10;
425     $path = "." if $path eq "";
426
427     my @nodes = $xc->findnodes($path);
428     if (@nodes == 0) {
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);
435
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);
442         }
443
444         $parent->appendChild($new);
445         return $new;
446     }
447     warn scalar(@nodes), " nodes match parent '$path'" if @nodes > 1;
448     return $nodes[0];
449 }
450
451
452 sub inheritance_tree {
453     my($type, $level) = @_;
454     $level = 0 if !defined $level;
455     return "Woah!  Too deep, man!\n" if $level > 20;
456
457     $type = ref $type if ref $type;
458     my $text = "";
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);
464     }
465
466     return $text;
467 }
468
469
470 # This function is made available in xslt using the register_function call
471 sub xslt_strcmp {
472     my ($arg1, $arg2) = @_;
473     return "$arg1" cmp "$arg2";
474 }
475
476
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",
482         4 =>    "Title",
483         5 =>    "Title series",
484         6 =>    "Title uniform",
485         7 =>    "ISBN",
486         8 =>    "ISSN",
487         9 =>    "LC card number",
488         10 =>   "BNB card no.",
489         11 =>   "BGF number",
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",
504         26 =>   "PA subject",
505         27 =>   "LC subject heading",
506         28 =>   "RVM subject heading",
507         29 =>   "Local subject index",
508         30 =>   "Date",
509         31 =>   "Date of publication",
510         32 =>   "Date of acquisition",
511         33 =>   "Title key",
512         34 =>   "Title collective",
513         35 =>   "Title parallel",
514         36 =>   "Title cover",
515         37 =>   "Title added title page",
516         38 =>   "Title caption",
517         39 =>   "Title running",
518         40 =>   "Title spine",
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",
530         52 =>   "Number db",
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",
538         60 =>   "CODEN",
539         61 =>   "Microform generation",
540         62 =>   "Abstract",
541         63 =>   "Note",
542         1000 => "Author-title",
543         1001 => "Record type",
544         1002 => "Name",
545         1003 => "Author",
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",
558         1016 => "Any",
559         1017 => "Server-choice",
560         1018 => "Publisher",
561         1019 => "Record-source",
562         1020 => "Editor",
563         1021 => "Bib-level",
564         1022 => "Geographic-class",
565         1023 => "Indexed-by",
566         1024 => "Map-scale",
567         1025 => "Music-key",
568         1026 => "Related-periodical",
569         1027 => "Report-number",
570         1028 => "Stock-number",
571         1030 => "Thematic-number",
572         1031 => "Material-type",
573         1032 => "Doc-id",
574         1033 => "Host-item",
575         1034 => "Content-type",
576         1035 => "Anywhere",
577         1036 => "Author-Title-Subject",
578         1032 => "Doc-id (semantic definition change)",
579         1037 => "SICI",
580         1038 => "Abstract-language",
581         1039 => "Application-kind",
582         1040 => "Classification",
583         1041 => "Classification-basic",
584         1042 => "Classification-local-record",
585         1043 => "Enzyme",
586         1044 => "Possessing-institution",
587         1045 => "Record-linking",
588         1046 => "Record-status",
589         1047 => "Treatment",
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",
639         1097 => "DC-Title",
640         1098 => "DC-Creator",
641         1099 => "DC-Subject",
642         1100 => "DC-Description",
643         1101 => "DC-Publisher",
644         1102 => "DC-Date",
645         1103 => "DC-ResourceType",
646         1104 => "DC-ResourceIdentifier",
647         1105 => "DC-Language",
648         1106 => "DC-OtherContributor",
649         1107 => "DC-Format",
650         1108 => "DC-Source",
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",
664         1122 => "Place",
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",
688         1146 => "Cost",
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",
696         1154 => "Linkage",
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",
717         1175 => "Purpose",
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",
727         1185 => "Performer",
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",
746         1204 => "Duration",
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",
756         1214 => "EAN",
757         1215 => "NLC",
758         1216 => "CRCS",
759         1217 => "Nationality",
760         1218 => "Equinox",
761         1219 => "Compression",
762         1220 => "Format",
763         1221 => "Subject - occupation",
764         1222 => "Subject - function",
765         1223 => "Edition",
766 );
767
768 sub bib1_access_point {
769     my($ap) = @_;
770
771     return $_bib1_access_point{$ap} ||
772         "unknown BIB-1 attribute '$ap'";
773 }
774
775
776 sub render_record {
777     my($rs, $which, $elementSetName) = @_;
778
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);
785
786     return $rec->render();
787 }
788
789
790 sub calc_reliability_string {
791     my($xc) = @_;
792
793     my($nok, $nall, $percent) = calc_reliability_stats($xc);
794     return "[untested]" if $nall == 0;
795     return "$nok/$nall = " . $percent . "%";
796 }
797
798
799 sub calc_reliability_stats {
800     my($xc) = @_;
801
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"]');
806     my $nok = @okpings;
807     my $percent = int(100*$nok/$nall);
808     return ($nok, $nall, $percent);
809 }
810
811
812 1;