File Coverage

blib/lib/XML/XSH/Functions.pm
Criterion Covered Total %
statement 10 12 83.3
branch n/a
condition n/a
subroutine 4 4 100.0
pod n/a
total 14 16 87.5


line stmt bran cond sub pod time code
1             # -*- cperl -*-
2             # $Id: Functions.pm,v 1.73 2003/09/10 15:54:09 pajas Exp $
3              
4             package XML::XSH::Functions;
5              
6             eval "no encoding";
7             undef $@;
8 4     4   20 use strict;
  4         7  
  4         134  
9 4     4   19 no warnings;
  4         7  
  4         148  
10              
11 4     4   4964 use XML::XSH::Help;
  4         8  
  4         141  
12 4     4   7364 use XML::XSH::Iterators;
  0            
  0            
13             use IO::File;
14              
15             use Exporter;
16             use vars qw/@ISA @EXPORT_OK %EXPORT_TAGS $VERSION $REVISION $OUT $LOCAL_ID $LOCAL_NODE
17             $_xml_module $_sigint
18             $_xsh $_xpc $_parser %_nodelist @stored_variables
19             $_newdoc
20             $TRAP_SIGINT $TRAP_SIGPIPE $_die_on_err $_on_exit
21             %_doc %_files %_defs %_includes %_chr %_ns
22             $ENCODING $QUERY_ENCODING
23             $INDENT $BACKUPS $SWITCH_TO_NEW_DOCUMENTS $EMPTY_TAGS $SKIP_DTD
24             $QUIET $DEBUG $TEST_MODE
25             $VALIDATION $RECOVERING $PARSER_EXPANDS_ENTITIES $KEEP_BLANKS
26             $PEDANTIC_PARSER $LOAD_EXT_DTD $PARSER_COMPLETES_ATTRIBUTES
27             $PARSER_EXPANDS_XINCLUDE
28             $XPATH_AXIS_COMPLETION
29             $XPATH_COMPLETION $DEFAULT_FORMAT
30             /;
31              
32             BEGIN {
33             $VERSION='1.8.2';
34             $REVISION='$Revision: 1.73 $';
35             @ISA=qw(Exporter);
36             my @PARAM_VARS=qw/$ENCODING
37             $QUERY_ENCODING
38             $INDENT
39             $EMPTY_TAGS
40             $SKIP_DTD
41             $BACKUPS
42             $SWITCH_TO_NEW_DOCUMENTS
43             $QUIET
44             $DEBUG
45             $TEST_MODE
46             $VALIDATION
47             $RECOVERING
48             $PARSER_EXPANDS_ENTITIES
49             $XPATH_AXIS_COMPLETION
50             $XPATH_COMPLETION
51             $KEEP_BLANKS
52             $PEDANTIC_PARSER
53             $LOAD_EXT_DTD
54             $PARSER_COMPLETES_ATTRIBUTES
55             $PARSER_EXPANDS_XINCLUDE
56             $DEFAULT_FORMAT
57             /;
58             *EMPTY_TAGS=*XML::LibXML::setTagCompression;
59             *SKIP_DTD=*XML::LibXML::skipDTD;
60             @EXPORT_OK=(qw(&xsh_init &xsh &xsh_get_output
61             &xsh_set_output &xsh_set_parser
62             &set_quiet &set_debug &set_compile_only_mode
63             &create_doc &open_doc &set_doc
64             &xsh_pwd &xsh_local_id &get_doc &out
65             &toUTF8 &fromUTF8 &set_local_doc
66             &xsh_xml_parser &xsh_parse_string &xsh_docs
67             ),@PARAM_VARS);
68             %EXPORT_TAGS = (
69             default => [@EXPORT_OK],
70             param_vars => [@PARAM_VARS]
71             );
72              
73             $TRAP_SIGINT=0;
74             $_xml_module='XML::XSH::LibXMLCompat';
75             $INDENT=1;
76             $EMPTY_TAGS=1; # no effect (reseted by XML::LibXML)
77             $SKIP_DTD=0; # no effect (reseted by XML::LibXML)
78             $BACKUPS=1;
79             $SWITCH_TO_NEW_DOCUMENTS=1;
80             $ENCODING='utf-8';
81             $QUERY_ENCODING='utf-8';
82             $QUIET=0;
83             $DEBUG=0;
84             $TEST_MODE=0;
85             $VALIDATION=0;
86             $RECOVERING=0;
87             $PARSER_EXPANDS_ENTITIES=1;
88             $KEEP_BLANKS=1;
89             $PEDANTIC_PARSER=0;
90             $LOAD_EXT_DTD=0;
91             $PARSER_COMPLETES_ATTRIBUTES=1;
92             $PARSER_EXPANDS_XINCLUDE=0;
93             $XPATH_COMPLETION=1;
94             $XPATH_AXIS_COMPLETION='always'; # never / when-empty
95             $DEFAULT_FORMAT='xml';
96             $_newdoc=1;
97             $_die_on_err=1;
98             %_nodelist=();
99              
100             %_chr = ( n => "\n", t => "\t", r => "\r",
101             f => "\f", b => "\b", a => "\a",
102             e => "\e" );
103             autoflush STDOUT;
104             autoflush STDERR;
105             }
106              
107             sub min { $_[0] > $_[1] ? $_[1] : $_[0] }
108              
109             sub out {
110             if (ref($OUT) eq 'GLOB' or ref($OUT) eq 'Term::ReadLine::Gnu::Var') {
111             print $OUT @_;
112             } else {
113             $OUT->print(@_);
114             }
115             }
116              
117             sub __debug {
118             _err(@_);
119             }
120              
121             sub __bug {
122             _err("BUG: ",@_);
123             }
124              
125              
126             # initialize XSH and XML parsers
127             sub xsh_init {
128             my $module=shift;
129             shift unless ref($_[0]);
130             if (ref($_[0])) {
131             $OUT=$_[0];
132             } else {
133             $OUT=\*STDOUT;
134             }
135             $_xml_module=$module if $module;
136             eval "require $_xml_module;";
137             if ($@) {
138             _err(
139             "\n------------------------------------------------------------\n",
140             $@,
141             "\n------------------------------------------------------------.\n",
142             "I suspect you have not installed XML::LibXML properly.\n",
143             "Please install and try again. If you are 100% sure you have, send\n",
144             "a full bug report to \n");
145             exit 1;
146             }
147             my $mod=$_xml_module->module();
148             if ($] >= 5.008) {
149             require Encode;
150             *encodeToUTF8=*Encode::decode;
151             *decodeFromUTF8=*Encode::encode;
152             } else {
153             no strict 'refs';
154             *encodeToUTF8=*{"$mod"."::encodeToUTF8"};
155             *decodeFromUTF8=*{"$mod"."::decodeFromUTF8"};
156             }
157             $_parser = $_xml_module->new_parser();
158              
159             xpc_init();
160             xsh_rd_parser_init();
161             }
162              
163             sub xsh_rd_parser_init {
164             if (eval { require XML::XSH::Parser; }) {
165             $_xsh=XML::XSH::Parser->new();
166             } else {
167             print STDERR "Parsing raw grammar...\n";
168             require XML::XSH::Grammar;
169             $_xsh=XML::XSH::Grammar->new();
170             print STDERR "... done.\n";
171             unless ($QUIET) {
172             print STDERR << 'EOF';
173             NOTE: To avoid this, you should regenerate the XML::XSH::Parser.pm
174             module from XML::XSH::Grammar.pm module by changing to XML/XSH/
175             directory in your load-path and running the following command:
176              
177             perl -MGrammar -e XML::XSH::Grammar::compile
178              
179             EOF
180             }
181             }
182             return $_xsh;
183             }
184              
185             sub set_validation { $VALIDATION=$_[0]; 1; }
186             sub set_recovering { $RECOVERING=$_[0]; 1; }
187             sub set_expand_entities { $PARSER_EXPANDS_ENTITIES=$_[0]; 1; }
188             sub set_keep_blanks { $KEEP_BLANKS=$_[0]; 1; }
189             sub set_pedantic_parser { $PEDANTIC_PARSER=$_[0]; 1; }
190             sub set_load_ext_dtd { $LOAD_EXT_DTD=$_[0]; 1; }
191             sub set_complete_attributes { $PARSER_COMPLETES_ATTRIBUTES=$_[0]; 1; }
192             sub set_expand_xinclude { $PARSER_EXPANDS_XINCLUDE=$_[0]; 1; }
193             sub set_indent { $INDENT=$_[0]; 1; }
194             sub set_empty_tags { $EMPTY_TAGS=$_[0]; 1; }
195             sub set_skip_dtd { $SKIP_DTD=$_[0]; 1; }
196             sub set_backups { $BACKUPS=$_[0]; 1; }
197             sub set_cdonopen { $SWITCH_TO_NEW_DOCUMENTS=$_[0]; 1; }
198             sub set_xpath_completion { $XPATH_COMPLETION=$_[0]; 1; }
199             sub set_xpath_axis_completion { $XPATH_AXIS_COMPLETION=$_[0];
200             if ($XPATH_AXIS_COMPLETION!~/^always|when-empty|never$/) {
201             $XPATH_AXIS_COMPLETION='never';
202             }
203             1; }
204              
205             sub get_validation { $VALIDATION }
206             sub get_recovering { $RECOVERING }
207             sub get_expand_entities { $PARSER_EXPANDS_ENTITIES }
208             sub get_keep_blanks { $KEEP_BLANKS }
209             sub get_pedantic_parser { $PEDANTIC_PARSER }
210             sub get_load_ext_dtd { $LOAD_EXT_DTD }
211             sub get_complete_attributes { $PARSER_COMPLETES_ATTRIBUTES }
212             sub get_expand_xinclude { $PARSER_EXPANDS_XINCLUDE }
213             sub get_indent { $INDENT }
214             sub get_empty_tags { $EMPTY_TAGS }
215             sub get_skip_dtd { $SKIP_DTD }
216             sub get_backups { $BACKUPS }
217             sub get_cdonopen { $SWITCH_TO_NEW_DOCUMENTS }
218             sub get_xpath_completion { $XPATH_COMPLETION }
219             sub get_xpath_axis_completion { $XPATH_AXIS_COMPLETION }
220              
221              
222             # initialize global XPathContext
223             sub xpc_init {
224             unless (eval { require XML::LibXML::XPathContext;
225             $_xpc=XML::LibXML::XPathContext->new();
226             }) {
227             require XML::XSH::DummyXPathContext;
228             print STDERR ("Warning: XML::LibXML::XPathContext not found!\n".
229             "XSH will lack namespace and function registering functionality!\n\n");
230             $_xpc=XML::XSH::DummyXPathContext->new();
231             }
232             $_xpc->registerVarLookupFunc(\&xpath_var_lookup,undef);
233             $_xpc->registerNs('xsh',$XML::XSH::xshNS);
234             $_xpc->registerFunctionNS('doc',$XML::XSH::xshNS,
235             sub {
236             die "Wrong number of arguments for function doc(id)!" if (@_!=1);
237             my ($id)=literal_value($_[0]);
238             die "Wrong number of arguments for function doc(id)!" if (@_!=1);
239             die "Document does not exist!" unless (exists($_doc{$id}));
240             return $_doc{$id};
241             });
242             $_xpc->registerFunctionNS('matches',$XML::XSH::xshNS,
243             sub {
244             die "Wrong number of arguments for function matches(string,regexp)!" if (@_!=2);
245             my ($string,$regexp)=@_;
246             $regexp=literal_value($regexp);
247             use utf8;
248             my $ret=literal_value($string)=~m{$regexp} ?
249             XML::LibXML::Boolean->True : XML::LibXML::Boolean->False;
250             $ret;
251             });
252             $_xpc->registerFunctionNS('grep',$XML::XSH::xshNS,
253             sub {
254             die "Wrong number of arguments for function grep(list,regexp)!" if (@_!=2);
255             my ($nodelist,$regexp)=@_;
256             die "1st argument must be a node-list in grep(list,regexp)!"
257             unless (ref($nodelist) and $nodelist->isa('XML::LibXML::NodeList'));
258             use utf8;
259             [grep { $_->to_literal=~m{$regexp} } @$nodelist];
260             });
261             $_xpc->registerFunctionNS('same',$XML::XSH::xshNS,
262             sub {
263             die "Wrong number of arguments for function same(node,node)!" if (@_!=2);
264             my ($nodea,$nodeb)=@_;
265             die "1st argument must be a node in grep(list,regexp)!"
266             unless (ref($nodea) and $nodea->isa('XML::LibXML::NodeList'));
267             die "2nd argument must be a node in grep(list,regexp)!"
268             unless (ref($nodeb) and $nodeb->isa('XML::LibXML::NodeList'));
269             return XML::LibXML::Boolean->new($nodea->size() && $nodeb->size() &&
270             $nodea->[0]->isSameNode($nodea->[0]));
271             });
272             }
273              
274             sub list_flags {
275             print "validation ".(get_validation() or "0").";\n";
276             print "recovering ".(get_recovering() or "0").";\n";
277             print "parser_expands_entities ".(get_expand_entities() or "0").";\n";
278             print "parser_expands_xinclude ".(get_expand_xinclude() or "0").";\n";
279             print "keep_blanks ".(get_keep_blanks() or "0").";\n";
280             print "pedantic_parser ".(get_pedantic_parser() or "0").";\n";
281             print "load_ext_dtd ".(get_load_ext_dtd() or "0").";\n";
282             print "complete_attributes ".(get_complete_attributes() or "0").";\n";
283             print "indent ".(get_indent() or "0").";\n";
284             print "empty_tags ".(get_empty_tags() or "0").";\n";
285             print "skip_dtd ".(get_skip_dtd() or "0").";\n";
286             print ((get_backups() ? "backups" : "nobackups"),";\n");
287             print (($QUIET ? "quiet" : "verbose"),";\n");
288             print (($DEBUG ? "debug" : "nodebug"),";\n");
289             print (($TEST_MODE ? "run-mode" : "test-mode"),";\n");
290             print "switch_to_new_documents ".(get_cdonopen() or "0").";\n";;
291             print "encoding '$ENCODING';\n";
292             print "query_encoding '$QUERY_ENCODING';\n";
293             print "xpath_completion ".(get_xpath_completion() or "0").";\n";
294             print "xpath_axis_completion \'".get_xpath_axis_completion()."';\n";
295             }
296              
297             sub toUTF8 {
298             # encode/decode from UTF8 returns undef if string not marked as utf8
299             # by perl (for example ascii)
300             my $res=eval { encodeToUTF8($_[0],$_[1]) };
301             if ($@ =~ /^SIGINT/) {
302             die $@
303             } else {
304             undef $@;
305             }
306             return defined($res) ? $res : $_[1];
307             }
308              
309             sub fromUTF8 {
310             # encode/decode from UTF8 returns undef if string not marked as utf8
311             # by perl (for example ascii)
312             my $res=eval { decodeFromUTF8($_[0],$_[1]) };
313             if ($@ =~ /^SIGINT/) {
314             die $@
315             } else {
316             undef $@;
317             }
318             return defined($res) ? $res : $_[1];
319             }
320              
321             # evaluate a XSH command
322             sub xsh {
323             xsh_init() unless (ref($_xsh));
324             if (ref($_xsh)) {
325             my $code=join "",@_;
326             return ($code=~/^\s*$/) ? 1 : $_xsh->startrule($code);
327             } else {
328             die "XSH init failed!\n";
329             }
330             }
331              
332             # setup output stream
333             sub xsh_set_output {
334             $OUT=$_[0];
335             return 1;
336             }
337              
338             # get output stream
339             sub xsh_get_output {
340             return $OUT;
341             }
342              
343             sub xsh_docs {
344             return keys %_doc;
345             }
346              
347             sub xsh_parse_string {
348             my $format=$_[1] || $DEFAULT_FORMAT;
349             if ($format eq 'xml') {
350             my $xmldecl;
351             $xmldecl="" unless $_[0]=~/^\s*\<\?xml /;
352             return $_xml_module->parse_string($_parser,$xmldecl.$_[0]);
353             } elsif ($format eq 'html') {
354             return $_xml_module->parse_html_string($_parser,$_[0]);
355             } elsif ($format eq 'docbook') {
356             print "parsing SGML\n";
357             return $_xml_module->parse_sgml_string($_parser,$_[0]);
358             }
359             }
360              
361             sub xsh_xml_parser {
362             xsh_init() unless ref($_parser);
363             return $_parser;
364             }
365              
366             # store a pointer to an XSH-Grammar parser
367             sub xsh_set_parser {
368             $_xsh=$_[0];
369             return 1;
370             }
371              
372             # print version info
373             sub print_version {
374             out("Main program: $::VERSION $::REVISION\n");
375             out("XML::XSH::Functions: $VERSION $REVISION\n");
376             out("XML::LibXML: $XML::LibXML::VERSION\n");
377             # out($_xml_module->module(),"\t",$_xml_module->version(),"\n");
378             out("XML::LibXSLT $XML::LibXSLT::VERSION\n")
379             if defined($XML::LibXSLT::VERSION);
380             out("XML::LibXML::XPathContext $XML::LibXML::XPathContext::VERSION\n")
381             if defined($XML::LibXML::XPathContext::VERSION);
382             return 1;
383             }
384              
385             # print a list of all open files
386             sub files {
387             out(map { "$_ = $_files{$_}\n" } sort keys %_files);
388             return 1;
389             }
390              
391             sub docs {
392             return sort keys %_files;
393             }
394              
395             sub _doc {
396             return $_doc{$_[0]} if exists($_doc{$_[0]});
397             }
398              
399             sub xpath_var_lookup {
400             my ($data,$name,$ns)=@_;
401             no strict;
402             if ($ns eq "") {
403             if ($name=~/^_\.(.*)$/ and exists($_nodelist{$1})) {
404             return $_nodelist{$1}[1];
405             } elsif (defined(${"XML::XSH::Map::$name"})) {
406             return ${"XML::XSH::Map::$name"};
407             } else {
408             die "Undefined nodelist variable `$name'\n";
409             }
410             }
411             }
412              
413             # return a value of the given XSH string or nodelist variable
414             sub var_value {
415             no strict;
416             if ($_[0]=~/^\$(.*)/ and defined(${"XML::XSH::Map::$1"})) {
417             return "".${"XML::XSH::Map::$1"};
418             } elsif ($_[0]=~/^\%(.*)/ and exists($_nodelist{$1})) {
419             return $_nodelist{$1};
420             } else {
421             return undef;
422             }
423             }
424              
425             sub string_vars {
426             no strict;
427             return sort grep { defined(${"XML::XSH::Map::$_"}) } keys %{"XML::XSH::Map::"};
428             }
429              
430             sub nodelist_vars {
431             no strict;
432             return sort keys %_nodelist;
433             }
434              
435             # print a list of XSH variables and their values
436             sub variables {
437             no strict;
438             foreach (keys %{"XML::XSH::Map::"}) {
439             out("\$$_='",fromUTF8($ENCODING,${"XML::XSH::Map::$_"}),"';\n") if defined(${"XML::XSH::Map::$_"});
440             }
441             return 1;
442             }
443              
444             # print value of an XSH variable
445             sub print_var {
446             no strict;
447             if ($_[0]=~/^\$?(.*)/) {
448             out("\$$1='",fromUTF8($ENCODING,${"XML::XSH::Map::$1"}),"';\n") if defined(${"XML::XSH::Map::$1"});
449             return 1;
450             }
451             return 0;
452             }
453              
454             sub echo { out(fromUTF8($ENCODING,join " ",expand(@_)),"\n"); return 1; }
455             sub set_quiet { $QUIET=$_[0]; return 1; }
456             sub set_debug { $DEBUG=$_[0]; return 1; }
457             sub set_compile_only_mode { $TEST_MODE=$_[0]; return 1; }
458              
459             sub test_enc {
460             my ($enc)=@_;
461             if (defined(toUTF8($enc,'')) and
462             defined(fromUTF8($enc,''))) {
463             return 1;
464             } else {
465             _err("Error: Cannot convert between $enc and utf-8\n");
466             return 0;
467             }
468             }
469              
470             sub set_encoding {
471             my $enc=expand($_[0]);
472             my $ok=test_enc($enc);
473             $ENCODING=$enc if $ok;
474             return $ok;
475             }
476              
477             sub set_qencoding {
478             my $enc=expand($_[0]);
479             my $ok=test_enc($enc);
480             $QUERY_ENCODING=$enc if $ok;
481             return $ok;
482             }
483              
484             sub print_encoding { print "$ENCODING\n"; return 1; }
485             sub print_qencoding { print "$QUERY_ENCODING\n"; return 1; }
486              
487             sub sigint {
488             if ($TRAP_SIGINT) {
489             print STDERR "\nCtrl-C pressed. \n";
490             die "SIGINT";
491             } else {
492             print STDERR "\nCtrl-C pressed. \n";
493             exit 1;
494             }
495             }
496              
497             sub sigpipe {
498             if ($TRAP_SIGPIPE) {
499             die "SIGPIPE";
500             } else {
501             _err('broken pipe (SIGPIPE)');
502             exit 1;
503             }
504             }
505              
506             sub flagsigint {
507             print STDERR "\nCtrl-C pressed. \n";
508             $_sigint=1;
509             }
510              
511             sub propagate_flagsigint {
512             if ($_sigint) {
513             $_sigint=0;
514             die 'SIGINT';
515             }
516             }
517              
518              
519             sub convertFromDocEncoding ($$\$) {
520             my ($doc,$encoding,$str)=@_;
521             return fromUTF8($encoding, toUTF8($_xml_module->doc_encoding($doc), $str));
522             }
523              
524             sub _err {
525             print STDERR @_,"\n";
526             }
527              
528             # if the argument is non-void then print it and return 0; return 1 otherwise
529             sub _check_err {
530             my ($err,$survive_int)=@_;
531             if ($err) {
532             if ($err=~/^SIGINT/) {
533             if ($survive_int) {
534             $err=~s/ at (?:.|\n)*$//;
535             _err($err);
536             return 0;
537             } else {
538             die $err; # propagate
539             }
540             } elsif ($_die_on_err) {
541             if ($err=~/^SIGPIPE/) {
542             _err('broken pipe (SIGPIPE)');
543             } else {
544             die $err; # propagate
545             }
546             } else {
547             if ($err=~/^SIGPIPE/) {
548             _err('broken pipe (SIGPIPE)');
549             } else {
550             _err($err);
551             }
552             return 0;
553             }
554             }
555             return 1;
556             }
557              
558             # return current document id
559             sub xsh_local_id {
560             return $LOCAL_ID;
561             }
562              
563              
564             # return current node for given document or document root if
565             # current node is not from the given document
566             sub get_local_node {
567             my ($id)=@_;
568             if ($LOCAL_NODE and $id eq $LOCAL_ID) {
569             return $LOCAL_NODE;
570             } else {
571             $id=$LOCAL_ID if ($id eq "");
572             return $_doc{$id} ? $_doc{$id} : undef;
573             }
574             }
575              
576             # return current document's id (and optionally the doc itself) if id is void
577             sub _id {
578             my ($id)=@_;
579             if ($id eq "") {
580             $id=$LOCAL_ID;
581             print STDERR "assuming current document $id\n" if $DEBUG;
582             }
583             return wantarray ? ($id,$_doc{$id}) : $id;
584             }
585              
586             # try to find a document ID by its node
587             sub _find_id {
588             my ($node)=@_;
589             if (ref($node)) {
590             my $doc=$_xml_module->owner_document($node);
591             foreach my $id (keys %_doc) {
592             if ($_xml_module->xml_equal($_doc{$id},$doc)) {
593             print STDERR "FOUND ID: $id\n" if $DEBUG;
594             return $id;
595             }
596             }
597             print STDERR "Error: no document found for current node\n";
598             my $uri=$_xml_module->doc_URI($doc);
599             if ($uri ne "") {
600             pirnt STDERR "Using document('$uri')\n" if $DEBUG;
601             return "document('$uri')";
602             }
603             }
604             return "";
605             }
606              
607             # extract document id, xpath query string and document pointer from XPath type
608             sub _xpath {
609             my ($id,$query)=expand(@{$_[0]});
610             ($id,my $doc)=_id($id);
611             return ($id,$query,$doc);
612             }
613              
614             # make given node current (no checking!)
615             sub set_local_node {
616             my ($node)=@_;
617             if (ref($node)) {
618             $LOCAL_NODE=$node;
619             $LOCAL_ID=_find_id($node);
620             } else {
621             $LOCAL_NODE=undef;
622             $LOCAL_ID=undef;
623             }
624             }
625              
626             # make root of the document the current node (no checking!)
627             sub set_local_doc {
628             my ($id)=@_;
629             $LOCAL_NODE=$_doc{$id};
630             $LOCAL_ID=$id;
631             }
632              
633              
634             # set current node to given XPath
635             sub set_local_xpath {
636             my ($xp)=@_;
637             my ($id,$query,$doc)=_xpath($xp);
638             unless (ref($doc)) {
639             die "No such document '$id'!\n";
640             }
641             if ($query eq "") {
642             set_local_doc($id);
643             return 1;
644             }
645             return 0 unless ref($doc);
646             my ($newlocal);
647             $newlocal=find_nodes($xp)->[0];
648             if (ref($newlocal)) {
649             set_local_node($newlocal);
650             } else {
651             die "No node in document $id matches XPath $query!\n";
652             }
653              
654             return 1;
655             }
656              
657             # return XPath identifying a node within its parent's subtree
658             sub node_address {
659             my ($node)=@_;
660             my $name;
661             if ($_xml_module->is_element($node)) {
662             $name=$node->getName();
663             } elsif ($_xml_module->is_text($node) or
664             $_xml_module->is_cdata_section($node)) {
665             $name="text()";
666             } elsif ($_xml_module->is_comment($node)) {
667             $name="comment()";
668             } elsif ($_xml_module->is_pi($node)) {
669             $name="processing-instruction()";
670             } elsif ($_xml_module->is_attribute($node)) {
671             return "@".$node->getName();
672             }
673             if ($node->parentNode) {
674             my @children;
675             if ($_xml_module->is_element($node)) {
676             @children=$node->parentNode->findnodes("./*[name()='$name']");
677             } else {
678             @children=$node->parentNode->findnodes("./$name");
679             }
680             if (@children == 1 and $_xml_module->xml_equal($node,$children[0])) {
681             return "$name";
682             }
683             for (my $pos=0;$pos<@children;$pos++) {
684             return "$name"."[".($pos+1)."]"
685             if ($_xml_module->xml_equal($node,$children[$pos]));
686             }
687             return undef;
688             } else {
689             return ();
690             }
691             }
692              
693             # parent element (even for attributes)
694             sub tree_parent_node {
695             my $node=$_[0];
696             if ($_xml_module->is_attribute($node)) {
697             return $node->ownerElement();
698             } else {
699             return $node->parentNode();
700             }
701             }
702              
703             # return canonical xpath for the given or current node
704             sub pwd {
705             my $node=$_[0] || $LOCAL_NODE || $_doc{$LOCAL_ID};
706             return undef unless ref($node);
707             my @pwd=();
708             do {
709             unshift @pwd,node_address($node);
710             $node=tree_parent_node($node);
711             } while ($node);
712             my $pwd="/".join "/",@pwd;
713             return $pwd;
714             }
715              
716             # return canonical xpath for current node (encoded)
717             sub xsh_pwd {
718             my $pwd;
719             my ($id, $doc)=_id();
720             return undef unless $doc;
721             $pwd=fromUTF8($ENCODING,pwd());
722             return $pwd;
723             }
724              
725             # print current node's xpath
726             sub print_pwd {
727             my $pwd=xsh_pwd();
728             if ($pwd) {
729             out("$pwd\n\n");
730             return $pwd;
731             } else {
732             return 0;
733             }
734             }
735              
736             # evaluate variable and xpath expresions given string
737             sub _expand {
738             my $l=$_[0];
739             my $k;
740             no strict;
741             $l=~/^/o;
742             while ($l !~ /\G$/gsco) {
743             if ($l=~/\G\\(.|\n)/gsco) {
744             if (exists($_chr{$1})) {
745             $k.=$_chr{$1};
746             } else {
747             $k.=$1;
748             }
749             } elsif ($l=~/\G([^\\\$]+)/gsco) {
750             $k.=$1;
751             } elsif ($l=~/\G\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}/gsco
752             or $l=~/\G\$([a-zA-Z_][a-zA-Z0-9_]*)/gsco) {
753             $k.=${"XML::XSH::Map::$1"};
754             } elsif ($l=~/\G\$\{\{\{(.+?)\}\}\}/gsco) {
755             $k.=perl_eval($1);
756             } elsif ($l=~/\G\$\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*):(?!:)(.*?)\}\}/gsco) {
757             $k.=count([$1,$2]);
758             } elsif ($l=~/\G\$\{\{([^\{].*?)\}\}/gsco) {
759             $k.=count([undef,$1]);
760             } elsif ($l=~/\G\$\{\(\s*([a-zA-Z_][a-zA-Z0-9_]*):(?!:)(.*?)\)\}/gsco) {
761             $k.=eval_xpath_literal([$1,$2]);
762             } elsif ($l=~/\G\$\{\((.+?)\)\}/gsco) {
763             $k.=eval_xpath_literal([undef,$1]);
764             } elsif ($l=~/\G(.|\n)/gsco) {
765             $k.=$1;
766             }
767             }
768             return $k;
769             }
770              
771             # expand one or all parameters (according to return context)
772             sub expand {
773             return wantarray ? (map { _expand($_) } @_) : _expand($_[0]);
774             }
775              
776             # assign a value to a variable
777             sub _assign {
778             my ($name,$value)=@_;
779             no strict 'refs';
780             $name=~/^\$(.+)/;
781             ${"XML::XSH::Map::$1"}=$value;
782             print STDERR "\$$1=",${"XML::XSH::Map::$1"},"\n" if $DEBUG;
783             return 1;
784             }
785              
786             sub _undef {
787             my ($name)=@_;
788             no strict 'refs';
789             $name=~/^\$(.+)/;
790             undef ${"XML::XSH::Map::$1"};
791             return 1;
792             }
793              
794             sub literal_value {
795             return ref($_[0]) ? $_[0]->value() : $_[0];
796             }
797              
798             # evaluate xpath and assign the result to a variable
799             sub xpath_assign {
800             my ($name,$xp)=@_;
801             _assign($name,count($xp));
802             return 1;
803             }
804              
805             sub xpath_assign_local {
806             store_variables(0,$_[0]);
807             xpath_assign(@_);
808             return 1;
809             }
810              
811             sub nodelist_assign_local {
812             my ($name)=@_;
813             $name=expand($name);
814             store_variables(0,"\%$name");
815             nodelist_assign(@_);
816             return 1;
817             }
818              
819             sub make_local {
820             foreach (@_) {
821             if ($_->[0] eq '$') {
822             xpath_assign_local($_->[1],undef);
823             } else {
824             nodelist_assign_local($_->[1],undef);
825             }
826             }
827             }
828              
829              
830             sub get_stored_nodelists {
831             return grep { ref($_) } map { @$_ } @stored_variables;
832             }
833              
834             sub store_variables {
835             my ($new,@vars)=@_;
836             my $pool;
837             if ($new) {
838             $pool=[];
839             } elsif (@stored_variables and ref($stored_variables[$#stored_variables])) {
840             $pool=$stored_variables[$#stored_variables];
841             } else {
842             print STDERR "WARNING: Ignoring attempt to make a local variable outside a localizable context!\n";
843             return 0;
844             }
845              
846             foreach (@vars) {
847             my $value=var_value($_);
848             push @$pool, $_ => $value;
849             }
850             push @stored_variables, $pool if ($new);
851              
852             return 1;
853             }
854              
855             sub restore_variables {
856             my $pool=pop @stored_variables;
857             unless (ref($pool)) {
858             __bug("Local variable pool is empty, which was not expected!\n");
859             return 0;
860             }
861             while (@$pool) {
862             my ($value,$name)=(pop(@$pool), pop(@$pool));
863             if ($name =~ m/^\$/) {
864             if (defined($value)) {
865             _assign($name,$value);
866             } else {
867             _undef($name);
868             }
869             } elsif ($name =~ m/^\%(.*)$/) {
870             if (defined($value)) {
871             $_nodelist{$1}=$value;
872             } else {
873             delete $_nodelist{$1};
874             }
875             } else {
876             __bug("Invalid variable name $1\n");
877             }
878             }
879             return 1;
880             }
881              
882             sub _xpc_find_nodes {
883             my ($node,$query)=@_;
884             $_xpc->setContextNode($node);
885             return $_xpc->findnodes($query);
886             }
887              
888             # findnodes wrapper which handles both xpaths and nodelist variables
889             sub _find_nodes {
890             my ($context,$q)=@_;
891             if ($q=~s/^\%([a-zA-Z_][a-zA-Z0-9_]*)(.*)$/\$_.$1$2/) { # node-list
892             my $query=$2;
893             my $name=$1;
894             unless (exists($_nodelist{$name})) {
895             die "No such nodelist '\%$name'\n";
896             }
897             if ($query =~ /\S/) {
898             if ($_xpc->isa('XML::LibXML::XPathContext')) {
899             if ($query =~m|^\s*\[(\d+)\](.*)$|) { # index on a node-list
900             return exists($_nodelist{$name}->[1]->[$1+1]) ?
901             scalar(_xpc_find_nodes($_nodelist{$name}->[1]->[$1],'./self::*'.$2)) : [];
902             } else {
903             return scalar(_xpc_find_nodes($_nodelist{$name}->[0], $q));
904             }
905             } else {
906             # workaround for dummy XPathContext
907             if ($query =~m|^\s*\[(\d+)\](.*)$|) { # index on a node-list
908             return $_nodelist{$name}->[1]->[$1+1] ?
909             [ grep {defined($_)} $_nodelist{$name}->[1]->[$1]->findnodes('./self::*'.$2) ] : [];
910             } elsif ($query =~m|^\s*\[|) { # filter in a nodelist
911             return [ grep {defined($_)} map { ($_->findnodes('./self::*'.$query)) }
912             @{$_nodelist{$name}->[1]}
913             ];
914             }
915             return [ grep {defined($_)} map { ($_->findnodes('.'.$query)) }
916             @{$_nodelist{$name}->[1]}
917             ];
918             }
919             } else {
920             return $_nodelist{$name}->[1];
921             }
922             } else {
923             return scalar(_xpc_find_nodes($context,$q));
924             }
925             }
926              
927             # _find_nodes wrapper with q-decoding
928             sub find_nodes {
929             my ($id,$query,$doc)=_xpath($_[0]);
930             if ($query eq "") { $query="."; }
931             unless (ref($doc)) {
932             die "No such document '$id'!\n";
933             }
934              
935             return _find_nodes(get_local_node($id),toUTF8($QUERY_ENCODING,$query));
936             }
937              
938             sub count_xpath {
939             my ($node,$xp)=@_;
940             my $result;
941             $_xpc->setContextNode($node);
942             $result=$_xpc->find($xp);
943              
944             if (ref($result)) {
945             if ($result->isa('XML::LibXML::NodeList')) {
946             return $result->size();
947             } elsif ($result->isa('XML::LibXML::Literal')) {
948             return $result->value();
949             } elsif ($result->isa('XML::LibXML::Number') or
950             $result->isa('XML::LibXML::Boolean')) {
951             return $result->value();
952             }
953             } else {
954             return $result;
955             }
956             }
957              
958             # assign a result of xpath search to a nodelist variable
959             sub nodelist_assign {
960             my ($name,$xp)=@_;
961             $name=expand($name);
962             my ($id,$query,$doc)=_xpath($xp);
963             if ($doc) {
964             if ($query eq "") {
965             $_nodelist{$name}=[$doc,[]];
966             } else {
967             $_nodelist{$name}=[$doc,find_nodes($xp)];
968             print STDERR "\nStored ",scalar(@{$_nodelist{$name}->[1]})," node(s).\n" unless "$QUIET";
969             }
970             }
971             }
972              
973             sub has_all_ancestors {
974             my ($node)=@_;
975             while ($node) {
976             return 1 if ($_xml_module->is_document($node));
977             $node=$node->parentNode;
978             }
979             return 0;
980             }
981              
982             # remove unbounded nodes from all nodelists of a given document
983             sub remove_dead_nodes_from_nodelists {
984             my ($doc)=@_;
985             foreach my $list (values(%_nodelist),get_stored_nodelists()) {
986             if ($_xml_module->xml_equal($doc,$list->[0])) {
987             $list->[1]=[ grep { has_all_ancestors($_) } @{$list->[1]} ];
988             }
989             }
990             }
991              
992             # remove given node and all its descendants from all nodelists
993             sub remove_node_from_nodelists {
994             my ($node,$doc)=@_;
995             foreach my $list (values(%_nodelist),get_stored_nodelists()) {
996             if ($_xml_module->xml_equal($doc,$list->[0])) {
997             $list->[1]=[ grep { !is_ancestor_or_self($node,$_) } @{$list->[1]} ];
998             }
999             }
1000             }
1001              
1002             # create new document
1003             sub create_doc {
1004             my ($id,$root_element,$format)=expand @_;
1005             $id=_id($id);
1006             my $doc;
1007             $root_element="<$root_element/>" unless ($root_element=~/^\s*
1008             $root_element=toUTF8($QUERY_ENCODING,$root_element);
1009             $root_element=~s/^\s+//;
1010             $doc=xsh_parse_string($root_element,$format);
1011             set_doc($id,$doc,"new_document$_newdoc.xml");
1012             $_newdoc++;
1013              
1014             set_local_doc($id) if $SWITCH_TO_NEW_DOCUMENTS;
1015             return $doc;
1016             }
1017              
1018             # bind a document with a given id and filename
1019             sub set_doc {
1020             my ($id,$doc,$file)=@_;
1021             $_doc{$id}=$doc;
1022             $_files{$id}=$file;
1023             return $doc;
1024             }
1025              
1026             # return DOM of the document identified by given id
1027             sub get_doc {
1028             return $_doc{$_[0]};
1029             }
1030              
1031             # create a new document by parsing a file
1032             sub open_doc {
1033             my ($id,$file)=expand @_[0,1];
1034             my $format;
1035             my $source;
1036             if ($_[2]=~/(?:open)?(?:(?:\s*|_|-)(HTML|XML|DOCBOOK|html|xml|docbook))?(?:(?:\s*|_|-)(FILE|file|PIPE|pipe|STRING|string))?/) {
1037             $format = lc($1) || $DEFAULT_FORMAT;
1038             $source = lc($2) || 'file';
1039             } else {
1040             $format=$DEFAULT_FORMAT;
1041             $source='file';
1042             }
1043             $file=expand($file);
1044             $file=~s{^(\~[^\/]*)}{(glob($1))[0]}eg;
1045             $id=_id($id);
1046             print STDERR "open [$file] as [$id]\n" if "$DEBUG";
1047             if ($id eq "" or $file eq "") {
1048             print STDERR "hint: open identifier=file-name\n" unless "$QUIET";
1049             return;
1050             }
1051             if (($source ne 'file') or
1052             (-f $file) or $file eq "-" or
1053             ($file=~/^[a-z]+:/)) {
1054             print STDERR "parsing $file\n" unless "$QUIET";
1055              
1056             my $doc;
1057             if ($source eq 'pipe') {
1058             open my $F,"$file|";
1059             $F || die "Cannot open pipe to $file: $!\n";
1060             if ($format eq 'xml') {
1061             $doc=$_xml_module->parse_fh($_parser,$F);
1062             } elsif ($format eq 'html') {
1063             $doc=$_xml_module->parse_html_fh($_parser,$F);
1064             } elsif ($format eq 'docbook') {
1065             $doc=$_xml_module->parse_sgml_fh($_parser,$F,$QUERY_ENCODING);
1066             }
1067             close $F;
1068             } elsif ($source eq 'string') {
1069             my $root_element=$file;
1070             $root_element="<$root_element/>" unless ($root_element=~/^\s*
1071             $root_element=toUTF8($QUERY_ENCODING,$root_element);
1072             $root_element=~s/^\s+//;
1073             $doc=xsh_parse_string($root_element,$format);
1074             set_doc($id,$doc,"new_document$_newdoc.xml");
1075             $_newdoc++;
1076             } else {
1077             if ($format eq 'xml') {
1078             $doc=$_xml_module->parse_file($_parser,$file);
1079             } elsif ($format eq 'html') {
1080             $doc=$_xml_module->parse_html_file($_parser,$file);
1081             } elsif ($format eq 'docbook') {
1082             $doc=$_xml_module->parse_sgml_file($_parser,$file,$QUERY_ENCODING);
1083             }
1084             }
1085             print STDERR "done.\n" unless "$QUIET";
1086             set_doc($id,$doc,$file);
1087             set_local_doc($id) if $SWITCH_TO_NEW_DOCUMENTS;
1088            
1089             # if ($@ =~ /^'' at /) {
1090             # print STDERR
1091             # "\nError: ",
1092             # "Parsing failed. LibXML returned no error message!\n";
1093             # print STDERR "Hint: Maybe you are trying to parse with validation on,\n".
1094             # "but your document has no DTD? Consider 'validation 0'.\n" if get_validation();
1095             # return 0;
1096             # }
1097             # return _check_err($@);
1098             } else {
1099             die "file not exists: $file\n";
1100             return 0;
1101             }
1102             }
1103              
1104             # close a document and destroy all nodelists that belong to it
1105             sub close_doc {
1106             my ($id)=expand(@_);
1107             $id=_id($id);
1108             unless (exists($_doc{$id})) {
1109             die "No such document '$id'!\n";
1110             }
1111             out("closing file $_files{$id}\n") unless "$QUIET";
1112             delete $_files{$id};
1113             foreach (values %_nodelist) {
1114             if ($_->[0]==$_doc{$id}) {
1115             delete $_nodelist{$_};
1116             }
1117             }
1118             delete $_doc{$id};
1119             if (xsh_local_id() eq $id) {
1120             if ($_doc{'scratch'}) {
1121             set_local_xpath(['scratch','/']);
1122             } else {
1123             set_local_node(undef);
1124             }
1125             }
1126             return 1;
1127             }
1128              
1129             sub open_io_file {
1130             my ($file)=@_;
1131             if ($file=~/^\s*[|>]/) {
1132             return IO::File->new($file);
1133             } elsif ($file=~/.gz\s*$/) {
1134             return IO::File->new("| gzip -c > $file");
1135             } else {
1136             return IO::File->new(">$file");
1137             }
1138             }
1139              
1140             sub is_xinclude {
1141             my ($node)=@_;
1142             return
1143             $_xml_module->is_xinclude_start($node) ||
1144             ($_xml_module->is_element($node) and
1145             $node->namespaceURI() eq 'http://www.w3.org/2001/XInclude' and
1146             $node->localname() eq 'include');
1147             }
1148              
1149             sub xinclude_start_tag {
1150             my ($xi)=@_;
1151             my %xinc = map { $_->nodeName() => $_->value() } $xi->attributes();
1152             $xinc{parse}='xml' if ($xinc{parse} eq "");
1153             return "<".$xi->nodeName()." href='".$xinc{href}."' parse='".$xinc{parse}."'>";
1154             }
1155              
1156             sub xinclude_end_tag {
1157             my ($xi)=@_;
1158             return "nodeName().">";
1159             }
1160              
1161             sub xinclude_print {
1162             my ($doc,$F,$node,$enc)=@_;
1163             return unless ref($node);
1164             if ($_xml_module->is_element($node) || $_xml_module->is_document($node)) {
1165             $F->print(fromUTF8($enc,start_tag($node))) if $_xml_module->is_element($node);
1166             my $child=$node->firstChild();
1167             while ($child) {
1168             if (is_xinclude($child)) {
1169             my %xinc = map { $_->nodeName() => $_->value() } $child->attributes();
1170             $xinc{parse}||='xml';
1171             $xinc{encoding}||=$enc; # may be used even to convert included XML
1172             my $elements=0;
1173             my @nodes=();
1174             my $node;
1175             my $expanded=$_xml_module->is_xinclude_start($child);
1176             if ($expanded) {
1177             $node=$child->nextSibling(); # in case of special XINCLUDE node
1178             } else {
1179             $node=$child->firstChild(); # in case of include element from XInclude NS
1180             }
1181             my $nested=0;
1182             while ($node and not($_xml_module->is_xinclude_end($node)
1183             and $nested==0
1184             and $expanded)) {
1185             if ($_xml_module->is_xinclude_start($node)) { $nested++ }
1186             elsif ($_xml_module->is_xinclude_end($node)) { $nested-- }
1187             push @nodes,$node;
1188             $elements++ if $_xml_module->is_element($node);
1189             $node=$node->nextSibling();
1190             }
1191             if ($nested>0) {
1192             print STDERR "Error: Unbalanced nested XInclude nodes.\n",
1193             " Ignoring this XInclude span!\n";
1194             $F->print("");
1195             } elsif (!$node and $_xml_module->is_xinclude_start($child)) {
1196             print STDERR "Error: XInclude end node not found.\n",
1197             " Ignoring this XInclude span!\n";
1198             $F->print("");
1199             } elsif ($xinc{parse} ne 'text' and $elements==0) {
1200             print STDERR "Warning: XInclude: No elements found in XInclude span.\n",
1201             " Ignoring whole XInclude span!\n";
1202             $F->print("");
1203             } elsif ($xinc{parse} ne 'xml' and $elements>1) {
1204             print STDERR "Error: XInclude: More than one element found in XInclude span.\n",
1205             " Ignoring whole XInclude span!\n";
1206             $F->print("");
1207             } elsif ($xinc{parse} eq 'text' and $elements>0) {
1208             print STDERR "Warning: XInclude: Element(s) found in textual XInclude span.\n",
1209             " Skipping whole XInclude span!\n";
1210             $F->print("");
1211             } else {
1212             $F->print(fromUTF8($enc,xinclude_start_tag($child)));
1213             save_xinclude_chunk($doc,\@nodes,$xinc{href},$xinc{parse},$xinc{encoding});
1214             $F->print(fromUTF8($enc,xinclude_end_tag($child)));
1215             $child=$node if ($expanded); # jump to XINCLUDE end node
1216             }
1217             } elsif ($_xml_module->is_xinclude_end($child)) {
1218             $F->print("");
1219             } else {
1220             xinclude_print($doc,$F,$child,$enc); # call recursion
1221             }
1222             $child=$child->nextSibling();
1223             }
1224             $F->print(fromUTF8($enc,end_tag($node))) if $_xml_module->is_element($node);
1225             } else {
1226             $F->print(fromUTF8($enc,$_xml_module->toStringUTF8($node,$INDENT)));
1227             }
1228             }
1229              
1230             sub save_xinclude_chunk {
1231             my ($doc,$nodes,$file,$parse,$enc)=@_;
1232              
1233             return unless @$nodes>0;
1234              
1235             if ($BACKUPS) {
1236             eval { rename $file, $file."~"; };
1237             _check_err($@);
1238             }
1239             my $F=open_io_file($file);
1240             $F || die "Cannot open $file\n";
1241              
1242             if ($parse eq 'text') {
1243             foreach my $node (@$nodes) {
1244             $F->print(fromUTF8($enc,literal_value($node->to_literal)));
1245             }
1246             } else {
1247             my $version=$doc->can('getVersion') ? $doc->getVersion() : '1.0';
1248             $F->print("\n");
1249             foreach my $node (@$nodes) {
1250             xinclude_print($doc,$F,$node,$enc);
1251             }
1252             $F->print("\n");
1253             }
1254             $F->close();
1255             }
1256              
1257             # save a document
1258             sub save_doc {
1259             my $type=$_[0];
1260             my ($id,$file,$enc)=expand($_[1],$_[2],@{$_[3]});
1261              
1262             ($id,my $doc)=_id($id);
1263             unless (ref($doc)) {
1264             die "No such document '$id'!\n";
1265             }
1266              
1267             my $format=$DEFAULT_FORMAT;
1268             my $target='file';
1269             if ($type=~/save(?:as|_as|-as)?(?:(?:\s*|_|-)(HTML|html|XML|xml|XINCLUDE|Xinclude|xinclude))?(?:(?:\s*|_|-)(FILE|file|PIPE|pipe|STRING|string))?/) {
1270             $format = lc($1) if $1;
1271             $target = lc($2) if $2;
1272             }
1273              
1274             if ($target eq 'file' and $file eq "") {
1275             $file=$_files{$id};
1276             if ($BACKUPS) {
1277             eval { rename $file, $file."~"; };
1278             _check_err($@);
1279             }
1280             }
1281              
1282             $enc = $enc || $_xml_module->doc_encoding($doc) || 'utf-8';
1283             print STDERR "saving $id=$_files{$id} to $file as $format (encoding $enc)\n" if "$DEBUG";
1284              
1285             if ($format eq 'xinclude') {
1286             if ($format ne 'file') {
1287             print STDERR "Saving to a ".uc($target)." not supported for XInclude\n";
1288             } else {
1289             save_xinclude_chunk($doc,[$doc->childNodes()],$file,'xml',$enc);
1290             }
1291             } else {
1292             if ($format eq 'xml') {
1293             if (lc($_xml_module->doc_encoding($doc)) ne lc($enc)
1294             and not($_xml_module->doc_encoding($doc) eq "" and
1295             lc($enc) eq 'utf-8')
1296             ) {
1297             $_xml_module->set_encoding($doc,$enc);
1298             }
1299             if ($target eq 'file') {
1300             if ($file=~/\.gz\s*$/) {
1301             $doc->setCompression(6);
1302             } else {
1303             $doc->setCompression(-1);
1304             }
1305             $doc->toFile($file,$INDENT); # should be document-encoding encoded
1306             $_files{$id}=$file;
1307             } elsif ($target eq 'pipe') {
1308             $file=~s/^\s*\|?//g;
1309             open my $F,"| $file" || die "Cannot open pipe to $file\n";
1310             $doc->toFH($F,$INDENT);
1311             close $F;
1312             } elsif ($target eq 'string') {
1313             if ($file =~ /^\$?([a-zA-Z_][a-zA-Z0-9_]*)$/) {
1314             no strict qw(refs);
1315             ${"XML::XSH::Map::$1"}=$doc->toString($INDENT);
1316             } else {
1317             out($doc->toString($INDENT));
1318             }
1319             }
1320             } elsif ($format eq 'html') {
1321             my $F;
1322             if ($target eq 'file') {
1323             ($F=open_io_file($file)) || die "Cannot open $file\n";
1324             $_files{$id}=$file;
1325             } elsif ($target eq 'pipe') {
1326             $file=~s/^\s*\|?//g;
1327             open $F,"| $file";
1328             $F || die "Cannot open pipe to $file\n";
1329             } elsif ($target eq 'string') {
1330             $F=$OUT;
1331             }
1332             $F->print("\n")
1333             unless ($_xml_module->has_dtd($doc));
1334             $F->print(fromUTF8($enc, toUTF8($_xml_module->doc_encoding($doc),
1335             $doc->toStringHTML())));
1336              
1337             $F->close() unless $target eq 'string';
1338             } elsif ($format eq 'docbook') {
1339             print STDERR "Docbook is not supported output format!\n";
1340             }
1341             }
1342              
1343             print STDERR "Document $id written.\n" unless ($@ or "$QUIET");
1344             return 1;
1345             }
1346              
1347              
1348             # create start tag for an element
1349              
1350             ###
1351             ### Workaround of a bug in XML::LibXML:
1352             ### getNamespaces, getName returns prefix only,
1353             ### prefix returns prefix not xmlns, getAttributes contains also namespaces
1354             ### findnodes('namespace::*') returns (namespaces,undef)
1355             ###
1356              
1357             sub start_tag {
1358             my ($element)=@_;
1359             return "<".$element->nodeName().
1360             join("",map { " ".$_->nodeName()."=\"".$_->nodeValue()."\"" }
1361             $element->attributes())
1362             # findnodes('attribute::*'))
1363             # . join("",map { " xmlns:".$_->getName()."=\"".$_->nodeValue()."\"" }
1364             # $element->can('getNamespaces') ?
1365             # $element->getNamespaces() :
1366             # $element->findnodes('namespace::*')
1367             # )
1368             .($element->hasChildNodes() ? ">" : "/>");
1369             }
1370              
1371             # create close tag for an element
1372             sub end_tag {
1373             my ($element)=@_;
1374             return $element->hasChildNodes() ? "getName().">" : "";
1375             }
1376              
1377             # convert a subtree to an XML string to the given depth
1378             sub to_string {
1379             my ($node,$depth,$folding)=@_;
1380             my $result;
1381             if ($node) {
1382             if (ref($node) and $_xml_module->is_element($node) and $folding and
1383             $node->hasAttributeNS($XML::XSH::xshNS,'fold')) {
1384             if ($depth>=0) {
1385             $depth = min($depth,$node->getAttributeNS($XML::XSH::xshNS,'fold'));
1386             } else {
1387             $depth = $node->getAttributeNS($XML::XSH::xshNS,'fold');
1388             }
1389             }
1390              
1391             if ($depth<0 and !$folding) {
1392             $result=ref($node) ? $_xml_module->toStringUTF8($node,$INDENT) : $node;
1393             } elsif (ref($node) and $_xml_module->is_element($node) and $depth==0) {
1394             $result=start_tag($node).
1395             ($node->hasChildNodes() ? "...".end_tag($node) : "");
1396             } elsif ($depth>0 or $folding) {
1397             if (!ref($node)) {
1398             $result=$node;
1399             } elsif ($_xml_module->is_element($node)) {
1400             $result= start_tag($node).
1401             join("",map { to_string($_,$depth-1,$folding) } $node->childNodes).
1402             end_tag($node);
1403             } elsif ($_xml_module->is_document($node)) {
1404             if ($node->can('getVersion') and $node->can('getEncoding')) {
1405             $result=
1406             'getVersion() || '1.0').'"'.
1407             ($node->getEncoding() ne "" ? ' encoding="'.$node->getEncoding().'"' : '').
1408             '?>'."\n";
1409             }
1410             $result.=
1411             join("\n",map { to_string($_,$depth-1,$folding) }
1412             grep { $SKIP_DTD ? !$_xml_module->is_dtd($_) : 1 } $node->childNodes);
1413             } else {
1414             $result=$_xml_module->toStringUTF8($node,$INDENT);
1415             }
1416             } else {
1417             $result = ref($node) ? $_xml_module->toStringUTF8($node,$INDENT) : $node;
1418             }
1419             }
1420             return $result;
1421             }
1422              
1423             # list nodes matching given XPath argument to a given depth
1424             sub list {
1425             my ($xp,$depth)=@_;
1426             my ($id,$query,$doc)=_xpath($xp);
1427             my $folding;
1428             if ($depth=~/^fold/) {
1429             $folding = 1;
1430             $depth=-1;
1431             }
1432             unless (ref($doc)) {
1433             die "No such document '$id'!\n";
1434             }
1435             print STDERR "listing $query from $id=$_files{$id}\n\n" if "$DEBUG";
1436              
1437             my $ql=find_nodes($xp);
1438             foreach (@$ql) {
1439             print STDERR "checking for folding\n" if "$DEBUG";
1440             my $fold=$folding && ($_xml_module->is_element($_) || $_xml_module->is_document($_)) &&
1441             $_->findvalue("count(.//\@*[local-name()='fold' and namespace-uri()='$XML::XSH::xshNS'])");
1442             print STDERR "folding: $fold\n" if "$DEBUG";
1443             out (fromUTF8($ENCODING,to_string($_,$depth,$fold)),"\n");
1444             }
1445             print STDERR "\nFound ",scalar(@$ql)," node(s).\n" unless "$QUIET";
1446              
1447             return 1;
1448             }
1449              
1450             # list namespaces in scope of the given nodes
1451             sub list_namespaces {
1452             my $xp = $_[0] || [undef,'.'];
1453             my ($id,$query,$doc)=_xpath($xp);
1454             unless (ref($doc)) {
1455             die "No such document '$id'!\n";
1456             }
1457             print STDERR "listing namespaces for $query from $id=$_files{$id}\n\n" if "$DEBUG";
1458              
1459             my $ql=find_nodes($xp);
1460             foreach my $node (@$ql) {
1461             my $n=$node;
1462             my %namespaces;
1463             while ($n) {
1464             foreach my $ns ($n->getNamespaces) {
1465             $namespaces{$ns->getName()}=$ns->getData()
1466             unless (exists($namespaces{$ns->getName()}));
1467             }
1468             $n=$n->parentNode();
1469             }
1470             out(fromUTF8($ENCODING,pwd($node)),":\n");
1471             foreach (sort { $a cmp $b } keys %namespaces) {
1472             out("xmlns", ($_ ne "" ? ":" : ""),
1473             fromUTF8($ENCODING,$_),"=\"",
1474             fromUTF8($ENCODING,$namespaces{$_}),"\"\n");
1475             }
1476             out("\n");
1477             }
1478             return 1;
1479             }
1480              
1481             sub mark_fold {
1482             my ($xp,$depth)=@_;
1483             $depth=expand($depth);
1484             $depth=0 if $depth eq "";
1485              
1486             my $l=find_nodes($xp);
1487             foreach my $node (@$l) {
1488             if ($_xml_module->is_element($node)) {
1489             $node->setAttributeNS($XML::XSH::xshNS,'xsh:fold',$depth);
1490             }
1491             }
1492             return 1;
1493             }
1494              
1495             sub mark_unfold {
1496             my ($xp)=@_;
1497             my ($id,$query,$doc)=_xpath($xp);
1498             my $l=find_nodes($xp);
1499             foreach my $node (@$l) {
1500             if ($_xml_module->is_element($node) and $node->hasAttributeNS($XML::XSH::xshNS,'fold')) {
1501             remove_node($node->getAttributeNodeNS($XML::XSH::xshNS,'fold'));
1502             }
1503             }
1504             remove_dead_nodes_from_nodelists($doc);
1505             return 1;
1506             }
1507              
1508              
1509             # print canonical xpaths identifying nodes matching given XPath
1510             sub locate {
1511             my ($xp)=@_;
1512             my ($id,$query,$doc)=_xpath($xp);
1513              
1514             print STDERR "locating $query from $id=$_files{$id}\n\n" if "$DEBUG";
1515             unless (ref($doc)) {
1516             die "No such document '$id'!\n";
1517             }
1518             my $ql=find_nodes($xp);
1519             foreach (@$ql) {
1520             out(fromUTF8($ENCODING,pwd($_)),"\n");
1521             }
1522             print STDERR "\nFound ",scalar(@$ql)," node(s).\n" unless "$QUIET";
1523             return 1;
1524             }
1525              
1526             # evaluate given xpath and output the result
1527             sub count {
1528             my ($xp)=@_;
1529             my ($id,$query,$doc)= _xpath($xp);
1530              
1531             return undef if ($id eq "" or $query eq "");
1532             unless (ref($doc)) {
1533             die "No such document: $id\n";
1534             }
1535             print STDERR "Query $query on $id=$_files{$id}\n" if $DEBUG;
1536             my $result=undef;
1537              
1538             if ($query=~/^%/) {
1539             $result=find_nodes($xp);
1540             $result=scalar(@$result);
1541             } else {
1542             $query=toUTF8($QUERY_ENCODING,$query);
1543             print STDERR "query: $query\n" if "$DEBUG";
1544             $result=fromUTF8($ENCODING,count_xpath(get_local_node($id), $query));
1545             print STDERR "result: $result" if "$DEBUG";
1546             }
1547             return $result;
1548             }
1549              
1550             # evaluate given xpath and return the text content of the result
1551             sub eval_xpath_literal {
1552             my ($xp)=@_;
1553             my ($id,$query)=_xpath($xp);
1554             $_xpc->setContextNode(get_local_node($id));
1555             my $result = $_xpc->find(toUTF8($QUERY_ENCODING,$query));
1556             if (!ref($result)) {
1557             return $result;
1558             } else {
1559             if ($result->isa('XML::LibXML::NodeList')) {
1560             if (wantarray) {
1561             return map { literal_value($_->to_literal) } @$result;
1562             } elsif ($result->[0]) {
1563             return literal_value($result->[0]->to_literal);
1564             } else {
1565             return '';
1566             }
1567             } else {
1568             return literal_value($result->to_literal);
1569             }
1570             }
1571             }
1572              
1573              
1574             # remove nodes matching given XPath from a document and
1575             # remove all their descendants from all nodelists
1576             sub prune {
1577             my ($xp)=@_;
1578             my ($id,$query,$doc)=_xpath($xp);
1579             unless (ref($doc)) {
1580             die "No such document '$id'!\n";
1581             }
1582             my $i=0;
1583              
1584             my $ql=find_nodes($xp);
1585             foreach my $node (@$ql) {
1586             remove_node($node,get_keep_blanks());
1587             $i++;
1588             }
1589             remove_dead_nodes_from_nodelists($doc);
1590             print STDERR "$i node(s) removed from $id=$_files{$id}\n" unless "$QUIET";
1591             return 1;
1592             }
1593              
1594             # evaluate given perl expression
1595             sub eval_substitution {
1596             my ($val,$expr)=@_;
1597             $_ = fromUTF8($QUERY_ENCODING,$val) if defined($val);
1598              
1599             eval "package XML::XSH::Map; no strict 'vars'; $expr";
1600             die $@ if $@; # propagate
1601             return toUTF8($QUERY_ENCODING,$_);
1602             }
1603              
1604             # sort given nodelist according to the given xsh code and perl code
1605             sub perlsort {
1606             my ($crit,$perl,$var)=@_;
1607             $var=expand($var);
1608             return 1 unless (exists($_nodelist{$var}));
1609             return 1 unless ref(my $list=$_nodelist{$var});
1610             my $doc=$list->[0];
1611              
1612             my @list = map {
1613             local $LOCAL_NODE=$_;
1614             local $LOCAL_ID=_find_id($_);
1615             [$_, (ref($crit) eq 'ARRAY') ? eval_xpath_literal($crit) : scalar(perl_eval($crit))]
1616             } @{$list->[1]};
1617              
1618             @{$list->[1]} = map { $_->[0] }
1619             sort {
1620             local $XML::XSH::Map::a = $a->[1];
1621             local $XML::XSH::Map::b = $b->[1];
1622             my $result=eval "package XML::XSH::Map; no strict 'vars'; $perl";
1623             die $@ if ($@); # propagate
1624             $result;
1625             } @list;
1626              
1627             return 1;
1628             }
1629              
1630             # Evaluate given perl expression over every element matching given XPath.
1631             # The element is passed to the expression by its name or value in the $_
1632             # variable.
1633             sub perlmap {
1634             my ($q, $expr)=@_;
1635             my ($id,$query,$doc)=_xpath($q);
1636              
1637             print STDERR "Executing $expr on $query in $id=$_files{$id}\n" if "$DEBUG";
1638             unless ($doc) {
1639             die "No such document $id\n";
1640             }
1641              
1642             my $sdoc=get_local_node($id);
1643              
1644             my $ql=_find_nodes($sdoc, toUTF8($QUERY_ENCODING,$query));
1645             foreach my $node (@$ql) {
1646             if ($_xml_module->is_attribute($node)) {
1647             my $val=$node->getValue();
1648             $node->setValue(eval_substitution("$val",$expr));
1649             } elsif ($_xml_module->is_element($node)) {
1650             my $val=$node->getName();
1651             if ($node->can('setName')) {
1652             $node->setName(eval_substitution("$val",$expr));
1653             } else {
1654             _err "Node renaming not supported by ",ref($node);
1655             }
1656             } elsif ($node->can('setData') and $node->can('getData')) {
1657             my $val=$node->getData();
1658             $node->setData(eval_substitution("$val",$expr));
1659             }
1660             }
1661             return 1;
1662             }
1663              
1664             sub perlrename {
1665             my ($q, $expr)=@_;
1666             my ($id,$query,$doc)=_xpath($q);
1667              
1668             print STDERR "Executing $expr on $query in $id=$_files{$id}\n" if "$DEBUG";
1669             unless ($doc) {
1670             die "No such document $id\n";
1671             }
1672              
1673             my $sdoc=get_local_node($id);
1674              
1675             my $ql=_find_nodes($sdoc, toUTF8($QUERY_ENCODING,$query));
1676             foreach my $node (@$ql) {
1677             if ($_xml_module->is_attribute($node) ||
1678             $_xml_module->is_element($node) ||
1679             $_xml_module->is_pi($node)) {
1680             if ($node->can('setName')) {
1681             my $val=$node->getName();
1682             $node->setName(eval_substitution("$val",$expr));
1683             } else {
1684             _err "Node renaming not supported by ",ref($node);
1685             }
1686             }
1687             }
1688             return 1;
1689             }
1690              
1691             sub set_attr_ns {
1692             my ($node,$ns,$name,$value)=@_;
1693             if ($ns eq "") {
1694             $node->setAttribute($name,$value);
1695             } else {
1696             $node->setAttributeNS("$ns",$name,$value);
1697             }
1698             }
1699              
1700             # return NS prefix used in the given name
1701             sub name_prefix {
1702             if ($_[0]=~/^([^:]+):/) {
1703             return $1;
1704             }
1705             }
1706              
1707             # try to safely clone a node
1708             sub node_copy {
1709             my ($node,$ns,$dest_doc,$dest)=@_;
1710              
1711             my $copy;
1712             if ($_xml_module->is_element($node) and !$node->hasChildNodes) {
1713             # -- prepare NS
1714             $ns=$node->namespaceURI() if ($ns eq "");
1715             if ($ns eq "" and name_prefix($node->getName) ne "") {
1716             $ns=$dest->lookupNamespaceURI(name_prefix($node->getName));
1717             }
1718             # --
1719             $copy=new_element($dest_doc,$node->getName(),$ns,
1720             [map { [$_->nodeName(),$_->nodeValue(), $_->namespaceURI()] } $node->attributes],$dest);
1721             } elsif ($_xml_module->is_document_fragment($node)) {
1722             $copy=$_parser->parse_xml_chunk($node->toString());
1723             } else {
1724             $copy=$_xml_module->clone_node($dest_doc,$node);
1725             }
1726             }
1727              
1728             # get element-children of a node (e.g. of a document fragment)
1729             sub get_subelements {
1730             my ($docfrag)=@_;
1731             return grep { $_xml_module->is_element($_) } $docfrag->childNodes();
1732             }
1733              
1734             sub get_following_siblings {
1735             my ($node)=@_;
1736             my @siblings;
1737             $node=$node->nextSibling();
1738             while ($node) {
1739             push @siblings,$node;
1740             $node=$node->nextSibling();
1741             }
1742             return @siblings;
1743             }
1744              
1745             # create new document element before the given nodelist
1746             sub new_document_element {
1747             my ($doc,$node,@nodelist)=@_;
1748             $doc->setDocumentElement($node);
1749             foreach my $n (reverse @nodelist) {
1750             $doc->removeChild($n);
1751             $doc->insertAfter($n,$node);
1752             }
1753             }
1754              
1755             # safely insert source node after, before or instead of the
1756             # destination node. Safety means here that nodes inserted on the
1757             # document level are given special care. the source node may only be
1758             # a document fragment, element, text, CDATA, Comment, Entity or
1759             # a PI (i.e. not an attribute).
1760              
1761             sub safe_insert {
1762             my ($source,$dest,$where) = @_;
1763             my $parent=$dest->parentNode();
1764             return unless $parent;
1765             if ($_xml_module->is_document($parent)) {
1766              
1767             # placing a node on the document-level
1768             # SOURCE: Element
1769             if ($_xml_module->is_element($source)) {
1770             if ($where eq 'after') {
1771             if ($parent->getDocumentElement()) {
1772             die("Error: cannot insert another element into /:\n",
1773             " there's one document element already!");
1774             } else {
1775             new_document_element($parent,$source,
1776             get_following_siblings($dest));
1777             }
1778             return 'keep';
1779             } elsif ($where eq 'before') {
1780             if ($parent->getDocumentElement()) {
1781             die("Error: cannot insert another element into /:\n",
1782             " there's one document element already!");
1783             } else {
1784             new_document_element($parent,$source,
1785             $dest,get_following_siblings($dest));
1786             }
1787             return 'keep';
1788             } elsif ($where eq 'replace') {
1789             # maybe we are loosing the document element here !
1790             if ($parent->getDocumentElement()) {
1791             if ($_xml_module->is_element($dest)) {
1792             my $nextnode = $parent->getDocumentElement()->nextSibling();
1793             new_document_element($parent,$source,
1794             $dest,get_following_siblings($dest));
1795             } else {
1796             die("Error: cannot insert another element into /:\n",
1797             " there's one document element already!");
1798             }
1799             } else {
1800             new_document_element($parent,$source,
1801             $dest,get_following_siblings($dest));
1802             }
1803             return 'remove';
1804             }
1805             } # SOURCE: PI or Comment or DocFragment with PI's or Comments
1806             elsif ($_xml_module->is_pi($source) ||
1807             $_xml_module->is_comment($source) ||
1808             $_xml_module->is_entity_reference($source) ||
1809             $_xml_module->is_document_fragment($source)) {
1810             # placing a node into an element
1811             if ($where eq 'after') {
1812             $parent->insertAfter($source,$dest);
1813             return 'keep';
1814             } elsif ($where eq 'before') {
1815             $parent->insertBefore($source,$dest);
1816             return 'keep';
1817             } elsif ($where eq 'replace') {
1818             # maybe we are loosing the document element here !
1819             $parent->insertBefore($source,$dest);
1820             return 'remove';
1821             }
1822             } else {
1823             die("Error: cannot insert node ",ref($source)," on a document level");
1824             }
1825             } else {
1826             if ($where eq 'after') {
1827             $parent->insertAfter($source,$dest);
1828             return 'keep';
1829             } elsif ($where eq 'before') {
1830             $parent->insertBefore($source,$dest);
1831             return 'keep';
1832             } elsif ($where eq 'replace') {
1833             $parent->insertBefore($source,$dest);
1834             return 'remove';
1835             }
1836             }
1837             }
1838              
1839             # insert given node to given destination performing
1840             # node-type conversion if necessary
1841             sub insert_node {
1842             my ($node,$dest,$dest_doc,$where,$ns)=@_;
1843              
1844             if ($_xml_module->is_document($node)) {
1845             die "Error: Can't insert/copy/move document nodes!";
1846             }
1847              
1848             # destination: Attribute
1849             if ($_xml_module->is_attribute($dest)) {
1850             # source: Text, CDATA, Comment, Entity, Element
1851             if ($_xml_module->is_text($node) ||
1852             $_xml_module->is_cdata_section($node) ||
1853             $_xml_module->is_comment($node) ||
1854             $_xml_module->is_element($node) ||
1855             $_xml_module->is_pi($node)) {
1856             my $val = $_xml_module->is_element($node) ?
1857             $node->textContent() : $node->getData();
1858             if ($where eq 'replace' or $where eq 'into') {
1859             $val=~s/^\s+|\s+$//g;
1860             # xcopy will replace the value several times, which may not be intended
1861             set_attr_ns($dest->ownerElement(),$dest->namespaceURI(),$dest->getName(),$val);
1862             return 'keep'; # as opposed to 'remove'
1863             } elsif ($where eq 'before' or $where eq 'prepend') {
1864             $val=~s/^\s+//g;
1865             set_attr_ns($dest->ownerElement(),$dest->namespaceURI(),$dest->getName(),
1866             $val.$dest->getValue());
1867             } elsif ($where eq 'after' or $where eq 'append') {
1868             $val=~s/\s+$//g;
1869             set_attr_ns($dest->ownerElement(),$dest->namespaceURI(),$dest->getName(),
1870             $dest->getValue().$val);
1871             }
1872              
1873             }
1874             # source: Attribute
1875             elsif ($_xml_module->is_attribute($node)) {
1876             my $name=$node->getName();
1877             my $value = $node->getValue();
1878             if ($where eq 'replace' or $where eq 'after' or $where eq 'before') {
1879             # -- prepare NS
1880             $ns=$node->namespaceURI() if ($ns eq "");
1881             if ($ns eq "" and name_prefix($name) ne "") {
1882             $ns=$dest->lookupNamespaceURI(name_prefix($name))
1883             }
1884             # --
1885             my $elem=$dest->ownerElement();
1886             set_attr_ns($elem,"$ns",$name,$value);
1887             if ($where eq 'replace' and $name ne $dest->getName()) {
1888             return 'remove'; # remove the destination node in the end
1889             } else {
1890             return 'keep'; # no need to remove the destination node
1891             }
1892             } else {
1893             # -- prepare NS
1894             $ns=$dest->namespaceURI(); # given value of $ns is ignored here
1895             # --
1896             if ($where eq 'append') {
1897             set_attr_ns($dest->ownerElement(),"$ns",$dest->getName,$dest->getValue().$value);
1898             } elsif ($where eq 'into') {
1899             set_attr_ns($dest->ownerElement(),"$ns",$dest->getName(),$value);
1900             } elsif ($where eq 'prepend') {
1901             set_attr_ns($dest->ownerElement(),"$ns",$dest->getName(),$value.$dest->getValue());
1902             }
1903             }
1904             } else {
1905             _err("Warning: Ignoring incompatible nodes in insert/copy/move operation:\n",
1906             ref($node)," $where ",ref($dest),"!");
1907             return 1;
1908             }
1909             }
1910             # destination: Document
1911             elsif ($_xml_module->is_document($dest)) {
1912             # source: Attribute, Text, CDATA
1913             if ($_xml_module->is_attribute($node) or
1914             $_xml_module->is_text($node) or
1915             $_xml_module->is_cdata_section($node)
1916             ) {
1917             _err("Warning: Ignoring incompatible nodes in insert/copy/move operation:\n",
1918             ref($node)," $where ",ref($dest),"!");
1919             return 1;
1920             } elsif ($_xml_module->is_element($node)) {
1921             # source: Element
1922             my $copy=node_copy($node,$ns,$dest_doc,$dest);
1923             my $destnode;
1924             my $newwhere;
1925             if ($where =~ /^(?:after|append|into)/) {
1926             $newwhere='after';
1927             $destnode=$dest->lastChild();
1928             } elsif ($where =~ /^(?:before|prepend)/) {
1929             $newwhere='before';
1930             $destnode=$dest->firstChild();
1931             } elsif ($where eq 'replace') {
1932             _err("Warning: Ignoring incompatible nodes in insert/copy/move operation:\n",
1933             ref($node)," $where ",ref($dest),"!");
1934             return 1;
1935             }
1936             if ($destnode) {
1937             return safe_insert($copy,$destnode,$newwhere);
1938             } else {
1939             new_document_element($dest,$copy);
1940             return 1;
1941             }
1942             } else {
1943             # source: Chunk, PI, Comment, Entity
1944             my $copy=node_copy($node,$ns,$dest_doc,$dest);
1945             if ($where =~ /^(?:after|append|into)/) {
1946             # rather than appendChild which does not work
1947             # for Chunks!
1948             $dest->insertAfter($copy,$dest->lastChild());
1949             } elsif ($where =~ /^(?:before|prepend)/) {
1950             $dest->insertBefore($copy,$dest->firstChild());
1951             } elsif ($where eq 'replace') {
1952             _err("Warning: Ignoring incompatible nodes in insert/copy/move operation:\n",
1953             ref($node)," $where ",ref($dest),"!");
1954             return 1;
1955             }
1956             }
1957             }
1958             # destination: Element
1959             elsif ($_xml_module->is_element($dest)) {
1960             # source: Attribute
1961             if ($_xml_module->is_attribute($node)) {
1962             # -- prepare NS
1963             $ns=$node->namespaceURI() if ($ns eq "");
1964             if ($ns eq "" and name_prefix($node->getName) ne "") {
1965             $ns=$dest->lookupNamespaceURI(name_prefix($node->getName))
1966             }
1967             # --
1968             if ($where eq 'into' or $where eq 'append' or $where eq 'prepend') {
1969             set_attr_ns($dest,"$ns",$node->getName(),$node->getValue());
1970             } elsif ($where eq 'replace') {
1971             my $parent=$dest->parentNode();
1972             if ($_xml_module->is_element($parent)) {
1973             set_attr_ns($dest,"$ns",$node->getName(),$node->getValue());
1974             } else {
1975             _err("Warning: Cannot replace ",ref($node)," with ",ref($parent),
1976             ": parent node is not an element!");
1977             return 1;
1978             }
1979             return 'remove';
1980             } else {
1981             _err("Warning: Ignoring incompatible nodes in insert/copy/move operation:\n",
1982             ref($node)," $where ",ref($dest),"!");
1983             return 1;
1984             # # converting attribute to element
1985             # my $new=new_element($dest_doc,$node->getName(),$ns,$dest);
1986             # $new->appendText($node->getValue());
1987             # my $parent=$dest->parentNode();
1988             # if ($_xml_module->is_element($parent)) {
1989             # if ($where eq 'before' or $where eq 'after') {
1990             # safe_insert($new,$dest,$where);
1991             # }
1992             # } elsif ($where eq 'append') {
1993             # $dest->appendChild($new);
1994             # } elsif ($where eq 'prepend') {
1995             # $dest->insertBefore($new,$dest->firstChild());
1996             # }
1997             }
1998             }
1999             # source: Any but Attribute
2000             else {
2001             my $copy=node_copy($node,$ns,$dest_doc,$dest);
2002             if ($where eq 'after' or $where eq 'before' or $where eq 'replace') {
2003             return safe_insert($copy,$dest,$where);
2004             } elsif ($where eq 'into' or $where eq 'append') {
2005             $dest->appendChild($copy);
2006             } elsif ($where eq 'prepend') {
2007             if ($dest->hasChildNodes()) {
2008             $dest->insertBefore($copy,$dest->firstChild());
2009             } else {
2010             $dest->appendChild($copy);
2011             }
2012             }
2013             }
2014             }
2015             # destination: Text, CDATA, Comment, PI
2016             elsif ($_xml_module->is_text($dest) ||
2017             $_xml_module->is_cdata_section($dest) ||
2018             $_xml_module->is_comment($dest) ||
2019             $_xml_module->is_pi($dest) ||
2020             $_xml_module->is_entity_reference($dest)
2021             ) {
2022             if ($where =~ /^(?:into|append|prepend)$/ and
2023             ($_xml_module->is_entity_reference($dest) ||
2024             $_xml_module->is_entity_reference($node))) {
2025             _err("Warning: Ignoring incompatible nodes in insert/copy/move operation:\n",
2026             ref($node)," $where ",ref($dest),"!");
2027             return 1;
2028             }
2029             if ($where eq 'into') {
2030             my $value=$_xml_module->is_element($node) ?
2031             $node->textContent() : $node->getData();
2032             $dest->setData($value);
2033             } elsif ($where eq 'append') {
2034             my $value=$_xml_module->is_element($node) ?
2035             $node->textContent() : $node->getData();
2036             $dest->setData($dest->getData().$value);
2037             } elsif ($where eq 'prepend') {
2038             my $value=$_xml_module->is_element($node) ?
2039             $node->textContent() : $node->getData();
2040             $dest->setData($value.$dest->getData());
2041             }
2042             # replace + source: Attribute
2043             elsif ($where eq 'replace' and $_xml_module->is_attribute($node)) {
2044             my $parent=$dest->parentNode();
2045             # -- prepare NS
2046             $ns=$node->namespaceURI() if ($ns eq "");
2047             if ($ns eq "" and name_prefix($node->getName) ne "") {
2048             $ns=$dest->lookupNamespaceURI(name_prefix($node->getName));
2049             }
2050             # --
2051             if ($_xml_module->is_element($parent)) {
2052             set_attr_ns($dest,"$ns",$node->getName(),$node->getValue());
2053             }
2054             return 'remove';
2055             } else {
2056             my $parent=$dest->parentNode();
2057             my $new;
2058             # source: Attribute
2059             if ($_xml_module->is_attribute($node)) {
2060             _err("Warning: Ignoring incompatible nodes in insert/copy/move operation:\n",
2061             ref($node)," $where ",ref($dest),"!");
2062             return 1;
2063             # # implicit conversion of attribute to element
2064             # # -- prepare NS
2065             # $ns=$node->namespaceURI() if ($ns eq "");
2066             # if ($ns eq "" and name_prefix($node->getName) ne "") {
2067             # $ns=$parent->lookupNamespaceURI(name_prefix($node->getName));
2068             # }
2069             # # --
2070             # $new=new_element($dest_doc,$node->getName(),$ns,$dest);
2071             # $new->appendText($node->getValue());
2072             }
2073             # source: All other
2074             else {
2075             $new=node_copy($node,$ns,$dest_doc,$dest);
2076             }
2077             if ($where =~ /^(?:after|before|replace)$/) {
2078             return safe_insert($new,$dest,$where);
2079             }
2080             }
2081             } else {
2082             print STDERR "Warning: unsupported/unknown destination type: ",ref($dest),"\n";
2083             }
2084             return 1;
2085             }
2086              
2087             # copy nodes matching one XPath expression to locations determined by
2088             # other XPath expression
2089             sub copy {
2090             my ($fxp,$txp,$where,$all_to_all)=@_;
2091             my ($fid,$fq,$fdoc)=_xpath($fxp); # from xpath
2092             my ($tid,$tq,$tdoc)=_xpath($txp); # to xpath
2093              
2094             unless (ref($fdoc)) {
2095             die "No such document '$fid'!\n";
2096             }
2097             unless (ref($tdoc)) {
2098             die "No such document '$tid'!\n";
2099             }
2100             my ($fl,$tl);
2101              
2102             $fl=find_nodes($fxp);
2103             $tl=find_nodes($txp);
2104              
2105             unless (@$tl) {
2106             print STDERR "No matching nodes found for $tq in $tid=$_files{$tid}\n" unless "$QUIET";
2107             return 0;
2108             }
2109             my $some_nodes_removed=0;
2110             if ($all_to_all) {
2111             foreach my $tp (@$tl) {
2112             my $replace=0;
2113             foreach my $fp (@$fl) {
2114             $replace = ((insert_node($fp,$tp,$tdoc,$where) eq 'remove') || $replace);
2115             }
2116             if ($replace) {
2117             $some_nodes_removed=1;
2118             remove_node($tp);
2119             }
2120             }
2121             } else {
2122             while (ref(my $fp=shift @$fl) and ref(my $tp=shift @$tl)) {
2123             my $replace=insert_node($fp,$tp,$tdoc,$where);
2124             if ($replace eq 'remove') {
2125             $some_nodes_removed=1;
2126             remove_node($tp);
2127             }
2128             }
2129             }
2130             if ($some_nodes_removed) {
2131             remove_dead_nodes_from_nodelists($tdoc);
2132             }
2133             return 1;
2134             }
2135              
2136             # parse a string and create attribute nodes
2137             sub create_attributes {
2138             my ($exp)=@_;
2139             my (@ret,$value,$name);
2140             while ($exp!~/\G$/gsco) {
2141             if ($exp=~/\G\s*([^ \n\r\t=]+)=/gsco) {
2142             my $name=$1;
2143             print STDERR "attribute_name=$1\n" if $DEBUG;
2144             if ($exp=~/\G"((?:[^\\"]|\\.)*)"/gsco or
2145             $exp=~/\G'((?:[^\\']|\\.)*)'/gsco or
2146             $exp=~/\G(.*?\S)(?=\s*[^ \n\r\t=]+=|\s*$)/gsco) {
2147             $value=$1;
2148             $value=~s/\\(.)/$1/g;
2149             print STDERR "creating $name=$value attribute\n" if $DEBUG;
2150             push @ret,[$name,$value];
2151             } else {
2152             $exp=~/\G(\S*\s*)/gsco;
2153             print STDERR "ignoring $name=$1\n";
2154             }
2155             } else {
2156             $exp=~/\G(\S*\s*)/gsco;
2157             print STDERR "ignoring characters $1\n";
2158             }
2159             }
2160             return @ret;
2161             }
2162              
2163             sub new_element {
2164             my ($doc,$name,$ns,$attrs,$dest)=@_;
2165             my $el;
2166             my $prefix;
2167             if ($name=~/^([^:>]+):(.*)$/) {
2168             $prefix=$1;
2169             die "Error: undefined namespace prefix `$prefix'\n" if ($ns eq "");
2170             if ($dest && $_xml_module->is_element($dest)) {
2171             $el=$dest->addNewChild($ns,$name);
2172             $el->unbindNode();
2173             } else {
2174             $el=$doc->createElementNS($ns,$name);
2175             }
2176             } else {
2177             $el=$doc->createElement($name);
2178             }
2179             if (ref($attrs)) {
2180             foreach (@$attrs) {
2181             if ($ns ne "" and ($_->[0]=~/^${prefix}:/)) {
2182             print STDERR "NS: $ns\n" if $DEBUG;
2183             $el->setAttributeNS($ns,$_->[0],$_->[1]);
2184             } elsif ($_->[0] eq "xmlns:(.*)") {
2185             # don't redeclare NS if already declared on destination node
2186             unless ($1 eq $ns or $dest->lookupNamespaceURI($1) eq $_->[2]) {
2187             $el->setAttribute($_->[0],$_->[1]) unless ($_->[1] eq $ns);
2188             }
2189             } elsif ($_->[0]=~/^([^:>]+):/) {
2190             my $lprefix=$1;
2191             if ($_->[2] ne "") {
2192             $el->setAttributeNS($_->[2],$_->[0],$_->[1]);
2193             } else {
2194             # add the attribute anyway (may have wrong qname!)
2195             $el->setAttribute($_->[0],$_->[1]);
2196             }
2197             } else {
2198             next if ($_->[0] eq "xmlns:$prefix" and $_->[1] eq $ns);
2199             $el->setAttribute($_->[0],$_->[1]); # what about other namespaces?
2200             }
2201             }
2202             }
2203             return $el;
2204             }
2205              
2206             # create nodes from their textual representation
2207             sub create_nodes {
2208             my ($type,$exp,$doc,$ns)=@_;
2209             my @nodes=();
2210             # return undef unless ($exp ne "" and ref($doc));
2211             if ($type eq 'attribute') {
2212             foreach (create_attributes($exp)) {
2213             my $at;
2214             if ($_->[0]=~/^([^:]+):/ and $1 ne 'xmlns') {
2215             die "Error: undefined namespace prefix `$1'\n" if ($ns eq "");
2216             $at=$doc->createAttributeNS($ns,$_->[0],$_->[1]);
2217             } else {
2218             $at=$doc->createAttribute($_->[0],$_->[1]);
2219             }
2220             push @nodes,$at;
2221             }
2222             } elsif ($type eq 'element') {
2223             my ($name,$attributes);
2224             if ($exp=~/^\]+)(\s+.*)?(?:\/?\>)?\s*$/) {
2225             print STDERR "element_name=$1\n" if $DEBUG;
2226             print STDERR "attributes=$2\n" if $DEBUG;
2227             my ($elt,$att)=($1,$2);
2228             my $el;
2229             if ($elt=~/^([^:>]+):(.*)$/) {
2230             print STDERR "NS: $ns\n" if $DEBUG;
2231             print STDERR "Name: $elt\n" if $DEBUG;
2232             die "Error: undefined namespace prefix `$1'\n" if ($ns eq "");
2233             $el=$doc->createElementNS($ns,$elt);
2234             } else {
2235             $el=$doc->createElement($elt);
2236             }
2237             if ($att ne "") {
2238             $att=~s/\/?\>?$//;
2239             foreach (create_attributes($att)) {
2240             print STDERR "atribute: ",$_->[0],"=",$_->[1],"\n" if $DEBUG;
2241             if ($elt=~/^([^:]+):/ and $1 ne 'xmlns') {
2242             print STDERR "NS: $ns\n" if $DEBUG;
2243             die "Error: undefined namespace prefix `$1'\n" if ($ns eq "");
2244             $el->setAttributeNS($ns,$_->[0],$_->[1]);
2245             } else {
2246             $el->setAttribute($_->[0],$_->[1]);
2247             }
2248             }
2249             }
2250             push @nodes,$el;
2251             } else {
2252             print STDERR "invalid element $exp\n" unless "$QUIET";
2253             }
2254             } elsif ($type eq 'text') {
2255             push @nodes,$doc->createTextNode($exp);
2256             print STDERR "text=$exp\n" if $DEBUG;
2257             } elsif ($type eq 'entity_reference') {
2258             push @nodes,$doc->createEntityReference($exp);
2259             print STDERR "entity_reference=$exp\n" if $DEBUG;
2260             } elsif ($type eq 'cdata') {
2261             push @nodes,$doc->createCDATASection($exp);
2262             print STDERR "cdata=$exp\n" if $DEBUG;
2263             } elsif ($type eq 'pi') {
2264             my ($name,$data)=($exp=~/^\s*(?:\<\?)?(\S+)(?:\s+(.*?)(?:\?\>)?)?$/);
2265             my $pi = $doc->createProcessingInstruction($name);
2266             $pi->setData($data);
2267             print STDERR "pi=\n" if $DEBUG;
2268             push @nodes,$pi;
2269             # print STDERR "cannot add PI yet\n" if $DEBUG;
2270             } elsif ($type eq 'comment') {
2271             push @nodes,$doc->createComment($exp);
2272             print STDERR "comment=$exp\n" if $DEBUG;
2273             }
2274             return @nodes;
2275             }
2276              
2277             # create new nodes from an expression and insert them to locations
2278             # identified by XPath
2279             sub insert {
2280             my ($type,$exp,$xpath,$where,$ns,$to_all)=@_;
2281              
2282             $exp = expand($exp);
2283             $ns = expand($ns);
2284              
2285             my ($tid,$tq,$tdoc)=_xpath($xpath); # destination(s)
2286              
2287             return 0 unless ref($tdoc);
2288              
2289             my @nodes;
2290             $ns=toUTF8($QUERY_ENCODING,$ns);
2291             unless ($type eq 'chunk') {
2292             $exp=toUTF8($QUERY_ENCODING,$exp);
2293             @nodes=grep {ref($_)} create_nodes($type,$exp,$tdoc,$ns);
2294             return unless @nodes;
2295             } else {
2296             if ($exp !~/^\s*]*encoding=[^>]*?>/) {
2297             $exp=toUTF8($QUERY_ENCODING,$exp);
2298             }
2299             @nodes=grep {ref($_)} ($_parser->parse_xml_chunk($exp));
2300             }
2301             my $tl=find_nodes($xpath);
2302             my $some_nodes_removed=0;
2303             if ($to_all) {
2304             foreach my $tp (@$tl) {
2305             my $replace=0;
2306             foreach my $node (@nodes) {
2307             $replace = (insert_node($node,$tp,$tdoc,$where) eq 'remove') || $replace;
2308             }
2309             if ($replace) {
2310             $some_nodes_removed=1;
2311             remove_node($tp);
2312             }
2313             }
2314             } elsif ($tl->[0]) {
2315             foreach my $node (@nodes) {
2316             if (ref($tl->[0])) {
2317             if (insert_node($node,$tl->[0],$tdoc,$where) eq 'remove') {
2318             $some_nodes_removed=1;
2319             remove_node($tl->[0]);
2320             }
2321             }
2322             }
2323             }
2324             if ($some_nodes_removed) {
2325             remove_dead_nodes_from_nodelists($tdoc);
2326             }
2327             return 1;
2328             }
2329              
2330             # normalize nodes
2331             sub normalize_nodes {
2332             my ($xp)=@_;
2333             my ($id,$query,$doc)=_xpath($xp);
2334              
2335             print STDERR "normalizing $query from $id=$_files{$id}\n\n" if "$DEBUG";
2336             unless (ref($doc)) {
2337             die "No such document '$id'!\n";
2338             }
2339             my $ql=find_nodes($xp);
2340             foreach (@$ql) {
2341             $_->normalize();
2342             }
2343             return 1;
2344             }
2345              
2346             sub _trim_ws {
2347             my ($text)=@_;
2348             $text=~s/^\s*//;
2349             $text=~s/\s*$//;
2350             return $text;
2351             }
2352              
2353             # strip whitespace from given nodes
2354             sub strip_ws {
2355             my ($xp)=@_;
2356             my ($id,$query,$doc)=_xpath($xp);
2357              
2358             print STDERR "stripping whitespace in $query from $id=$_files{$id}\n\n" if "$DEBUG";
2359             unless (ref($doc)) {
2360             die "No such document '$id'!\n";
2361             }
2362             my $ql=find_nodes($xp);
2363             foreach my $node (@$ql) {
2364             if ($_xml_module->is_text($node)
2365             or
2366             $_xml_module->is_cdata_section($node)
2367             or
2368             $_xml_module->is_comment($node)
2369             ) {
2370             my $data=_trim_ws($node->getData());
2371             if ($data ne "") {
2372             $node->setData($data);
2373             } else {
2374             $node->unbindNode();
2375             }
2376             } elsif ($_xml_module->is_pi($node)) {
2377             $node->setData(_trim_ws($node->getData($node)));
2378             } elsif ($_xml_module->is_attribute($node)) {
2379             $node->setValue(_trim_ws($node->getValue));
2380             } elsif ($_xml_module->is_element($node) or
2381             $_xml_module->is_document($node)) {
2382             # traverse children, skip comments, strip text nodes
2383             # until first element or PI or text node containing
2384             # a non-ws character
2385             my $child=$node->firstChild();
2386             while ($child) {
2387             if ($_xml_module->is_text($child) or
2388             $_xml_module->is_cdata_section($child)) {
2389             my $data=_trim_ws($child->getData());
2390             if ($data ne "") {
2391             $child->setData($data);
2392             last;
2393             } else {
2394             $child->unbindNode();
2395             }
2396             } elsif ($_xml_module->is_element($child) or
2397             $_xml_module->is_pi($child)) {
2398             last;
2399             }
2400             $child=$child->nextSibling();
2401             }
2402             # traverse children (upwards), skip comments, strip text nodes
2403             # until first element or PI or text node containing a non-ws
2404             # character
2405             my $child=$node->lastChild();
2406             while ($child) {
2407             if ($_xml_module->is_text($child) or
2408             $_xml_module->is_cdata_section($child)) {
2409             my $data=_trim_ws($child->getData());
2410             if ($data ne "") {
2411             $child->setData($data);
2412             last;
2413             } else {
2414             $child->unbindNode();
2415             }
2416             } elsif ($_xml_module->is_element($child) or
2417             $_xml_module->is_pi($child)) {
2418             last;
2419             }
2420             $child=$child->previousSibling();
2421             }
2422             }
2423             }
2424             return 1;
2425             }
2426              
2427             # fetch document's DTD
2428             sub get_dtd {
2429             my ($doc)=@_;
2430             my $dtd;
2431             $dtd=$_xml_module->get_dtd($doc,$QUIET);
2432              
2433             return $dtd;
2434             }
2435              
2436             # check document validity
2437             sub validate_doc {
2438             my ($show_errors,$schema,$id)=@_;
2439             $id=expand $id;
2440             __debug("SCHEMA @$schema");
2441             my @schema = expand @$schema;
2442             __debug("SCHEMA @schema");
2443             ($id,my $doc)=_id($id);
2444             unless (ref($doc)) {
2445             die "No such document '$id' (to validate)!\n";
2446             }
2447              
2448             if ($doc->can('is_valid')) {
2449             if (@schema) {
2450             my $type = shift @schema;
2451             my $format = shift @schema;
2452             if ($type eq 'DTD') {
2453             my $dtd;
2454             eval { XML::LibXML::Dtd->can('new') } ||
2455             die "DTD validation not supported by your version of XML::LibXML\n";
2456             if ($format eq 'FILE') {
2457             __debug("PUBLIC $schema[0], SYSTEM $schema[1]");
2458             $dtd=XML::LibXML::Dtd->new(@schema);
2459             __debug($dtd);
2460             } elsif ($format eq 'STRING') {
2461             __debug("STRING $schema[0]");
2462             $dtd=XML::LibXML::Dtd->parse_string($schema[0]);
2463             __debug($dtd);
2464             __debug($dtd->toString());
2465             } else {
2466             die "Unknown DTD format '$format!'\n";
2467             }
2468             if ($show_errors) {
2469             $doc->validate($dtd);
2470             } else {
2471             out(($doc->is_valid($dtd) ? "yes\n" : "no\n"));
2472             }
2473             } elsif ($type eq 'RNG') {
2474             eval { XML::LibXML::RelaxNG->can('new') } ||
2475             die "RelaxNG validation not supported by your version of XML::LibXML\n";
2476             my $rng;
2477             if ($format eq 'FILE') {
2478             $rng=XML::LibXML::RelaxNG->new(location => $schema[0]);
2479             } elsif ($format eq 'STRING') {
2480             $rng=XML::LibXML::RelaxNG->new(string => $schema[0]);
2481             } elsif ($format eq 'DOC') {
2482             my $rngdoc=_doc($schema[0]);
2483             unless (ref($rngdoc)) {
2484             die "No such document '$schema[0]'!\n";
2485             }
2486             $rng=XML::LibXML::RelaxNG->new(DOM => $rngdoc);
2487             } else {
2488             die "Unknown RelaxNG format '$format!'\n";
2489             }
2490             eval { $rng->validate($doc) };
2491             if ($show_errors) {
2492             die "$@\n";
2493             } else {
2494             out($@ ? "no\n" : "yes\n");
2495             }
2496             } elsif ($type eq 'XSD') {
2497             eval { XML::LibXML::Schema->can('new') } ||
2498             die "Schema validation not supported by your version of XML::LibXML\n";
2499             my $xsd;
2500             if ($format eq 'FILE') {
2501             $xsd=XML::LibXML::Schema->new(location => $schema[0]);
2502             } elsif ($format eq 'STRING') {
2503             $xsd=XML::LibXML::Schema->new(string => $schema[0]);
2504             } elsif ($format eq 'DOC') {
2505             my $xsddoc=_doc($schema[0]);
2506             unless (ref($xsddoc)) {
2507             die "No such document '$schema[0]'!\n";
2508             }
2509             $xsd=XML::LibXML::Schema->new(string => $xsddoc->toString());
2510             } else {
2511             die "Unknown Schema format '$format!'\n";
2512             }
2513             eval { $xsd->validate($doc) };
2514             if ($show_errors) {
2515             die "$@\n";
2516             } else {
2517             out($@ ? "no\n" : "yes\n");
2518             }
2519             }
2520             } else {
2521             if ($show_errors) {
2522             $doc->validate();
2523             } else {
2524             out(($doc->is_valid() ? "yes\n" : "no\n"));
2525             }
2526             }
2527             } else {
2528             die("Vaidation not supported by ",ref($doc));
2529             }
2530             return 1;
2531             }
2532              
2533             # process XInclude elements in a document
2534             sub process_xinclude {
2535             my ($id)=expand @_;
2536             ($id, my $doc)=_id($id);
2537             unless (ref($doc)) {
2538             die "No such document '$id'!\n";
2539             }
2540             $_xml_module->doc_process_xinclude($_parser,$doc);
2541             return 1;
2542             }
2543              
2544             # print document's DTD
2545             sub list_dtd {
2546             my ($id)=expand @_;
2547             ($id, my $doc)=_id($id);
2548             unless (ref($doc)) {
2549             die "No such document '$id'!\n";
2550             }
2551             my $dtd=get_dtd($doc);
2552              
2553             if ($dtd) {
2554             out(fromUTF8($ENCODING,$_xml_module->toStringUTF8($dtd)),"\n");
2555             }
2556             return 1;
2557             }
2558              
2559             # print document's encoding
2560             sub print_enc {
2561             my ($id)=expand @_;
2562             ($id, my $doc)=_id($id);
2563             unless (ref($doc)) {
2564             die "No such document '$id'!\n";
2565             }
2566             out($_xml_module->doc_encoding($doc),"\n");
2567             return 1;
2568             }
2569              
2570             sub set_doc_enc {
2571             my ($encoding,$id)=expand @_;
2572             ($id, my $doc)=_id($id);
2573             unless (ref($doc)) {
2574             die "No such document '$id'!\n";
2575             }
2576             $_xml_module->set_encoding($doc,$encoding);
2577             return 1;
2578             }
2579              
2580             sub set_doc_standalone {
2581             my ($standalone,$id)=expand @_;
2582             ($id, my $doc)=_id($id);
2583             unless (ref($doc)) {
2584             die "No such document '$id'!\n";
2585             }
2586             $standalone=1 if $standalone=~/yes/i;
2587             $standalone=0 if $standalone=~/no/i;
2588             $_xml_module->set_standalone($doc,$standalone);
2589             return 1;
2590             }
2591              
2592             sub doc_info {
2593             my ($id)=expand @_;
2594             ($id, my $doc)=_id($id);
2595             unless (ref($doc)) {
2596             die "No such document '$id'!\n";
2597             }
2598             out("type=",$doc->nodeType,"\n");
2599             out("version=",$doc->version(),"\n");
2600             out("encoding=",$doc->encoding(),"\n");
2601             out("standalone=",$doc->standalone(),"\n");
2602             out("compression=",$doc->compression(),"\n");
2603             }
2604              
2605             # create an identical copy of a document
2606             sub clone {
2607             my ($id1,$id2)=@_;
2608             ($id2, my $doc)=_id(expand $id2);
2609              
2610             return if ($id2 eq "" or $id2 eq "" or !ref($doc));
2611             print STDERR "duplicating $id2=$_files{$id2}\n" unless "$QUIET";
2612              
2613             set_doc($id1,$_xml_module->parse_string($_parser,
2614             $doc->toString($INDENT)),
2615             $_files{$id2});
2616             print STDERR "done.\n" unless "$QUIET";
2617             return 1;
2618             }
2619              
2620             # test if $nodea is an ancestor of $nodeb
2621             sub is_ancestor_or_self {
2622             my ($nodea,$nodeb)=@_;
2623             while ($nodeb) {
2624             if ($_xml_module->xml_equal($nodea,$nodeb)) {
2625             return 1;
2626             }
2627             $nodeb=tree_parent_node($nodeb);
2628             }
2629             }
2630              
2631             # remove node and all its surrounding whitespace textual siblings
2632             # from a document; remove all its descendant from all nodelists
2633             # change current element to the nearest ancestor
2634             sub remove_node {
2635             my ($node,$trim_space)=@_;
2636             if (is_ancestor_or_self($node,$LOCAL_NODE)) {
2637             $LOCAL_NODE=tree_parent_node($node);
2638             }
2639             my $doc;
2640             $doc=$_xml_module->owner_document($node);
2641             if ($trim_space) {
2642             my $sibling=$node->nextSibling();
2643             if ($sibling and
2644             $_xml_module->is_text($sibling) and
2645             $sibling->getData =~ /^\s+$/) {
2646             # remove_node_from_nodelists($sibling,$doc);
2647             $_xml_module->remove_node($sibling);
2648             }
2649             }
2650             # remove_node_from_nodelists($node,$doc);
2651             $_xml_module->remove_node($node);
2652             }
2653              
2654             # move nodes matching one XPath expression to locations determined by
2655             # other XPath expression
2656             sub move {
2657             my ($xp)=@_; #source xpath
2658             my ($id,$query,$doc)= _xpath($xp);
2659             my $sourcenodes;
2660             unless (ref($doc)) {
2661             die "No such document '$id'!\n";
2662             }
2663             my $i=0;
2664             $sourcenodes=find_nodes($xp);
2665             if (copy(@_)) {
2666             foreach my $node (@$sourcenodes) {
2667             remove_node($node);
2668             $i++;
2669             }
2670             if ($i) {
2671             remove_dead_nodes_from_nodelists($doc);
2672             }
2673             return 1;
2674             } else {
2675             return 0;
2676             }
2677             }
2678              
2679             # call a shell command and print out its output
2680             sub sh {
2681             my $cmd=expand($_[0]);
2682             out(`$cmd`);
2683             return 1;
2684             }
2685              
2686             # print the result of evaluating an XPath expression in scalar context
2687             sub print_count {
2688             my $count=count(@_);
2689             out("$count\n");
2690             return 1;
2691             }
2692              
2693             sub perl_eval {
2694             if (wantarray) {
2695             my @result=eval("package XML::XSH::Map; no strict 'vars'; $_[0]");
2696             die $@ if $@;
2697             return @result;
2698             } else {
2699             my $result=eval("package XML::XSH::Map; no strict 'vars'; $_[0]");
2700             die $@ if $@;
2701             return $result;
2702             }
2703             }
2704              
2705             # evaluate a perl expression
2706             # (OBSOLETE! and print out the result)
2707             sub print_eval {
2708             my ($expr)=@_;
2709             my $result=perl_eval($expr);
2710             # out("$result\n") unless "$QUIET";
2711             return 1;
2712             }
2713              
2714             # change current directory
2715             sub cd {
2716             unless (chdir $_[0]) {
2717             print STDERR "Can't change directory to $_[0]\n";
2718             return 0;
2719             } else {
2720             print "$_[0]\n" unless "$QUIET";
2721             }
2722             return 1;
2723             }
2724              
2725             # call methods from a list
2726             sub run_commands {
2727             return 0 unless ref($_[0]) eq "ARRAY";
2728             my @cmds=@{$_[0]};
2729             my $top_level=$_[1];
2730             my $trapsignals=$top_level;
2731             my $result=0;
2732              
2733             my ($cmd,@params);
2734              
2735             # make sure errors throw exceptions
2736             local $_die_on_err=1 unless ($top_level);
2737              
2738             store_variables(1);
2739             eval {
2740             local $SIG{INT}=\&sigint if $trapsignals;
2741             local $SIG{PIPE}=\&sigpipe if $trapsignals;
2742             foreach my $run (@cmds) {
2743             if (ref($run) eq 'ARRAY') {
2744             ($cmd,@params)=@$run;
2745             if ($cmd eq "test-mode") { $TEST_MODE=1; $result=1; next; }
2746             if ($cmd eq "run-mode") { $TEST_MODE=0; $result=1; next; }
2747             next if $TEST_MODE;
2748             $result=&{$cmd}(@params);
2749             } else {
2750             $result=1;
2751             }
2752             }
2753             };
2754             do {
2755             local $SIG{INT}=\&flagsigint;
2756             restore_variables();
2757             propagate_flagsigint();
2758             };
2759             if (!$trapsignals and $@ =~ /^SIGINT|^SIGPIPE/) {
2760             die $@
2761             } else {
2762             _check_err($@,1);
2763             }
2764             return $result;
2765             }
2766              
2767             # redirect output and call methods from a list
2768             sub pipe_command {
2769             return 1 if $TEST_MODE;
2770              
2771             local $SIG{PIPE}=sub { };
2772             my ($cmd,$pipe)=@_;
2773              
2774             return 0 unless (ref($cmd) eq 'ARRAY');
2775              
2776             if ($pipe ne '') {
2777             my $out=$OUT;
2778             local *PIPE;
2779             print STDERR "openning pipe $pipe\n" if $DEBUG;
2780             eval {
2781             open(PIPE,"| $pipe") || die "cannot open pipe $pipe\n";
2782             $OUT=\*PIPE;
2783             run_commands($cmd);
2784             };
2785             do {
2786             local $SIG{INT}=\&flagsigint;
2787             $OUT=$out;
2788             close PIPE;
2789             propagate_flagsigint();
2790             };
2791             die $@ if $@; # propagate
2792             }
2793             return 1;
2794             }
2795              
2796             # redirect output to a string and call methods from a list
2797             sub string_pipe_command {
2798             my ($cmd,$name)=@_;
2799             return 0 unless (ref($cmd) eq 'ARRAY');
2800             if ($name ne '') {
2801             my $out=$OUT;
2802             print STDERR "Pipe to $name\n" if $DEBUG;
2803             $OUT=new IO::MyString;
2804             eval {
2805             run_commands($cmd);
2806             };
2807             do {
2808             local $SIG{INT}=\&flagsigint;
2809             _assign($name,$OUT->value()) unless $@;
2810             $OUT=$out;
2811             propagate_flagsigint();
2812             };
2813             die $@ if $@; # propagate
2814             }
2815             return 0;
2816             }
2817              
2818              
2819             # call methods as long as given XPath returns positive value
2820             sub while_statement {
2821             my ($xp,$command)=@_;
2822             my $result=1;
2823             if (ref($xp) eq 'ARRAY') {
2824             while (count($xp)) {
2825             eval {
2826             $result = run_commands($command) && $result;
2827             };
2828             if (ref($@) and $@->isa('XML::XSH::Internal::LoopTerminatingException')) {
2829             if ($@->label =~ /^(?:next|last|redo)$/ and $@->[1]>1) {
2830             $@->[1]--;
2831             die $@; # propagate to a higher level
2832             }
2833             if ($@->label eq 'next') {
2834             next;
2835             } elsif ($@->label eq 'last') {
2836             last;
2837             } elsif ($@->label eq 'redo') {
2838             redo;
2839             } else {
2840             die $@; # propagate
2841             }
2842             } elsif ($@) {
2843             die $@; # propagate
2844             }
2845             }
2846             } else {
2847             while (perl_eval($xp)) {
2848             eval {
2849             $result = run_commands($command) && $result;
2850             };
2851             if (ref($@) and $@->isa('XML::XSH::Internal::LoopTerminatingException')) {
2852             if ($@->label =~ /^(?:next|last|redo)$/ and $@->[1]>1) {
2853             $@->[1]--;
2854             die $@; # propagate to a higher level
2855             }
2856             if ($@->label eq 'next') {
2857             next;
2858             } elsif ($@->label eq 'last') {
2859             last;
2860             } elsif ($@->label eq 'redo') {
2861             redo;
2862             } else {
2863             die $@; # propagate
2864             }
2865             } elsif ($@) {
2866             die $@; # propagate
2867             }
2868             }
2869             }
2870             return $result;
2871             }
2872              
2873             sub throw_exception {
2874             die expand($_[0])."\n";
2875             }
2876              
2877             sub try_catch {
2878             my ($try,$catch,$var)=@_;
2879             eval {
2880             local $TRAP_SIGPIPE=1;
2881             local $SIG{INT}=\&sigint;
2882             local $SIG{PIPE}=\&sigpipe;
2883             # local $_die_on_err=1; # make sure errors cause an exception
2884             run_commands($try);
2885             };
2886             if (ref($@) and $@->isa('XML::XSH::Internal::UncatchableException')) {
2887             die $@; # propagate
2888             } elsif ($@) {
2889             if ($@ =~ /^SIGINT/) {
2890             die $@; # propagate sigint
2891             } else {
2892             chomp($@) unless ref($@);
2893             if (ref($var) and @{$var}>1) {
2894             store_variables(1,$var->[0]);
2895             _assign($var->[0],$@);
2896             eval {
2897             run_commands($catch);
2898             };
2899             do {
2900             local $SIG{INT}=\&flagsigint;
2901             restore_variables();
2902             propagate_flagsigint();
2903             };
2904             die $@ if $@; # propagate
2905             } else {
2906             _assign($var->[0],$@) if ref($var);
2907             run_commands($catch);
2908             }
2909             }
2910             }
2911             }
2912              
2913             sub loop_next {
2914             die XML::XSH::Internal::LoopTerminatingException->new('next',expand(@_));
2915             }
2916             sub loop_prev {
2917             die XML::XSH::Internal::LoopTerminatingException->new('prev',expand(@_));
2918             }
2919             sub loop_redo {
2920             die XML::XSH::Internal::LoopTerminatingException->new('redo',expand(@_));
2921             }
2922             sub loop_last {
2923             die XML::XSH::Internal::LoopTerminatingException->new('last',expand(@_));
2924             }
2925              
2926             # call methods on every node matching an XPath
2927             sub foreach_statement {
2928             my ($xp,$command)=@_;
2929             if (ref($xp) eq 'ARRAY') {
2930             my ($id,$query,$doc)=_xpath($xp);
2931             unless (ref($doc)) {
2932             die "No such document '$id'!\n";
2933             }
2934             my $old_local=$LOCAL_NODE;
2935             my $old_id=$LOCAL_ID;
2936             eval {
2937             my $ql=find_nodes($xp);
2938             foreach my $node (@$ql) {
2939             $LOCAL_NODE=$node;
2940             $LOCAL_ID=_find_id($node);
2941             eval {
2942             run_commands($command);
2943             };
2944             if (ref($@) and $@->isa('XML::XSH::Internal::LoopTerminatingException')) {
2945             if ($@->label =~ /^(?:next|last|redo)$/ and $@->[1]>1) {
2946             $@->[1]--;
2947             die $@; # propagate to a higher level
2948             }
2949             if ($@->label eq 'next') {
2950             next;
2951             } elsif ($@->label eq 'last') {
2952             last;
2953             } elsif ($@->label eq 'redo') {
2954             redo;
2955             } else {
2956             die $@; # propagate
2957             }
2958             } elsif ($@) {
2959             die $@; # propagate
2960             }
2961             }
2962             };
2963             do {
2964             local $SIG{INT}=\&flagsigint;
2965             $LOCAL_NODE=$old_local;
2966             $LOCAL_ID=$old_id;
2967             propagate_flagsigint();
2968             };
2969             die $@ if $@; # propagate
2970             } else {
2971             foreach $XML::XSH::Map::__ (perl_eval($xp)) {
2972             eval {
2973             run_commands($command);
2974             };
2975             if (ref($@) and $@->isa('XML::XSH::Internal::LoopTerminatingException')) {
2976             if ($@->label =~ /^(?:next|last|redo)$/ and $@->[1]>1) {
2977             $@->[1]--;
2978             die $@; # propagate to a higher level
2979             }
2980             if ($@->label eq 'next') {
2981             next;
2982             } elsif ($@->label eq 'last') {
2983             last;
2984             } elsif ($@->label eq 'redo') {
2985             redo;
2986             } else {
2987             die $@; # propagate
2988             }
2989             } elsif ($@) {
2990             die $@; # propagate
2991             }
2992             }
2993             }
2994             return 1;
2995             }
2996              
2997             # run commands if given XPath holds
2998             sub if_statement {
2999             my @cases=@_;
3000             # print STDERR "Parsed $xp\n";
3001             foreach (@cases) {
3002             my ($xp,$command)=@$_;
3003             if (!defined($xp) or
3004             (ref($xp) eq 'ARRAY') && count($xp) ||
3005             !ref($xp) && perl_eval($xp)) {
3006             return run_commands($command);
3007             }
3008             }
3009             return 1;
3010             }
3011              
3012             # run commands unless given XPath holds
3013             sub unless_statement {
3014             my ($xp,$command,$else)=@_;
3015             unless ((ref($xp) eq 'ARRAY')&&count($xp) ||
3016             !ref($xp) && perl_eval($xp)) {
3017             return run_commands($command);
3018             } else {
3019             return ref($else) ? run_commands($else->[1]) : 1;
3020             }
3021             }
3022              
3023             # transform a document with an XSLT stylesheet
3024             # and create a new document from the result
3025             sub xslt {
3026             my ($id,$stylefile,$newid)=expand @_[0..2];
3027             $id=_id($id);
3028             my $params=$_[3];
3029             print STDERR "running xslt on @_\n" if "$DEBUG";
3030             return unless $_doc{$id};
3031             my %params;
3032             %params=map { expand($_) } map { @$_ } @$params if ref($params);
3033             if ($DEBUG) {
3034             print STDERR map { "$_ -> $params{$_} " } keys %params;
3035             print STDERR "\n";
3036             }
3037              
3038             if ((-f $stylefile) or
3039             ($stylefile=~/^[a-z]+:/)) {
3040             require XML::LibXSLT;
3041              
3042             local *SAVE;
3043              
3044             my $_xsltparser=XML::LibXSLT->new();
3045             my $st=$_xsltparser->parse_stylesheet_file($stylefile);
3046             $stylefile=~s/\..*$//;
3047             my $doc=$st->transform($_doc{$id},%params);
3048             set_doc($newid,$doc,
3049             "$stylefile"."_transformed_".$_files{$id});
3050             } else {
3051             die "File not exists $stylefile\n";
3052             }
3053             return 1;
3054             }
3055              
3056             # perform xupdate processing over a document
3057             sub xupdate {
3058             my ($xupdate_id,$id)=expand(@_);
3059             $id=_id($id);
3060             if (get_doc($xupdate_id) and get_doc($id)) {
3061             require XML::XUpdate::LibXML;
3062             require XML::Normalize::LibXML;
3063             my $xupdate = XML::XUpdate::LibXML->new();
3064             $XML::XUpdate::LibXML::debug=1;
3065             $xupdate->process(get_doc($id)->getDocumentElement(),get_doc($xupdate_id));
3066             } else {
3067             if (get_doc($xupdate_id)) {
3068             die "No such document $id\n";
3069             } else {
3070             die "No such document $xupdate_id\n";
3071             }
3072             return 0;
3073             }
3074             }
3075              
3076             sub call_return { die XML::XSH::Internal::SubTerminatingException->new('return'); }
3077              
3078             # call a named set of commands
3079             sub call {
3080             my ($name,$args)=@_;
3081             $name=expand($name);
3082             if (exists $_defs{$name}) {
3083             my @vars=();
3084             if (ref($args)) {
3085             @vars=@{ $_defs{$name} };
3086             shift @vars;
3087             }
3088             my $result;
3089             store_variables(1,@vars);
3090             eval {
3091             if (ref($args)) {
3092             my $var;
3093             foreach (@$args) {
3094             $var=shift @vars;
3095             if (defined($var)) {
3096             if ($var =~ /^\$/) {
3097             _assign($var,expand($_)); # string assignment
3098             } elsif ($var =~ /^\%(.*)$/) {
3099             local $QUIET=1;
3100             nodelist_assign($1,$_); # nodelist assignment
3101             }
3102             }
3103             }
3104             }
3105             $result = run_commands($_defs{$name}->[0]);
3106             };
3107             do {
3108             local $SIG{INT}=\&flagsigint;
3109             restore_variables() if (ref($args));
3110             propagate_flagsigint();
3111             };
3112             if (ref($@) and $@->isa('XML::XSH::Internal::SubTerminatingException')) {
3113             undef $@;
3114             return 1;
3115             }
3116             die $@ if $@; # propagate
3117             return $result;
3118             } else {
3119             die "ERROR: $name not defined\n";
3120             }
3121             }
3122              
3123              
3124             sub undef_sub {
3125             my ($name)=@_;
3126             if (exists($_defs{$name})) {
3127             delete $_defs{$name};
3128             } else {
3129             foreach (keys %_defs) {
3130             delete $_defs{$_} if /^$name$/;
3131             }
3132             }
3133             }
3134              
3135             # define a named set of commands
3136             sub def {
3137             my ($name,$block,$args)=@_;
3138             my ($command)=@$block;
3139             if (exists($_defs{$name})) {
3140             my ($prevcmd, @prevargs)=@{$_defs{$name}};
3141             if ($prevcmd) {
3142             _err "Error: Subroutine $name already defined!";
3143             return 0;
3144             } elsif (!$command) {
3145             _err "Error: Subroutine $name already pre-declared!";
3146             return 0;
3147             } else {
3148             if (@$args != @prevargs) {
3149             _err "Error: Different number of arguments in declaration and pre-declarartion of $name!";
3150             return 0;
3151             }
3152             my $parg;
3153             foreach (@$args) {
3154             $parg=shift @prevargs;
3155             if (substr($parg,0,1) ne substr($_,0,1)) {
3156             _err "Error: Argument types of $_ and $parg in declarations of $name do not match!";
3157             return 0;
3158             }
3159             }
3160             }
3161             }
3162             $_defs{$name} = [ $command, @$args ];
3163             return 1;
3164             }
3165              
3166             # return a list of all definined subroutines
3167             sub defs {
3168             return sort keys %_defs;
3169             }
3170              
3171             # list all defined subroutines
3172             sub list_defs {
3173             foreach (sort keys (%_defs)) {
3174             out(join(" ",$_,@{ $_defs{$_} }[1..$#{ $_defs{$_} }] ),"\n" );
3175             }
3176             return 1;
3177             }
3178              
3179             # load a file
3180             sub load {
3181             my ($file)=@_;
3182             my $l;
3183             print STDERR "loading file $file\n" unless "$QUIET";
3184             local *F;
3185             if (open F,"$file") {
3186             return join "",;
3187             } else {
3188             die "ERROR: couldn't open input file $file";
3189             }
3190             }
3191              
3192             # call XSH to evaluate commands from a given file
3193             sub include {
3194             my $f=expand(shift);
3195             my $conditionally = shift;
3196             if (!$conditionally || !$_includes{$f}) {
3197             $_includes{$f}=1;
3198             my $l=load($f);
3199             return $_xsh->startrule($l);
3200             }
3201             }
3202              
3203             # print help
3204             sub help {
3205             my ($command)=expand @_;
3206             if ($command) {
3207             if (exists($XML::XSH::Help::HELP{$command})) {
3208             out($XML::XSH::Help::HELP{$command}->[0]);
3209             } else {
3210             my @possible =
3211             grep { index($_,$command)==0 }
3212             keys(%XML::XSH::Help::HELP);
3213             my %h = map { $XML::XSH::Help::HELP{$_} => $_ } @possible;
3214             if (keys(%h) == 1) {
3215             out($XML::XSH::Help::HELP{$possible[0]}->[0]);
3216             return 1;
3217             } elsif (keys(%h) > 1) {
3218             out("No help available on $command\n");
3219             out("Did you mean some of ", join(', ',@possible)," ?\n");
3220             } else {
3221             out("No help available on $command\n");
3222             return 0;
3223             }
3224             }
3225             } else {
3226             out($XML::XSH::Help::HELP);
3227             }
3228             return 1;
3229             }
3230              
3231             # load catalog file to the parser
3232             sub load_catalog {
3233             $_xml_module->load_catalog($_parser,expand($_[0]));
3234             return 1;
3235             }
3236              
3237             sub stream_process_node {
3238             my ($node,$command,$input,$id)=@_;
3239             set_doc($id,$_xml_module->owner_document($node),$input);
3240             my $old_local=$LOCAL_NODE;
3241             my $old_id=$LOCAL_ID;
3242             eval {
3243             foreach (1) {
3244             $LOCAL_NODE=$node;
3245             $LOCAL_ID=$id;
3246             eval {
3247             run_commands($command);
3248             };
3249             if (ref($@) and $@->isa('XML::XSH::Internal::LoopTerminatingException')) {
3250             if ($@->label =~ /^(?:next|redo)$/ and $@->[1]>1) {
3251             $@->[1]--;
3252             die $@; # propagate to a higher level
3253             }
3254             if ($@->label eq 'next') {
3255             last;
3256             } elsif ($@->label eq 'redo') {
3257             redo;
3258             } else {
3259             die $@; # propagate
3260             }
3261             } elsif ($@) {
3262             die $@; # propagate
3263             }
3264             }
3265             };
3266             do {
3267             local $SIG{INT}=\&flagsigint;
3268             delete $_doc{$id};
3269             delete $_files{$id};
3270             $LOCAL_NODE=$old_local;
3271             $LOCAL_ID=$old_id;
3272             propagate_flagsigint();
3273             };
3274             die $@ if $@; # propagate
3275             }
3276              
3277             sub stream_process {
3278             my ($itype, $input, $otype, $output, $process)=@_;
3279             ($input,$output)=expand($input,$output);
3280             require XML::Filter::DOMFilter::LibXML;
3281             require XML::LibXML::SAX;
3282             require XML::SAX::Writer;
3283              
3284             my $out;
3285             my $termout;
3286             my $i=1;
3287             $i++ while (exists($_doc{"_stream_$i"}));
3288             if ($otype =~ /pipe/i) {
3289             open $out,"| $output";
3290             $out || die "Cannot open pipe to $output\n";
3291             } elsif ($otype =~ /string/i) {
3292             if ($output =~ /^\$?([a-zA-Z_][a-zA-Z0-9_]*)$/) {
3293             no strict qw(refs);
3294             $out=\${"XML::XSH::Map::$1"};
3295             } elsif (ref($OUT)=~/Term::ReadLine/) {
3296             $out = *$OUT;
3297             $termout=1;
3298             } else {
3299             $out = $OUT;
3300             $termout=1;
3301             }
3302             } else {
3303             $out = $output;
3304             }
3305             my $parser=XML::LibXML::SAX
3306             ->new( Handler =>
3307             XML::Filter::DOMFilter::LibXML
3308             ->new(Handler =>
3309             XML::SAX::Writer::XML
3310             ->new(
3311             Output => $out,
3312             Writer => 'XML::SAX::Writer::XMLEnc'
3313             ),
3314             XPathContext => $_xpc,
3315             Process => [
3316             map {
3317             $_->[0] => [\&stream_process_node,$_->[1],
3318             $input,"_stream_$i"] }
3319             @$process
3320             ]
3321             )
3322             );
3323             if ($itype =~ /pipe/i) {
3324             open my $F,"$input|";
3325             $F || die "Cannot open pipe to $input: $!\n";
3326             $parser->parse_fh($F);
3327             close $F;
3328             } elsif ($itype =~ /string/i) {
3329             $parser->parse_string($input);
3330             } else { #file
3331             $parser->parse_uri($input);
3332             }
3333             if ($otype =~ /pipe/i) {
3334             close($out);
3335             }
3336             if ($termout) { out("\n"); }
3337             return 1;
3338             }
3339              
3340             sub iterate {
3341             my ($code,$axis,$nodefilter,$filter)=@_;
3342              
3343             return unless get_local_node(_id());
3344              
3345             $axis =~ s/::$//;
3346             $axis=~s/-/_/g;
3347              
3348             $filter =~ s/^\[\s*((?:.|\n)*?)\s*\]$/$1/ if defined $filter;
3349             my $test;
3350             if ($nodefilter eq "comment()") {
3351             $test = q{ $_xml_module->is_comment($_[0]) }
3352             } if ($nodefilter eq "text()") {
3353             $test = q{ $_xml_module->is_text_or_cdata($_[0]) }
3354             } elsif ($nodefilter =~ /processing-instruction\((\s*['"]([^'"]+)['"]\s*)?\)$/) {
3355             $test = q{ $_xml_module->is_pi($_[0]) };
3356             $test .= qq{ && (\$_[0]->nodeName eq '$1') } if $1 ne "";
3357             } elsif ($nodefilter eq 'node()') {
3358             $test = '1 ';
3359             } elsif ($nodefilter =~ /^(?:([^:]+):)?(.+)$/) {
3360             $test = q{ $_xml_module->is_element($_[0]) };
3361             $test .= qq{ && (\$_[0]->getLocalName() eq '$2') } unless ($2 eq '*');
3362             if ($1 ne "") {
3363             my $ns = get_local_node(_id())->lookupNamespaceURI($1);
3364             die("Unrecognized namespace prefix '$1:'!") if ($ns eq "");
3365             $test .= qq{ && (\$_[0]->namespaceURI() eq '$ns') };
3366             }
3367             }
3368              
3369             die("Position index filter not supported for iteration ([$filter])") if $filter =~ /^\d+$/;
3370             if ($filter ne '') {
3371             $filter =~ s/\\/\\\\/g;
3372             $filter =~ s/'/\\'/g;
3373             $test .= qq{ && count_xpath(\$_[0],'$filter') };
3374             }
3375              
3376             my $filter_sub = eval "sub { $test }";
3377             my $iterator;
3378             do {
3379             my $start=get_local_node(_id());
3380             $iterator=XML::XSH::Iterators->create_iterator($start,$axis,$filter_sub);
3381             };
3382             return 1 unless defined $iterator;
3383              
3384             my $old_local=$LOCAL_NODE;
3385             my $old_id=$LOCAL_ID;
3386              
3387             eval {
3388             ITER: while ($iterator->current()) {
3389             $LOCAL_NODE=$iterator->current();
3390             eval {
3391             run_commands($code);
3392             };
3393             if (ref($@) and $@->isa('XML::XSH::Internal::LoopTerminatingException')) {
3394             if ($@->label =~ /^(?:next|last|redo|prev)$/ and $@->[1]>1) {
3395             $@->[1]--;
3396             die $@; # propagate to a higher level
3397             }
3398             if ($@->label eq 'next') {
3399             $iterator->next() || last;
3400             next;
3401             } elsif ($@->label eq 'prev') {
3402             $iterator->prev() || die("No previous node to iterate to!");
3403             next;
3404             } elsif ($@->label eq 'last') {
3405             last;
3406             } elsif ($@->label eq 'redo') {
3407             redo;
3408             } else {
3409             die $@; # propagate
3410             }
3411             } elsif ($@) {
3412             die $@; # propagate
3413             }
3414             $iterator->next() || last;
3415             }
3416             };
3417             do {
3418             local $SIG{INT}=\&flagsigint;
3419             $LOCAL_NODE=$old_local;
3420             $LOCAL_ID=$old_id;
3421             propagate_flagsigint();
3422             };
3423             die $@ if $@; # propagate
3424             return 1;
3425             }
3426              
3427             # quit
3428             sub quit {
3429             if (ref($_on_exit)) {
3430             &{$_on_exit->[0]}($_[0],@{$_on_exit}[1..$#$_on_exit]); # run on exit hook
3431             }
3432             exit(int($_[0]));
3433             }
3434              
3435             sub register_ns {
3436             my ($prefix,$ns)=expand(@_);
3437             $_ns{$prefix}=$ns;
3438             $_xpc->registerNs($prefix,$ns);
3439             return 1;
3440             }
3441              
3442             sub unregister_ns {
3443             my ($prefix)=expand(@_);
3444             delete $_ns{$prefix};
3445             $_xpc->unregisterNs($prefix);
3446             return 1;
3447             }
3448              
3449             sub register_func {
3450             my ($name,$code)=(expand($_[0]),$_[1]);
3451             my $sub;
3452             if ($code =~ /^\s*{/) {
3453             $sub=eval("package XML::XSH::Map; no strict; sub $code");
3454             } elsif ($code =~/^\s*([A-Za-z_][A-Za-z_0-9]*(::[A-Za-z_][A-Za-z_0-9]*)*)\s*$/) {
3455             if ($2 ne "") {
3456             $sub=\&{"$1"};
3457             } else {
3458             $sub=\&{"XML::XSH::Map::$1"};
3459             }
3460             } else {
3461             $sub=eval("package XML::XSH::Map; no strict; sub { $code }");
3462             }
3463             die $@ if $@;
3464             if ($name =~ /^([^:]+):(.*)$/) {
3465             if (exists($_ns{$1})) {
3466             $_xpc->registerFunctionNS($2, $_ns{$1}, $sub);
3467             } else {
3468             die "Registration failed: unknown namespace prefix $1!\n";
3469             }
3470             } else {
3471             $_xpc->registerFunction($name, $sub);
3472             }
3473             return 1;
3474             }
3475              
3476             sub unregister_func {
3477             my ($name)=expand(@_);
3478             $_xpc->unregisterFunction($name);
3479             return 1;
3480             }
3481              
3482             #######################################################################
3483             #######################################################################
3484              
3485              
3486             package XML::XSH::Map;
3487              
3488             import XML::XSH::Functions ':param_vars';
3489              
3490             # make this command available from perl expressions
3491             sub echo {
3492             &XML::XSH::Functions::out(XML::XSH::Functions::fromUTF8($XML::XSH::Functions::ENCODING,join("",@_)));
3493             return 1;
3494             }
3495              
3496             # make this command available from perl expressions
3497             sub xsh {
3498             &XML::XSH::Functions::xsh(join "",@_);
3499             }
3500              
3501             sub count {
3502             my $xp=$_[0];
3503             $xp=~/^(?:([a-zA-Z_][a-zA-Z0-9_]*):(?!:))?((?:.|\n)*)$/;
3504             return &XML::XSH::Functions::count([$1,$2]);
3505             }
3506              
3507             sub xml_list {
3508             my ($xp)=@_;
3509             $xp=~/^(?:([a-zA-Z_][a-zA-Z0-9_]*):(?!:))?((?:.|\n)*)$/;
3510             my ($id,$query,$doc)=&XML::XSH::Functions::_xpath([$1,$2]);
3511              
3512             unless (ref($doc)) {
3513             die "No such document '$id'!\n";
3514             }
3515             my $ql=&XML::XSH::Functions::find_nodes([$id,$query]);
3516             my $result='';
3517             foreach (@$ql) {
3518             $result.=$_->toString();
3519             }
3520             return $result;
3521             }
3522              
3523             sub literal {
3524             my ($xp)=@_;
3525             my $xp=$_[0];
3526             $xp=~/^(?:([a-zA-Z_][a-zA-Z0-9_]*):(?!:))?((?:.|\n)*)$/;
3527             return XML::XSH::Functions::eval_xpath_literal([$1,$2]);
3528             }
3529              
3530             sub type {
3531             my ($xp)=@_;
3532             $xp='.' if $xp eq "";
3533             $xp=~/^(?:([a-zA-Z_][a-zA-Z0-9_]*):(?!:))?((?:.|\n)*)$/;
3534             my ($id,$query,$doc)=&XML::XSH::Functions::_xpath([$1,$2]);
3535              
3536             unless (ref($doc)) {
3537             die "No such document '$id'!\n";
3538             }
3539             my $ql=&XML::XSH::Functions::find_nodes([$id,$query]);
3540              
3541              
3542             my $xm=$XML::XSH::Functions::_xml_module;
3543             my @result;
3544             foreach (@$ql) {
3545             if ($xm->is_element($_)) {
3546             push @result, 'element';
3547             } elsif ($xm->is_attribute($_)) {
3548             push @result, 'attribute';
3549             } elsif ($xm->is_text($_)) {
3550             push @result, 'text';
3551             } elsif ($xm->is_cdata_section($_)) {
3552             push @result, 'cdata';
3553             } elsif ($xm->is_pi($_)) {
3554             push @result, 'pi';
3555             } elsif ($xm->is_entity_reference($_)) {
3556             push @result, 'entity_reference';
3557             } elsif ($xm->is_document($_)) {
3558             push @result, 'document';
3559             } elsif ($xm->is_document_fragment($_)) {
3560             push @result, 'chunk';
3561             } elsif ($xm->is_comment($_)) {
3562             push @result, 'comment';
3563             } elsif ($xm->is_namespace($_)) {
3564             push @result, 'namespace';
3565             } else {
3566             push @result, 'unknown';
3567             }
3568             return $result[0] unless (wantarray);
3569             }
3570             return @result;
3571             }
3572              
3573             #######################################################################
3574             #######################################################################
3575              
3576             package XML::XSH::Internal::Exception;
3577              
3578             sub new {
3579             my $class=(ref($_[0]) || $_[0]);
3580             shift;
3581             return bless [@_], $class;
3582             }
3583              
3584             sub set_label {
3585             my ($label)=@_;
3586             return $_[0]->[0]=$label;
3587             }
3588              
3589             sub label {
3590             return $_[0]->[0];
3591             }
3592              
3593             sub value {
3594             my ($index)=@_;
3595             return $_[0]->[$index];
3596             }
3597              
3598             sub set_value {
3599             my ($index,$value)=@_;
3600             return $_[0]->[$index]=$value;
3601             }
3602              
3603             package XML::XSH::Internal::UncatchableException;
3604             use vars qw(@ISA);
3605             @ISA=qw(XML::XSH::Internal::Exception);
3606              
3607             package XML::XSH::Internal::LoopTerminatingException;
3608             use vars qw(@ISA);
3609             @ISA=qw(XML::XSH::Internal::UncatchableException);
3610              
3611             package XML::XSH::Internal::SubTerminatingException;
3612             use vars qw(@ISA);
3613             @ISA=qw(XML::XSH::Internal::UncatchableException);
3614              
3615              
3616             #######################################################################
3617             #######################################################################
3618              
3619             package IO::MyString;
3620              
3621             use vars qw(@ISA);
3622             @ISA=qw(IO::Handle);
3623              
3624             sub new {
3625             my $class=(ref($_[0]) || $_[0]);
3626             return bless [""], $class;
3627             }
3628              
3629             sub print {
3630             my $self=shift;
3631             $self->[0].=join("",@_);
3632             }
3633              
3634             sub value {
3635             return $_[0]->[0];
3636             }
3637              
3638             sub close {
3639             $_[0]->[0]=undef;
3640             }
3641              
3642             package XML::SAX::Writer::XMLEnc;
3643             use vars qw(@ISA);
3644             @ISA=qw(XML::SAX::Writer::XML);
3645              
3646             sub xml_decl {
3647             my ($self,$data) = @_;
3648             if ($data->{Encoding}) {
3649             $self->{EncodeTo}=$data->{Encoding};
3650             $self->setConverter();
3651             }
3652             $self->SUPER::xml_decl($data);
3653             }
3654              
3655             1;