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