63677617eac44b9cdb0a0d52dfc3ee4e2c59a173
[irspy-moved-to-github.git] / lib / ZOOM / IRSpy / Utils.pm
1 # $Id: Utils.pm,v 1.19 2006-12-05 17:19:35 mike Exp $
2
3 package ZOOM::IRSpy::Utils;
4
5 use 5.008;
6 use strict;
7 use warnings;
8
9 use Exporter 'import';
10 our @EXPORT_OK = qw(isodate
11                     xml_encode 
12                     cql_quote
13                     cql_target
14                     irspy_xpath_context
15                     modify_xml_document);
16
17 use XML::LibXML;
18 use XML::LibXML::XPathContext;
19
20 our $IRSPY_NS = 'http://indexdata.com/irspy/1.0';
21
22
23 # Utility functions follow, exported for use of web UI
24 sub isodate {
25     my($time) = @_;
26
27     my($sec, $min, $hour, $mday, $mon, $year) = localtime($time);
28     return sprintf("%04d-%02d-%02dT%02d:%02d:%02d",
29                    $year+1900, $mon+1, $mday, $hour, $min, $sec);
30 }
31
32
33 # I can't -- just can't, can't, can't -- believe that this function
34 # isn't provided by one of the core XML modules.  But the evidence all
35 # says that it's not: among other things, XML::Generator and
36 # Template::Plugin both roll their own.  So I will do likewise.  D'oh!
37 #
38 sub xml_encode {
39     my($text, $fallback, $opts) = @_;
40     if (!defined $opts && ref $fallback) {
41         # The second and third arguments are both optional
42         $opts = $fallback;
43         $fallback = undef;
44     }
45     $opts = {} if !defined $opts;
46
47     $text = $fallback if !defined $text;
48     use Carp;
49     confess "xml_encode(): text and fallback both undefined"
50         if !defined $text;
51
52     $text =~ s/&/&/g;
53     $text =~ s/</&lt;/g;
54     $text =~ s/>/&gt;/g;
55     # Internet Explorer can't display &apos; (!) so don't create it
56     #$text =~ s/['']/&apos;/g;
57     $text =~ s/[""]/&quot;/g;
58     $text =~ s/ /&nbsp;/g if $opts->{nbsp};
59
60     return $text;
61 }
62
63
64 # Quotes a term for use in a CQL query
65 sub cql_quote {
66     my($term) = @_;
67
68     $term =~ s/([""\\])/\\$1/g;
69     $term = qq["$term"] if $term =~ /\s/;
70     return $term;
71 }
72
73
74 # Makes a CQL query that finds a specified target
75 sub cql_target {
76     my($host, $port, $db) = @_;
77
78     return ("host=" . cql_quote($host) . " and " .
79             "port=" . cql_quote($port) . " and " .
80             "path=" . cql_quote($db));
81 }
82
83
84 # PRIVATE to irspy_namespace() and irspy_xpath_context()
85 my %_namespaces = (
86                    e => 'http://explain.z3950.org/dtd/2.0/',
87                    i => $IRSPY_NS,
88                    );
89
90
91 sub irspy_namespace {
92     my($prefix) = @_;
93
94     use Carp;
95     confess "irspy_namespace(undef)" if !defined $prefix;
96     my $uri = $_namespaces{$prefix};
97     die "irspy_namespace(): no URI for namespace prefix '$prefix'"
98         if !defined $uri;
99
100     return $uri;
101 }
102
103
104 sub irspy_xpath_context {
105     my($record) = @_;
106
107     my $xml = ref $record ? $record->render() : $record;
108     my $parser = new XML::LibXML();
109     my $doc = $parser->parse_string($xml);
110     my $root = $doc->getDocumentElement();
111     my $xc = XML::LibXML::XPathContext->new($root);
112     foreach my $prefix (keys %_namespaces) {
113         $xc->registerNs($prefix, $_namespaces{$prefix});
114     }
115     return $xc;
116 }
117
118
119 sub modify_xml_document {
120     my($xc, $fieldsByKey, $data) = @_;
121
122     my @changes = ();
123     foreach my $key (keys %$data) {
124         my $value = $data->{$key};
125         my $ref = $fieldsByKey->{$key} or die "no field '$key'";
126         my($name, $nlines, $caption, $xpath, @addAfter) = @$ref;
127         #print "Considering $key='$value' ($xpath)<br/>\n";
128         my @nodes = $xc->findnodes($xpath);
129         if (@nodes) {
130             warn scalar(@nodes), " nodes match '$xpath'" if @nodes > 1;
131             my $node = $nodes[0];
132
133             if ($node->isa("XML::LibXML::Attr")) {
134                 if ($value ne $node->getValue()) {
135                     $node->setValue($value);
136                     push @changes, $ref;
137                     #print "Attr $key: '", $node->getValue(), "' -> '$value' ($xpath)<br/>\n";
138                 }
139             } elsif ($node->isa("XML::LibXML::Element")) {
140                 # The contents could be any mixture of text and
141                 # comments and maybe even other crud such as processing
142                 # instructions.  The simplest thing is just to throw it all
143                 # away and start again, making a single Text node the
144                 # canonical representation.  But before we do that,
145                 # we'll check whether the element is already
146                 # canonical, to determine whether our change is a
147                 # no-op.
148                 my $old = "???";
149                 my @children = $node->childNodes();
150                 if (@children == 1) {
151                     my $child = $node->firstChild();
152                     if (ref $child && ref $child eq "XML::LibXML::Text") {
153                         $old = $child->getData();
154                         next if $value eq $old;
155                     }
156                 }
157
158                 $node->removeChildNodes();
159                 my $child = new XML::LibXML::Text($value);
160                 $node->appendChild($child);
161                 push @changes, $ref;
162                 #print "Elem $key: '$old' -> '$value' ($xpath)<br/>\n";
163             } else {
164                 warn "unexpected node type $node";
165             }
166
167         } else {
168             next if !$value; # No need to create a new empty node
169             my($ppath, $selector) = $xpath =~ /(.*)\/(.*)/;
170             dom_add_node($xc, $ppath, $selector, $value, @addAfter);
171             #print "New $key ($xpath) = '$value'<br/>\n";
172             push @changes, $ref;
173         }
174     }
175
176     return @changes;
177 }
178
179
180 sub dom_add_node {
181     my($xc, $ppath, $selector, $value, @addAfter) = @_;
182
183     #print "Adding $selector='$value' at '$ppath' after (", join(", ", map { "'$_'" } @addAfter), ")<br/>\n";
184     my $node = find_or_make_node($xc, $ppath, 0);
185     die "couldn't find or make node '$node'" if !defined $node;
186
187     my $is_attr = ($selector =~ s/^@//);
188     my(undef, $prefix, $simpleSel) = $selector =~ /((.*?):)?(.*)/;
189     #warn "selector='$selector', prefix='$prefix', simpleSel='$simpleSel'";
190     if ($is_attr) {
191         if (defined $prefix) {
192             ### This seems to no-op (thank, DOM!) but I have have no
193             # idea, and it's not needed for IRSpy, so I am not going
194             # to debug it now.
195             $node->setAttributeNS(irspy_namespace($prefix),
196                                   $simpleSel, $value);
197         } else {
198             $node->setAttribute($simpleSel, $value);
199         }
200         return;
201     }
202
203     my $new = new XML::LibXML::Element($simpleSel);
204     $new->setNamespace(irspy_namespace($prefix), $prefix)
205         if defined $prefix;
206
207     $new->appendText($value);
208     foreach my $predecessor (reverse @addAfter) {
209         my($child) = $xc->findnodes($predecessor, $node);
210         if (defined $child) {
211             $node->insertAfter($new, $child);
212             #warn "Added after '$predecessor'";
213             return;
214         }
215     }
216
217     # Didn't find any of the nodes that are supposed to precede the
218     # new one, so we need to insert the new node as the first of the
219     # parent's children.  However *sigh* there is no prependChild()
220     # analogous to appendChild(), so we have to go the long way round.
221     my @children = $node->childNodes();
222     if (@children) {
223         $node->insertBefore($new, $children[0]);
224         #warn "Added new first child";
225     } else {
226         $node->appendChild($new);
227         #warn "Added new only child";
228     }
229
230     if (0) {
231         my $text = xml_encode(inheritance_tree($xc));
232         $text =~ s/\n/<br\/>$&/sg;
233         print "<pre>$text</pre>\n";
234     }
235 }
236
237
238 sub find_or_make_node {
239     my($xc, $path, $recursion_level) = @_;
240
241     die "deep recursion in find_or_make_node($path)"
242         if $recursion_level == 10;
243     $path = "." if $path eq "";
244
245     my @nodes = $xc->findnodes($path);
246     if (@nodes == 0) {
247         # Oh dear, the parent node doesn't exist.  We could make it,
248         my(undef, $ppath, $element) = $path =~ /((.*)\/)?(.*)/;
249         $ppath = "" if !defined $ppath;
250         #warn "path='$path', ppath='$ppath', element='$element'";
251         #warn "no node '$path': making it";
252         my $parent = find_or_make_node($xc, $ppath, $recursion_level-1);
253
254         my(undef, $prefix, $nsElem) = $element =~ /((.*?):)?(.*)/;
255         #warn "element='$element', prefix='$prefix', nsElem='$nsElem'";
256         my $new = new XML::LibXML::Element($nsElem);
257         if (defined $prefix) {
258             #warn "setNamespace($prefix)";
259             $new->setNamespace(irspy_namespace($prefix), $prefix);
260         }
261
262         $parent->appendChild($new);
263         return $new;
264     }
265     warn scalar(@nodes), " nodes match parent '$path'" if @nodes > 1;
266     return $nodes[0];
267 }
268
269
270 sub inheritance_tree {
271     my($type, $level) = @_;
272     $level = 0 if !defined $level;
273     return "Woah!  Too deep, man!\n" if $level > 20;
274
275     $type = ref $type if ref $type;
276     my $text = "";
277     $text = "--> " if $level == 0;
278     $text .= ("\t" x $level) . "$type\n";
279     my @ISA = eval "\@${type}::ISA";
280     foreach my $superclass (@ISA) {
281         $text .= inheritance_tree($superclass, $level+1);
282     }
283
284     return $text;
285 }
286
287
288 #print "Loaded ZOOM::IRSpy::Utils.pm";
289
290
291 1;