home *** CD-ROM | disk | FTP | other *** search
/ Netrunner 2004 October / NETRUNNER0410.ISO / regular / ActivePerl-5.8.4.810-MSWin32-x86.msi / _1d06d717904acd5f2d8d9b32648a2959 < prev    next >
Text File  |  2004-06-01  |  168KB  |  5,013 lines

  1. # ======================================================================
  2. #
  3. # Copyright (C) 2000-2001 Paul Kulchenko (paulclinger@yahoo.com)
  4. # SOAP::Lite is free software; you can redistribute it
  5. # and/or modify it under the same terms as Perl itself.
  6. #                      
  7. # $Id: Lite.pm,v 1.47 2002/04/15 16:17:38 paulk Exp $
  8. #
  9. # ======================================================================
  10.  
  11. package SOAP::Lite;
  12.  
  13. use 5.004;
  14. use strict;
  15. use vars qw($VERSION);
  16. $VERSION = sprintf("%d.%s", map {s/_//g; $_} q$Name: release-0_55-public $ =~ /-(\d+)_([\d_]+)/)
  17.   or warn "warning: unspecified/non-released version of ", __PACKAGE__, "\n";
  18.  
  19. # ======================================================================
  20.  
  21. package SOAP::XMLSchemaSOAP1_1::Deserializer;
  22.  
  23. sub anyTypeValue { 'ur-type' }
  24.  
  25. sub as_boolean { shift; my $value = shift; $value eq '1' || $value eq 'true' ? 1 : $value eq '0' || $value eq 'false' ? 0 : die "Wrong boolean value '$value'\n" }
  26. sub as_base64 { shift; require MIME::Base64; MIME::Base64::decode_base64(shift) }
  27. sub as_ur_type { $_[1] }
  28.  
  29. BEGIN {
  30.   no strict 'refs';
  31.   for my $method (qw(
  32.     string float double decimal timeDuration recurringDuration uriReference
  33.     integer nonPositiveInteger negativeInteger long int short byte
  34.     nonNegativeInteger unsignedLong unsignedInt unsignedShort unsignedByte
  35.     positiveInteger timeInstant time timePeriod date month year century 
  36.     recurringDate recurringDay language
  37.   )) { my $name = 'as_' . $method; *$name = sub { $_[1] } }
  38. }
  39.  
  40. # ----------------------------------------------------------------------
  41.  
  42. package SOAP::XMLSchemaSOAP1_2::Deserializer;
  43.  
  44. sub anyTypeValue { 'anyType' }
  45.  
  46. sub as_boolean; *as_boolean = \&SOAP::XMLSchemaSOAP1_1::Deserializer::as_boolean;
  47. sub as_base64 { shift; require MIME::Base64; MIME::Base64::decode_base64(shift) }
  48. sub as_anyType { $_[1] }
  49.  
  50. BEGIN {
  51.   no strict 'refs';
  52.   for my $method (qw(
  53.     string float double decimal dateTime timePeriod gMonth gYearMonth gYear century 
  54.     gMonthDay gDay duration recurringDuration anyURI
  55.     language integer nonPositiveInteger negativeInteger long int short byte
  56.     nonNegativeInteger unsignedLong unsignedInt unsignedShort unsignedByte
  57.     positiveInteger date time dateTime
  58.   )) { my $name = 'as_' . $method; *$name = sub { $_[1] } }
  59. }
  60.  
  61. # ----------------------------------------------------------------------
  62.  
  63. package SOAP::XMLSchemaApacheSOAP::Deserializer;
  64.  
  65. sub as_map { 
  66.   my $self = shift;
  67.   +{ map { my $hash = ($self->decode_object($_))[1]; ($hash->{key} => $hash->{value}) } @{$_[3] || []} };
  68. }
  69. sub as_Map; *as_Map = \&as_map;
  70.  
  71. # ----------------------------------------------------------------------
  72.  
  73. package SOAP::XMLSchema::Serializer;
  74.  
  75. use vars qw(@ISA);
  76.  
  77. sub xmlschemaclass {
  78.   my $self = shift;
  79.   return $ISA[0] unless @_;
  80.   @ISA = (shift);
  81.   return $self;
  82. }
  83.  
  84. # ----------------------------------------------------------------------
  85.  
  86. package SOAP::XMLSchema1999::Serializer;
  87.  
  88. use vars qw(@EXPORT $AUTOLOAD);
  89.  
  90. sub AUTOLOAD {
  91.   local($1,$2);
  92.   my($package, $method) = $AUTOLOAD =~ m/(?:(.+)::)([^:]+)$/;
  93.   return if $method eq 'DESTROY';
  94.  
  95.   no strict 'refs';
  96.   die "Type '$method' can't be found in a schema class '$package'\n"
  97.     unless $method =~ s/^as_// && grep {$_ eq $method} @{"$package\::EXPORT"};
  98.  
  99.   $method =~ s/_/-/; # fix ur-type
  100.  
  101.   *$AUTOLOAD = sub { 
  102.     my $self = shift;
  103.     my($value, $name, $type, $attr) = @_;
  104.     return [$name, {'xsi:type' => "xsd:$method", %$attr}, $value];
  105.   };
  106.   goto &$AUTOLOAD;
  107. }
  108.  
  109. BEGIN {
  110.   @EXPORT = qw(ur_type
  111.     float double decimal timeDuration recurringDuration uriReference
  112.     integer nonPositiveInteger negativeInteger long int short byte
  113.     nonNegativeInteger unsignedLong unsignedInt unsignedShort unsignedByte
  114.     positiveInteger timeInstant time timePeriod date month year century 
  115.     recurringDate recurringDay language
  116.     base64 hex string boolean
  117.   );
  118.   # predeclare subs, so ->can check will be positive 
  119.   foreach (@EXPORT) { eval "sub as_$_" } 
  120. }
  121.  
  122. sub nilValue { 'null' }
  123. sub anyTypeValue { 'ur-type' }
  124.  
  125. sub as_base64 {
  126.   my $self = shift;
  127.   my($value, $name, $type, $attr) = @_;
  128.   require MIME::Base64;
  129.   return [$name, {'xsi:type' => SOAP::Utils::qualify($self->encprefix => 'base64'), %$attr}, MIME::Base64::encode_base64($value,'')];
  130. }
  131.  
  132. sub as_hex { 
  133.   my $self = shift;
  134.   my($value, $name, $type, $attr) = @_;
  135.   return [$name, {'xsi:type' => 'xsd:hex', %$attr}, join '', map {uc sprintf "%02x", ord} split '', $value];
  136. }
  137.  
  138. sub as_string {
  139.   my $self = shift;
  140.   my($value, $name, $type, $attr) = @_;
  141.   die "String value expected instead of @{[ref $value]} reference\n" if ref $value;
  142.   return [$name, {'xsi:type' => 'xsd:string', %$attr}, SOAP::Utils::encode_data($value)];
  143. }
  144.  
  145. sub as_undef { $_[1] ? '1' : '0' }
  146.  
  147. sub as_boolean {
  148.   my $self = shift;
  149.   my($value, $name, $type, $attr) = @_;
  150.   return [$name, {'xsi:type' => 'xsd:boolean', %$attr}, $value ? '1' : '0'];
  151. }
  152.  
  153. # ----------------------------------------------------------------------
  154.  
  155. package SOAP::XMLSchema1999::Deserializer;
  156.  
  157. sub anyTypeValue { 'ur-type' }
  158.  
  159. sub as_string; *as_string = \&SOAP::XMLSchemaSOAP1_1::Deserializer::as_string;
  160. sub as_boolean; *as_boolean = \&SOAP::XMLSchemaSOAP1_1::Deserializer::as_boolean;
  161. sub as_hex { shift; my $value = shift; $value =~ s/([a-zA-Z0-9]{2})/chr oct '0x'.$1/ge; $value }
  162. sub as_ur_type { $_[1] }
  163. sub as_undef { shift; my $value = shift; $value eq '1' || $value eq 'true' ? 1 : $value eq '0' || $value eq 'false' ? 0 : die "Wrong null/nil value '$value'\n" }
  164.  
  165. BEGIN {
  166.   no strict 'refs';
  167.   for my $method (qw(
  168.     float double decimal timeDuration recurringDuration uriReference
  169.     integer nonPositiveInteger negativeInteger long int short byte
  170.     nonNegativeInteger unsignedLong unsignedInt unsignedShort unsignedByte
  171.     positiveInteger timeInstant time timePeriod date month year century 
  172.     recurringDate recurringDay language
  173.   )) { my $name = 'as_' . $method; *$name = sub { $_[1] } }
  174. }
  175.  
  176. # ----------------------------------------------------------------------
  177.  
  178. package SOAP::XMLSchema2001::Serializer;
  179.  
  180. use vars qw(@EXPORT);
  181.  
  182. # no more warnings about "used only once"
  183. *AUTOLOAD if 0; 
  184.  
  185. *AUTOLOAD = \&SOAP::XMLSchema1999::Serializer::AUTOLOAD;
  186.  
  187. BEGIN {
  188.   @EXPORT = qw(anyType anySimpleType
  189.     float double decimal dateTime timePeriod gMonth gYearMonth gYear century 
  190.     gMonthDay gDay duration recurringDuration anyURI
  191.     language integer nonPositiveInteger negativeInteger long int short byte
  192.     nonNegativeInteger unsignedLong unsignedInt unsignedShort unsignedByte
  193.     positiveInteger date time
  194.     string hex base64 boolean
  195.   );
  196.   # predeclare subs, so ->can check will be positive 
  197.   foreach (@EXPORT) { eval "sub as_$_" } 
  198. }
  199.  
  200. sub nilValue { 'nil' }
  201. sub anyTypeValue { 'anyType' }
  202.  
  203. sub as_hexBinary { 
  204.   my $self = shift;
  205.   my($value, $name, $type, $attr) = @_;
  206.   return [$name, {'xsi:type' => 'xsd:hexBinary', %$attr}, join '', map {uc sprintf "%02x", ord} split '', $value];
  207. }
  208.  
  209. sub as_base64Binary {
  210.   my $self = shift;
  211.   my($value, $name, $type, $attr) = @_;
  212.   require MIME::Base64;
  213.   return [$name, {'xsi:type' => 'xsd:base64Binary', %$attr}, MIME::Base64::encode_base64($value,'')];
  214. }
  215.  
  216. sub as_string; *as_string = \&SOAP::XMLSchema1999::Serializer::as_string;
  217. sub as_hex; *as_hex = \&as_hexBinary;
  218. sub as_base64; *as_base64 = \&as_base64Binary;
  219. sub as_timeInstant; *as_timeInstant = \&as_dateTime;
  220.  
  221. sub as_undef { $_[1] ? 'true' : 'false' }
  222.  
  223. sub as_boolean {
  224.   my $self = shift;
  225.   my($value, $name, $type, $attr) = @_;
  226.   return [$name, {'xsi:type' => 'xsd:boolean', %$attr}, $value ? 'true' : 'false'];
  227. }
  228.  
  229. # ----------------------------------------------------------------------
  230.  
  231. package SOAP::XMLSchema2001::Deserializer;
  232.  
  233. sub anyTypeValue { 'anyType' }
  234.  
  235. sub as_string; *as_string = \&SOAP::XMLSchema1999::Deserializer::as_string;
  236. sub as_boolean; *as_boolean = \&SOAP::XMLSchemaSOAP1_2::Deserializer::as_boolean;
  237. sub as_base64Binary; *as_base64Binary = \&SOAP::XMLSchemaSOAP1_2::Deserializer::as_base64;
  238. sub as_hexBinary; *as_hexBinary = \&SOAP::XMLSchema1999::Deserializer::as_hex;
  239. sub as_undef; *as_undef = \&SOAP::XMLSchema1999::Deserializer::as_undef;
  240.  
  241. BEGIN {
  242.   no strict 'refs';
  243.   for my $method (qw(
  244.     anyType anySimpleType
  245.     float double decimal dateTime timePeriod gMonth gYearMonth gYear century 
  246.     gMonthDay gDay duration recurringDuration anyURI
  247.     language integer nonPositiveInteger negativeInteger long int short byte
  248.     nonNegativeInteger unsignedLong unsignedInt unsignedShort unsignedByte
  249.     positiveInteger date time dateTime
  250.   )) { my $name = 'as_' . $method; *$name = sub { $_[1] } }
  251. }
  252.  
  253. # ======================================================================
  254.  
  255. package SOAP::Constants;
  256.  
  257. BEGIN {
  258.  
  259.   use vars qw($NSMASK $ELMASK);
  260.  
  261.   $NSMASK = '[a-zA-Z_:][\w.\-:]*'; 
  262.   $ELMASK = '^(?![xX][mM][lL])[a-zA-Z_][\w.\-]*$';
  263.  
  264.   use vars qw($NEXT_ACTOR $NS_ENV $NS_ENC $NS_APS
  265.               $FAULT_CLIENT $FAULT_SERVER $FAULT_VERSION_MISMATCH
  266.               $HTTP_ON_FAULT_CODE $HTTP_ON_SUCCESS_CODE $FAULT_MUST_UNDERSTAND
  267.               $NS_XSI_ALL $NS_XSI_NILS %XML_SCHEMAS $DEFAULT_XML_SCHEMA
  268.               $SOAP_VERSION %SOAP_VERSIONS $WRONG_VERSION
  269.               $NS_SL_HEADER $NS_SL_PERLTYPE $PREFIX_ENV $PREFIX_ENC
  270.               $DO_NOT_USE_XML_PARSER $DO_NOT_CHECK_MUSTUNDERSTAND 
  271.               $DO_NOT_USE_CHARSET $DO_NOT_PROCESS_XML_IN_MIME
  272.               $DO_NOT_USE_LWP_LENGTH_HACK $DO_NOT_CHECK_CONTENT_TYPE
  273.               $MAX_CONTENT_SIZE
  274.   );  
  275.  
  276.   $FAULT_CLIENT = 'Client';
  277.   $FAULT_SERVER = 'Server';
  278.   $FAULT_VERSION_MISMATCH = 'VersionMismatch';
  279.   $FAULT_MUST_UNDERSTAND = 'MustUnderstand';
  280.   
  281.   $HTTP_ON_SUCCESS_CODE = 200; # OK
  282.   $HTTP_ON_FAULT_CODE   = 500; # INTERNAL_SERVER_ERROR
  283.  
  284.   $WRONG_VERSION = 'Wrong SOAP version specified.';
  285.  
  286.   %SOAP_VERSIONS = (
  287.     ($SOAP_VERSION = 1.1) => {
  288.       NEXT_ACTOR => 'http://schemas.xmlsoap.org/soap/actor/next',
  289.       NS_ENV => 'http://schemas.xmlsoap.org/soap/envelope/',
  290.       NS_ENC => 'http://schemas.xmlsoap.org/soap/encoding/',
  291.       DEFAULT_XML_SCHEMA => 'http://www.w3.org/1999/XMLSchema',
  292.     },
  293.     1.2 => {
  294.       NEXT_ACTOR => 'http://www.w3.org/2001/06/soap-envelope/actor/next',
  295.       NS_ENV => 'http://www.w3.org/2001/06/soap-envelope',
  296.       NS_ENC => 'http://www.w3.org/2001/06/soap-encoding',
  297.       DEFAULT_XML_SCHEMA => 'http://www.w3.org/2001/XMLSchema',
  298.     },
  299.   );
  300.  
  301.   # schema namespaces                                    
  302.   %XML_SCHEMAS = (
  303.     'http://www.w3.org/1999/XMLSchema' => 'SOAP::XMLSchema1999',
  304.     'http://www.w3.org/2001/XMLSchema' => 'SOAP::XMLSchema2001',
  305.     'http://schemas.xmlsoap.org/soap/encoding/' => 'SOAP::XMLSchemaSOAP1_1',
  306.     'http://www.w3.org/2001/06/soap-encoding' => 'SOAP::XMLSchemaSOAP1_2',
  307.   );
  308.   
  309.   $NS_XSI_ALL = join join('|', map {"$_-instance"} grep {/XMLSchema/} keys %XML_SCHEMAS),
  310.                      '(?:', ')';
  311.   $NS_XSI_NILS = join join('|', map { my $class = $XML_SCHEMAS{$_} . '::Serializer'; "\{($_)-instance\}" . $class->nilValue
  312.                                     } grep {/XMLSchema/} keys %XML_SCHEMAS),
  313.                       '(?:', ')';
  314.   
  315.   # ApacheSOAP namespaces
  316.   $NS_APS = 'http://xml.apache.org/xml-soap';
  317.   
  318.   # SOAP::Lite namespace
  319.   $NS_SL_HEADER = 'http://namespaces.soaplite.com/header';
  320.   $NS_SL_PERLTYPE = 'http://namespaces.soaplite.com/perl';
  321.  
  322.   # default prefixes
  323.   $PREFIX_ENV = 'SOAP-ENV';
  324.   $PREFIX_ENC = 'SOAP-ENC';
  325.   
  326.   # others
  327.   $DO_NOT_USE_XML_PARSER = 0;
  328.   $DO_NOT_CHECK_MUSTUNDERSTAND = 0;
  329.   $DO_NOT_USE_CHARSET = 0;
  330.   $DO_NOT_PROCESS_XML_IN_MIME = 0;
  331.   $DO_NOT_USE_LWP_LENGTH_HACK = 0;
  332.   $DO_NOT_CHECK_CONTENT_TYPE = 0;
  333. }
  334.   
  335. # ======================================================================
  336.  
  337. package SOAP::Utils;
  338.  
  339. sub qualify { $_[1] ? $_[1] =~ /:/ ? $_[1] : join(':', $_[0] || (), $_[1]) : defined $_[1] ? $_[0] : '' }
  340. sub overqualify (&$) { for ($_[1]) { &{$_[0]}; s/^:|:$//g } }
  341. sub disqualify {
  342.   (my $qname = shift) =~ s/^($SOAP::Constants::NSMASK?)://;
  343.   $qname;
  344. }
  345. sub splitqname { local($1,$2); $_[0] =~ /^(?:([^:]+):)?(.+)$/; return ($1,$2) }
  346. sub longname { defined $_[0] ? sprintf('{%s}%s', $_[0], $_[1]) : $_[1] }
  347. sub splitlongname { local($1,$2); $_[0] =~ /^(?:\{(.*)\})?(.+)$/; return ($1,$2) }
  348.  
  349. # Q: why only '&' and '<' are encoded, but not '>'?
  350. # A: because it is not required according to XML spec.
  351. #
  352. # [http://www.w3.org/TR/REC-xml#syntax]
  353. # The ampersand character (&) and the left angle bracket (<) may appear in 
  354. # their literal form only when used as markup delimiters, or within a comment, 
  355. # a processing instruction, or a CDATA section. If they are needed elsewhere, 
  356. # they must be escaped using either numeric character references or the 
  357. # strings "&" and "<" respectively. The right angle bracket (>) may be 
  358. # represented using the string ">", and must, for compatibility, be 
  359. # escaped using ">" or a character reference when it appears in the 
  360. # string "]]>" in content, when that string is not marking the end of a 
  361. # CDATA section.
  362.  
  363. my %encode_attribute = ('&' => '&', '<' => '<', '"' => '"');
  364. sub encode_attribute { (my $e = $_[0]) =~ s/([&<"])/$encode_attribute{$1}/g; $e }
  365.  
  366. my %encode_data = ('&' => '&', '<' => '<', "\xd" => ' ');
  367. sub encode_data { (my $e = $_[0]) =~ s/([&<\015])/$encode_data{$1}/g; $e =~ s/\]\]>/\]\]>/g; $e }
  368.  
  369. # methods for internal tree (SOAP::Deserializer, SOAP::SOM and SOAP::Serializer)
  370.  
  371. sub o_qname { $_[0]->[0] }
  372. sub o_attr  { $_[0]->[1] }
  373. sub o_child { ref $_[0]->[2] ? $_[0]->[2] : undef }
  374. sub o_chars { ref $_[0]->[2] ? undef : $_[0]->[2] }
  375.             # $_[0]->[3] is not used. Serializer stores object ID there
  376. sub o_value { $_[0]->[4] }
  377. sub o_lname { $_[0]->[5] }
  378. sub o_lattr { $_[0]->[6] }
  379.  
  380. # make bytelength that calculates length in bytes regardless of utf/byte settings
  381. # either we can do 'use bytes' or length will count bytes already      
  382. BEGIN { 
  383.   sub bytelength; 
  384.   eval ( eval('use bytes; 1') # 5.6.0 and later?
  385.     ? 'sub bytelength { use bytes; length(@_ ? $_[0] : $_) }; 1'
  386.     : 'sub bytelength { length(@_ ? $_[0] : $_) }; 1' 
  387.   ) or die;
  388. }
  389.  
  390. # ======================================================================
  391.  
  392. package SOAP::Cloneable;
  393.  
  394. sub clone {
  395.   my $self = shift;
  396.   return unless ref $self && UNIVERSAL::isa($self => __PACKAGE__);
  397.   my $clone = bless {} => ref($self) || $self;
  398.   foreach (keys %$self) {
  399.     my $value = $self->{$_};
  400.     $clone->{$_} = ref $value && UNIVERSAL::isa($value => __PACKAGE__) ? $value->clone : $value;
  401.   }
  402.   $clone;
  403. }
  404.  
  405. # ======================================================================
  406.  
  407. package SOAP::Transport;
  408.  
  409. use vars qw($AUTOLOAD @ISA);
  410.  
  411. @ISA = qw(SOAP::Cloneable);
  412.  
  413. sub DESTROY { SOAP::Trace::objects('()') }
  414.  
  415. sub new { 
  416.   my $self = shift;
  417.   my $class = ref($self) || $self;
  418.   return $self if ref $self;
  419.  
  420.   SOAP::Trace::objects('()');
  421.   return bless {} => $class;
  422. }
  423.  
  424. sub proxy {
  425.   my $self = shift->new;
  426.   my $class = ref $self;
  427.  
  428.   return $self->{_proxy} unless @_;
  429.   $_[0] =~ /^(\w+):/ or die "proxy: transport protocol not specified\n";
  430.   my $protocol = uc "$1"; # untainted now
  431.   # https: should be done through Transport::HTTP.pm
  432.   for ($protocol) { s/^HTTPS$/HTTP/ }
  433.  
  434.   (my $protocol_class = "${class}::$protocol") =~ s/-/_/g;
  435.   no strict 'refs';
  436.   unless (defined %{"$protocol_class\::Client::"} && UNIVERSAL::can("$protocol_class\::Client" => 'new')) {
  437.     eval "require $protocol_class";
  438.     die "Unsupported protocol '$protocol'\n" if $@ =~ m!^Can't locate SOAP/Transport/!;
  439.     die if $@;
  440.   }
  441.   $protocol_class .= "::Client";
  442.   return $self->{_proxy} = $protocol_class->new(endpoint => shift, @_);
  443. }
  444.  
  445. sub AUTOLOAD {
  446.   my $method = substr($AUTOLOAD, rindex($AUTOLOAD, '::') + 2);
  447.   return if $method eq 'DESTROY';
  448.  
  449.   no strict 'refs';
  450.   *$AUTOLOAD = sub { shift->proxy->$method(@_) };
  451.   goto &$AUTOLOAD;
  452. }
  453.  
  454. # ======================================================================
  455.  
  456. package SOAP::Fault;
  457.  
  458. use Carp ();
  459.  
  460. use overload fallback => 1, '""' => "stringify";
  461.  
  462. sub DESTROY { SOAP::Trace::objects('()') }
  463.  
  464. sub new { 
  465.   my $self = shift;
  466.  
  467.   unless (ref $self) {
  468.     my $class = ref($self) || $self;
  469.     $self = bless {} => $class;
  470.     SOAP::Trace::objects('()');
  471.   }
  472.  
  473.   Carp::carp "Odd (wrong?) number of parameters in new()" if $^W && (@_ & 1); 
  474.   while (@_) { my $method = shift; $self->$method(shift) if $self->can($method) }
  475.  
  476.   return $self;
  477. }
  478.  
  479. sub stringify {
  480.   my $self = shift;
  481.   return join ': ', $self->faultcode, $self->faultstring;
  482. }
  483.  
  484. sub BEGIN {
  485.   no strict 'refs';
  486.   for my $method (qw(faultcode faultstring faultactor faultdetail)) {
  487.     my $field = '_' . $method;
  488.     *$method = sub {
  489.       my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  490.       if (@_) { $self->{$field} = shift; return $self }
  491.       return $self->{$field};
  492.     }
  493.   }
  494.   *detail = \&faultdetail;
  495. }
  496.  
  497. # ======================================================================
  498.  
  499. package SOAP::Data;
  500.  
  501. use vars qw(@ISA @EXPORT_OK);
  502. use Exporter;
  503. use Carp ();
  504.  
  505. @ISA = qw(Exporter);
  506. @EXPORT_OK = qw(name type attr value uri);
  507.  
  508. sub DESTROY { SOAP::Trace::objects('()') }
  509.  
  510. sub new { 
  511.   my $self = shift;
  512.  
  513.   unless (ref $self) {
  514.     my $class = ref($self) || $self;
  515.     $self = bless {_attr => {}, _value => [], _signature => []} => $class;
  516.     SOAP::Trace::objects('()');
  517.   }
  518.  
  519.   Carp::carp "Odd (wrong?) number of parameters in new()" if $^W && (@_ & 1); 
  520.   while (@_) { my $method = shift; $self->$method(shift) if $self->can($method) }
  521.  
  522.   return $self;
  523. }
  524.  
  525. sub name {
  526.   my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  527.   if (@_) { 
  528.     my($name, $uri, $prefix) = shift;
  529.     if ($name) {
  530.       ($uri, $name) = SOAP::Utils::splitlongname($name);
  531.       unless (defined $uri) { 
  532.         ($prefix, $name) = SOAP::Utils::splitqname($name);
  533.         $self->prefix($prefix) if defined $prefix;
  534.       } else {
  535.         $self->uri($uri);
  536.       }
  537.     }
  538.     $self->{_name} = $name;
  539.  
  540.     $self->value(@_) if @_; 
  541.     return $self;
  542.   }
  543.   return $self->{_name};
  544. }
  545.  
  546. sub attr {
  547.   my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  548.   if (@_) { $self->{_attr} = shift; $self->value(@_) if @_; return $self }
  549.   return $self->{_attr};
  550. }
  551.  
  552. sub type {
  553.   my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  554.   if (@_) { 
  555.     $self->{_type} = shift; 
  556.     $self->value(@_) if @_; 
  557.     return $self;
  558.   }
  559.   if (!defined $self->{_type} && (my @types = grep {/^\{$SOAP::Constants::NS_XSI_ALL}type$/o} keys %{$self->{_attr}})) {
  560.     $self->{_type} = (SOAP::Utils::splitlongname(delete $self->{_attr}->{shift(@types)}))[1];
  561.   }
  562.   return $self->{_type};
  563. }
  564.  
  565. BEGIN {
  566.   no strict 'refs';
  567.   for my $method (qw(root mustUnderstand)) {
  568.     my $field = '_' . $method;
  569.     *$method = sub {
  570.       my $attr = $method eq 'root' ? "{$SOAP::Constants::NS_ENC}$method" : "{$SOAP::Constants::NS_ENV}$method";
  571.       my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  572.       if (@_) {
  573.         $self->{_attr}->{$attr} = $self->{$field} = shift() ? 1 : 0; 
  574.         $self->value(@_) if @_; 
  575.         return $self;
  576.       }
  577.       $self->{$field} = SOAP::XMLSchemaSOAP1_2::Deserializer->as_boolean($self->{_attr}->{$attr})
  578.         if !defined $self->{$field} && defined $self->{_attr}->{$attr}; 
  579.       return $self->{$field};
  580.     }
  581.   }
  582.   for my $method (qw(actor encodingStyle)) {
  583.     my $field = '_' . $method;
  584.     *$method = sub {
  585.       my $attr = "{$SOAP::Constants::NS_ENV}$method";
  586.       my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  587.       if (@_) {
  588.         $self->{_attr}->{$attr} = $self->{$field} = shift;
  589.         $self->value(@_) if @_;
  590.         return $self;
  591.       }
  592.       $self->{$field} = $self->{_attr}->{$attr}
  593.         if !defined $self->{$field} && defined $self->{_attr}->{$attr}; 
  594.       return $self->{$field};
  595.     }
  596.   }
  597. }
  598.  
  599. sub prefix {
  600.   my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  601.   return $self->{_prefix} unless @_;
  602.   $self->{_prefix} = shift; 
  603.   $self->value(@_) if @_;
  604.   return $self;
  605. }
  606.  
  607. sub uri {
  608.   my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  609.   return $self->{_uri} unless @_;
  610.   my $uri = $self->{_uri} = shift; 
  611.   warn "Usage of '::' in URI ($uri) deprecated. Use '/' instead\n"
  612.     if defined $uri && $^W && $uri =~ /::/;
  613.   $self->value(@_) if @_;
  614.   return $self;
  615. }
  616.  
  617. sub set_value {
  618.   my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  619.   $self->{_value} = [@_];
  620.   return $self; 
  621. }
  622.  
  623. sub value {
  624.   my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  625.   @_ ? ($self->set_value(@_), return $self) 
  626.      : wantarray ? return @{$self->{_value}} : return $self->{_value}->[0];
  627. }
  628.  
  629. sub signature {
  630.   my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) ? shift->new : __PACKAGE__->new;
  631.   @_ ? ($self->{_signature} = shift, return $self) : (return $self->{_signature});
  632. }
  633.  
  634. # ======================================================================
  635.  
  636. package SOAP::Header;
  637.  
  638. use vars qw(@ISA);
  639. @ISA = qw(SOAP::Data);
  640.  
  641. # ======================================================================
  642.  
  643. package SOAP::Serializer;
  644.  
  645. use Carp ();
  646. use vars qw(@ISA);
  647.  
  648. @ISA = qw(SOAP::Cloneable SOAP::XMLSchema::Serializer);
  649.  
  650. BEGIN {
  651.   # namespaces and anonymous data structures
  652.   my $ns   = 0; 
  653.   my $name = 0; 
  654.   my $prefix = 'c-';
  655.   sub gen_ns { 'namesp' . ++$ns } 
  656.   sub gen_name { join '', $prefix, 'gensym', ++$name } 
  657.   sub prefix { $prefix =~ s/^[^\-]+-/$_[1]-/; $_[0]; }
  658. }
  659.  
  660. sub DESTROY { SOAP::Trace::objects('()') }
  661.  
  662. sub new { 
  663.   my $self = shift;
  664.  
  665.   unless (ref $self) {
  666.     my $class = ref($self) || $self;
  667.     $self = bless {
  668.       _level => 0,
  669.       _autotype => 1,
  670.       _readable => 0,
  671.       _multirefinplace => 0,
  672.       _seen => {},
  673.       _typelookup => {
  674.         base64 => [10, sub {$_[0] =~ /[^\x09\x0a\x0d\x20-\x7f]/}, 'as_base64'],
  675.         'int'  => [20, sub {$_[0] =~ /^[+-]?\d+$/}, 'as_int'],
  676.         float  => [30, sub {$_[0] =~ /^(-?(?:\d+(?:\.\d*)?|\.\d+|NaN|INF)|([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?)$/}, 'as_float'],
  677.         string => [40, sub {1}, 'as_string'],
  678.       },
  679.       _encoding => 'UTF-8',
  680.       _objectstack => {},
  681.       _signature => [],
  682.       _maptype => {SOAPStruct => $SOAP::Constants::NS_APS},
  683.       _on_nonserialized => sub {Carp::carp "Cannot marshall @{[ref shift]} reference" if $^W; return},
  684.       _attr => {
  685.         "{$SOAP::Constants::NS_ENV}encodingStyle" => $SOAP::Constants::NS_ENC,
  686.       },
  687.       _namespaces => {
  688.         $SOAP::Constants::NS_ENC => $SOAP::Constants::PREFIX_ENC,
  689.         $SOAP::Constants::PREFIX_ENV ? ($SOAP::Constants::NS_ENV => $SOAP::Constants::PREFIX_ENV) : (),
  690.       },
  691.       _soapversion => SOAP::Lite->soapversion,
  692.     } => $class;
  693.  
  694.     $self->xmlschema($SOAP::Constants::DEFAULT_XML_SCHEMA);
  695.  
  696.     SOAP::Trace::objects('()');
  697.   }
  698.  
  699.   Carp::carp "Odd (wrong?) number of parameters in new()" if $^W && (@_ & 1); 
  700.   while (@_) { my $method = shift; $self->$method(shift) if $self->can($method) }
  701.  
  702.   return $self;
  703. }
  704.  
  705. sub soapversion {
  706.   my $self = shift;
  707.   return $self->{_soapversion} unless @_;
  708.   return $self if $self->{_soapversion} eq SOAP::Lite->soapversion;
  709.   $self->{_soapversion} = shift;
  710.  
  711.   $self->attr({
  712.     "{$SOAP::Constants::NS_ENV}encodingStyle" => $SOAP::Constants::NS_ENC,
  713.   });
  714.   $self->namespaces({
  715.     $SOAP::Constants::NS_ENC => $SOAP::Constants::PREFIX_ENC,
  716.     $SOAP::Constants::PREFIX_ENV ? ($SOAP::Constants::NS_ENV => $SOAP::Constants::PREFIX_ENV) : (),
  717.   });
  718.   $self->xmlschema($SOAP::Constants::DEFAULT_XML_SCHEMA);
  719.  
  720.   $self;
  721. }
  722.  
  723. sub xmlschema {
  724.   my $self = shift->new;
  725.   return $self->{_xmlschema} unless @_;
  726.  
  727.   my @schema;
  728.   if ($_[0]) {
  729.     @schema = grep {/XMLSchema/ && /$_[0]/} keys %SOAP::Constants::XML_SCHEMAS;
  730.     Carp::croak "More than one schema match parameter '$_[0]': @{[join ', ', @schema]}" if @schema > 1;
  731.     Carp::croak "No schema match parameter '$_[0]'" if @schema != 1;
  732.   }
  733.  
  734.   # do nothing if current schema is the same as new
  735.   return $self if $self->{_xmlschema} && $self->{_xmlschema} eq $schema[0];
  736.  
  737.   my $ns = $self->namespaces;
  738.  
  739.   # delete current schema from namespaces
  740.   if (my $schema = $self->{_xmlschema}) {
  741.     delete $ns->{$schema};
  742.     delete $ns->{"$schema-instance"};
  743.   }
  744.  
  745.   # add new schema into namespaces
  746.   if (my $schema = $self->{_xmlschema} = shift @schema) {
  747.     $ns->{$schema} = 'xsd';
  748.     $ns->{"$schema-instance"} = 'xsi';
  749.   }
  750.  
  751.   # and here is the class serializer should work with
  752.   my $class = exists $SOAP::Constants::XML_SCHEMAS{$self->{_xmlschema}} ?
  753.     $SOAP::Constants::XML_SCHEMAS{$self->{_xmlschema}} . '::Serializer' : $self;
  754.  
  755.   $self->xmlschemaclass($class);
  756.  
  757.   return $self;
  758. }
  759.  
  760. sub namespace {
  761.   Carp::carp "'SOAP::Serializer->namespace' method is deprecated. Instead use '->envprefix'" if $^W;
  762.   shift->envprefix(@_);
  763. }
  764.  
  765. sub encodingspace {
  766.   Carp::carp "'SOAP::Serializer->encodingspace' method is deprecated. Instead use '->encprefix'" if $^W;
  767.   shift->encprefix(@_);
  768. }
  769.  
  770. sub envprefix {
  771.   my $self = shift->new;
  772.   return $self->namespaces->{$SOAP::Constants::NS_ENV} unless @_;
  773.   $self->namespaces->{$SOAP::Constants::NS_ENV} = shift;
  774.   return $self;
  775. }
  776.  
  777. sub encprefix {
  778.   my $self = shift->new;
  779.   return $self->namespaces->{$SOAP::Constants::NS_ENC} unless @_;
  780.   $self->namespaces->{$SOAP::Constants::NS_ENC} = shift;
  781.   return $self;
  782. }
  783.  
  784. sub BEGIN {
  785.   no strict 'refs';
  786.   for my $method (qw(readable level seen autotype typelookup uri attr maptype
  787.                      namespaces multirefinplace encoding signature
  788.                      on_nonserialized)) {
  789.     my $field = '_' . $method;
  790.     *$method = sub {
  791.       my $self = shift->new;
  792.       @_ ? ($self->{$field} = shift, return $self) : return $self->{$field};
  793.     }
  794.   }
  795.   for my $method (qw(method fault freeform)) { # aliases for envelope
  796.     *$method = sub { shift->envelope($method => @_) }
  797.   }
  798.   for my $method (qw(qualify overqualify disqualify)) { # import from SOAP::Utils
  799.     *$method = \&{'SOAP::Utils::'.$method};
  800.   }
  801. }
  802.  
  803. sub gen_id { sprintf "%U", $_[1] }
  804.  
  805. sub multiref_object {
  806.   my $self = shift;
  807.   my $object = shift;
  808.   my $id = $self->gen_id($object);
  809.   my $seen = $self->seen;
  810.   $seen->{$id}->{count}++;
  811.   $seen->{$id}->{multiref} ||= $seen->{$id}->{count} > 1;
  812.   $seen->{$id}->{value} = $object;
  813.   $seen->{$id}->{recursive} ||= 0;
  814.   return $id;
  815. }
  816.  
  817. sub recursive_object { 
  818.   my $self = shift; 
  819.   $self->seen->{$self->gen_id(shift)}->{recursive} = 1;
  820. }
  821.  
  822. sub is_href { 
  823.   my $self = shift;
  824.   my $seen = $self->seen->{shift || return} or return;
  825.   return 1 if $seen->{id};
  826.   return $seen->{multiref} &&
  827.          !($seen->{id} = (shift || 
  828.                           $seen->{recursive} || 
  829.                           $seen->{multiref} && $self->multirefinplace));
  830. }
  831.  
  832. sub multiref_anchor { 
  833.   my $seen = shift->seen->{my $id = shift || return undef};
  834.   return $seen->{multiref} ? "ref-$id" : undef;
  835. }
  836.  
  837. sub encode_multirefs {
  838.   my $self = shift;
  839.   return if $self->multirefinplace;
  840.  
  841.   my $seen = $self->seen;
  842.   map { $_->[1]->{_id} = 1; $_ 
  843.       } map { $self->encode_object($seen->{$_}->{value}) 
  844.             } grep { $seen->{$_}->{multiref} && !$seen->{$_}->{recursive}
  845.                    } keys %$seen;
  846. }
  847.  
  848. # ----------------------------------------------------------------------
  849.  
  850. sub maptypetouri {
  851.   my($self, $type, $simple) = @_;
  852.  
  853.   return $type unless defined $type;
  854.   my($prefix, $name) = SOAP::Utils::splitqname($type);
  855.  
  856.   unless (defined $prefix) {
  857.     $name =~ s/__|\./::/g;
  858.     $self->maptype->{$name} = $simple 
  859.         ? die "Schema/namespace for type '$type' is not specified\n"
  860.         : $SOAP::Constants::NS_SL_PERLTYPE
  861.       unless exists $self->maptype->{$name};
  862.     $type = $self->maptype->{$name} 
  863.       ? qualify($self->namespaces->{$self->maptype->{$name}} ||= gen_ns, $type)
  864.       : undef;
  865.   }
  866.   return $type;
  867. }
  868.  
  869. sub encode_object {
  870.   my($self, $object, $name, $type, $attr) = @_;
  871.  
  872.   $attr ||= {};
  873.  
  874.   return $self->encode_scalar($object, $name, $type, $attr) unless ref $object;
  875.  
  876.   my $id = $self->multiref_object($object); 
  877.  
  878.   use vars '%objectstack';           # we'll play with symbol table 
  879.   local %objectstack = %objectstack; # want to see objects ONLY in the current tree
  880.   # did we see this object in current tree? Seems to be recursive refs
  881.   $self->recursive_object($object) if ++$objectstack{$id} > 1;
  882.   # return if we already saw it twice. It should be already properly serialized
  883.   return if $objectstack{$id} > 2;
  884.  
  885.   if (UNIVERSAL::isa($object => 'SOAP::Data')) { 
  886.     # use $object->SOAP::Data:: to enable overriding name() and others in inherited classes
  887.     $object->SOAP::Data::name($name) unless defined $object->SOAP::Data::name;
  888.  
  889.     # apply ->uri() and ->prefix() which can modify name and attributes of
  890.     # element, but do not modify SOAP::Data itself
  891.     my($name, $attr) = $self->fixattrs($object);
  892.     $attr = $self->attrstoqname($attr);
  893.  
  894.     my @realvalues = $object->SOAP::Data::value;
  895.     return [$name || gen_name, $attr] unless @realvalues;
  896.  
  897.     my $method = "as_" . ($object->SOAP::Data::type || '-'); # dummy type if not defined
  898.     # try to call method specified for this type
  899.     my @values = map { 
  900.       # store null/nil attribute if value is undef
  901.       local $attr->{qualify(xsi => $self->xmlschemaclass->nilValue)} = $self->xmlschemaclass->as_undef(1)
  902.         unless defined;
  903.          $self->can($method) && $self->$method($_, $name || gen_name, $object->SOAP::Data::type, $attr)
  904.       || $self->typecast($_, $name || gen_name, $object->SOAP::Data::type, $attr)
  905.       || $self->encode_object($_, $name, $object->SOAP::Data::type, $attr)
  906.     } @realvalues;
  907.     $object->SOAP::Data::signature([map {join $;, $_->[0], disqualify($_->[1]->{'xsi:type'} || '')} @values]) if @values;
  908.     return wantarray ? @values : $values[0];
  909.   } 
  910.  
  911.   my $class = ref $object;
  912.   if ($class !~ /^(?:SCALAR|ARRAY|HASH|REF)$/o) { 
  913.     # we could also check for CODE|GLOB|LVALUE, but we cannot serialize 
  914.     # them anyway, so they'll be cought by check below
  915.     $class =~ s/::/__/g;
  916.  
  917.     $name = $class if !defined $name;
  918.     $type = $class if !defined $type && $self->autotype;
  919.  
  920.     my $method = 'as_' . $class;
  921.     if ($self->can($method)) {
  922.       my $encoded = $self->$method($object, $name, $type, $attr);
  923.       return $encoded if ref $encoded;
  924.       # return only if handled, otherwise handle with default handlers
  925.     }
  926.   }
  927.  
  928.   return 
  929.     UNIVERSAL::isa($object => 'REF') ||
  930.     UNIVERSAL::isa($object => 'SCALAR') ? $self->encode_scalar($object, $name, $type, $attr) :
  931.     UNIVERSAL::isa($object => 'ARRAY')  ? $self->encode_array($object, $name, $type, $attr) :
  932.     UNIVERSAL::isa($object => 'HASH')   ? $self->encode_hash($object, $name, $type, $attr) :
  933.                                           $self->on_nonserialized->($object); 
  934. }
  935.  
  936. sub encode_scalar {
  937.   my($self, $value, $name, $type, $attr) = @_;
  938.   $name ||= gen_name;
  939.  
  940.   my $schemaclass = $self->xmlschemaclass;
  941.  
  942.   # null reference
  943.   return [$name, {%$attr, qualify(xsi => $schemaclass->nilValue) => $schemaclass->as_undef(1)}] unless defined $value;
  944.  
  945.   # object reference
  946.   return [$name, {'xsi:type' => $self->maptypetouri($type), %$attr}, [$self->encode_object($$value)], $self->gen_id($value)] if ref $value;
  947.  
  948.   # autodefined type 
  949.   if ($self->autotype) {
  950.     my $lookup = $self->typelookup;
  951.     for (sort {$lookup->{$a}->[0] <=> $lookup->{$b}->[0]} keys %$lookup) {
  952.       my $method = $lookup->{$_}->[2];
  953.       return $self->can($method) && $self->$method($value, $name, $type, $attr)
  954.           || $method->($value, $name, $type, $attr)
  955.         if $lookup->{$_}->[1]->($value);
  956.     }
  957.   }
  958.  
  959.   # invariant
  960.   return [$name, $attr, $value];
  961. }
  962.  
  963. sub encode_array {
  964.   my($self, $array, $name, $type, $attr) = @_;
  965.   my $items = 'item'; 
  966.  
  967. # TD: add support for multidimensional, partially transmitted and sparse arrays
  968.   my @items = map {$self->encode_object($_, $items)} @$array;
  969.   my $num = @items;
  970.   my($arraytype, %types) = '-';
  971.   for (@items) { $arraytype = $_->[1]->{'xsi:type'} || '-'; $types{$arraytype}++ }
  972.   $arraytype = sprintf "%s\[$num]", keys %types > 1 || $arraytype eq '-' ? qualify(xsd => $self->xmlschemaclass->anyTypeValue) : $arraytype;
  973.  
  974.   $type = qualify($self->encprefix => 'Array') if $self->autotype && !defined $type;
  975.  
  976.   return [$name || qualify($self->encprefix => 'Array'), 
  977.           {qualify($self->encprefix => 'arrayType') => $arraytype, 'xsi:type' => $self->maptypetouri($type), %$attr},
  978.           [@items], 
  979.           $self->gen_id($array)
  980.   ];
  981. }
  982.  
  983. sub encode_hash {
  984.   my($self, $hash, $name, $type, $attr) = @_;
  985.  
  986.   if ($self->autotype && grep {!/$SOAP::Constants::ELMASK/o} keys %$hash) {
  987.     warn qq!Cannot encode @{[$name ? "'$name'" : 'unnamed']} element as 'hash'. Will be encoded as 'map' instead\n! if $^W;
  988.     return $self->as_map($hash, $name || gen_name, $type, $attr);
  989.   }
  990.  
  991.   $type = 'SOAPStruct' if $self->autotype && !defined($type) && exists $self->maptype->{SOAPStruct};
  992.   return [$name || gen_name, 
  993.           {'xsi:type' => $self->maptypetouri($type), %$attr},
  994.           [map {$self->encode_object($hash->{$_}, $_)} keys %$hash], 
  995.           $self->gen_id($hash)
  996.   ];
  997. }
  998.  
  999. # ----------------------------------------------------------------------
  1000.  
  1001. sub as_ordered_hash {
  1002.   my $self = shift;
  1003.   my($value, $name, $type, $attr) = @_;
  1004.   die "Not an ARRAY reference for 'ordered_hash' type" unless UNIVERSAL::isa($value => 'ARRAY');
  1005.   return [$name, $attr, 
  1006.     [map{$self->encode_object(@{$value}[2*$_+1,2*$_])} 0..$#$value/2], 
  1007.     $self->gen_id($value)
  1008.   ];
  1009. }
  1010.  
  1011. sub as_map {
  1012.   my $self = shift;
  1013.   my($value, $name, $type, $attr) = @_;
  1014.   die "Not a HASH reference for 'map' type" unless UNIVERSAL::isa($value => 'HASH');
  1015.   my $prefix = ($self->namespaces->{$SOAP::Constants::NS_APS} ||= 'apachens');
  1016.   my @items = map {$self->encode_object(SOAP::Data->type(ordered_hash => [key => $_, value => $value->{$_}]), 'item', '')} keys %$value;
  1017.   return [$name, {'xsi:type' => "$prefix:Map", %$attr}, [@items], $self->gen_id($value)];
  1018. }
  1019.  
  1020. sub as_xml {
  1021.   my $self = shift;
  1022.   my($value, $name, $type, $attr) = @_;
  1023.   return [$name, {'_xml' => 1}, $value];
  1024. }
  1025.  
  1026. sub typecast {
  1027.   my $self = shift;
  1028.   my($value, $name, $type, $attr) = @_;
  1029.   return if ref $value; # skip complex object, caller knows how to deal with it
  1030.   return if $self->autotype && !defined $type; # we don't know, autotype knows
  1031.   return [$name,
  1032.           {(defined $type && $type gt '' ? ('xsi:type' => $self->maptypetouri($type, 'simple type')) : ()), %$attr},
  1033.           $value
  1034.   ];
  1035. }
  1036.  
  1037. # ----------------------------------------------------------------------
  1038.  
  1039. sub fixattrs {
  1040.   my $self = shift;
  1041.   my $data = shift;
  1042.   my($name, $attr) = ($data->SOAP::Data::name, {%{$data->SOAP::Data::attr}});
  1043.   my($xmlns, $prefix) = ($data->uri, $data->prefix);
  1044.   return ($name, $attr) unless defined($xmlns) || defined($prefix);
  1045.   $name ||= gen_name; # local name
  1046.   $prefix = gen_ns if !defined $prefix && $xmlns gt '';
  1047.   $prefix = '' if defined $xmlns  && $xmlns eq '' || 
  1048.                   defined $prefix && $prefix eq '';
  1049.  
  1050.   $attr->{join ':', xmlns => $prefix || ()} = $xmlns if defined $xmlns; 
  1051.   $name = join ':', $prefix, $name                   if $prefix;
  1052.  
  1053.   return ($name, $attr);
  1054. }
  1055.  
  1056. sub toqname {
  1057.   my $self = shift;
  1058.   my $long = shift;
  1059.  
  1060.   return $long unless $long =~ /^\{(.*)\}(.+)$/;
  1061.   return qualify $self->namespaces->{$1} ||= gen_ns, $2;
  1062. }
  1063.  
  1064. sub attrstoqname {
  1065.   my $self = shift;
  1066.   my $attrs = shift;
  1067.  
  1068.   return {
  1069.     map { /^\{(.*)\}(.+)$/ 
  1070.       ? ($self->toqname($_) => $2 eq 'type' || $2 eq 'arrayType' ? $self->toqname($attrs->{$_}) : $attrs->{$_})
  1071.       : ($_ => $attrs->{$_})
  1072.    } keys %$attrs
  1073.   };
  1074. }
  1075.  
  1076. sub tag {
  1077.   my $self = shift;
  1078.   my($tag, $attrs, @values) = @_;
  1079.   my $value = join '', @values;
  1080.   my $level = $self->level;
  1081.   my $indent = $self->readable ? "\n" . ' ' x (($level-1)*2) : '';
  1082.   # check for special attribute
  1083.   return "$indent$value" if exists $attrs->{_xml} && delete $attrs->{_xml}; 
  1084.   die "Element '$tag' can't be allowed in valid XML message. Died\n"
  1085.     if $tag !~ /^(?![xX][mM][lL])$SOAP::Constants::NSMASK$/o;
  1086.  
  1087.   my $prolog = '';
  1088.   if ($level == 1) {
  1089.     my $namespaces = $self->namespaces;
  1090.     foreach (keys %$namespaces) { $attrs->{qualify(xmlns => $namespaces->{$_})} = $_ }
  1091.     $prolog = qq!<?xml version="1.0" encoding="@{[$self->encoding]}"?>!
  1092.       if defined $self->encoding;
  1093.   }
  1094.  
  1095.   my $tagattrs = join(' ', '', map { sprintf '%s="%s"', $_, SOAP::Utils::encode_attribute($attrs->{$_}) } 
  1096.                               grep { $_ && defined $attrs->{$_} && ($_ ne 'xsi:type' || $attrs->{$_} ne '')
  1097.                                    } keys %$attrs);
  1098.   $value gt '' 
  1099.     ? sprintf("$prolog$indent<%s%s$indent>%s</%s>", $tag, $tagattrs, $value, $tag) 
  1100.     : sprintf("$prolog$indent<%s%s/>", $tag, $tagattrs);
  1101. }
  1102.  
  1103. sub xmlize {
  1104.   my $self = shift;
  1105.   my($name, $attrs, $values, $id) = @{+shift}; $attrs ||= {};
  1106.  
  1107.   local $self->{_level} = $self->{_level} + 1;
  1108.   return $self->tag($name, $attrs) unless defined $values;
  1109.   return $self->tag($name, $attrs, $values) unless UNIVERSAL::isa($values => 'ARRAY');
  1110.   return $self->tag($name, {%$attrs, href => '#' . $self->multiref_anchor($id)}) if $self->is_href($id, delete($attrs->{_id}));
  1111.   return $self->tag($name, {%$attrs, id => $self->multiref_anchor($id)}, map {$self->xmlize($_)} @$values); 
  1112. }
  1113.  
  1114. sub uriformethod {
  1115.   my $self = shift;
  1116.  
  1117.   my $method_is_data = ref $_[0] && UNIVERSAL::isa($_[0] => 'SOAP::Data');
  1118.  
  1119.   # drop prefrix from method that could be string or SOAP::Data object
  1120.   my($prefix, $method) = $method_is_data 
  1121.     ? ($_[0]->prefix, $_[0]->name)
  1122.     : SOAP::Utils::splitqname($_[0]);
  1123.  
  1124.   my $attr = {reverse %{$self->namespaces}};
  1125.   # try to define namespace that could be stored as
  1126.   #   a) method is SOAP::Data 
  1127.   #        ? attribute in method's element as xmlns= or xmlns:${prefix}=
  1128.   #        : uri
  1129.   #   b) attribute in Envelope element as xmlns= or xmlns:${prefix}=
  1130.   #   c) no prefix or prefix equal serializer->envprefix
  1131.   #        ? '', but see coment below
  1132.   #        : die with error message
  1133.   my $uri = $method_is_data 
  1134.     ? ref $_[0]->attr && ($_[0]->attr->{$prefix ? "xmlns:$prefix" : 'xmlns'} || $_[0]->uri)
  1135.     : $self->uri;
  1136.  
  1137.   defined $uri or $uri = $attr->{$prefix || ''};
  1138.  
  1139.   defined $uri or $uri = !$prefix || $prefix eq $self->envprefix 
  1140.     # still in doubts what should namespace be in this case 
  1141.     # but will keep it like this for now and be compatible with our server
  1142.     ? ( $method_is_data && $^W && warn("URI is not provided as an attribute for method ($method)\n"),
  1143.         ''
  1144.       )
  1145.     : die "Can't find namespace for method ($prefix:$method)\n";
  1146.  
  1147.   return ($uri, $method);
  1148. }
  1149.  
  1150. sub serialize { SOAP::Trace::trace('()');
  1151.   my $self = shift->new;
  1152.   @_ == 1 or Carp::croak "serialize() method accepts one parameter";
  1153.  
  1154.   $self->seen({}); # reinitialize multiref table
  1155.   my($encoded) = $self->encode_object($_[0]);
  1156.  
  1157.   # now encode multirefs if any
  1158.   #                 v -------------- subelements of Envelope
  1159.   push(@{$encoded->[2]}, $self->encode_multirefs) if ref $encoded->[2];
  1160.   return $self->xmlize($encoded);
  1161. }
  1162.  
  1163. sub envelope { SOAP::Trace::trace('()');
  1164.   my $self = shift->new;
  1165.   my $type = shift;
  1166.  
  1167.   my(@parameters, @header);
  1168.   for (@_) { 
  1169.     defined $_ && ref $_ && UNIVERSAL::isa($_ => 'SOAP::Header') 
  1170.       ? push(@header, $_) : push(@parameters, $_);
  1171.   }
  1172.   my $header = @header ? SOAP::Data->set_value(@header) : undef;
  1173.   my($body,$parameters);
  1174.   if ($type eq 'method' || $type eq 'response') {
  1175.     SOAP::Trace::method(@parameters);
  1176.     my $method = shift(@parameters) or die "Unspecified method for SOAP call\n";
  1177.     $parameters = @parameters ? SOAP::Data->set_value(@parameters) : undef;
  1178.     $body = UNIVERSAL::isa($method => 'SOAP::Data') 
  1179.       ? $method : SOAP::Data->name($method)->uri($self->uri);
  1180.     $body->set_value($parameters ? \$parameters : ());
  1181.   } elsif ($type eq 'fault') {
  1182.     SOAP::Trace::fault(@parameters);
  1183.     $body = SOAP::Data
  1184.       -> name(qualify($self->envprefix => 'Fault'))
  1185.     # commented on 2001/03/28 because of failing in ApacheSOAP
  1186.     # need to find out more about it
  1187.     # -> attr({'xmlns' => ''})
  1188.       -> value(\SOAP::Data->set_value(
  1189.         SOAP::Data->name(faultcode => qualify($self->envprefix => $parameters[0])),
  1190.         SOAP::Data->name(faultstring => $parameters[1]),
  1191.         defined($parameters[2]) ? SOAP::Data->name(detail => do{my $detail = $parameters[2]; ref $detail ? \$detail : $detail}) : (),
  1192.         defined($parameters[3]) ? SOAP::Data->name(faultactor => $parameters[3]) : (),
  1193.       ));
  1194.   } elsif ($type eq 'freeform') {
  1195.     SOAP::Trace::freeform(@parameters);
  1196.     $body = SOAP::Data->set_value(@parameters);
  1197.   } else {
  1198.     die "Wrong type of envelope ($type) for SOAP call\n";
  1199.   }
  1200.  
  1201.   $self->seen({}); # reinitialize multiref table
  1202.   my($encoded) = $self->encode_object(
  1203.     SOAP::Data->name(qualify($self->envprefix => 'Envelope') => \SOAP::Data->value(
  1204.       ($header ? SOAP::Data->name(qualify($self->envprefix => 'Header') => \$header) : ()),
  1205.       SOAP::Data->name(qualify($self->envprefix => 'Body')   => \$body)
  1206.     ))->attr($self->attr)
  1207.   );
  1208.   $self->signature($parameters->signature) if ref $parameters;
  1209.  
  1210.   # IMHO multirefs should be encoded after Body, but only some
  1211.   # toolkits understand this encoding, so we'll keep them for now (04/15/2001)
  1212.   # as the last element inside the Body 
  1213.   #                 v -------------- subelements of Envelope
  1214.   #                      vv -------- last of them (Body)
  1215.   #                            v --- subelements
  1216.   push(@{$encoded->[2]->[-1]->[2]}, $self->encode_multirefs) if ref $encoded->[2]->[-1]->[2];
  1217.   return $self->xmlize($encoded);
  1218. }
  1219.  
  1220. # ======================================================================
  1221.  
  1222. package SOAP::Parser;
  1223.  
  1224. sub DESTROY { SOAP::Trace::objects('()') }
  1225.  
  1226. sub xmlparser {
  1227.   my $self = shift;
  1228.   return eval { $SOAP::Constants::DO_NOT_USE_XML_PARSER ? undef : do {require XML::Parser; XML::Parser->new} } || 
  1229.          eval { require XML::Parser::Lite; XML::Parser::Lite->new } ||
  1230.          die "XML::Parser is not @{[$SOAP::Constants::DO_NOT_USE_XML_PARSER ? 'used' : 'available']} and ", $@;
  1231. }
  1232.  
  1233. sub parser {
  1234.   my $self = shift->new;
  1235.   @_ ? ($self->{'_parser'} = shift, return $self) : return ($self->{'_parser'} ||= $self->xmlparser);
  1236. }
  1237.  
  1238. sub new { 
  1239.   my $self = shift;
  1240.   my $class = ref($self) || $self;
  1241.  
  1242.   return $self if ref $self;
  1243.  
  1244.   SOAP::Trace::objects('()');
  1245.  
  1246.   return bless {_parser => shift} => $class;
  1247. }
  1248.  
  1249. sub decode { SOAP::Trace::trace('()');
  1250.   my $self = shift;
  1251.  
  1252.   $self->parser->setHandlers(
  1253.     Final => sub { shift; $self->final(@_) },
  1254.     Start => sub { shift; $self->start(@_) },
  1255.     End   => sub { shift; $self->end(@_)   },
  1256.     Char  => sub { shift; $self->char(@_)  },
  1257.   );
  1258.   $self->parser->parse($_[0]);
  1259. }
  1260.  
  1261. sub final { 
  1262.   my $self = shift; 
  1263.  
  1264.   # clean handlers, otherwise SOAP::Parser won't be deleted: 
  1265.   # it refers to XML::Parser which refers to subs from SOAP::Parser
  1266.   # Thanks to Ryan Adams <iceman@mit.edu>
  1267.   # and Craig Johnston <craig.johnston@pressplay.com>
  1268.   # checked by number of tests in t/02-payload.t
  1269.  
  1270.   undef $self->{_values};
  1271.   $self->parser->setHandlers(
  1272.     Final => undef, Start => undef, End   => undef, Char  => undef,
  1273.   );
  1274.   $self->{_done};
  1275. }
  1276.  
  1277. sub start { push @{shift->{_values}}, [shift, {@_}] }
  1278.  
  1279. # string concatenation changed to arrays which should improve performance
  1280. # for strings with many entity-encoded elements.
  1281. # Thanks to Mathieu Longtin <mrdamnfrenchy@yahoo.com>
  1282. sub char { push @{shift->{_values}->[-1]->[3]}, shift }
  1283.  
  1284. sub end { 
  1285.   my $self = shift; 
  1286.   my $done = pop @{$self->{_values}};
  1287.   $done->[2] = defined $done->[3] ? join('',@{$done->[3]}) : '' unless ref $done->[2];
  1288.   undef $done->[3]; 
  1289.   @{$self->{_values}} ? (push @{$self->{_values}->[-1]->[2]}, $done)
  1290.                       : ($self->{_done} = $done);
  1291. }
  1292.  
  1293. # ======================================================================
  1294.  
  1295. package SOAP::MIMEParser;
  1296.  
  1297. use vars qw(@ISA);
  1298.  
  1299. @ISA = qw(MIME::Parser);
  1300.  
  1301. sub DESTROY { SOAP::Trace::objects('()') }
  1302.  
  1303. sub new { local $^W; require MIME::Parser; Exporter::require_version('MIME::Parser' => 5.220); 
  1304.   my $self = shift;
  1305.  
  1306.   unless (ref $self) {
  1307.     my $class = ref($self) || $self;
  1308.     $self = $class->SUPER::new();
  1309.     unshift(@_, output_to_core => 'ALL', tmp_to_core => 1, ignore_errors => 1);
  1310.     SOAP::Trace::objects('()');
  1311.   }
  1312.  
  1313.   while (@_) { my $method = shift; $self->$method(shift) if $self->can($method) }
  1314.  
  1315.   return $self;
  1316. }
  1317.  
  1318. sub get_multipart_id { (shift || '') =~ /^<(.+)>$/; $1 || '' }
  1319.  
  1320. sub decode { 
  1321.   my $self = shift;
  1322.  
  1323.   my $entity = eval { $self->parse_data(shift) } or die "Something wrong with MIME message: @{[$@ || $self->last_error]}\n";
  1324.  
  1325.   my @result = 
  1326.     $entity->head->mime_type eq 'multipart/form-data' ? $self->decode_form_data($entity) :
  1327.     $entity->head->mime_type eq 'multipart/related' ? $self->decode_related($entity) :
  1328.     $entity->head->mime_type eq 'text/xml' ? () :
  1329.     die "Can't handle MIME messsage with specified type (@{[$entity->head->mime_type]})\n";
  1330.  
  1331.   @result ? @result 
  1332.           : $entity->bodyhandle->as_string ? [undef, '', undef, $entity->bodyhandle->as_string]
  1333.                                            : die "No content in MIME message\n";
  1334. }
  1335.  
  1336. sub decode_form_data { 
  1337.   my($self, $entity) = @_;
  1338.  
  1339.   my @result;
  1340.   foreach my $part ($entity->parts) {
  1341.     my $name = $part->head->mime_attr('content-disposition.name');
  1342.     my $type = $part->head->mime_type || '';
  1343.  
  1344.     $name eq 'payload' 
  1345.       ? unshift(@result, [$name, '', $type, $part->bodyhandle->as_string])
  1346.       : push(@result, [$name, '', $type, $part->bodyhandle->as_string]);
  1347.   }
  1348.   @result;
  1349. }
  1350.  
  1351. sub decode_related { 
  1352.   my($self, $entity) = @_;
  1353.   my $start = get_multipart_id($entity->head->mime_attr('content-type.start'));
  1354.   my $location = $entity->head->mime_attr('content-location') || 'thismessage:/';
  1355.  
  1356.   my @result;
  1357.   foreach my $part ($entity->parts) {
  1358.     my $pid = get_multipart_id($part->head->get('content-id',0));
  1359.     my $plocation = $part->head->get('content-location',0) || '';
  1360.     my $type = $part->head->mime_type || '';
  1361.  
  1362.     $start && $pid eq $start 
  1363.       ? unshift(@result, [$start, $location, $type, $part->bodyhandle->as_string])
  1364.       : push(@result, [$pid, $plocation, $type, $part->bodyhandle->as_string]);
  1365.   }
  1366.   die "Can't find 'start' parameter in multipart MIME message\n"
  1367.     if @result > 1 && !$start;
  1368.   @result;
  1369. }
  1370.  
  1371. # ======================================================================
  1372.  
  1373. package SOAP::SOM;
  1374.  
  1375. use Carp ();
  1376.  
  1377. sub BEGIN {
  1378.   no strict 'refs';
  1379.   my %path = (
  1380.     root        => '/',
  1381.     envelope    => '/Envelope',
  1382.     body        => '/Envelope/Body',
  1383.     header      => '/Envelope/Header',
  1384.     headers     => '/Envelope/Header/[>0]',
  1385.     fault       => '/Envelope/Body/Fault',
  1386.     faultcode   => '/Envelope/Body/Fault/faultcode',
  1387.     faultstring => '/Envelope/Body/Fault/faultstring',
  1388.     faultactor  => '/Envelope/Body/Fault/faultactor',
  1389.     faultdetail => '/Envelope/Body/Fault/detail',
  1390.   );
  1391.   for my $method (keys %path) {
  1392.     *$method = sub { 
  1393.       my $self = shift;
  1394.       ref $self or return $path{$method};
  1395.       Carp::croak "Method '$method' is readonly and doesn't accept any parameters" if @_;
  1396.       return $self->valueof($path{$method});
  1397.     };
  1398.   }
  1399.   my %results = (
  1400.     method    => '/Envelope/Body/[1]',
  1401.     result    => '/Envelope/Body/[1]/[1]',
  1402.     freeform  => '/Envelope/Body/[>0]',
  1403.     paramsin  => '/Envelope/Body/[1]/[>0]',
  1404.     paramsall => '/Envelope/Body/[1]/[>0]',
  1405.     paramsout => '/Envelope/Body/[1]/[>1]',
  1406.   );
  1407.   for my $method (keys %results) {
  1408.     *$method = sub { 
  1409.       my $self = shift;
  1410.       ref $self or return $results{$method};
  1411.       Carp::croak "Method '$method' is readonly and doesn't accept any parameters" if @_;
  1412.       defined $self->fault ? return : return $self->valueof($results{$method});
  1413.     };
  1414.   }
  1415.  
  1416.   for my $method (qw(o_child o_value o_lname o_lattr o_qname)) { # import from SOAP::Utils
  1417.     *$method = \&{'SOAP::Utils::'.$method};
  1418.   }
  1419. }
  1420.  
  1421. # use object in boolean context return true/false on last match
  1422. # Ex.: $som->match('//Fault') ? 'SOAP call failed' : 'success';
  1423. use overload fallback => 1, 'bool'  => sub { @{shift->{_current}} > 0 };
  1424.  
  1425. sub DESTROY { SOAP::Trace::objects('()') }
  1426.  
  1427. sub new { 
  1428.   my $self = shift;
  1429.   my $class = ref($self) || $self;
  1430.   my $content = shift;
  1431.   SOAP::Trace::objects('()');
  1432.   return bless { _content => $content, _current => [$content] } => $class;
  1433. }
  1434.  
  1435. sub current {
  1436.   my $self = shift;
  1437.   $self->{_current} = [@_], return $self if @_;
  1438.   return wantarray ? @{$self->{_current}} : $self->{_current}->[0];
  1439. }
  1440.  
  1441. sub valueof {
  1442.   my $self = shift;
  1443.   local $self->{_current} = $self->{_current}; 
  1444.   $self->match(shift) if @_;
  1445.   return wantarray ? map {o_value($_)} @{$self->{_current}} 
  1446.                    : @{$self->{_current}} ? o_value($self->{_current}->[0]) : undef;
  1447. }
  1448.  
  1449. sub headerof { # SOAP::Header is the same as SOAP::Data, so just rebless it
  1450.   wantarray 
  1451.     ? map { bless $_ => 'SOAP::Header' } shift->dataof(@_) 
  1452.     : do { # header returned by ->dataof can be undef in scalar context
  1453.         my $header = shift->dataof(@_); 
  1454.         ref $header ? bless($header => 'SOAP::Header') : undef;
  1455.       };
  1456. }
  1457.  
  1458. sub dataof {
  1459.   my $self = shift;
  1460.   local $self->{_current} = $self->{_current}; 
  1461.   $self->match(shift) if @_;
  1462.   return wantarray ? map {$self->_as_data($_)} @{$self->{_current}} 
  1463.                    : @{$self->{_current}} ? $self->_as_data($self->{_current}->[0]) : undef;
  1464. }
  1465.  
  1466. sub namespaceuriof {
  1467.   my $self = shift;
  1468.   local $self->{_current} = $self->{_current}; 
  1469.   $self->match(shift) if @_;
  1470.   return wantarray ? map {(SOAP::Utils::splitlongname(o_lname($_)))[0]} @{$self->{_current}} 
  1471.                    : @{$self->{_current}} ? (SOAP::Utils::splitlongname(o_lname($self->{_current}->[0])))[0] : undef;
  1472. }
  1473.  
  1474. sub _as_data {
  1475.   my $self = shift;
  1476.   my $pointer = shift;
  1477.  
  1478.   SOAP::Data
  1479.     -> new(prefix => '', name => o_qname($pointer), name => o_lname($pointer), attr => o_lattr($pointer))
  1480.     -> set_value(o_value($pointer));
  1481. }
  1482.  
  1483. sub match { 
  1484.   my $self = shift;
  1485.   my $path = shift;
  1486.   $self->{_current} = [
  1487.     $path =~ s!^/!! || !@{$self->{_current}}
  1488.       ? $self->_traverse($self->{_content}, 1 => split '/' => $path)
  1489.       : map {$self->_traverse_tree(o_child($_), split '/' => $path)} @{$self->{_current}}
  1490.   ];
  1491.   return $self;
  1492. }
  1493.  
  1494. sub _traverse {
  1495.   my $self = shift;
  1496.   my($pointer, $itself, $path, @path) = @_;
  1497.  
  1498.   die "Incorrect parameter" unless $itself =~ /^\d*$/;
  1499.  
  1500.   if ($path && substr($path, 0, 1) eq '{') {
  1501.     $path = join '/', $path, shift @path while @path && $path !~ /}/;
  1502.   }
  1503.  
  1504.   my($op, $num) = $path =~ /^\[(<=|<|>=|>|=|!=?)?(\d+)\]$/ if defined $path;
  1505.  
  1506.   return $pointer unless defined $path;
  1507.  
  1508.   $op = '==' unless $op; $op .= '=' if $op eq '=' || $op eq '!';
  1509.   my $numok = defined $num && eval "$itself $op $num";
  1510.   my $nameok = (o_lname($pointer) || '') =~ /(?:^|\})$path$/ if defined $path; # name can be with namespace
  1511.  
  1512.   my $anynode = $path eq '';
  1513.   unless ($anynode) {
  1514.     if (@path) {
  1515.       return if defined $num && !$numok || !defined $num && !$nameok;
  1516.     } else {
  1517.       return $pointer if defined $num && $numok || !defined $num && $nameok;
  1518.       return;
  1519.     }
  1520.   }
  1521.  
  1522.   my @walk;
  1523.   push @walk, $self->_traverse_tree([$pointer], @path) if $anynode;
  1524.   push @walk, $self->_traverse_tree(o_child($pointer), $anynode ? ($path, @path) : @path);
  1525.   return @walk;
  1526. }
  1527.  
  1528. sub _traverse_tree {
  1529.   my $self = shift;
  1530.   my($pointer, @path) = @_;
  1531.  
  1532.   # can be list of children or value itself. Traverse only children
  1533.   return unless ref $pointer eq 'ARRAY'; 
  1534.  
  1535.   my $itself = 1;
  1536.  
  1537.   grep {defined} 
  1538.     map {$self->_traverse($_, $itself++, @path)} 
  1539.       grep {!ref o_lattr($_) ||
  1540.             !exists o_lattr($_)->{"{$SOAP::Constants::NS_ENC}root"} || 
  1541.             o_lattr($_)->{"{$SOAP::Constants::NS_ENC}root"} ne '0'}
  1542.         @$pointer;
  1543. }
  1544.  
  1545. # ======================================================================
  1546.  
  1547. package SOAP::Deserializer;
  1548.  
  1549. use vars qw(@ISA);
  1550.  
  1551. @ISA = qw(SOAP::Cloneable);
  1552.  
  1553. sub DESTROY { SOAP::Trace::objects('()') }
  1554.  
  1555. sub BEGIN {
  1556.   no strict 'refs';
  1557.   for my $method (qw(ids hrefs parser base xmlschemas xmlschema)) {
  1558.     my $field = '_' . $method;
  1559.     *$method = sub {
  1560.       my $self = shift->new;
  1561.       @_ ? ($self->{$field} = shift, return $self) : return $self->{$field};
  1562.     }
  1563.   }
  1564. }
  1565.  
  1566. sub new { 
  1567.   my $self = shift;
  1568.   my $class = ref($self) || $self;
  1569.   return $self if ref $self;
  1570.  
  1571.   SOAP::Trace::objects('()');
  1572.   return bless {
  1573.     _ids => {}, 
  1574.     _hrefs => {},
  1575.     _parser => SOAP::Parser->new,
  1576.     _xmlschemas => {
  1577.       $SOAP::Constants::NS_APS => 'SOAP::XMLSchemaApacheSOAP::Deserializer', 
  1578.       map { $_ => $SOAP::Constants::XML_SCHEMAS{$_} . '::Deserializer'
  1579.           } keys %SOAP::Constants::XML_SCHEMAS
  1580.     },
  1581.   } => $class;
  1582. }
  1583.  
  1584. sub mimeparser {
  1585.   my $field = '_mimeparser';
  1586.   my $self = shift->new;
  1587.   @_ ? ($self->{$field} = shift, return $self) 
  1588.      : return $self->{$field} ||= new SOAP::MIMEParser;
  1589. }
  1590.  
  1591. sub is_xml {
  1592.   # Added check for envelope delivery. Fairly standard with MMDF and sendmail
  1593.   # Thanks to Chris Davies <Chris.Davies@ManheimEurope.com> 
  1594.   $_[1] =~ /^\s*</ || $_[1] !~ /^(?:[\w-]+:|From )/;
  1595. }
  1596.  
  1597. sub baselocation { 
  1598.   my $self = shift;
  1599.   my $location = shift;
  1600.   if ($location) { 
  1601.     my $uri = URI->new($location); 
  1602.     # make absolute location if relative
  1603.     $location = $uri->abs($self->base)->as_string unless $uri->scheme;
  1604.   }
  1605.   $location;
  1606. }
  1607.  
  1608. sub mimedecode {
  1609.   my $self = shift->new;
  1610.  
  1611.   my $body;
  1612.   foreach ($self->mimeparser->decode($_[0])) {
  1613.     my($id, $location, $type, $value) = @$_;
  1614.  
  1615.     unless ($body) { # we are here for the first time, so it's a MAIN part
  1616.       $body = $self->parser->decode($value);
  1617.       $self->base($location); # store the base location
  1618.     } else {
  1619.       $location = $self->baselocation($location);
  1620.       my $part = $type eq 'text/xml' && !$SOAP::Constants::DO_NOT_PROCESS_XML_IN_MIME ? $self->parser->decode($value) : ['mimepart', {}, $value];
  1621.       $self->ids->{$id} = $part if $id;
  1622.       $self->ids->{$location} = $part if $location;
  1623.     }
  1624.   }
  1625.   return $body;
  1626. }
  1627.  
  1628. sub decode {
  1629.   my $self = shift->new;
  1630.   return $self->is_xml($_[0]) 
  1631.     ? $self->parser->decode($_[0]) 
  1632.     : $self->mimedecode($_[0]);
  1633. }
  1634.  
  1635. sub deserialize { SOAP::Trace::trace('()');
  1636.   my $self = shift->new;
  1637.  
  1638.   # initialize 
  1639.   $self->hrefs({}); 
  1640.   $self->ids({}); 
  1641.  
  1642.   # TBD: find better way to signal parsing errors
  1643.   my $parsed = $self->decode($_[0]); # TBD: die on possible errors in Parser?
  1644.  
  1645.   # if there are some IDs (from mime processing), then process others
  1646.   # otherwise delay till we first meet IDs
  1647.   if (keys %{$self->ids()}) {$self->traverse_ids($parsed)} else {$self->ids($parsed)}
  1648.  
  1649.   $self->decode_object($parsed);
  1650.   return SOAP::SOM->new($parsed);
  1651. }
  1652.  
  1653. sub traverse_ids {
  1654.   my $self = shift;
  1655.   my $ref = shift;
  1656.   my($undef, $attrs, $children) = @$ref;
  1657.   #  ^^^^^^ to fix nasty error on Mac platform (Carl K. Cunningham)
  1658.  
  1659.   $self->ids->{$attrs->{id}} = $ref if exists $attrs->{id};
  1660.   return unless ref $children;
  1661.   for (@$children) {$self->traverse_ids($_)};
  1662. }
  1663.  
  1664. sub decode_object {
  1665.   my $self = shift;              
  1666.   my $ref = shift;
  1667.   my($name, $attrs, $children, $value) = @$ref;
  1668.  
  1669.   $ref->[6] = $attrs = {%$attrs}; # make a copy for long attributes
  1670.  
  1671.   use vars qw(%uris);
  1672.   local %uris = (%uris, map { 
  1673.       do { (my $ns = $_) =~ s/^xmlns:?//; $ns } => delete $attrs->{$_} 
  1674.     } grep {/^xmlns(:|$)/} keys %$attrs);
  1675.  
  1676.   foreach (keys %$attrs) {
  1677.     next unless m/^($SOAP::Constants::NSMASK?):($SOAP::Constants::NSMASK)$/;
  1678.  
  1679.     $1 =~ /^[xX][mM][lL]/ ||
  1680.       $uris{$1} && 
  1681.         do { 
  1682.           $attrs->{SOAP::Utils::longname($uris{$1}, $2)} = do { 
  1683.             my $value = $attrs->{$_};
  1684.             $2 ne 'type' && $2 ne 'arrayType'
  1685.               ? $value 
  1686.               : SOAP::Utils::longname($value =~ m/^($SOAP::Constants::NSMASK?):(${SOAP::Constants::NSMASK}(?:\[[\d,]*\])*)/ 
  1687.                   ? ($uris{$1} || die("Unresolved prefix '$1' for attribute value '$value'\n"), $2)
  1688.                   : ($uris{''} || die("Unspecified namespace for type '$value'\n"), $value)
  1689.                 );
  1690.           };
  1691.           1;
  1692.         } || 
  1693.       die "Unresolved prefix '$1' for attribute '$_'\n";
  1694.   }
  1695.  
  1696.   # Check if any of the attribute values could be qnames, in which
  1697.   # case we replace them with a QNameValue object so that we capture
  1698.   # the namespace that the prefix mapped to.
  1699.   foreach (values %$attrs) {
  1700.       if ($uris{''} && /^[a-zA-Z][\w\.\-]*$/) {
  1701.       $_ = SOAP::Lite::QNameValue->new($_, $uris{''}, $_);
  1702.       }
  1703.       elsif (/^([a-zA-Z][\w\.\-]*):([a-zA-Z][\w\.\-]*)$/ && $uris{$1}) {
  1704.       $_ = SOAP::Lite::QNameValue->new($_, $uris{$1}, $2);
  1705.       }
  1706.   }
  1707.  
  1708.   # and now check the element
  1709.   my $ns = ($name =~ s/^($SOAP::Constants::NSMASK?):// ? $1 : '');
  1710.   $ref->[5] = SOAP::Utils::longname(
  1711.     $ns ? ($uris{$ns} || die "Unresolved prefix '$ns' for element '$name'\n")
  1712.         : (defined $uris{''} ? $uris{''} : undef),
  1713.     $name
  1714.   );
  1715.  
  1716.   ($children, $value) = (undef, $children) unless ref $children;
  1717.  
  1718.   return $name => ($ref->[4] = $self->decode_value(
  1719.     [$ref->[5], $attrs, $children, $value]
  1720.   ));
  1721. }
  1722.  
  1723. sub decode_value {
  1724.   my $self = shift;
  1725.   my $ref = shift;
  1726.   my($name, $attrs, $children, $value) = @$ref;
  1727.  
  1728.   # check SOAP version if applicable
  1729.   use vars '$level'; local $level = $level || 0;
  1730.   if (++$level == 1) {
  1731.     my($namespace, $envelope) = SOAP::Utils::splitlongname($name);
  1732.     SOAP::Lite->soapversion($namespace) if $envelope eq 'Envelope' && $namespace;
  1733.   }
  1734.  
  1735.   # check encodingStyle
  1736.   # future versions may bind deserializer to encodingStyle
  1737.   my $encodingStyle = $attrs->{"{$SOAP::Constants::NS_ENV}encodingStyle"};
  1738.   die "Unrecognized/unsupported value of encodingStyle attribute '$encodingStyle'\n"
  1739.     if defined $encodingStyle &&
  1740.        length($encodingStyle) != 0 && # encodingStyle=""
  1741.        $encodingStyle !~ /(?:^|\b)$SOAP::Constants::NS_ENC/;
  1742.                         # ^^^^^^^^ \b causing problems (!?) on some systems 
  1743.                         # as reported by David Dyck <dcd@tc.fluke.com>
  1744.                         # so use (?:^|\b) instead
  1745.  
  1746.   use vars '$arraytype'; # type of Array element specified on Array itself 
  1747.   # either specified with xsi:type, or <enc:name/> or array element 
  1748.   my($type) = grep {defined} 
  1749.                 map($attrs->{$_}, sort grep {/^\{$SOAP::Constants::NS_XSI_ALL\}type$/o} keys %$attrs), 
  1750.                 $name =~ /^\{$SOAP::Constants::NS_ENC\}/ ? $name : $arraytype;
  1751.   local $arraytype; # it's used only for one level, we don't need it anymore
  1752.  
  1753.   # $name is not used here since type should be encoded as type, not as name
  1754.   my($schema, $class) = SOAP::Utils::splitlongname($type) if $type;
  1755.  
  1756.   my $schemaclass = $schema && $self->xmlschemas->{$schema}
  1757.                             || $self;
  1758.   # store schema that is used in parsed message 
  1759.   $self->xmlschema($schema) if $schema && $schema =~ /XMLSchema/;
  1760.  
  1761.   # don't use class/type if anyType/ur-type is specified on wire
  1762.   undef $class if $schemaclass->can('anyTypeValue') && $schemaclass->anyTypeValue eq $class;
  1763.  
  1764.   my $method = 'as_' . ($class || '-'); # dummy type if not defined
  1765.   $class =~ s/__|\./::/g if $class;
  1766.  
  1767.   my $id = $attrs->{id};
  1768.  
  1769.   if (defined $id && exists $self->hrefs->{$id}) {
  1770.     return $self->hrefs->{$id};
  1771.   } elsif (exists $attrs->{href}) {
  1772.     (my $id = delete $attrs->{href}) =~ s/^(#|cid:)?//;
  1773.     # convert to absolute if not internal '#' or 'cid:'
  1774.     $id = $self->baselocation($id) unless $1;
  1775.     return $self->hrefs->{$id} if exists $self->hrefs->{$id};
  1776.     my $ids = $self->ids;
  1777.     # first time optimization. we don't traverse IDs unless asked for it
  1778.     if (ref $ids ne 'HASH') { $self->ids({}); $self->traverse_ids($ids); $ids = $self->ids }
  1779.     if (exists $ids->{$id}) {
  1780.       my $obj = ($self->decode_object(delete $ids->{$id}))[1];
  1781.       return $self->hrefs->{$id} = $obj; 
  1782.     } else {
  1783.       die "Unresolved (wrong?) href ($id) in element '$name'\n";
  1784.     }
  1785.   }
  1786.  
  1787.   return undef if grep {
  1788.     /^$SOAP::Constants::NS_XSI_NILS$/ && 
  1789.     $self->xmlschemas->{$1 || $2}->as_undef($attrs->{$_})
  1790.   } keys %$attrs;
  1791.  
  1792.   # try to handle with typecasting
  1793.   my $res = $self->typecast($value, $name, $attrs, $children, $type);
  1794.   return $res if defined $res;
  1795.  
  1796.   # ok, continue with others
  1797.   if (exists $attrs->{"{$SOAP::Constants::NS_ENC}arrayType"}) {
  1798.     my $res = [];
  1799.     $self->hrefs->{$id} = $res if defined $id;
  1800.  
  1801.     # check for arrayType which could be [1], [,2][5] or [] 
  1802.     # [,][1] will NOT be allowed right now (multidimensional sparse array)
  1803.     my($type, $multisize) = $attrs->{"{$SOAP::Constants::NS_ENC}arrayType"} 
  1804.       =~ /^(.+)\[(\d*(?:,\d+)*)\](?:\[(?:\d+(?:,\d+)*)\])*$/
  1805.       or die qq!Unrecognized/unsupported format of arrayType attribute '@{[$attrs->{"{$SOAP::Constants::NS_ENC}arrayType"}]}'\n!;
  1806.  
  1807.     my @dimensions = map { $_ || undef } split /,/, $multisize;
  1808.     my $size = 1; foreach (@dimensions) { $size *= $_ || 0 }
  1809.  
  1810.     local $arraytype = $type;
  1811.  
  1812.     # multidimensional
  1813.     if ($multisize =~ /,/) { 
  1814.       @$res = splitarray(
  1815.         [@dimensions], 
  1816.         [map { scalar(($self->decode_object($_))[1]) } @{$children || []}]
  1817.       );
  1818.  
  1819.     # normal
  1820.     } else {
  1821.       @$res = map { scalar(($self->decode_object($_))[1]) } @{$children || []};
  1822.     }
  1823.  
  1824.     # sparse (position)
  1825.     if (ref $children && exists SOAP::Utils::o_lattr($children->[0])->{"{$SOAP::Constants::NS_ENC}position"}) {
  1826.       my @new;
  1827.       for (my $pos = 0; $pos < @$children; $pos++) {
  1828.         # TBD implement position in multidimensional array
  1829.         my($position) = SOAP::Utils::o_lattr($children->[$pos])->{"{$SOAP::Constants::NS_ENC}position"} =~ /^\[(\d+)\]$/
  1830.           or die "Position must be specified for all elements of sparse array\n";
  1831.         $new[$position] = $res->[$pos];
  1832.       }
  1833.       @$res = @new;
  1834.     }
  1835.  
  1836.     # partially transmitted (offset)
  1837.     # TBD implement offset in multidimensional array
  1838.     my($offset) = $attrs->{"{$SOAP::Constants::NS_ENC}offset"} =~ /^\[(\d+)\]$/
  1839.       if exists $attrs->{"{$SOAP::Constants::NS_ENC}offset"};
  1840.     unshift(@$res, (undef) x $offset) if $offset;
  1841.  
  1842.     die "Too many elements in array. @{[scalar@$res]} instead of claimed $multisize ($size)\n"
  1843.       if $multisize && $size < @$res;
  1844.  
  1845.     # extend the array if number of elements is specified
  1846.     $#$res = $dimensions[0]-1 if defined $dimensions[0] && @$res < $dimensions[0];
  1847.  
  1848.     return defined $class && $class ne 'Array' ? bless($res => $class) : $res;
  1849.  
  1850.   } elsif ($name =~ /^\{$SOAP::Constants::NS_ENC\}Struct$/ || !$schemaclass->can($method) && (ref $children || defined $class && $value =~ /^\s*$/)) {
  1851.     my $res = {};
  1852.     $self->hrefs->{$id} = $res if defined $id;
  1853.     %$res = map {$self->decode_object($_)} @{$children || []};
  1854.     return defined $class && $class ne 'SOAPStruct' ? bless($res => $class) : $res;
  1855.  
  1856.   } else {
  1857.     my $res;
  1858.     if ($schemaclass->can($method)) {
  1859.       $method = "$schemaclass\::$method" unless ref $schemaclass; 
  1860.       $res = $self->$method($value, $name, $attrs, $children, $type);
  1861.     } else {
  1862.       $res = $self->typecast($value, $name, $attrs, $children, $type);
  1863.       $res = $class ? die "Unrecognized type '$type'\n" : $value
  1864.         unless defined $res;
  1865.     }
  1866.     $self->hrefs->{$id} = $res if defined $id;
  1867.     return $res;
  1868.   }
  1869. }
  1870.  
  1871. sub splitarray {
  1872.   my @sizes = @{+shift};
  1873.   my $size = shift @sizes;
  1874.   my $array = shift;
  1875.  
  1876.   return splice(@$array, 0, $size) unless @sizes;
  1877.   my @array = ();
  1878.   push @array, [splitarray([@sizes], $array)] while @$array && (!defined $size || $size--);
  1879.   return @array;
  1880. }
  1881.  
  1882. sub typecast { } # typecast is called for both objects AND scalar types
  1883.                  # check ref of the second parameter (first is the object)
  1884.                  # return undef if you don't want to handle it
  1885.  
  1886. # ======================================================================
  1887.  
  1888. package SOAP::Lite::QNameValue;
  1889.  
  1890. use overload fallback => 1, '""' => sub { $_[0][0] };
  1891.  
  1892. sub new {
  1893.     my($class, $orig_val, $ns, $name) = @_;
  1894.     bless [$orig_val, $ns, $name], $class;
  1895. }
  1896.  
  1897. sub qname {
  1898.     my $self = shift;
  1899.     return SOAP::Utils::longname($self->[1], $self->[2]);
  1900. }
  1901.  
  1902. sub namespace { $_[0][1] }
  1903. sub localpart { $_[0][2] }
  1904.  
  1905. # ======================================================================
  1906.  
  1907. package SOAP::Client;
  1908.  
  1909. sub BEGIN {
  1910.   no strict 'refs';
  1911.   for my $method (qw(endpoint code message is_success status options)) {
  1912.     my $field = '_' . $method;
  1913.     *$method = sub {
  1914.       my $self = shift->new;
  1915.       @_ ? ($self->{$field} = shift, return $self) : return $self->{$field};
  1916.     }
  1917.   }
  1918. }
  1919.  
  1920. # ======================================================================
  1921.  
  1922. package SOAP::Server::Object;
  1923.  
  1924. sub gen_id; *gen_id = \&SOAP::Serializer::gen_id;
  1925.  
  1926. my %alive;
  1927. my %objects;
  1928.  
  1929. sub objects_by_reference { 
  1930.   shift; 
  1931.   while (@_) { @alive{shift()} = ref $_[0] ? shift : sub { $_[1]-$_[$_[5] ? 5 : 4] > 600 } } 
  1932.   keys %alive;
  1933. }
  1934.  
  1935. sub reference {
  1936.   my $self = shift;
  1937.   my $stamp = time;
  1938.   my $object = shift; 
  1939.   my $id = $stamp . $self->gen_id($object);
  1940.  
  1941.   # this is code for garbage collection
  1942.   my $time = time;
  1943.   my $type = ref $object;
  1944.   my @objects = grep { $objects{$_}->[1] eq $type } keys %objects;
  1945.   for (grep { $alive{$type}->(scalar @objects, $time, @{$objects{$_}}) } @objects) { 
  1946.     delete $objects{$_}; 
  1947.   } 
  1948.  
  1949.   $objects{$id} = [$object, $type, $stamp];
  1950.   bless { id => $id } => ref $object;
  1951. }
  1952.  
  1953. sub references {
  1954.   my $self = shift;
  1955.   return @_ unless %alive; # small optimization
  1956.   map { ref($_) && exists $alive{ref $_} ? $self->reference($_) : $_ } @_;
  1957. }
  1958.  
  1959. sub object {
  1960.   my $self = shift;
  1961.   my $class = ref($self) || $self;
  1962.   my $object = shift;
  1963.   return $object unless ref($object) && $alive{ref $object} && exists $object->{id};
  1964.   my $reference = $objects{$object->{id}};
  1965.   die "Object with specified id couldn't be found\n" unless ref $reference->[0];
  1966.   $reference->[3] = time; # last access time
  1967.   return $reference->[0]; # reference to actual object
  1968. }
  1969.  
  1970. sub objects {
  1971.   my $self = shift; 
  1972.   return @_ unless %alive; # small optimization
  1973.   map { ref($_) && exists $alive{ref $_} && exists $_->{id} ? $self->object($_) : $_ } @_;
  1974. }
  1975.  
  1976. # ======================================================================
  1977.  
  1978. package SOAP::Server::Parameters;
  1979.  
  1980. sub byNameOrOrder {
  1981.   unless (UNIVERSAL::isa($_[-1] => 'SOAP::SOM')) {
  1982.     warn "Last parameter is expected to be envelope\n" if $^W;
  1983.     pop;
  1984.     return @_;
  1985.   }
  1986.   my $params = pop->method;
  1987.   my @mandatory = ref $_[0] eq 'ARRAY' ? @{shift()} : die "list of parameters expected as the first parameter for byName";
  1988.   my $byname = 0; 
  1989.   my @res = map { $byname += exists $params->{$_}; $params->{$_} } @mandatory;
  1990.   return $byname ? @res : @_;
  1991. }
  1992.  
  1993. sub byName {
  1994.   unless (UNIVERSAL::isa($_[-1] => 'SOAP::SOM')) {
  1995.     warn "Last parameter is expected to be envelope\n" if $^W;
  1996.     pop;
  1997.     return @_;
  1998.   }
  1999.   return @{pop->method}{ref $_[0] eq 'ARRAY' ? @{shift()} : die "list of parameters expected as the first parameter for byName"};
  2000. }
  2001.  
  2002. # ======================================================================
  2003.  
  2004. package SOAP::Server;
  2005.  
  2006. use Carp ();
  2007.  
  2008. sub DESTROY { SOAP::Trace::objects('()') }
  2009.  
  2010. sub new { 
  2011.   my $self = shift;
  2012.  
  2013.   unless (ref $self) {
  2014.     my $class = ref($self) || $self;
  2015.     my(@params, @methods);
  2016.  
  2017.     while (@_) { my($method, $params) = splice(@_,0,2);
  2018.       $class->can($method) ? push(@methods, $method, $params) 
  2019.                            : $^W && Carp::carp "Unrecognized parameter '$method' in new()";
  2020.     }
  2021.     $self = bless {
  2022.       _dispatch_to => [], 
  2023.       _dispatch_with => {}, 
  2024.       _dispatched => [],
  2025.       _action => '',
  2026.       _options => {},
  2027.     } => $class;
  2028.     unshift(@methods, $self->initialize);
  2029.     while (@methods) { my($method, $params) = splice(@methods,0,2);
  2030.       $self->$method(ref $params eq 'ARRAY' ? @$params : $params) 
  2031.     }
  2032.     SOAP::Trace::objects('()');
  2033.   }
  2034.  
  2035.   Carp::carp "Odd (wrong?) number of parameters in new()" if $^W && (@_ & 1); 
  2036.   while (@_) { my($method, $params) = splice(@_,0,2);
  2037.     $self->can($method) 
  2038.       ? $self->$method(ref $params eq 'ARRAY' ? @$params : $params)
  2039.       : $^W && Carp::carp "Unrecognized parameter '$method' in new()"
  2040.   }
  2041.  
  2042.   return $self;
  2043. }
  2044.  
  2045. sub initialize {
  2046.   return (
  2047.     serializer => SOAP::Serializer->new,
  2048.     deserializer => SOAP::Deserializer->new,
  2049.     on_action => sub {},
  2050.     on_dispatch => sub {return},
  2051.   );
  2052. }
  2053.  
  2054. sub BEGIN {
  2055.   no strict 'refs';
  2056.   for my $method (qw(action myuri serializer deserializer options dispatch_with)) {
  2057.     my $field = '_' . $method;
  2058.     *$method = sub {
  2059.       my $self = shift->new;
  2060.       @_ ? ($self->{$field} = shift, return $self) : return $self->{$field};
  2061.     }
  2062.   }
  2063.   for my $method (qw(on_action on_dispatch)) {
  2064.     my $field = '_' . $method;
  2065.     *$method = sub {
  2066.       my $self = shift->new;
  2067.       return $self->{$field} unless @_;
  2068.       local $@;
  2069.       # commented out because that 'eval' was unsecure
  2070.       # > ref $_[0] eq 'CODE' ? shift : eval shift;
  2071.       # Am I paranoid enough?
  2072.       $self->{$field} = shift; 
  2073.       Carp::croak $@ if $@;
  2074.       Carp::croak "$method() expects subroutine (CODE) or string that evaluates into subroutine (CODE)"
  2075.         unless ref $self->{$field} eq 'CODE';
  2076.       return $self;
  2077.     }
  2078.   }
  2079.   for my $method (qw(dispatch_to)) {
  2080.     my $field = '_' . $method;
  2081.     *$method = sub {
  2082.       my $self = shift->new;
  2083.       @_ ? ($self->{$field} = [@_], return $self) 
  2084.          : return @{$self->{$field}};
  2085.     }
  2086.   }
  2087. }
  2088.  
  2089. sub objects_by_reference { 
  2090.   my $self = shift->new;
  2091.   @_ ? (SOAP::Server::Object->objects_by_reference(@_), return $self) 
  2092.      : SOAP::Server::Object->objects_by_reference; 
  2093. }
  2094.  
  2095. sub dispatched {
  2096.   my $self = shift->new;
  2097.   @_ ? (push(@{$self->{_dispatched}}, @_), return $self) 
  2098.      : return @{$self->{_dispatched}};
  2099. }
  2100.  
  2101. sub find_target {
  2102.   my $self = shift;
  2103.   my $request = shift;
  2104.  
  2105.   # try to find URI/method from on_dispatch call first
  2106.   my($method_uri, $method_name) = $self->on_dispatch->($request);
  2107.  
  2108.   # if nothing there, then get it from envelope itself
  2109.   $request->match((ref $request)->method);
  2110.   ($method_uri, $method_name) = ($request->namespaceuriof || '', $request->dataof->name)
  2111.     unless $method_name;
  2112.  
  2113.   $self->on_action->(my $action = $self->action, $method_uri, $method_name);
  2114.  
  2115.   # check to avoid security vulnerability: Protected->Unprotected::method(@parameters)
  2116.   # see for more details: http://www.phrack.org/phrack/58/p58-0x09
  2117.   die "Denied access to method ($method_name)\n" unless $method_name =~ /^\w+$/;
  2118.  
  2119.   my($class, $static);
  2120.   # try to bind directly
  2121.   if (defined($class = $self->dispatch_with->{$method_uri} 
  2122.                     || $self->dispatch_with->{$action}
  2123.                     || ($action =~ /^"(.+)"$/ ? $self->dispatch_with->{$1} : undef))) {
  2124.     # return object, nothing else to do here
  2125.     return ($class, $method_uri, $method_name) if ref $class;
  2126.     $static = 1;
  2127.   } else {
  2128.     die "URI path shall map to class" unless defined ($class = URI->new($method_uri)->path);
  2129.  
  2130.     for ($class) { s!^/|/$!!g; s!/!::!g; s/^$/main/; } 
  2131.     die "Failed to access class ($class)" unless $class =~ /^(\w[\w:]*)$/;
  2132.  
  2133.     my $fullname = "$class\::$method_name";
  2134.     foreach ($self->dispatch_to) {
  2135.       return ($_, $method_uri, $method_name) if ref eq $class; # $OBJECT
  2136.       next if ref;                                   # skip other objects
  2137.       # will ignore errors, because it may complain on 
  2138.       # d:\foo\bar, which is PATH and not regexp
  2139.       eval {
  2140.         $static ||= 
  2141.           $class =~ /^$_$/ ||                          # MODULE
  2142.           $fullname =~ /^$_$/ ||                       # MODULE::method
  2143.           $method_name =~ /^$_$/ && ($class eq 'main') # method ('main' assumed)
  2144.         ;
  2145.       };
  2146.     }
  2147.   }
  2148.  
  2149.   no strict 'refs';
  2150.   unless (defined %{"${class}::"}) {   
  2151.     # allow all for static and only specified path for dynamic bindings
  2152.     local @INC = (($static ? @INC : ()), grep {!ref && m![/\\.]!} $self->dispatch_to);
  2153.     eval 'local $^W; ' . "require $class";
  2154.     die "Failed to access class ($class): $@" if $@;
  2155.     $self->dispatched($class) unless $static;
  2156.   } 
  2157.  
  2158.   die "Denied access to method ($method_name) in class ($class)"  
  2159.     unless $static || grep {/^$class$/} $self->dispatched;
  2160.  
  2161.   return ($class, $method_uri, $method_name);
  2162. }
  2163.  
  2164. sub handle { SOAP::Trace::trace('()'); 
  2165.   my $self = shift;
  2166.  
  2167.   # we want to restore it when we are done
  2168.   local $SOAP::Constants::DEFAULT_XML_SCHEMA = $SOAP::Constants::DEFAULT_XML_SCHEMA;
  2169.  
  2170.   # SOAP version WILL NOT be restored when we are done.
  2171.   # is it problem?
  2172.  
  2173.   my $result = eval { local $SIG{__DIE__}; 
  2174.  
  2175.     $self->serializer->soapversion(1.1);
  2176.   
  2177.     my $request = eval { $self->deserializer->deserialize($_[0]) };
  2178.     die SOAP::Fault->faultcode($SOAP::Constants::FAULT_VERSION_MISMATCH)
  2179.                    ->faultstring($@)
  2180.       if $@ && $@ =~ /^$SOAP::Constants::WRONG_VERSION/;
  2181.     die "Application failed during request deserialization: $@" if $@;
  2182.   
  2183.     my $som = ref $request;
  2184.   
  2185.     die "Can't find root element in the message" unless $request->match($som->envelope);
  2186.   
  2187.     $self->serializer->soapversion(SOAP::Lite->soapversion);
  2188.     $self->serializer->xmlschema($SOAP::Constants::DEFAULT_XML_SCHEMA = $self->deserializer->xmlschema)
  2189.       if $self->deserializer->xmlschema;
  2190.   
  2191.     die SOAP::Fault->faultcode($SOAP::Constants::FAULT_MUST_UNDERSTAND)
  2192.                    ->faultstring("Unrecognized header has mustUnderstand attribute set to 'true'")
  2193.       if !$SOAP::Constants::DO_NOT_CHECK_MUSTUNDERSTAND &&
  2194.          grep { $_->mustUnderstand && (!$_->actor || $_->actor eq $SOAP::Constants::NEXT_ACTOR)
  2195.               } $request->dataof($som->headers);
  2196.   
  2197.     die "Can't find method element in the message" unless $request->match($som->method);
  2198.   
  2199.     my($class, $method_uri, $method_name) = $self->find_target($request);
  2200.   
  2201.     my @results = eval { local $^W;
  2202.       my @parameters = $request->paramsin;
  2203.   
  2204.       # SOAP::Trace::dispatch($fullname);
  2205.       SOAP::Trace::parameters(@parameters);
  2206.   
  2207.       push @parameters, $request if UNIVERSAL::isa($class => 'SOAP::Server::Parameters');
  2208.       SOAP::Server::Object->references(
  2209.         defined $parameters[0] && ref $parameters[0] && UNIVERSAL::isa($parameters[0] => $class) 
  2210.          ? do { 
  2211.              my $object = shift @parameters;
  2212.              SOAP::Server::Object->object(ref $class ? $class : $object)->$method_name(
  2213.                SOAP::Server::Object->objects(@parameters)), 
  2214.              # send object back as a header
  2215.              # preserve name, specify URI
  2216.              SOAP::Header->uri($SOAP::Constants::NS_SL_HEADER => $object)
  2217.                          ->name($request->dataof($som->method.'/[1]')->name)
  2218.            }
  2219.          : $class->$method_name(SOAP::Server::Object->objects(@parameters))
  2220.       );
  2221.     };
  2222.   
  2223.     SOAP::Trace::result(@results);
  2224.   
  2225.     # let application errors pass through with 'Server' code
  2226.     die ref $@ ? 
  2227.           $@ : $@ =~ /^Can't locate object method "$method_name"/ ? 
  2228.           "Failed to locate method ($method_name) in class ($class)" : 
  2229.           SOAP::Fault->faultcode($SOAP::Constants::FAULT_SERVER)->faultstring($@)
  2230.       if $@;
  2231.   
  2232.     return $self->serializer
  2233.       -> prefix('s') # distinguish generated element names between client and server
  2234.       -> uri($method_uri) 
  2235.       -> envelope(response => $method_name . 'Response', @results);
  2236.   };
  2237.  
  2238.   # void context
  2239.   return unless defined wantarray;
  2240.  
  2241.   # normal result
  2242.   return $result unless $@;
  2243.  
  2244.   # check fails, something wrong with message
  2245.   return $self->make_fault($SOAP::Constants::FAULT_CLIENT, $@) unless ref $@;
  2246.  
  2247.   # died with SOAP::Fault
  2248.   return $self->make_fault($@->faultcode   || $SOAP::Constants::FAULT_SERVER, 
  2249.                            $@->faultstring || 'Application error',
  2250.                            $@->faultdetail, $@->faultactor)
  2251.     if UNIVERSAL::isa($@ => 'SOAP::Fault');
  2252.  
  2253.   # died with complex detail
  2254.   return $self->make_fault($SOAP::Constants::FAULT_SERVER, 'Application error' => $@);
  2255. }
  2256.  
  2257. sub make_fault { 
  2258.   my $self = shift; 
  2259.   my($code, $string, $detail, $actor) = @_;
  2260.   $self->serializer->fault($code, $string, $detail, $actor || $self->myuri);
  2261.  
  2262. # ======================================================================
  2263.  
  2264. package SOAP::Trace;
  2265.  
  2266. use Carp ();
  2267.  
  2268. my @list = qw(transport dispatch result parameters headers objects method fault freeform trace debug);
  2269. { no strict 'refs'; for (@list) { *$_ = sub {} } }
  2270.  
  2271. sub defaultlog { 
  2272.   my $caller = (caller(1))[3];
  2273.   $caller = (caller(2))[3] if $caller =~ /eval/;
  2274.   chomp(my $msg = join ' ', @_); 
  2275.   printf STDERR "%s: %s\n", $caller, $msg;
  2276.  
  2277. sub import { no strict 'refs'; local $^W;
  2278.   my $pack = shift;
  2279.   my(@notrace, @symbols);
  2280.   for (@_) {
  2281.     if (ref eq 'CODE') {
  2282.       my $call = $_;
  2283.       foreach (@symbols) { *$_ = sub { $call->(@_) } }
  2284.       @symbols = ();
  2285.     } else {
  2286.       local $_ = $_;
  2287.       my $minus = s/^-//;
  2288.       my $all = $_ eq 'all';
  2289.       Carp::carp "Illegal symbol for tracing ($_)" unless $all || $pack->can($_);
  2290.       $minus ? push(@notrace, $all ? @list : $_) : push(@symbols, $all ? @list : $_);
  2291.     }
  2292.   }
  2293.   foreach (@symbols) { *$_ = \&defaultlog }
  2294.   foreach (@notrace) { *$_ = sub {} }
  2295. }
  2296.  
  2297. # ======================================================================
  2298.  
  2299. package SOAP::Custom::XML::Data;
  2300.  
  2301. use vars qw(@ISA $AUTOLOAD);
  2302. @ISA = qw(SOAP::Data);
  2303.  
  2304. use overload fallback => 1, '""' => sub { shift->value };
  2305.  
  2306. sub _compileit {
  2307.   no strict 'refs';
  2308.   my $method = shift;
  2309.   *$method = sub { 
  2310.     return __PACKAGE__->SUPER::name($method => $_[0]->attr->{$method})
  2311.       if exists $_[0]->attr->{$method};
  2312.     my @elems = grep {
  2313.       ref $_ && UNIVERSAL::isa($_ => __PACKAGE__) && $_->SUPER::name =~ /(^|:)$method$/
  2314.     } $_[0]->value;
  2315.     return wantarray? @elems : $elems[0];
  2316.   }
  2317. }
  2318.  
  2319. sub BEGIN { foreach (qw(name type import)) { _compileit($_) } }
  2320.  
  2321. sub AUTOLOAD {
  2322.   my $method = substr($AUTOLOAD, rindex($AUTOLOAD, '::') + 2);
  2323.   return if $method eq 'DESTROY';
  2324.  
  2325.   _compileit($method);
  2326.   goto &$AUTOLOAD;
  2327. }
  2328.  
  2329. # ======================================================================
  2330.  
  2331. package SOAP::Custom::XML::Deserializer;
  2332.  
  2333. use vars qw(@ISA);
  2334. @ISA = qw(SOAP::Deserializer);
  2335.  
  2336. sub decode_value {
  2337.   my $self = shift;
  2338.   my $ref = shift;
  2339.   my($name, $attrs, $children, $value) = @$ref;
  2340.  
  2341.   # base class knows what to do with it
  2342.   return $self->SUPER::decode_value($ref) if exists $attrs->{href};
  2343.  
  2344.   SOAP::Custom::XML::Data
  2345.     -> SOAP::Data::name($name) 
  2346.     -> attr($attrs)
  2347.     -> set_value(ref $children && @$children ? map(scalar(($self->decode_object($_))[1]), @$children) : $value);
  2348. }
  2349.  
  2350. # ======================================================================
  2351.  
  2352. package SOAP::Schema::Deserializer;
  2353.  
  2354. use vars qw(@ISA);
  2355. @ISA = qw(SOAP::Custom::XML::Deserializer);
  2356.  
  2357. # ======================================================================
  2358.  
  2359. package SOAP::Schema::WSDL;
  2360.  
  2361. use vars qw(%imported);
  2362.  
  2363. sub new { 
  2364.   my $self = shift;
  2365.  
  2366.   unless (ref $self) {
  2367.     my $class = ref($self) || $self;
  2368.     $self = bless {} => $class;
  2369.   }
  2370.   return $self;
  2371. }
  2372.  
  2373. sub base {
  2374.   my $self = shift->new;
  2375.   @_ ? ($self->{_base} = shift, return $self) : return $self->{_base};
  2376. }
  2377.  
  2378. sub import {
  2379.   my $self = shift->new;
  2380.   my $s = shift;
  2381.   my $base = shift || $self->base || die "Missing base argument for ", __PACKAGE__, "\n";
  2382.  
  2383.   my $schema;
  2384.   my @a = $s->import;
  2385.   local %imported = %imported;
  2386.   foreach (@a) {
  2387.     next unless $_->location;
  2388.     my $location = URI->new_abs($_->location->value, $base)->as_string;
  2389.     if ($imported{$location}++) { 
  2390.       warn "Recursion loop detected in service description from '$location'. Ignored\n" if $^W;
  2391.       return $s;
  2392.     }
  2393.     $schema ||= SOAP::Schema->new;
  2394.     my $root = $self->import($schema->deserializer->deserialize($schema->access($location))->root, $location);
  2395.     $root->SOAP::Data::name eq 'definitions' ? $s->set_value($s->value, $root->value) : 
  2396.     $root->SOAP::Data::name eq 'schema' ? do { # add <types> element if there is no one
  2397.       $s->set_value($s->value, SOAP::Schema::Deserializer->deserialize('<types></types>')->root) unless $s->types;
  2398.       $s->types->set_value($s->types->value, $root) } : 
  2399.     die "Don't know what to do with '@{[$root->SOAP::Data::name]}' in schema imported from '$location'\n";
  2400.   }
  2401.   $s;
  2402. }
  2403.  
  2404. sub parse {
  2405.   my $self = shift->new;
  2406.   my($s, $service, $port) = @_;
  2407.   my @result;
  2408.  
  2409.   # handle imports
  2410.   $self->import($s);
  2411.  
  2412.   # handle descriptions without <service>, aka tModel-type descriptions
  2413.   my @services = $s->service;
  2414.   # if there is no <service> element we'll provide it
  2415.   @services = SOAP::Schema::Deserializer->deserialize(<<"FAKE")->root->service unless @services;
  2416. <definitions>
  2417.   <service name="@{[$service || 'FakeService']}">
  2418.     <port name="@{[$port || 'FakePort']}" binding="@{[$s->binding->name]}"/>
  2419.   </service>
  2420. </definitions>
  2421. FAKE
  2422.   foreach (@services) {
  2423.     my $name = $_->name;
  2424.     next if $service && $service ne $name;
  2425.     my %services;
  2426.     foreach ($_->port) {
  2427.       next if $port && $port ne $_->name;
  2428.       my $binding = SOAP::Utils::disqualify($_->binding);
  2429.       my $endpoint = ref $_->address ? $_->address->location : undef;
  2430.       foreach ($s->binding) {
  2431.         # is this a SOAP binding?
  2432.         next unless grep { $_->uri eq 'http://schemas.xmlsoap.org/wsdl/soap/' } $_->binding;
  2433.         next unless $_->name eq $binding;
  2434.         my $porttype = SOAP::Utils::disqualify($_->type);
  2435.         foreach ($_->operation) {
  2436.           my $opername = $_->name;
  2437.           my $soapaction = $_->operation->soapAction;
  2438.           my $namespace = $_->input->body->namespace;
  2439.           my @parts;
  2440.           foreach ($s->portType) {
  2441.             next unless $_->name eq $porttype;
  2442.             foreach ($_->operation) {
  2443.               next unless $_->name eq $opername;
  2444.               my $inputmessage = SOAP::Utils::disqualify($_->input->message);
  2445.               foreach ($s->message) {
  2446.                 next unless $_->name eq $inputmessage;
  2447.                 @parts = $_->part;
  2448.               }
  2449.             }
  2450.           }
  2451.           $services{$opername} = {}; # should be initialized in 5.7 and after
  2452.           for ($services{$opername}) {
  2453.             $_->{endpoint} = $endpoint;
  2454.             $_->{soapaction} = $soapaction;
  2455.             $_->{uri} = $namespace;
  2456.             foreach (@parts) {
  2457.               my $t = $_->type || next;
  2458.               my $tval = $t->value;
  2459.               next unless ref $tval;
  2460.               my $attr = $_->attr;
  2461.               $attr->{'xmlns:ns'} = $tval->namespace;
  2462.               $attr->{'type'} = "ns:" . $tval->localpart;
  2463.             }
  2464.             $_->{parameters} = [@parts];
  2465.           }
  2466.         }
  2467.       }
  2468.     }
  2469.     # fix nonallowed characters in package name, and add 's' if started with digit
  2470.     for ($name) { s/\W+/_/g; s/^(\d)/s$1/ } 
  2471.     push @result, $name => \%services;
  2472.   }
  2473.   return @result;
  2474. }  
  2475.  
  2476. # ======================================================================
  2477.  
  2478. package SOAP::Schema;
  2479.  
  2480. use Carp ();
  2481.  
  2482. sub DESTROY { SOAP::Trace::objects('()') }
  2483.  
  2484. sub new { 
  2485.   my $self = shift;
  2486.  
  2487.   unless (ref $self) {
  2488.     my $class = ref($self) || $self;
  2489.     $self = bless {
  2490.       _deserializer => SOAP::Schema::Deserializer->new,
  2491.     } => $class;
  2492.    
  2493.     SOAP::Trace::objects('()');
  2494.   }
  2495.  
  2496.   Carp::carp "Odd (wrong?) number of parameters in new()" if $^W && (@_ & 1); 
  2497.   while (@_) { my $method = shift; $self->$method(shift) if $self->can($method) }
  2498.  
  2499.   return $self;
  2500. }
  2501.  
  2502. sub BEGIN {
  2503.   no strict 'refs';
  2504.   for my $method (qw(deserializer schema services)) {
  2505.     my $field = '_' . $method;
  2506.     *$method = sub {
  2507.       my $self = shift->new;
  2508.       @_ ? ($self->{$field} = shift, return $self) : return $self->{$field};
  2509.     }
  2510.   }
  2511. }
  2512.  
  2513. sub parse {
  2514.   my $self = shift->new;
  2515.   my $s = $self->deserializer->deserialize($self->access)->root;
  2516.   # here should be something that defines what schema description we want to use
  2517.   $self->services({SOAP::Schema::WSDL->base($self->schema)->parse($s, @_)});
  2518. }
  2519.  
  2520. sub load {
  2521.   my $self = shift->new;
  2522.   local $^W; # supress warnings about redefining
  2523.   foreach (keys %{$self->services || Carp::croak 'Nothing to load. Schema is not specified'}) { 
  2524.     eval $self->stub($_) or Carp::croak "Bad stub: $@";
  2525.   }
  2526.   $self;
  2527. }
  2528.  
  2529. sub access { require LWP::UserAgent;
  2530.   my $self = shift->new;
  2531.   my $url = shift || $self->schema || Carp::croak 'Nothing to access. URL is not specified';
  2532.   my $ua = LWP::UserAgent->new;
  2533.   $ua->env_proxy if $ENV{'HTTP_proxy'};
  2534.  
  2535.   my $req = HTTP::Request->new(GET => $url);
  2536.   $req->proxy_authorization_basic($ENV{'HTTP_proxy_user'}, $ENV{'HTTP_proxy_pass'})
  2537.     if ($ENV{'HTTP_proxy_user'} && $ENV{'HTTP_proxy_pass'});
  2538.  
  2539.   my $resp = $ua->request($req);
  2540.   $resp->is_success ? $resp->content : die "Service description '$url' can't be loaded: ",  $resp->status_line, "\n";
  2541. }
  2542.  
  2543. sub stub {
  2544.   my $self = shift->new;
  2545.   my $package = shift;
  2546.   my $services = $self->services->{$package};
  2547.   my $schema = $self->schema;
  2548.   join("\n", 
  2549.     "package $package;\n",
  2550.     "# -- generated by SOAP::Lite (v$SOAP::Lite::VERSION) for Perl -- soaplite.com -- Copyright (C) 2000-2001 Paul Kulchenko --",
  2551.     ($schema ? "# -- generated from $schema [@{[scalar localtime]}]\n" : "\n"),
  2552.     'my %methods = (',
  2553.     (map { my $service = $_;
  2554.            join("\n", 
  2555.                 "  $_ => {", 
  2556.                 map("    $_ => '$services->{$service}{$_}',", qw/endpoint soapaction uri/),
  2557.                 "    parameters => [",
  2558.                 map("      SOAP::Data->new(name => '" . $_->name . 
  2559.                            "', type => '" . $_->type . 
  2560.                            "', attr => {" . do{ my %attr = %{$_->attr}; join ', ', map {"'$_' => '$attr{$_}'"} grep {/^xmlns:(?!-)/} keys %attr} . 
  2561.                     "}),", @{$services->{$service}{parameters}}),
  2562.                 "    ],\n  },",
  2563.                ), 
  2564.          } keys %$services),
  2565.     ");", <<'EOP');
  2566.  
  2567. use SOAP::Lite;
  2568. use Exporter;
  2569. use Carp ();
  2570.  
  2571. use vars qw(@ISA $AUTOLOAD @EXPORT_OK %EXPORT_TAGS);
  2572. @ISA = qw(Exporter SOAP::Lite);
  2573. @EXPORT_OK = (keys %methods);
  2574. %EXPORT_TAGS = ('all' => [@EXPORT_OK]);
  2575.  
  2576. no strict 'refs';
  2577. for my $method (@EXPORT_OK) {
  2578.   my %method = %{$methods{$method}};
  2579.   *$method = sub {
  2580.     my $self = UNIVERSAL::isa($_[0] => __PACKAGE__) 
  2581.       ? ref $_[0] ? shift # OBJECT
  2582.                   # CLASS, either get self or create new and assign to self
  2583.                   : (shift->self || __PACKAGE__->self(__PACKAGE__->new))
  2584.       # function call, either get self or create new and assign to self
  2585.       : (__PACKAGE__->self || __PACKAGE__->self(__PACKAGE__->new));
  2586.     $self->proxy($method{endpoint} || Carp::croak "No server address (proxy) specified") unless $self->proxy;
  2587.     my @templates = @{$method{parameters}};
  2588.     my $som = $self
  2589.       -> endpoint($method{endpoint})
  2590.       -> uri($method{uri})
  2591.       -> on_action(sub{qq!"$method{soapaction}"!})
  2592.       -> call($method => map {@templates ? shift(@templates)->value($_) : $_} @_); 
  2593.     UNIVERSAL::isa($som => 'SOAP::SOM') ? wantarray ? $som->paramsall : $som->result 
  2594.                                         : $som;
  2595.   }
  2596. }
  2597.  
  2598. sub AUTOLOAD {
  2599.   my $method = substr($AUTOLOAD, rindex($AUTOLOAD, '::') + 2);
  2600.   return if $method eq 'DESTROY';
  2601.  
  2602.   die "Unrecognized method '$method'. List of available method(s): @EXPORT_OK\n";
  2603. }
  2604.  
  2605. 1;
  2606. EOP
  2607. }
  2608.  
  2609. # ======================================================================
  2610.  
  2611. package SOAP;
  2612.  
  2613. use vars qw($AUTOLOAD);
  2614. use URI;
  2615.  
  2616. my $soap; # shared between SOAP and SOAP::Lite packages
  2617.  
  2618. { no strict 'refs';
  2619.   *AUTOLOAD = sub {
  2620.     local($1,$2);
  2621.     my($package, $method) = $AUTOLOAD =~ m/(?:(.+)::)([^:]+)$/;
  2622.     return if $method eq 'DESTROY';
  2623.  
  2624.     my $soap = ref $_[0] && UNIVERSAL::isa($_[0] => 'SOAP::Lite') ? $_[0] : $soap;
  2625.  
  2626.     my $uri = URI->new($soap->uri);
  2627.     my $currenturi = $uri->path;
  2628.     $package = 
  2629.       ref $_[0] && UNIVERSAL::isa($_[0] => 'SOAP::Lite') ? $currenturi :
  2630.       $package eq 'SOAP' ? ref $_[0] || ($_[0] eq 'SOAP' 
  2631.         ? $currenturi || Carp::croak "URI is not specified for method call" : $_[0]) :
  2632.       $package eq 'main' ? $currenturi || $package  
  2633.                          : $package;
  2634.  
  2635.     # drop first parameter if it's a class name
  2636.     {
  2637.       my $pack = $package;
  2638.       for ($pack) { s!^/!!; s!/!::!g; }
  2639.       shift @_ if !ref $_[0] && ($_[0] eq $pack || $_[0] eq 'SOAP') || 
  2640.                    ref $_[0] && UNIVERSAL::isa($_[0] => 'SOAP::Lite');
  2641.     }
  2642.  
  2643.     for ($package) { s!::!/!g; s!^/?!/!; }
  2644.     $uri->path($package);
  2645.  
  2646.     my $som = $soap->uri($uri->as_string)->call($method => @_);
  2647.     UNIVERSAL::isa($som => 'SOAP::SOM') ? wantarray ? $som->paramsall : $som->result
  2648.                                         : $som;
  2649.   };
  2650. }
  2651.  
  2652. # ======================================================================
  2653.  
  2654. package SOAP::Lite;
  2655.  
  2656. use vars qw($AUTOLOAD @ISA);
  2657. use Carp ();
  2658.  
  2659. @ISA = qw(SOAP::Cloneable);
  2660.  
  2661. # provide access to global/autodispatched object
  2662. sub self { @_ > 1 ? $soap = $_[1] : $soap } 
  2663.  
  2664. # no more warnings about "used only once"
  2665. *UNIVERSAL::AUTOLOAD if 0; 
  2666.  
  2667. sub autodispatched { \&{*UNIVERSAL::AUTOLOAD} eq \&{*SOAP::AUTOLOAD} };
  2668.  
  2669. sub soapversion {
  2670.   my $self = shift;
  2671.   my $version = shift or return $SOAP::Constants::SOAP_VERSION;
  2672.  
  2673.   ($version) = grep { $SOAP::Constants::SOAP_VERSIONS{$_}->{NS_ENV} eq $version
  2674.                     } keys %SOAP::Constants::SOAP_VERSIONS
  2675.     unless exists $SOAP::Constants::SOAP_VERSIONS{$version};
  2676.  
  2677.   die qq!$SOAP::Constants::WRONG_VERSION Supported versions:\n@{[
  2678.         join "\n", map {"  $_ ($SOAP::Constants::SOAP_VERSIONS{$_}->{NS_ENV})"} keys %SOAP::Constants::SOAP_VERSIONS
  2679.         ]}\n!
  2680.     unless defined($version) && defined(my $def = $SOAP::Constants::SOAP_VERSIONS{$version});
  2681.  
  2682.   foreach (keys %$def) {
  2683.     eval "\$SOAP::Constants::$_ = '$SOAP::Constants::SOAP_VERSIONS{$version}->{$_}'";
  2684.   }
  2685.  
  2686.   $SOAP::Constants::SOAP_VERSION = $version;
  2687.   $self;
  2688. }
  2689.  
  2690. BEGIN { SOAP::Lite->soapversion(1.1) }
  2691.  
  2692. sub import {
  2693.   my $pkg = shift;
  2694.   my $caller = caller;
  2695.   no strict 'refs'; 
  2696.  
  2697.   # emulate 'use SOAP::Lite 0.99' behavior
  2698.   $pkg->require_version(shift) if defined $_[0] && $_[0] =~ /^\d/;
  2699.  
  2700.   while (@_) {
  2701.     my $command = shift;
  2702.  
  2703.     my @parameters = UNIVERSAL::isa($_[0] => 'ARRAY') ? @{shift()} : shift
  2704.       if @_ && $command ne 'autodispatch';
  2705.     if ($command eq 'autodispatch' || $command eq 'dispatch_from') { 
  2706.       $soap = ($soap||$pkg)->new;
  2707.       no strict 'refs';
  2708.       foreach ($command eq 'autodispatch' ? 'UNIVERSAL' : @parameters) {
  2709.         my $sub = "${_}::AUTOLOAD";
  2710.         defined &{*$sub}
  2711.           ? (\&{*$sub} eq \&{*SOAP::AUTOLOAD} ? () : Carp::croak "$sub already assigned and won't work with DISPATCH. Died")
  2712.           : (*$sub = *SOAP::AUTOLOAD);
  2713.       }
  2714.     } elsif ($command eq 'service' || $command eq 'schema') {
  2715.       warn "'schema =>' interface is changed. Use 'service =>' instead\n" 
  2716.         if $command eq 'schema' && $^W;
  2717.       foreach (keys %{SOAP::Schema->schema(shift(@parameters))->parse(@parameters)->load->services}) {
  2718.         $_->export_to_level(1, undef, ':all');
  2719.       }
  2720.     } elsif ($command eq 'debug' || $command eq 'trace') { 
  2721.       SOAP::Trace->import(@parameters ? @parameters : 'all');
  2722.     } elsif ($command eq 'import') {
  2723.       local $^W; # supress warnings about redefining
  2724.       my $package = shift(@parameters);
  2725.       $package->export_to_level(1, undef, @parameters ? @parameters : ':all') if $package;
  2726.     } else {
  2727.       Carp::carp "Odd (wrong?) number of parameters in import(), still continue" if $^W && !(@parameters & 1);
  2728.       $soap = ($soap||$pkg)->$command(@parameters);
  2729.     }
  2730.   }
  2731. }
  2732.  
  2733. sub DESTROY { SOAP::Trace::objects('()') }
  2734.  
  2735. sub new { 
  2736.   my $self = shift;
  2737.  
  2738.   unless (ref $self) {
  2739.     my $class = ref($self) || $self;
  2740.     # check whether we can clone. Only the SAME class allowed, no inheritance
  2741.     $self = ref($soap) eq $class ? $soap->clone : {
  2742.       _transport => SOAP::Transport->new,
  2743.       _serializer => SOAP::Serializer->new,
  2744.       _deserializer => SOAP::Deserializer->new,
  2745.       _autoresult => 0,
  2746.       _on_action => sub { sprintf '"%s#%s"', shift || '', shift },
  2747.       _on_fault => sub {ref $_[1] ? return $_[1] : Carp::croak $_[0]->transport->is_success ? $_[1] : $_[0]->transport->status},
  2748.     };
  2749.     bless $self => $class;
  2750.    
  2751.     $self->on_nonserialized($self->on_nonserialized || $self->serializer->on_nonserialized);
  2752.     SOAP::Trace::objects('()');
  2753.   }
  2754.  
  2755.   Carp::carp "Odd (wrong?) number of parameters in new()" if $^W && (@_ & 1); 
  2756.   while (@_) { my($method, $params) = splice(@_,0,2);
  2757.     $self->can($method) 
  2758.       ? $self->$method(ref $params eq 'ARRAY' ? @$params : $params)
  2759.       : $^W && Carp::carp "Unrecognized parameter '$method' in new()"
  2760.   }
  2761.  
  2762.   return $self;
  2763. }
  2764.  
  2765. sub BEGIN {
  2766.   no strict 'refs';
  2767.   for my $method (qw(endpoint transport serializer deserializer outputxml autoresult)) {
  2768.     my $field = '_' . $method;
  2769.     *$method = sub {
  2770.       my $self = shift->new;
  2771.       @_ ? ($self->{$field} = shift, return $self) : return $self->{$field};
  2772.     }
  2773.   }
  2774.   for my $method (qw(on_action on_fault on_nonserialized)) {
  2775.     my $field = '_' . $method;
  2776.     *$method = sub {
  2777.       my $self = shift->new;
  2778.       return $self->{$field} unless @_;
  2779.       local $@;
  2780.       # commented out because that 'eval' was unsecure
  2781.       # > ref $_[0] eq 'CODE' ? shift : eval shift;
  2782.       # Am I paranoid enough?
  2783.       $self->{$field} = shift;
  2784.       Carp::croak $@ if $@;
  2785.       Carp::croak "$method() expects subroutine (CODE) or string that evaluates into subroutine (CODE)"
  2786.         unless ref $self->{$field} eq 'CODE';
  2787.       return $self;
  2788.     }
  2789.   }
  2790.   for my $method (qw(proxy)) {
  2791.     *$method = sub { 
  2792.       my $self = shift->new;
  2793.       @_ ? ($self->transport->$method(@_), return $self) : return $self->transport->$method();
  2794.     }
  2795.   }                                                
  2796.   for my $method (qw(autotype readable namespace encodingspace envprefix encprefix 
  2797.                      multirefinplace encoding typelookup uri header maptype xmlschema)) {
  2798.     *$method = sub { 
  2799.       my $self = shift->new;
  2800.       @_ ? ($self->serializer->$method(@_), return $self) : return $self->serializer->$method();
  2801.     }
  2802.   }                                                
  2803. }
  2804.  
  2805. sub service {
  2806.   my $field = '_service';
  2807.   my $self = shift->new;
  2808.   return $self->{$field} unless @_;
  2809.  
  2810.   my %services = %{SOAP::Schema->schema($self->{$field} = shift)->parse(@_)->load->services};
  2811.  
  2812.   Carp::croak "More than one service in service description. Service and port names have to be specified\n" 
  2813.     if keys %services > 1; 
  2814.   return (keys %services)[0]->new;
  2815. }
  2816.  
  2817. sub schema {
  2818.   warn "SOAP::Lite->schema(...) interface is changed. Use ->service() instead\n" if $^W;
  2819.   shift->service(@_);
  2820. }
  2821.  
  2822. sub on_debug { 
  2823.   my $self = shift; 
  2824.   # comment this warning for now, till we redesign SOAP::Trace (2001/02/20)
  2825.   # Carp::carp "'SOAP::Lite->on_debug' method is deprecated. Instead use 'SOAP::Lite +debug ...'" if $^W;
  2826.   SOAP::Trace->import(debug => shift);
  2827.   $self;
  2828. }
  2829.  
  2830. sub AUTOLOAD {
  2831.   my $method = substr($AUTOLOAD, rindex($AUTOLOAD, '::') + 2);
  2832.   return if $method eq 'DESTROY';
  2833.  
  2834.   ref $_[0] or Carp::croak qq!Can't locate class method "$method" via package "! . __PACKAGE__ .'"';
  2835.  
  2836.   no strict 'refs';
  2837.   *$AUTOLOAD = sub { 
  2838.     my $self = shift;
  2839.     my $som = $self->call($method => @_);
  2840.     return $self->autoresult && UNIVERSAL::isa($som => 'SOAP::SOM') 
  2841.       ? wantarray ? $som->paramsall : $som->result 
  2842.       : $som;
  2843.   };
  2844.   goto &$AUTOLOAD;
  2845. }
  2846.  
  2847. sub call { SOAP::Trace::trace('()');
  2848.   my $self = shift;
  2849.  
  2850.   return $self->{_call} unless @_;
  2851.  
  2852.   my $serializer = $self->serializer;
  2853.  
  2854.   die "Transport is not specified (using proxy() method or service description)\n"
  2855.     unless defined $self->proxy && UNIVERSAL::isa($self->proxy => 'SOAP::Client');
  2856.  
  2857.   $serializer->on_nonserialized($self->on_nonserialized);
  2858.   my $response = $self->transport->send_receive(
  2859.     endpoint => $self->endpoint, 
  2860.     action   => scalar($self->on_action->($serializer->uriformethod($_[0]))),
  2861.                 # leave only parameters so we can later update them if required
  2862.     envelope => $serializer->envelope(method => shift, @_), 
  2863.     encoding => $serializer->encoding,
  2864.   );
  2865.  
  2866.   return $response if $self->outputxml;
  2867.  
  2868.   # deserialize and store result
  2869.   my $result = $self->{_call} = eval { $self->deserializer->deserialize($response) } if $response;
  2870.  
  2871.   if (!$self->transport->is_success || # transport fault
  2872.       $@ ||                            # not deserializible
  2873.       # fault message even if transport OK 
  2874.       # or no transport error (for example, fo TCP, POP3, IO implementations)
  2875.       UNIVERSAL::isa($result => 'SOAP::SOM') && $result->fault) {
  2876.     return $self->{_call} = ($self->on_fault->($self, $@ ? $@ . ($response || '') : $result) || $result);
  2877.   }
  2878.  
  2879.   return unless $response; # nothing to do for one-ways
  2880.  
  2881.   # little bit tricky part that binds in/out parameters
  2882.   if (UNIVERSAL::isa($result => 'SOAP::SOM') && 
  2883.       ($result->paramsout || $result->headers) && 
  2884.       $serializer->signature) {
  2885.     my $num = 0;
  2886.     my %signatures = map {$_ => $num++} @{$serializer->signature};
  2887.     for ($result->dataof(SOAP::SOM::paramsout), $result->dataof(SOAP::SOM::headers)) {
  2888.       my $signature = join $;, $_->name, $_->type || '';
  2889.       if (exists $signatures{$signature}) {
  2890.         my $param = $signatures{$signature};
  2891.         my($value) = $_->value; # take first value
  2892.         UNIVERSAL::isa($_[$param] => 'SOAP::Data') ? $_[$param]->SOAP::Data::value($value) :
  2893.         UNIVERSAL::isa($_[$param] => 'ARRAY')      ? (@{$_[$param]} = @$value) :
  2894.         UNIVERSAL::isa($_[$param] => 'HASH')       ? (%{$_[$param]} = %$value) :
  2895.         UNIVERSAL::isa($_[$param] => 'SCALAR')     ? (${$_[$param]} = $$value) :
  2896.                                                      ($_[$param] = $value)
  2897.       }
  2898.     }
  2899.   }
  2900.   return $result;
  2901. }
  2902.  
  2903. # ======================================================================
  2904.  
  2905. package SOAP::Lite::COM;
  2906.  
  2907. require SOAP::Lite;
  2908.  
  2909. sub required {
  2910.   foreach (qw(
  2911.     URI::_foreign URI::http URI::https
  2912.     LWP::Protocol::http LWP::Protocol::https LWP::Authen::Basic LWP::Authen::Digest
  2913.     HTTP::Daemon Compress::Zlib SOAP::Transport::HTTP
  2914.     XMLRPC::Lite XMLRPC::Transport::HTTP
  2915.   )) {
  2916.     eval join ';', 'local $SIG{__DIE__}', "require $_";
  2917.   }
  2918. }
  2919.  
  2920. sub new    { required; SOAP::Lite->new(@_) } 
  2921.  
  2922. sub create; *create = \&new; # make alias. Somewhere 'new' is registered keyword
  2923.  
  2924. sub soap; *soap = \&new;     # also alias. Just to be consistent with .xmlrpc call
  2925.  
  2926. sub xmlrpc { required; XMLRPC::Lite->new(@_) } 
  2927.  
  2928. sub server { required; shift->new(@_) }
  2929.  
  2930. sub data   { SOAP::Data->new(@_) }
  2931.  
  2932. sub header { SOAP::Header->new(@_) }
  2933.  
  2934. sub hash   { +{@_} }
  2935.  
  2936. sub instanceof { 
  2937.   my $class = shift; 
  2938.   die "Incorrect class name" unless $class =~ /^(\w[\w:]*)$/; 
  2939.   eval "require $class"; 
  2940.   $class->new(@_); 
  2941. }
  2942.  
  2943. # ======================================================================
  2944.  
  2945. 1;
  2946.  
  2947. __END__
  2948.  
  2949. =head1 NAME
  2950.  
  2951. SOAP::Lite - Client and server side SOAP implementation
  2952.  
  2953. =head1 SYNOPSIS
  2954.  
  2955.   use SOAP::Lite;
  2956.   print SOAP::Lite
  2957.     -> uri('http://www.soaplite.com/Temperatures')
  2958.     -> proxy('http://services.soaplite.com/temper.cgi')
  2959.     -> f2c(32)
  2960.     -> result;
  2961.  
  2962. The same code with autodispatch: 
  2963.  
  2964.   use SOAP::Lite +autodispatch =>
  2965.     uri => 'http://www.soaplite.com/Temperatures',
  2966.     proxy => 'http://services.soaplite.com/temper.cgi';
  2967.  
  2968.   print f2c(32);
  2969.  
  2970. Code in OO-style:
  2971.  
  2972.   use SOAP::Lite +autodispatch =>
  2973.     uri => 'http://www.soaplite.com/Temperatures',
  2974.     proxy => 'http://services.soaplite.com/temper.cgi';
  2975.  
  2976.   my $temperatures = Temperatures->new(32); # get object
  2977.   print $temperatures->as_celsius;          # invoke method
  2978.  
  2979. Code with service description:
  2980.  
  2981.   use SOAP::Lite;
  2982.   print SOAP::Lite
  2983.     -> service('http://www.xmethods.net/sd/StockQuoteService.wsdl')
  2984.     -> getQuote('MSFT');
  2985.  
  2986. Code for SOAP server (CGI):
  2987.  
  2988.   use SOAP::Transport::HTTP;
  2989.   SOAP::Transport::HTTP::CGI
  2990.     -> dispatch_to('/Your/Path/To/Deployed/Modules', 'Module::Name', 'Module::method') 
  2991.     -> handle;
  2992.  
  2993. Visual Basic client (through COM interface): 
  2994.  
  2995.   MsgBox CreateObject("SOAP.Lite").new( _
  2996.     "proxy", "http://services.xmethods.net/soap", _
  2997.     "uri",   "urn:xmethods-delayed-quotes" _
  2998.   ).getQuote("MSFT").result
  2999.  
  3000. mod_soap enabled SOAP server: 
  3001.  
  3002.   .htaccess
  3003.  
  3004.   SetHandler perl-script
  3005.   PerlHandler Apache::SOAP
  3006.   PerlSetVar dispatch_to "/Your/Path/To/Deployed/Modules, Module::Name"
  3007.  
  3008. ASP/VB SOAP server: 
  3009.  
  3010.   <%
  3011.     Response.ContentType = "text/xml"
  3012.     Response.Write(Server.CreateObject("SOAP.Lite") _
  3013.       .server("SOAP::Server") _ 
  3014.       .dispatch_to("/Your/Path/To/Deployed/Modules") _
  3015.       .handle(Request.BinaryRead(Request.TotalBytes)) _
  3016.     )
  3017.   %>
  3018.  
  3019. =head1 DESCRIPTION
  3020.  
  3021. SOAP::Lite is a collection of Perl modules which provides a 
  3022. simple and lightweight interface to the Simple Object Access Protocol 
  3023. (SOAP) both on client and server side.
  3024.  
  3025. This version of SOAP::Lite supports the SOAP 1.1 specification ( http://www.w3.org/TR/SOAP ).
  3026.  
  3027. The main features of the library are:
  3028.  
  3029. =over 3
  3030.  
  3031. =item *
  3032.  
  3033. Supports SOAP 1.1 spec. 
  3034.  
  3035. =item *
  3036.  
  3037. Interoperability tests with different implementations: Apache SOAP, Frontier, 
  3038. Microsoft SOAP, Microsoft .NET, DevelopMentor, XMethods, 4s4c, Phalanx, 
  3039. Kafka, SQLData, Lucin (in Java, Perl, C++, Python, VB, COM, XSLT). 
  3040.  
  3041. =item *
  3042.  
  3043. Provides COM interface. Single dll (standalone [2.5MB] or minimal [32kB]). 
  3044. Works on Windows 9x/Me/NT/2K. Doesn't require ROPE or MSXML. 
  3045. Examples in VB, Excel/VBA, C#, ASP, JavaScript, PerlScript and Perl. 
  3046.  
  3047. =item *
  3048.  
  3049. Provides transparent compression support for HTTP transport. 
  3050.  
  3051. =item *
  3052.  
  3053. Provides mod_soap module. Make SOAP server with a few lines in .htaccess 
  3054. or .conf file. 
  3055.  
  3056. =item *
  3057.  
  3058. Includes XML::Parser::Lite (regexp-based XML parser) which runs instead 
  3059. of XML::Parser where Perl 5.6 runs (even on WinCE) with some limitations. 
  3060.  
  3061. =item *
  3062.  
  3063. Includes XMLRPC::Lite, implementation of XML-RPC protocol on client and 
  3064. server side. All transports and features of SOAP::Lite are available. 
  3065.  
  3066. =item *
  3067.  
  3068. Supports multipart/form-data MIME attachments. 
  3069.  
  3070. =item *
  3071.  
  3072. Supports circular linked lists and multiple references. 
  3073.  
  3074. =item *
  3075.  
  3076. Supports Map datatype (encoding of maps/hashes with arbitrary keys). 
  3077.  
  3078. =item *
  3079.  
  3080. Supports HTTPS protocol. 
  3081.  
  3082. =item *
  3083.  
  3084. Provides proxy support. 
  3085.  
  3086. =item *
  3087.  
  3088. Provides CGI/daemon/mod_perl/Apache::Registry server implementations. 
  3089.  
  3090. =item *
  3091.  
  3092. Provides TCP server implementation. 
  3093.  
  3094. =item *
  3095.  
  3096. Provides IO (STDIN/STDOUT/File) server implementation. 
  3097.  
  3098. =item *
  3099.  
  3100. Provides FTP client implementation. 
  3101.  
  3102. =item *
  3103.  
  3104. Supports single/multipart MIME attachment (parsing side only). 
  3105.  
  3106. =item *
  3107.  
  3108. Supports SMTP protocol. 
  3109.  
  3110. =item *
  3111.  
  3112. Provides POP3 server implementation. 
  3113.  
  3114. =item *
  3115.  
  3116. Supports M-POST and redirects in HTTP transport. 
  3117.  
  3118. =item *
  3119.  
  3120. Supports Basic/Digest server authentication. 
  3121.  
  3122. =item *
  3123.  
  3124. Works with CGI accelerators, like VelociGen and PerlEx. 
  3125.  
  3126. =item *
  3127.  
  3128. Supports UDDI interface on client side. See UDDI::Lite for details. 
  3129.  
  3130. =item *
  3131.  
  3132. Supports UDDI publishing API. Examples and documentation provided. 
  3133.  
  3134. =item *
  3135.  
  3136. Supports WSDL schema with stub and run-time access. 
  3137.  
  3138. =item *
  3139.  
  3140. Supports blessed object references. 
  3141.  
  3142. =item *
  3143.  
  3144. Supports arrays (both serialization and deserialization with autotyping). 
  3145.  
  3146. =item *
  3147.  
  3148. Supports custom serialization. 
  3149.  
  3150. =item *
  3151.  
  3152. Provides exception transport with custom exceptions 
  3153.  
  3154. =item *
  3155.  
  3156. Supports Base64 encoding. 
  3157.  
  3158. =item *
  3159.  
  3160. Supports XML entity encoding. 
  3161.  
  3162. =item *
  3163.  
  3164. Supports header attributes. 
  3165.  
  3166. =item *
  3167.  
  3168. Supports dynamic and static class/method binding. 
  3169.  
  3170. =item *
  3171.  
  3172. Supports objects-by-reference with simple garbage collection and activation. 
  3173.  
  3174. =item *
  3175.  
  3176. Provides shell for interactive SOAP sessions. 
  3177.  
  3178. =item *
  3179.  
  3180. Supports out parameters binding. 
  3181.  
  3182. =item *
  3183.  
  3184. Supports transparent SOAP calls with autodispatch feature. 
  3185.  
  3186. =item *
  3187.  
  3188. Provides easy services deployment. Put module in specified directory and 
  3189. it'll be accessible. 
  3190.  
  3191. =item *
  3192.  
  3193. Has tests, examples and documentation to let you be up and running in no time.
  3194.  
  3195. =back
  3196.  
  3197. =head2 WHERE TO FIND EXAMPLES
  3198.  
  3199. See F<t/*.t>, F<examples/*.pl> and the module documentation for a client-side 
  3200. examples that demonstrate the serialization of a SOAP request, sending it 
  3201. via HTTP to the server and receiving the response, and the deserialization 
  3202. of the response. See F<examples/server/*> for server-side implementations.
  3203.  
  3204. =head1 OVERVIEW OF CLASSES AND PACKAGES
  3205.  
  3206. This table should give you a quick overview of the classes provided by the
  3207. library.
  3208.  
  3209.  SOAP::Lite.pm
  3210.  -- SOAP::Lite           -- Main class provides all logic
  3211.  -- SOAP::Transport      -- Supports transport architecture
  3212.  -- SOAP::Data           -- Provides extensions for serialization architecture
  3213.  -- SOAP::Header         -- Provides extensions for header serialization
  3214.  -- SOAP::Parser         -- Parses XML file into object tree
  3215.  -- SOAP::Serializer     -- Serializes data structures to SOAP package
  3216.  -- SOAP::Deserializer   -- Deserializes results of SOAP::Parser into objects
  3217.  -- SOAP::SOM            -- Provides access to deserialized object tree
  3218.  -- SOAP::Constants      -- Provides access to common constants
  3219.  -- SOAP::Trace          -- Provides tracing facilities
  3220.  -- SOAP::Schema         -- Provides access and stub(s) for schema(s)
  3221.  -- SOAP::Schema::WSDL   -- WSDL implementation for SOAP::Schema
  3222.  -- SOAP::Server         -- Handles requests on server side 
  3223.  -- SOAP::Server::Object -- Handles objects-by-reference 
  3224.  -- SOAP::Fault          -- Provides support for Faults on server side
  3225.  
  3226.  SOAP::Transport::HTTP.pm
  3227.  -- SOAP::Transport::HTTP::Client  -- Client interface to HTTP transport
  3228.  -- SOAP::Transport::HTTP::Server  -- Server interface to HTTP transport
  3229.  -- SOAP::Transport::HTTP::CGI     -- CGI implementation of server interface
  3230.  -- SOAP::Transport::HTTP::Daemon  -- Daemon implementation of server interface
  3231.  -- SOAP::Transport::HTTP::Apache  -- mod_perl implementation of server interface
  3232.  
  3233.  SOAP::Transport::POP3.pm
  3234.  -- SOAP::Transport::POP3::Server  -- Server interface to POP3 protocol
  3235.  
  3236.  SOAP::Transport::MAILTO.pm
  3237.  -- SOAP::Transport::MAILTO::Client -- Client interface to SMTP/sendmail
  3238.  
  3239.  SOAP::Transport::LOCAL.pm
  3240.  -- SOAP::Transport::LOCAL::Client -- Client interface to local transport
  3241.  
  3242.  SOAP::Transport::TCP.pm
  3243.  -- SOAP::Transport::TCP::Server -- Server interface to TCP protocol
  3244.  -- SOAP::Transport::TCP::Client -- Client interface to TCP protocol
  3245.  
  3246.  SOAP::Transport::IO.pm
  3247.  -- SOAP::Transport::IO::Server -- Server interface to IO transport
  3248.  
  3249. =head2 SOAP::Lite
  3250.  
  3251. All methods that C<SOAP::Lite> provides can be used for both
  3252. setting and retrieving values. If you provide no parameters, you will
  3253. get current value, and if parameters are provided, a new value
  3254. will be assigned to the object and the method in question will return 
  3255. the current object (if not stated otherwise). This is suitable for stacking
  3256. these calls like:
  3257.  
  3258.   $lite = SOAP::Lite
  3259.     -> uri('http://simon.fell.com/calc')
  3260.     -> proxy('http://soap.4s4c.com/ssss4c/soap.asp')
  3261.   ;
  3262.  
  3263. The order is insignificant and you may call the new() method first. If you
  3264. don't do it, SOAP::Lite will do it for you. However, the new() method
  3265. gives you an additional syntax:
  3266.  
  3267.   $lite = new SOAP::Lite
  3268.     uri => 'http://simon.fell.com/calc',
  3269.     proxy => 'http://soap.4s4c.com/ssss4c/soap.asp'
  3270.   ;
  3271.  
  3272. =over 4
  3273.  
  3274. =item new()
  3275.  
  3276. new() accepts a hash with method names as keys. It will call the 
  3277. appropriate methods together with the passed values. Since new() is 
  3278. optional it won't be mentioned anymore.
  3279.  
  3280. =item transport()
  3281.  
  3282. Provides access to the L</"SOAP::Transport"> object. The object will be created 
  3283. for you. You can reassign it (but generally you should not).
  3284.  
  3285. =item serializer()
  3286.  
  3287. Provides access to the L</"SOAP::Serialization"> object. The object will be 
  3288. created for you. You can reassign it (but generally you should not).
  3289.  
  3290. =item proxy()
  3291.  
  3292. Shortcut for C<< transport->proxy() >>. This lets you specify an endpoint 
  3293. (service address) and also loads the required module at the same time. It is 
  3294. required for dispatching SOAP calls. The name of the module will be defined 
  3295. depending on the protocol specific for the endpoint. The prefix 
  3296. C<SOAP::Transport> will be prepended, the module will be loaded and object of 
  3297. class (with appended C<::Client>) will be created. 
  3298.  
  3299. For example, for F<http://localhost/>, the class for creating objects will 
  3300. look for C<SOAP::Transport:HTTP::Client>;
  3301.  
  3302. In addition to endpoint parameter, proxy() can accept any transport specific
  3303. parameters that could be passed as name => value pairs. For example, to 
  3304. specify proxy settings for HTTP protocol you may do:
  3305.  
  3306.   $soap->proxy('http://endpoint.server/', 
  3307.                proxy => ['http' => 'http://my.proxy.server/']);
  3308.  
  3309. Notice that since proxy (second one) expects to get more than one 
  3310. parameter you should wrap them in array.
  3311.  
  3312. Another useful example can be the client that is sensitive to cookie-based
  3313. authentication. You can provide this with:
  3314.  
  3315.   $soap->proxy('http://localhost/', 
  3316.                cookie_jar => HTTP::Cookies->new(ignore_discard => 1));
  3317.  
  3318. You may specify timeout for HTTP transport with following code:
  3319.  
  3320.   $soap->proxy('http://localhost/', timeout => 5);
  3321.  
  3322. =item endpoint()
  3323.  
  3324. Lets you specify an endpoint B<without> changing/loading the protocol module. 
  3325. This is useful for switching endpoints without switching protocols. You should 
  3326. call C<proxy()> first. No checks for protocol equivalence will be made.
  3327.  
  3328. =item outputxml()
  3329.  
  3330. Lets you specify the kind of output from all method calls. If C<true>, all 
  3331. methods will return unprocessed, raw XML code. You can parse it with 
  3332. XML::Parser, SOAP::Deserializer or any other appropriate module.
  3333.  
  3334. =item autotype()
  3335.  
  3336. Shortcut for C<< serializer->autotype() >>. This lets you specify whether 
  3337. the serializer will try to make autotyping for you or not. Default setting 
  3338. is C<true>.
  3339.  
  3340. =item readable()
  3341.  
  3342. Shortcut for C<< serializer->readable() >>. This lets you specify the format 
  3343. for the generated XML code. Carriage returns <CR> and indentation will be 
  3344. added for readability. Useful in the case you want to see the generated code 
  3345. in a debugger. By default, there are no additional characters in generated 
  3346. XML code. 
  3347.  
  3348. =item namespace()
  3349.  
  3350. Shortcut for C<< serializer->namespace() >>. This lets you specify the default
  3351. namespace for generated envelopes (C<'SOAP-ENV'> by default).
  3352.  
  3353. =item encodingspace()
  3354.  
  3355. Shortcut for C<< serializer->encodingspace() >>. This lets you specify the 
  3356. default encoding namespace for generated envelopes (C<'SOAP-ENC'> by default).
  3357.  
  3358. =item encoding()
  3359.  
  3360. Shortcut for C<< serializer->encoding() >>. This lets you specify the encoding 
  3361. for generated envelopes. It does not actually change envelope
  3362. encoding, it will just modify the XML declaration (C<'UTF-8'> by default).
  3363. Use C<undef> value to B<not> generate XML declaration.
  3364.  
  3365. =item typelookup()
  3366.  
  3367. Shortcut for C<< serializer->typelookup() >>. This gives you access to 
  3368. the C<typelookup> table that is used for autotyping. For more information
  3369. see L</"SOAP::Serializer">.
  3370.  
  3371. =item uri()
  3372.  
  3373. Shortcut for C<< serializer->uri() >>. This lets you specify the uri for SOAP 
  3374. methods. Nothing is specified by default and your call will definitely fail 
  3375. if you don't specify the required uri. 
  3376.  
  3377. B<WARNING>: URIs are just identifiers. They may B<look like URLs>, but they are
  3378. not guaranteed to point to anywhere and shouldn't be used as such pointers.
  3379. URIs assume to be unique within the space of all XML documents, so consider
  3380. them as unique identifiers and nothing else.
  3381.  
  3382. =item multirefinplace()
  3383.  
  3384. Shortcut for C<< serializer->multirefinplace() >>. If true, the serializer will
  3385. put values for multireferences in the first occurrence of the reference. 
  3386. Otherwise it will be encoded as top independent element, right after C<method>
  3387. element inside C<Body>. Default value is C<false>. 
  3388.  
  3389. =item header() 
  3390.  
  3391. B<DEPRECATED>: Use SOAP::Header instead. 
  3392.  
  3393. Shortcut for C<< serializer->header() >>. This lets you specify the header for 
  3394. generated envelopes. You can specify C<root>, C<mustUnderstand> or any
  3395. other header using L</"SOAP::Data"> class:
  3396.  
  3397.   $serializer = SOAP::Serializer->envelope('method' => 'mymethod', 1,
  3398.     SOAP::Header->name(t1 => 5)->mustUnderstand(1),
  3399.     SOAP::Header->name(t2 => 7)->mustUnderstand(2),
  3400.   );
  3401.  
  3402. will be serialized into:
  3403.  
  3404.   <SOAP-ENV:Envelope ...attributes skipped>
  3405.     <SOAP-ENV:Header>
  3406.       <t1 xsi:type="xsd:int" SOAP-ENV:mustUnderstand="1">5</t1>
  3407.       <t2 xsi:type="xsd:int" SOAP-ENV:mustUnderstand="1">7</t2>
  3408.     </SOAP-ENV:Header>
  3409.     <SOAP-ENV:Body>
  3410.       <namesp1:mymethod xmlns:namesp1="urn:SOAP__Serializer">
  3411.         <c-gensym6 xsi:type="xsd:int">1</c-gensym6>
  3412.       </namesp1:mymethod>
  3413.     </SOAP-ENV:Body>
  3414.   </SOAP-ENV:Envelope>
  3415.  
  3416. You can mix C<SOAP::Header> parameters with other parameters and you can also
  3417. return C<SOAP::Header> parameters as a result of a remote call. They will be 
  3418. placed into the header. See C<My::Parameters::addheader> as an example.
  3419.  
  3420. =item on_action()
  3421.  
  3422. This lets you specify a handler for C<on_action event>. It is triggered when 
  3423. creating SOAPAction. The default handler will set SOAPAction to 
  3424. C<"uri#method">. You can change this behavior globally 
  3425. (see L</"DEFAULT SETTINGS">) or locally, for a particular object.
  3426.  
  3427. =item on_fault()
  3428.  
  3429. This lets you specify a handler for C<on_fault> event. The default behavior is 
  3430. to B<die> on an transport error and to B<do nothing> on other error conditions. You 
  3431. may change this behavior globally (see L</"DEFAULT SETTINGS">) or locally, for a 
  3432. particular object.
  3433.  
  3434. =item on_debug()
  3435.  
  3436. This lets you specify a handler for C<on_debug event>. Default behavior is to 
  3437. do nothing. Use C<+trace/+debug> option for SOAP::Lite instead. If you use if 
  3438. be warned that since this method is just interface to C<+trace/+debug> it has
  3439. B<global> effect, so if you install it for one object it'll be in effect for 
  3440. all subsequent calls (even for other objects).
  3441.  
  3442. =item on_nonserialized()
  3443.  
  3444. This lets you specify a handler for C<on_nonserialized event>. The default 
  3445. behavior is to produce a warning if warnings are on for everything that cannot 
  3446. be properly serialized (like CODE references or GLOBs).
  3447.  
  3448. =item call()
  3449.  
  3450. Provides alternative interface for remote method calls. You can always
  3451. run C<< SOAP::Lite->new(...)->method(@parameters) >>, but call() gives
  3452. you several additional options:
  3453.  
  3454. =over 4
  3455.  
  3456. =item prefixed method
  3457.  
  3458. If you want to specify prefix for generated method's element one of the
  3459. available options is do it with call() interface:
  3460.  
  3461.   print SOAP::Lite
  3462.     -> new(....)
  3463.     -> call('myprefix:method' => @parameters)
  3464.     -> result;
  3465.  
  3466. This example will work on client side only. If you want to change prefix
  3467. on server side you should override default serializer. See 
  3468. F<examples/server/soap.*> for examples. 
  3469.  
  3470. =item access to any method
  3471.  
  3472. If for some reason you want to get access to remote procedures that have 
  3473. the same name as methods of SOAP::Lite object these calls (obviously) won't 
  3474. be dispatched. In that case you can originate your call trough call():
  3475.  
  3476.   print SOAP::Lite
  3477.     -> new(....)
  3478.     -> call(new => @parameters) 
  3479.     -> result;
  3480.  
  3481. =item implementation of OO interface
  3482.  
  3483. With L<autodispatch|/"AUTODISPATCHING AND SOAP:: PREFIX"> you can make CLASS/OBJECT calls like:
  3484.  
  3485.   my $obj = CLASS->new(@parameters);
  3486.   print $obj->method;
  3487.  
  3488. However, because of side effects L<autodispatch|/"AUTODISPATCHING AND SOAP:: PREFIX"> 
  3489. has, it's not always possible to use this syntax. call() provides you with
  3490. alternative:
  3491.  
  3492.   # you should specify uri()
  3493.   my $soap = SOAP::Lite
  3494.     -> uri('http://my.own.site/CLASS') # <<< CLASS goes here
  3495.     # ..... other parameters
  3496.   ;
  3497.  
  3498.   my $obj = $soap->call(new => @parameters)->result;
  3499.   print $soap->call(method => $obj)->result;
  3500.   # $obj object will be updated here if necessary, 
  3501.   # as if you call $obj->method() and method() updates $obj
  3502.  
  3503.   # Update of modified object MAY not work if server on another side 
  3504.   # is not SOAP::Lite
  3505.  
  3506. =item ability to set method's attributes
  3507.  
  3508. Additionally this syntax lets you specify attributes for method element:
  3509.  
  3510.   print SOAP::Lite
  3511.     -> new(....)
  3512.     -> call(SOAP::Data->name('method')->attr({xmlns => 'mynamespace'})
  3513.             => @parameters)
  3514.     -> result;
  3515.  
  3516. You can specify B<any> attibutes and C<name> of C<SOAP::Data> element becomes
  3517. name of method. Everything else except attributes is ignored and parameters
  3518. should be provided as usual.
  3519.  
  3520. Be warned, that though you have more control using this method, you B<should> 
  3521. specify namespace attribute for method explicitely, even if you made uri() 
  3522. call earlier. So, if you have to have namespace on method element, instead of:
  3523.  
  3524.   print SOAP::Lite
  3525.     -> new(....)
  3526.     -> uri('mynamespace') # will be ignored 
  3527.     -> call(SOAP::Data->name('method') => @parameters)
  3528.     -> result;
  3529.  
  3530. do
  3531.  
  3532.   print SOAP::Lite
  3533.     -> new(....)
  3534.     -> call(SOAP::Data->name('method')->attr({xmlns => 'mynamespace'})
  3535.             => @parameters)
  3536.     -> result;
  3537.  
  3538. because in the former call uri() will be ignored and namespace won't be 
  3539. specified. If you run script with C<-w> option (as recommended) SOAP::Lite
  3540. gives you a warning:
  3541.  
  3542.   URI is not provided as attribute for method (method)
  3543.  
  3544. Moreover, it'll become fatal error if you try to call it with prefixed name:
  3545.  
  3546.   print SOAP::Lite
  3547.     -> new(....)
  3548.     -> uri('mynamespace') # will be ignored 
  3549.     -> call(SOAP::Data->name('a:method') => @parameters)
  3550.     -> result;
  3551.  
  3552. gives you:
  3553.  
  3554.   Can't find namespace for method (a:method)
  3555.  
  3556. because nothing is associated with prefix C<'a'>. 
  3557.  
  3558. =back
  3559.  
  3560. One more comment. One case when SOAP::Lite will change something that 
  3561. you specified is when you specified prefixed name and empty namespace name:
  3562.  
  3563.   print SOAP::Lite
  3564.     -> new(....)
  3565.     -> uri('') 
  3566.     -> call('a:method' => @parameters)
  3567.     -> result;
  3568.  
  3569. This code will generate:
  3570.  
  3571.   <method xmlns="">....</method>
  3572.  
  3573. instead of 
  3574.  
  3575.   <a:method xmlns:a="">....</method>
  3576.  
  3577. because later is not allowed according to XML Namespace specification.
  3578.  
  3579. In all other aspects C<< ->call(mymethod => @parameters) >> is just a 
  3580. synonim for C<< ->mymethod(@parameters) >>.
  3581.  
  3582. =item self()
  3583.  
  3584. Returns object reference to B<global> defaul object specified with 
  3585. C<use SOAP::Lite ...> interface. Both class method and object method return
  3586. reference to B<global> object, so:
  3587.  
  3588.   use SOAP::Lite
  3589.     proxy => 'http://my.global.server'
  3590.   ;
  3591.  
  3592.   my $soap = SOAP::Lite->proxy('http://my.local.server');
  3593.  
  3594.   print $soap->self->proxy;
  3595.  
  3596. prints C<'http://my.global.server'> (the same as C<< SOAP::Lite->self->proxy >>). 
  3597. See L</"DEFAULT SETTINGS"> for more information.
  3598.  
  3599. =item dispatch_from()
  3600.  
  3601. Does exactly the same as L<autodispatch|/"AUTODISPATCHING AND SOAP:: PREFIX">
  3602. does, but doesn't install UNIVERSAL::AUTOLOAD handler and only install
  3603. AUTOLOAD handlers in specified classes. Can be used only with C<use SOAP::Lite ...>
  3604. clause and should be specified first:
  3605.  
  3606.   use SOAP::Lite 
  3607.     dispatch_from => ['A', 'B'], # use "dispatch_from => 'A'" for one class
  3608.     uri => ....,
  3609.     proxy => ....,
  3610.   ;
  3611.  
  3612.   A->a;
  3613.   B->b;
  3614.  
  3615. =back
  3616.  
  3617. =head2 SOAP::Data
  3618.  
  3619. You can use this class if you want to specify a value, a name, atype, a uri or 
  3620. attributes for SOAP elements (use C<value()>, C<name()>, C<type()>, 
  3621. C<uri()> and C<attr()> methods correspondingly). 
  3622. For example, C<< SOAP::Data->name('abc')->value(123) >> will be serialized
  3623. into C<< <abc>123</abc> >>, as well as will C<< SOAP::Data->name(abc => 123) >>.
  3624. Each of them (except the value() method) can accept a value as the second 
  3625. parameter. All methods return the current value if you call them without 
  3626. parameters. The return the object otherwise, so you can stack them. See tests 
  3627. for more examples. You can import these methods with: 
  3628.    
  3629.   SOAP::Data->import('name'); 
  3630.  
  3631. or 
  3632.  
  3633.   import SOAP::Data 'name'; 
  3634.  
  3635. and then use C<< name(abc => 123) >> for brevity. 
  3636.  
  3637. An interface for specific attributes is also provided. You can use the C<actor()>,
  3638. C<mustUnderstand()>, C<encodingStyle()> and C<root()> methods to set/get
  3639. values of the correspondent attributes.
  3640.  
  3641.   SOAP::Data
  3642.     ->name(c => 3)
  3643.     ->encodingStyle('http://xml.apache.org/xml-soap/literalxml')
  3644.  
  3645. will be serialized into:
  3646.  
  3647.   <c SOAP-ENV:encodingStyle="http://xml.apache.org/xml-soap/literalxml"
  3648.      xsi:type="xsd:int">3</c>
  3649.  
  3650. =head2 SOAP::Serializer
  3651.  
  3652. Usually you don't need to interact directly with this module. The only 
  3653. case when you need it, it when using autotyping. This feature lets you specify 
  3654. types for your data according to your needs as well as to introduce new
  3655. data types (like ordered hash for example). 
  3656.  
  3657. You can specify a type with C<< SOAP::Data->type(float => 123) >>. During
  3658. the serialization stage the module will try to serialize your data with the 
  3659. C<as_float> method. It then calls the C<typecast> method (you can override it 
  3660. or inherit your own class from L</"SOAP::Data">) and only then it will try to 
  3661. serialize it according to data type (C<SCALAR>, C<ARRAY> or C<HASH>). For example:
  3662.  
  3663.   SOAP::Data->type('ordered_hash' => [a => 1, b => 2]) 
  3664.  
  3665. will be serialized as an ordered hash, using the C<as_ordered_hash> method.
  3666.  
  3667. If you do not specify a type directly, the serialization module will try
  3668. to autodefine the type for you according to the C<typelookup> hash. It contains 
  3669. the type name as key and the following 3-element array as value:
  3670.  
  3671.   priority, 
  3672.   check_function (CODE reference), 
  3673.   typecast function (METHOD name or CODE reference)
  3674.  
  3675. For example, if you want to add C<uriReference> to autodefined types,
  3676. you should add something like this:
  3677.  
  3678.   $s->typelookup->{uriReference} =
  3679.     [11, sub { $_[0] =~ m!^http://! }, 'as_uriReference'];
  3680.  
  3681. and add the C<as_uriReference> method to the L</"SOAP::Serializer"> class:
  3682.  
  3683.   sub SOAP::Serializer::as_uriReference {
  3684.     my $self = shift;
  3685.     my($value, $name, $type, $attr) = @_;
  3686.     return [$name, {'xsi:type' => 'xsd:uriReference', %$attr}, $value];
  3687.   }
  3688.  
  3689. The specified methods will work for both autotyping and direct typing, so you
  3690. can use either 
  3691.  
  3692.   SOAP::Data->type(uriReference => 'http://yahoo.com')>
  3693.  
  3694. or just 
  3695.  
  3696.   'http://yahoo.com'
  3697.  
  3698. and it will be serialized into the same type. For more examples see C<as_*> 
  3699. methods in L</"SOAP::Serializer">.
  3700.  
  3701. The SOAP::Serializer provides you with C<autotype()>, C<readable()>, C<namespace()>,
  3702. C<encodingspace()>, C<encoding()>, C<typelookup()>, C<uri()>, C<multirefinplace()> and 
  3703. C<envelope()> methods. All methods (except C<envelope()>) are described in the
  3704. L</"SOAP::Lite"> section.
  3705.  
  3706. =over 4
  3707.  
  3708. =item envelope()
  3709.  
  3710. This method allows you to build three kind of envelopes depending on the first 
  3711. parameter:
  3712.  
  3713. =over 4
  3714.  
  3715. =item method
  3716.  
  3717.   envelope(method => 'methodname', @parameters);
  3718.  
  3719. or
  3720.  
  3721.   method('methodname', @parameters);
  3722.  
  3723. Lets you build a request/response envelope.
  3724.  
  3725. =item fault
  3726.  
  3727.   envelope(fault => 'faultcode', 'faultstring', $details);
  3728.  
  3729. or 
  3730.   
  3731.   fault('faultcode', 'faultstring', $details);
  3732.  
  3733. Lets you build a fault envelope. Faultcode will be properly qualified and
  3734. details could be string or object.
  3735.  
  3736. =item freeform
  3737.  
  3738.   envelope(freeform => 'something that I want to serialize');
  3739.  
  3740. or
  3741.  
  3742.   freeform('something that I want to serialize');
  3743.            
  3744. Reserved for nonRPC calls. Lets you build your own payload inside a SOAP 
  3745. envelope. All SOAP 1.1 specification rules are enforced, except method 
  3746. specific ones. See UDDI::Lite as example.
  3747.  
  3748. =back
  3749.  
  3750. =back 
  3751.  
  3752. For more examples see tests and SOAP::Transport::HTTP.pm
  3753.  
  3754. =head2 SOAP::SOM
  3755.  
  3756. All calls you are making through object oriented interface will 
  3757. return SOAP::SOM object, and you can access actual values with it.
  3758. Next example gives you brief overview of the class:
  3759.  
  3760.   my $soap = SOAP::Lite .....;
  3761.   my $som = $soap->method(@parameters);
  3762.  
  3763.   if ($som->fault) { # will be defined if Fault element is in the message
  3764.     print $som->faultdetail; # returns value of 'detail' element as
  3765.                              # string or object
  3766.     $som->faultcode;   #
  3767.     $som->faultstring; # also available
  3768.     $som->faultactor;  # 
  3769.   } else {
  3770.     $som->result; # gives you access to result of call  
  3771.                   # it could be any data structure, for example reference 
  3772.                   # to array if server didi something like: return [1,2];
  3773.   
  3774.     $som->paramsout; # gives you access to out parameters if any
  3775.                      # for example, you'll get array (1,2) if
  3776.                      # server returns ([1,2], 1, 2); 
  3777.                      # [1,2] will be returned as $som->result
  3778.                      # and $som->paramsall will return ([1,2], 1, 2)
  3779.                      # see section IN/OUT, OUT PARAMETERS AND AUTOBINDING
  3780.                      # for more information
  3781.  
  3782.     $som->paramsall; # gives access to result AND out parameters (if any)
  3783.                      # and returns them as one array
  3784.   
  3785.     $som->valueof('//myelement'); # returns value(s) (as perl data) of
  3786.                                   # 'myelement' if any. All elements in array
  3787.                                   # context and only first one in scalar
  3788.   
  3789.     $h = $som->headerof('//myheader'); # returns element as SOAP::Header, so
  3790.                                        # you can access attributes and values
  3791.                                        # with $h->mustUnderstand, $h->actor
  3792.                                        # or $h->attr (for all attributes)
  3793.   }
  3794.    
  3795. SOAP::SOM object gives you access to the deserialized envelope via several 
  3796. methods. All methods accept a node path (similar to XPath notations). 
  3797. SOM interprets '/' as the root node, '//' as relative location path
  3798. ('//Body' will find all bodies in document, as well as 
  3799. '/Envelope//nums' will find all 'nums' nodes under Envelope node),
  3800. '[num]' as node number and '[op num]' with C<op> being a comparison 
  3801. operator ('<', '>', '<=', '>=', '!', '=').
  3802.  
  3803. All nodes in nodeset will be returned in document order.
  3804.  
  3805. =over 4
  3806.  
  3807. =item match()
  3808.  
  3809. Accepts a path to a node and returns true/false in a boolean context and
  3810. a SOM object otherwise. C<valueof()> and C<dataof()> can be used to get 
  3811. value(s) of matched node(s).
  3812.  
  3813. =item valueof()
  3814.  
  3815. Returns the value of a (previously) matched node. It accepts a node path. 
  3816. In this case, it returns the value of matched node, but does not change the current
  3817. node. Suitable when you want to match a  node and then navigate through
  3818. node children:
  3819.  
  3820.   $som->match('/Envelope/Body/[1]'); # match method
  3821.   $som->valueof('[1]');              # result
  3822.   $som->valueof('[2]');              # first out parameter (if present)
  3823.  
  3824. The returned value depends on the context. In a scalar context it will return 
  3825. the first element from matched nodeset. In an array context it will return 
  3826. all matched elements.
  3827.  
  3828. =item dataof()        
  3829.  
  3830. Same as C<valueof()>, but it returns a L</"SOAP::Data"> object, so you can get 
  3831. access to the name, the type and attributes of an element.
  3832.  
  3833. =item headerof()
  3834.  
  3835. Same as C<dataof()>, but it returns L</"SOAP::Header"> object, so you can get 
  3836. access to the name, the type and attributes of an element. Can be used for 
  3837. modifying headers (if you want to see updated header inside Header element, 
  3838. it's better to use this method instead of C<dataof()> method).
  3839.  
  3840. =item namespaceuriof()
  3841.  
  3842. Returns the uri associated with the matched element. This uri can also be 
  3843. inherited, for example, if you have 
  3844.  
  3845.   <a xmlns='http://my.namespace'>
  3846.     <b>
  3847.        value
  3848.     </b>
  3849.   </a>
  3850.  
  3851. this method will return same value for 'b' element as for 'a'.
  3852.  
  3853. =back
  3854.  
  3855. SOAP::SOM also provides  methods for direct access to the envelope, the body, 
  3856. methods and parameters (both in and out). All these methods return real
  3857. values (in most cases it will be a hash reference), if called as object
  3858. method. Returned values also depend on context: in an array context it will 
  3859. return an array of values and in scalar context it will return the first
  3860. element. So, if you want to access the first output parameter, you can call
  3861. C<< $param = $som->paramsout >>; 
  3862. and you will get it regardless of the actual number of output parameters. 
  3863. If you call it as class function (for example, SOAP::SOM::method)
  3864. it returns an XPath string that matches the current element 
  3865. ('/Envelope/Body/[1]' in case of 'method'). The method will return C<undef> 
  3866. if not present OR if you try to access an undefined element. To distinguish 
  3867. between these two cases you can first access the C<match()> method that 
  3868. will return true/false in a boolean context and then get the real value:
  3869.  
  3870.   if ($som->match('//myparameter')) {
  3871.     $value = $som->valueof; # can be undef too
  3872.   } else {
  3873.     # doesn't exist
  3874.   }
  3875.  
  3876. =over 4
  3877.  
  3878. =item root()
  3879.  
  3880. Returns the value (as hash) of the root element. Do exactly the same as 
  3881. C<< $som->valueof('/') >> does.
  3882.  
  3883. =item envelope()
  3884.  
  3885. Returns the value (as hash) of the C<Envelope> element. Keys in this hash will be 
  3886. 'Header' (if present), 'Body' and any other (optional) elements. Values will 
  3887. be the deserialized header, body, and elements, respectively.
  3888. If called as function (C<SOAP::SOM::envelope>) it will return a Xpath string 
  3889. that matches the envelope content. Useful when you want just match it and 
  3890. then iterate over the content by yourself. Example:
  3891.  
  3892.   if ($som->match(SOAP::SOM::envelope)) {
  3893.     $som->valueof('Header'); # should give access to header if present
  3894.     $som->valueof('Body');   # should give access to body
  3895.   } else {
  3896.     # hm, are we doing SOAP or what?
  3897.   }
  3898.  
  3899. =item header()
  3900.  
  3901. Returns the value (as hash) of the C<Header> element. If you want to access all 
  3902. attributes in the header use:
  3903.  
  3904.   # get element as SOAP::Data object 
  3905.   $transaction = $som->match(join '/', SOAP::SOM::header, 'transaction')->dataof;
  3906.   # then you can access all attributes of 'transaction' element
  3907.   $transaction->attr; 
  3908.  
  3909. =item headers()
  3910.  
  3911. Returns a node set of values with deserialized headers. The difference between 
  3912. the C<header()> and C<headers()> methods is that the first gives you access 
  3913. to the whole header and second to the headers inside the 'Header' tag:
  3914.  
  3915.   $som->headerof(join '/', SOAP::SOM::header, '[1]');
  3916.   # gives you first header as SOAP::Header object
  3917.  
  3918.   ($som->headers)[0];
  3919.   # gives you value of the first header, same as
  3920.   $som->valueof(join '/', SOAP::SOM::header, '[1]');
  3921.  
  3922.   $som->header->{name_of_your_header_here}
  3923.   # gives you value of name_of_your_header_here
  3924.  
  3925. =item body()
  3926.  
  3927. Returns the value (as hash) of the C<Body> element. 
  3928.  
  3929. =item fault()
  3930.  
  3931. Returns the value (as hash) of C<Fault> element: C<faultcode>, C<faultstring> and
  3932. C<detail>. If C<Fault> element is present, C<result()>, C<paramsin()>, 
  3933. C<paramsout()> and C<method()> will return an undef.
  3934.  
  3935. =item faultcode()
  3936.  
  3937. Returns the value of the C<faultcode> element if present and undef otherwise.
  3938.  
  3939. =item faultstring()
  3940.  
  3941. Returns the value of the C<faultstring> element if present and undef otherwise.
  3942.  
  3943. =item faultactor()
  3944.  
  3945. Returns the value of the C<faultactor> element if present and undef otherwise.
  3946.  
  3947. =item faultdetail()
  3948.  
  3949. Returns the value of the C<detail> element if present and undef otherwise.
  3950.  
  3951. =item method()
  3952.  
  3953. Returns the value of the method element (all input parameters if you call it on 
  3954. a deserialized request envelope, and result/output parameters if you call it
  3955. on a deserialized response envelope). Returns undef if the 'Fault' element is 
  3956. present.
  3957.  
  3958. =item result()
  3959.  
  3960. Returns the value of the C<result> of the method call. In fact, it will return 
  3961. the first child element (in document order) of the method element.
  3962.  
  3963. =item paramsin()
  3964.  
  3965. Returns the value(s) of all passed parameters.
  3966.  
  3967. =item paramsout()
  3968.  
  3969. Returns value(s) of the output parameters. 
  3970.  
  3971. =item paramsall()
  3972.  
  3973. Returns value(s) of the result AND output parameters as one array.
  3974.  
  3975. =back
  3976.  
  3977. =head2 SOAP::Schema
  3978.  
  3979. SOAP::Schema gives you ability to load schemas and create stubs according 
  3980. to these schemas. Different syntaxes are provided:
  3981.  
  3982. =over 4
  3983.  
  3984. =item *
  3985.  
  3986.   use SOAP::Lite
  3987.     service => 'http://www.xmethods.net/sd/StockQuoteService.wsdl',
  3988.     # service => 'file:/your/local/path/StockQuoteService.wsdl',
  3989.     # service => 'file:./StockQuoteService.wsdl',
  3990.   ;
  3991.   print getQuote('MSFT'), "\n";
  3992.  
  3993. =item *
  3994.  
  3995.   use SOAP::Lite;
  3996.   print SOAP::Lite
  3997.     -> service('http://www.xmethods.net/sd/StockQuoteService.wsdl')
  3998.     -> getQuote('MSFT'), "\n";
  3999.  
  4000. =item *
  4001.  
  4002.   use SOAP::Lite;
  4003.   my $service = SOAP::Lite
  4004.     -> service('http://www.xmethods.net/sd/StockQuoteService.wsdl');
  4005.   print $service->getQuote('MSFT'), "\n";
  4006.  
  4007. =back
  4008.  
  4009. You can create stub with B<stubmaker> script:
  4010.  
  4011.   perl stubmaker.pl http://www.xmethods.net/sd/StockQuoteService.wsdl
  4012.  
  4013. and you'll be able to access SOAP services in one line:
  4014.  
  4015.   perl "-MStockQuoteService qw(:all)" -le "print getQuote('MSFT')" 
  4016.  
  4017. or dynamically:
  4018.  
  4019.   perl "-MSOAP::Lite service=>'file:./quote.wsdl'" -le "print getQuote('MSFT')"
  4020.  
  4021. Other supported syntaxes with stub(s) are:
  4022.  
  4023. =over 4
  4024.  
  4025. =item *
  4026.  
  4027.   use StockQuoteService ':all';
  4028.   print getQuote('MSFT'), "\n";
  4029.  
  4030. =item *
  4031.  
  4032.   use StockQuoteService;
  4033.   print StockQuoteService->getQuote('MSFT'), "\n";
  4034.  
  4035. =item *
  4036.  
  4037.   use StockQuoteService;
  4038.   my $service = StockQuoteService->new;
  4039.   print $service->getQuote('MSFT'), "\n";
  4040.  
  4041. =back
  4042.  
  4043. Support for schemas is limited for now. Though module was tested with dozen
  4044. different schemas it won't understand complex objects and will work only
  4045. with WSDL. 
  4046.  
  4047. =head2 SOAP::Trace
  4048.  
  4049. SOAP::Trace provides you with a trace/debug facility for the SOAP::Lite 
  4050. library. To activate it you need to specify a list of traceable 
  4051. events/parts of SOAP::Lite:
  4052.  
  4053.   use SOAP::Lite +trace =>
  4054.     qw(list of available traces here);
  4055.  
  4056. Available events are:
  4057.  
  4058.  transport  -- (client) access to request/response for transport layer
  4059.  dispatch   -- (server) shows full name of dispatched call 
  4060.  result     -- (server) result of method call
  4061.  parameters -- (server) parameters for method call
  4062.  headers    -- (server) headers of received message
  4063.  objects    -- (both)   new/DESTROY calls
  4064.  method     -- (both)   parameters for '->envelope(method =>' call
  4065.  fault      -- (both)   parameters for '->envelope(fault =>' call
  4066.  freeform   -- (both)   parameters for '->envelope(freeform =>' call
  4067.  trace      -- (both)   trace enters into some important functions
  4068.  debug      -- (both)   details about transport 
  4069.  
  4070. For example:
  4071.  
  4072.   use SOAP::Lite +trace =>
  4073.     qw(method fault);
  4074.  
  4075. lets you output the parameter values for all your fault/normal envelopes onto STDERR. 
  4076. If you want to log it you can either redirect STDERR to some file
  4077.  
  4078.   BEGIN { open(STDERR, '>>....'); }
  4079.  
  4080. or (preferably) define your own function for a particular event:
  4081.  
  4082.   use SOAP::Lite +trace =>
  4083.     method => sub {'log messages here'}, fault => \&log_faults;
  4084.  
  4085. You can share the same function for several events:
  4086.  
  4087.   use SOAP::Lite +trace =>
  4088.     method, fault => \&log_methods_and_faults;
  4089.  
  4090. Also you can use 'all' to get all available tracing and use '-' in front of an event to 
  4091. disable particular event:
  4092.  
  4093.   use SOAP::Lite +trace =>
  4094.     all, -transport; # to get all logging without transport messages
  4095.  
  4096. Finally,
  4097.  
  4098.   use SOAP::Lite +trace; 
  4099.  
  4100. will switch all debugging on.
  4101.  
  4102. You can use 'debug' instead of 'trace'. I prefer 'trace', others 'debug'. 
  4103. Also C<on_debug> is available for backward compatibility, as in
  4104.  
  4105.   use SOAP::Lite;
  4106.  
  4107.   my $s = SOAP::Lite 
  4108.     -> uri('http://tempuri.org/')
  4109.     -> proxy('http://beta.search.microsoft.com/search/MSComSearchService.asmx')
  4110.     -> on_debug(sub{print@_}) # show you request/response with headers
  4111.   ;
  4112.   print $s->GetVocabulary(SOAP::Data->name(Query => 'something')->uri('http://tempuri.org/'))
  4113.           ->valueof('//FOUND');
  4114.  
  4115. or switch it on individually, with
  4116.  
  4117.   use SOAP::Lite +trace => debug;
  4118.  
  4119. or
  4120.   
  4121.   use SOAP::Lite +trace => debug => sub {'do_what_I_want_here'};
  4122.  
  4123. Compare this with: 
  4124.  
  4125.   use SOAP::Lite +trace => transport;
  4126.  
  4127. which gives you access to B<actual> request/response objects, so you can even 
  4128. set/read cookies or do whatever you want there.
  4129.  
  4130. The difference between C<debug> and C<transport> is that C<transport> will get 
  4131. a HTTP::Request/HTTP::Response object and C<debug> will get a stringified request 
  4132. (NOT OBJECT!). It can also be called in other places too. 
  4133.  
  4134. =head2 SOAP::Fault
  4135.  
  4136. This class gives you access to Fault generated on server side. To make a
  4137. Fault message you might simply die on server side and SOAP processor will 
  4138. wrap you message as faultstring element and will transfer Fault on client
  4139. side. But in some cases you need to have more control over this process and
  4140. SOAP::Fault class gives it to you. To use it, simply die with SOAP::Fault
  4141. object as a parameter:
  4142.  
  4143.   die SOAP::Fault->faultcode('Server.Custom') # will be qualified
  4144.                  ->faultstring('Died in server method')
  4145.                  ->faultdetail(bless {code => 1} => 'BadError')
  4146.                  ->faultactor('http://www.soaplite.com/custom');
  4147.  
  4148. faultdetail() and faultactor() methods are optional and since faultcode and
  4149. faultstring are required to represent fault message SOAP::Lite will use
  4150. default values ('Server' and 'Application error') if not specified.
  4151.  
  4152. =head2 SOAP::Constants
  4153.  
  4154. This class gives you access to number of options that may affect behavior of
  4155. SOAP::Lite objects. They are not true contstants, aren't they?
  4156.  
  4157. =over
  4158.  
  4159. =item $DO_NOT_USE_XML_PARSER
  4160.  
  4161. By default SOAP::Lite tries to load XML::Parser and if it fails, then to 
  4162. load XML::Parser::Lite. You may skip the first step and use XML::Parser::Lite
  4163. even if XML::Parser is presented in your system if assign true value like this:
  4164.  
  4165.   $SOAP::Constants::DO_NOT_USE_XML_PARSER = 1;
  4166.  
  4167. =item $DO_NOT_USE_CHARSET
  4168.  
  4169. By default SOAP::Lite specifies charset in content-type. Since not every
  4170. toolkit likes it you have an option to switch it off if you set 
  4171. C<$DO_NOT_USE_CHARSET> to true.
  4172.  
  4173. =item $DO_NOT_CHECK_CONTENT_TYPE
  4174.  
  4175. By default SOAP::Lite verifies that content-type in successful response has
  4176. value 'multipart/related' or 'multipart/form-data' for MIME-encoded messages
  4177. and 'text/xml' for all other ocassions. SOAP::Lite will raise exception for
  4178. all other values. C<$DO_NOT_CHECK_CONTENT_TYPE> when set to true will allow 
  4179. you to accept those values as valid.
  4180.  
  4181. =back
  4182.  
  4183. =head1 FEATURES AND OPTIONS
  4184.  
  4185. =head2 DEFAULT SETTINGS
  4186.  
  4187. Though this feature looks similar to L<autodispatch|/"AUTODISPATCHING AND SOAP:: PREFIX"> they have (almost) 
  4188. nothing in common. It lets you create default object and all objects 
  4189. created after that will be cloned from default object and hence get its 
  4190. properties. If you want to provide common proxy() or uri() settings for 
  4191. all SOAP::Lite objects in your application you may do:
  4192.  
  4193.   use SOAP::Lite
  4194.     proxy => 'http://localhost/cgi-bin/soap.cgi',
  4195.     uri => 'http://my.own.com/My/Examples'
  4196.   ;
  4197.  
  4198.   my $soap1 = new SOAP::Lite; # will get the same proxy()/uri() as above
  4199.   print $soap1->getStateName(1)->result;
  4200.  
  4201.   my $soap2 = SOAP::Lite->new; # same thing as above
  4202.   print $soap2->getStateName(2)->result;
  4203.  
  4204.   # or you may override any settings you want
  4205.   my $soap3 = SOAP::Lite->proxy('http://localhost/'); 
  4206.   print $soap3->getStateName(1)->result;
  4207.  
  4208. B<Any> SOAP::Lite properties can be propagated this way. Changes in object
  4209. copies will not affect global settings and you may still change global
  4210. settings with C<< SOAP::Lite->self >> call which returns reference to
  4211. global object. Provided parameter will update this object and you can
  4212. even set it to C<undef>:
  4213.  
  4214.   SOAP::Lite->self(undef);
  4215.  
  4216. The C<use SOAP::Lite> syntax also lets you specify default event handlers 
  4217. for your code. If you have different SOAP objects and want to share the 
  4218. same C<on_action()> (or C<on_fault()> for that matter) handler. You can 
  4219. specify C<on_action()> during initialization for every object, but 
  4220. you may also do:
  4221.  
  4222.   use SOAP::Lite 
  4223.     on_action => sub {sprintf '%s#%s', @_}
  4224.   ;
  4225.  
  4226. and this handler will be the default handler for all your SOAP objects. 
  4227. You can override it if you specify a handler for a particular object.
  4228. See F<t/*.t> for example of on_fault() handler.
  4229.  
  4230. Be warned, that since C<use ...> is executed at compile time B<all> C<use> 
  4231. statements will be executed B<before> script execution that can make 
  4232. unexpected results. Consider code:
  4233.  
  4234.   use SOAP::Lite proxy => 'http://localhost/';
  4235.  
  4236.   print SOAP::Lite->getStateName(1)->result;
  4237.   
  4238.   use SOAP::Lite proxy => 'http://localhost/cgi-bin/soap.cgi';
  4239.  
  4240.   print SOAP::Lite->getStateName(1)->result;
  4241.  
  4242. B<BOTH> SOAP calls will go to C<'http://localhost/cgi-bin/soap.cgi'>. If
  4243. you want to execute C<use> at run-time, put it in C<eval>:
  4244.  
  4245.   eval "use SOAP::Lite proxy => 'http://localhost/cgi-bin/soap.cgi'; 1" or die;
  4246.  
  4247. or use
  4248.  
  4249.   SOAP::Lite->self->proxy('http://localhost/cgi-bin/soap.cgi');
  4250.  
  4251. =head2 IN/OUT, OUT PARAMETERS AND AUTOBINDING
  4252.  
  4253. SOAP::Lite gives you access to all parameters (both in/out and out) and
  4254. also does some additional work for you. Lets consider following example:
  4255.  
  4256.   <mehodResponse>
  4257.     <res1>name1</res1>
  4258.     <res2>name2</res2>
  4259.     <res3>name3</res3>
  4260.   </mehodResponse>
  4261.  
  4262. In that case:
  4263.  
  4264.   $result = $r->result; # gives you 'name1'
  4265.   $paramout1 = $r->paramsout;      # gives you 'name2', because of scalar context
  4266.   $paramout1 = ($r->paramsout)[0]; # gives you 'name2' also
  4267.   $paramout2 = ($r->paramsout)[1]; # gives you 'name3'
  4268.  
  4269. or
  4270.  
  4271.   @paramsout = $r->paramsout; # gives you ARRAY of out parameters
  4272.   $paramout1 = $paramsout[0]; # gives you 'res2', same as ($r->paramsout)[0]
  4273.   $paramout2 = $paramsout[1]; # gives you 'res3', same as ($r->paramsout)[1]
  4274.  
  4275. Generally, if server returns C<return (1,2,3)> you will get C<1> as the result 
  4276. and C<2> and C<3> as out parameters.
  4277.  
  4278. If the server returns C<return [1,2,3]> you will get an ARRAY from C<result()> and 
  4279. C<undef> from C<paramsout()> .
  4280. Results can be arbitrary complex: they can be an array of something, they can
  4281. be objects, they can be anything and still be returned by C<result()> . If only
  4282. one parameter is returned, C<paramsout()> will return C<undef>.
  4283.  
  4284. But there is more.
  4285. If you have in your output parameters a parameter with the same
  4286. signature (name+type) as in the input parameters this parameter will be mapped
  4287. into your input automatically. Example:
  4288.  
  4289. B<server>:
  4290.  
  4291.   sub mymethod {
  4292.     shift; # object/class reference
  4293.     my $param1 = shift;
  4294.     my $param2 = SOAP::Data->name('myparam' => shift() * 2);
  4295.     return $param1, $param2;
  4296.   }
  4297.  
  4298. B<client>:
  4299.  
  4300.   $a = 10;
  4301.   $b = SOAP::Data->name('myparam' => 12);
  4302.   $result = $soap->mymethod($a, $b);
  4303.  
  4304. After that, C<< $result == 10 and $b->value == 24 >>! Magic? Sort of. 
  4305. Autobinding gives it to you. That will work with objects also with 
  4306. one difference: you do not need to worry about the name and the type of
  4307. object parameter. Consider the C<PingPong> example (F<examples/My/PingPong.pm> and
  4308. F<examples/pingpong.pl>):
  4309.  
  4310. B<server>:
  4311.  
  4312.   package My::PingPong;
  4313.  
  4314.   sub new { 
  4315.     my $self = shift;
  4316.     my $class = ref($self) || $self;
  4317.     bless {_num=>shift} => $class;
  4318.   }
  4319.  
  4320.   sub next {
  4321.     my $self = shift;
  4322.     $self->{_num}++;
  4323.   }
  4324.  
  4325. B<client>:
  4326.  
  4327.   use SOAP::Lite +autodispatch =>
  4328.     uri => 'urn:', 
  4329.     proxy => 'http://localhost/'
  4330.   ;
  4331.  
  4332.   my $p = My::PingPong->new(10); # $p->{_num} is 10 now, real object returned 
  4333.   print $p->next, "\n";          # $p->{_num} is 11 now!, object autobinded
  4334.  
  4335. =head2 AUTODISPATCHING AND SOAP:: PREFIX
  4336.  
  4337. B<WARNING>: C<autodispatch> feature can have side effects for your application 
  4338. and can affect functionality of other modules/libraries because of overloading
  4339. UNIVERSAL::AUTOLOAD. All unresolved calls will be dispatched as SOAP calls,
  4340. however it could be not what you want in some cases. If so, consider using 
  4341. object interface (see C<implementation of OO interface>). 
  4342.  
  4343. SOAP::Lite provides an autodispatching feature that lets you create 
  4344. code which looks the same for local and remote access.
  4345.  
  4346. For example:
  4347.    
  4348.   use SOAP::Lite +autodispatch =>
  4349.     uri => 'urn:/My/Examples', 
  4350.     proxy => 'http://localhost/'
  4351.   ;
  4352.  
  4353. tells SOAP to 'autodispatch' all calls to the 'http://localhost/' endpoint with
  4354. the 'urn:/My/Examples' uri. All consequent method calls can look like:
  4355.  
  4356.   print getStateName(1), "\n";
  4357.   print getStateNames(12,24,26,13), "\n";
  4358.   print getStateList([11,12,13,42])->[0], "\n";
  4359.   print getStateStruct({item1 => 10, item2 => 4})->{item2}, "\n";
  4360.  
  4361. As you can see, there is no SOAP specific coding at all.
  4362.  
  4363. The same logic will work for objects as well:
  4364.  
  4365.   print "Session iterator\n";
  4366.   my $p = My::SessionIterator->new(10);     
  4367.   print $p->next, "\n";  
  4368.   print $p->next, "\n";   
  4369.  
  4370. This will access the remote My::SessionIterator module, gets an object, and then 
  4371. calls remote methods again. The object will be transferred to the server, the 
  4372. method is executed there and the result (and the modified object!) will be 
  4373. transferred back to the client.
  4374.  
  4375. Autodispatch will work B<only> if you do not have the same method in your
  4376. code. For example, if you have C<use My::SessionIterator> somewhere in your
  4377. code of our previous example, all methods will be resolved locally  and no
  4378. SOAP calls will be done. If you want to get access to remote objects/methods 
  4379. even in that case, use C<SOAP::> prefix to your methods, like:
  4380.  
  4381.   print $p->SOAP::next, "\n";  
  4382.  
  4383. See C<pingpong.pl> for example of a script, that works with the same object
  4384. locally and remotely.
  4385.  
  4386. C<SOAP::> prefix also gives you ability to access methods that have the same
  4387. name as methods of SOAP::Lite itself. For example, you want to call method
  4388. new() for your class C<My::PingPong> through OO interface. 
  4389. First attempt could be:
  4390.  
  4391.   my $s = SOAP::Lite 
  4392.     -> uri('http://www.soaplite.com/My/PingPong')
  4393.     -> proxy('http://localhost/cgi-bin/soap.cgi')
  4394.   ;
  4395.   my $obj = $s->new(10);
  4396.  
  4397. but it won't work, because SOAP::Lite has method new() itself. To provide 
  4398. a hint, you should use C<SOAP::> prefix and call will be dispatched remotely:
  4399.  
  4400.   my $obj = $s->SOAP::new(10);
  4401.  
  4402. You can mix autodispatch and usual SOAP calls in the same code if
  4403. you need it. Keep in mind, that calls with SOAP:: prefix should always be a
  4404. method call, so if you want to call functions, use C<< SOAP->myfunction() >>
  4405. instead of C<SOAP::myfunction()>.
  4406.  
  4407. Be warned though Perl has very flexible syntax some versions will complain
  4408.  
  4409.   Bareword "autodispatch" not allowed while "strict subs" in use ...
  4410.  
  4411. if you try to put 'autodispatch' and '=>' on separate lines. So, keep them
  4412. on the same line, or put 'autodispatch' in quotes: 
  4413.  
  4414.   use SOAP::Lite 'autodispatch' # DON'T use plus in this case
  4415.     => .... 
  4416.   ; 
  4417.  
  4418. =head2 ACCESSING HEADERS AND ENVELOPE ON SERVER SIDE
  4419.  
  4420. SOAP::Lite gives you direct access to all headers and the whole envelope on 
  4421. the server side. Consider the following code from My::Parameters.pm:
  4422.  
  4423.   sub byname { 
  4424.     my($a, $b, $c) = @{pop->method}{qw(a b c)};
  4425.     return "a=$a, b=$b, c=$c";
  4426.   }
  4427.  
  4428. You will get this functionality ONLY if you inherit your class from 
  4429. the SOAP::Server::Parameters class. This should keep existing code working and
  4430. provides this feature only when you need it.
  4431.  
  4432. Every method on server side will be called as class/object method, so it will
  4433. get an B<object reference> or a B<class name> as the first parameter, then the 
  4434. method parameters, and then an envelope as SOAP::SOM object. Shortly:
  4435.  
  4436.   $self [, @parameters] , $envelope
  4437.  
  4438. If you have a fixed number of parameters, you can do:
  4439.  
  4440.   my $self = shift;
  4441.   my($param1, $param2) = @_;
  4442.  
  4443. and ignore the envelope. If you need access to the envelope you can do:
  4444.  
  4445.   my $envelope = pop; 
  4446.  
  4447. since the envelope is always the last element in the parameters list.
  4448. The C<byname()> method C<< pop->method >> will return a hash with
  4449. parameter names as hash keys and parameter values as hash values:
  4450.  
  4451.   my($a, $b, $c) = @{pop->method}{qw(a b c)};
  4452.  
  4453. gives you by-name access to your parameters.
  4454.  
  4455. =head2 SERVICE DEPLOYMENT. STATIC AND DYNAMIC
  4456.  
  4457. Let us scrutinize the deployment process. When designing your SOAP server you 
  4458. can consider two kind of deployment: B<static> and B<dynamic>.
  4459. For both, static and dynamic,  you should specify C<MODULE>, 
  4460. C<MODULE::method>, C<method> or C<PATH/> when creating C<use>ing the 
  4461. SOAP::Lite module. The difference between static and dynamic deployment is 
  4462. that in case of 'dynamic', any module which is not present will be loaded on
  4463. demand. See the L</"SECURITY"> section for detailed description.
  4464.  
  4465. Example for B<static> deployment:
  4466.  
  4467.   use SOAP::Transport::HTTP;
  4468.   use My::Examples;           # module is preloaded 
  4469.  
  4470.   SOAP::Transport::HTTP::CGI
  4471.     # deployed module should be present here or client will get 'access denied'
  4472.     -> dispatch_to('My::Examples') 
  4473.     -> handle;
  4474.  
  4475. Example for B<dynamic> deployment:
  4476.  
  4477.   use SOAP::Transport::HTTP;
  4478.   # name is unknown, module will be loaded on demand
  4479.  
  4480.   SOAP::Transport::HTTP::CGI
  4481.     # deployed module should be present here or client will get 'access denied'
  4482.     -> dispatch_to('/Your/Path/To/Deployed/Modules', 'My::Examples') 
  4483.     -> handle;
  4484.  
  4485. For static deployment you should specify the MODULE name directly. 
  4486. For dynamic deployment you can specify the name either directly (in that 
  4487. case it will be C<require>d without any restriction) or indirectly, with a PATH
  4488. In that case, the ONLY path that will be available will be the PATH given
  4489. to the dispatch_to() method). For information how to handle this situation
  4490. see L</"SECURITY"> section.
  4491.  
  4492. You should also use static binding when you have several different classes 
  4493. in one file and want to make them available for SOAP calls.
  4494.  
  4495. B<SUMMARY>: 
  4496.  
  4497.   dispatch_to(
  4498.     # dynamic dispatch that allows access to ALL modules in specified directory
  4499.     PATH/TO/MODULES          
  4500.     # 1. specifies directory 
  4501.     # -- AND --
  4502.     # 2. gives access to ALL modules in this directory without limits
  4503.  
  4504.     # static dispatch that allows access to ALL methods in particular MODULE
  4505.     MODULE 
  4506.     #  1. gives access to particular module (all available methods)
  4507.     #  PREREQUISITES:
  4508.     #    module should be loaded manually (for example with 'use ...')
  4509.     #    -- OR --
  4510.     #    you can still specify it in PATH/TO/MODULES
  4511.  
  4512.     # static dispatch that allows access to particular method ONLY
  4513.     MODULE::method 
  4514.     # same as MODULE, but gives access to ONLY particular method,
  4515.     # so there is not much sense to use both MODULE and MODULE::method 
  4516.     # for the same MODULE
  4517.   )
  4518.  
  4519. In addition to this SOAP::Lite also supports experimental syntax that
  4520. allows you bind specific URL or SOAPAction to CLASS/MODULE or object:
  4521.  
  4522.   dispatch_with({
  4523.     URI => MODULE,        # 'http://www.soaplite.com/' => 'My::Class',
  4524.     SOAPAction => MODULE, # 'http://www.soaplite.com/method' => 'Another::Class',
  4525.     URI => object,        # 'http://www.soaplite.com/obj' => My::Class->new,
  4526.   })
  4527.  
  4528. URI is checked before SOAPAction. You may use both C<dispatch_to()> and
  4529. C<dispatch_with()> syntax and C<dispatch_with()> has more priority, so
  4530. first checked URI, then SOAPAction and only then will be checked 
  4531. C<dispatch_to()>. See F<t/03-server.t> for more information and examples.
  4532.  
  4533. =head2 SECURITY
  4534.  
  4535. Due to security reasons, the current path for perl modules (C<@INC>) will be disabled
  4536. once you have chosen dynamic deployment and specified your own C<PATH/>.
  4537. If you want to access other modules in your included package you have 
  4538. several options:
  4539.  
  4540. =over 4
  4541.  
  4542. =item 1
  4543.  
  4544. Switch to static linking:
  4545.  
  4546.    use MODULE;
  4547.    $server->dispatch_to('MODULE');
  4548.  
  4549. It can be useful also when you want to import something specific
  4550. from the deployed modules: 
  4551.  
  4552.    use MODULE qw(import_list);
  4553.  
  4554. =item 2
  4555.  
  4556. Change C<use> to C<require>. The path is unavailable only during 
  4557. the initialization part, and it is available again during execution. 
  4558. So, if you do C<require> somewhere in your package, it will work.
  4559.  
  4560. =item 3
  4561.  
  4562. Same thing, but you can do: 
  4563.  
  4564.    eval 'use MODULE qw(import_list)'; die if $@;
  4565.  
  4566. =item 4
  4567.  
  4568. Assign a C<@INC> directory in your package and then make C<use>.
  4569. Don't forget to put C<@INC> in C<BEGIN{}> block or it won't work:
  4570.  
  4571.    BEGIN { @INC = qw(my_directory); use MODULE }
  4572.  
  4573. =back
  4574.  
  4575. =head2 COMPRESSION
  4576.  
  4577. SOAP::Lite provides you option for enabling compression on wire (for HTTP 
  4578. transport only). Both server and client should support this capability, 
  4579. but this logic should be absolutely transparent for your application. 
  4580.  
  4581. Compression can be enabled by specifying threshold for compression on client 
  4582. or server side:
  4583.  
  4584. =over 4
  4585.  
  4586. =item Client
  4587.  
  4588.   print SOAP::Lite
  4589.     -> uri('http://localhost/My/Parameters')
  4590.     -> proxy('http://localhost/', options => {compress_threshold => 10000})
  4591.     -> echo(1 x 10000)
  4592.     -> result
  4593.   ;
  4594.  
  4595. =item Server
  4596.  
  4597.   my $server = SOAP::Transport::HTTP::CGI
  4598.     -> dispatch_to('My::Parameters')
  4599.     -> options({compress_threshold => 10000})
  4600.     -> handle;
  4601.  
  4602. =back
  4603.  
  4604. For more information see L<COMPRESSION section|SOAP::Transport::HTTP/"COMPRESSION"> 
  4605. in HTTP transport documentation.
  4606.  
  4607. =head2 OBJECTS-BY-REFERENCE
  4608.  
  4609. SOAP::Lite implements an experimental (yet functional) support for
  4610. objects-by-reference. You should not see any difference on the client side 
  4611. when using this. On the server side you should specify the names of the 
  4612. classes you want to be returned by reference (instead of by value) in the 
  4613. C<objects_by_reference()> method for your server implementation (see 
  4614. soap.pop3, soap.daemon and Apache.pm).
  4615.  
  4616. Garbage collection is done on the server side (not earlier than after 600 
  4617. seconds of inactivity time), and you can overload the default behavior with 
  4618. specific functions for any particular class. 
  4619.  
  4620. Binding does not have any special syntax and is implemented on server side 
  4621. (see the differences between My::SessionIterator and My::PersistentIterator). 
  4622. On the client side, objects will have same type/class as before 
  4623. (C<< My::SessionIterator->new() >> will return an object of class 
  4624. My::SessionIterator). However, this object is just a stub with an object ID 
  4625. inside.
  4626.  
  4627. =head2 INTEROPERABILITY
  4628.  
  4629. =over 4
  4630.  
  4631. =item Microsoft's .NET 
  4632.  
  4633. To use .NET client and SOAP::Lite server
  4634.  
  4635. =over 4
  4636.  
  4637. =item qualify all elements
  4638.  
  4639. use fully qualified names for your return values, e.g.: 
  4640.  
  4641.   return SOAP::Data->name('myname') 
  4642.                    ->type('string')
  4643.                    ->uri('http://tempuri.org/')
  4644.                    ->value($output);
  4645.  
  4646. Use namespace that you specify for URI instead of 'http://tempuri.org/'.
  4647.  
  4648. In addition see comment about default incoding in .NET Web Services below.
  4649.  
  4650. =back
  4651.  
  4652. To use SOAP::Lite client and .NET server
  4653.  
  4654. =over 4
  4655.  
  4656. =item declare proper soapAction (uri/method) in your call
  4657.  
  4658. For example, use C<on_action(sub{join '', @_})>.
  4659.  
  4660. =item disable charset in content-type
  4661.  
  4662. Specify C<$SOAP::Constants::DO_NOT_USE_CHARSET = 1> somewhere in your code 
  4663. after C<use SOAP::Lite> if you are getting error:
  4664.  
  4665.   Server found request content type to be 'text/xml; charset=utf-8',
  4666.   but expected 'text/xml'
  4667.  
  4668. =item qualify all elements
  4669.  
  4670. Any of following actions should work:
  4671.  
  4672. =over 4
  4673.  
  4674. =item use fully qualified name for method parameters
  4675.  
  4676. Use C<< SOAP::Data->name(Query  => 'biztalk')->uri('http://tempuri.org/') >> instead of 
  4677. C<< SOAP::Data->name('Query'  => 'biztalk') >>.
  4678.  
  4679. Example of SOAPsh call (all parameters should be in one line):
  4680.  
  4681.   > perl SOAPsh.pl 
  4682.     "http://beta.search.microsoft.com/search/mscomsearchservice.asmx" 
  4683.     "http://tempuri.org/" 
  4684.     "on_action(sub{join '', @_})" 
  4685.     "GetVocabulary(SOAP::Data->name(Query  => 'biztalk')->uri('http://tempuri.org/'))"
  4686.  
  4687. =item make method in default namespace
  4688.  
  4689. instead of 
  4690.  
  4691.   my @rc = $soap->call(add => @parms)->result;
  4692.   # -- OR --
  4693.   my @rc = $soap->add(@parms)->result;
  4694.  
  4695. use
  4696.  
  4697.   my $method = SOAP::Data->name('add')
  4698.                          ->attr({xmlns => 'http://tempuri.org/'});
  4699.   my @rc = $soap->call($method => @parms)->result;
  4700.  
  4701. =item modify .NET server if you are in charge for that
  4702.  
  4703. Stefan Pharies <stefanph@microsoft.com>:
  4704.  
  4705. SOAP::Lite uses the SOAP encoding (section 5 of the soap 1.1 spec), and
  4706. the default for .NET Web Services is to use a literal encoding. So
  4707. elements in the request are unqualified, but your service expects them to 
  4708. be qualified. .Net Web Services has a way for you to change the expected 
  4709. message format, which should allow you to get your interop working. 
  4710. At the top of your class in the asmx, add this attribute (for Beta 1):
  4711.  
  4712.   [SoapService(Style=SoapServiceStyle.RPC)]
  4713.  
  4714. Another source said it might be this attribute (for Beta 2):
  4715.  
  4716.   [SoapRpcService]
  4717.  
  4718. Full Web Service text may look like:
  4719.  
  4720.   <%@ WebService Language="C#" Class="Test" %>
  4721.   using System;
  4722.   using System.Web.Services;
  4723.   using System.Xml.Serialization;
  4724.  
  4725.   [SoapService(Style=SoapServiceStyle.RPC)]
  4726.   public class Test : WebService {
  4727.     [WebMethod] 
  4728.     public int add(int a, int b) {
  4729.       return a + b;
  4730.     }
  4731.   }
  4732.  
  4733. Another example from Kirill Gavrylyuk <kirillg@microsoft.com>:
  4734.  
  4735. "You can insert [SoapRpcService()] attribute either on your class or on 
  4736. operation level".
  4737.  
  4738.   <%@ WebService Language=CS class="DataType.StringTest"%>
  4739.  
  4740.   namespace DataType {
  4741.  
  4742.     using System;
  4743.     using System.Web.Services;
  4744.     using System.Web.Services.Protocols;
  4745.     using System.Web.Services.Description;
  4746.  
  4747.    [SoapRpcService()]
  4748.    public class StringTest: WebService {
  4749.      [WebMethod]
  4750.      [SoapRpcMethod()]
  4751.      public string RetString(string x) {
  4752.        return(x);
  4753.      }
  4754.    }
  4755.  }
  4756.  
  4757. Example from Yann Christensen <yannc@microsoft.com>:
  4758.  
  4759.   using System;
  4760.   using System.Web.Services;
  4761.   using System.Web.Services.Protocols;
  4762.  
  4763.   namespace Currency {
  4764.     [WebService(Namespace="http://www.yourdomain.com/example")]
  4765.     [SoapRpcService]
  4766.     public class Exchange {
  4767.       [WebMethod]
  4768.       public double getRate(String country, String country2) {
  4769.         return 122.69;
  4770.       }
  4771.     }
  4772.   }
  4773.  
  4774. =back
  4775.  
  4776. =back
  4777.  
  4778. Thanks to 
  4779.   Petr Janata <petr.janata@i.cz>, 
  4780.   Stefan Pharies <stefanph@microsoft.com>,
  4781.   Brian Jepson <bjepson@jepstone.net>, and others 
  4782. for description and examples.
  4783.  
  4784. =back
  4785.  
  4786. =head2 TROUBLESHOOTING
  4787.  
  4788. =over 4
  4789.  
  4790. =item HTTP transport
  4791.  
  4792. See L<TROUBLESHOOTING|SOAP::Transport::HTTP/"TROUBLESHOOTING"> section in 
  4793. documentation for HTTP transport.
  4794.  
  4795. =item COM interface
  4796.  
  4797. =over 4
  4798.  
  4799. =item Can't call method "server" on undefined value
  4800.  
  4801. Probably you didn't register Lite.dll with 'regsvr32 Lite.dll'
  4802.  
  4803. =item Failed to load PerlCtrl runtime
  4804.  
  4805. Probably you have two Perl installations in different places and
  4806. ActiveState's Perl isn't the first Perl specified in PATH. Rename the
  4807. directory with another Perl (at least during the DLL's startup) or put
  4808. ActiveState's Perl on the first place in PATH.
  4809.  
  4810. =back
  4811.  
  4812. =item XML Parsers
  4813.  
  4814. =over 4
  4815.  
  4816. =item SAX parsers
  4817.  
  4818. SAX 2.0 has a known bug in org.xml.sax.helpers.ParserAdapter
  4819.      rejects Namespace prefix used before declaration
  4820.  
  4821. (http://www.megginson.com/SAX/index.html).
  4822.  
  4823. That means that in some cases SOAP messages created by SOAP::Lite may not
  4824. be parsed properly by SAX2/Java parser, because Envelope
  4825. element contains namespace declarations and attributes that depends on this
  4826. declarations. According to XML specification order of these attributes is
  4827. not significant. SOAP::Lite does NOT have a problem parsing such messages.
  4828.  
  4829. Thanks to Steve Alpert (Steve_Alpert@idx.com) for pointing on it.
  4830.  
  4831. =back
  4832.  
  4833. =back
  4834.  
  4835. =head2 PERFORMANCE
  4836.  
  4837. =over 4
  4838.  
  4839. =item Processing of XML encoded fragments
  4840.  
  4841. SOAP::Lite is based on XML::Parser which is basically wrapper around James 
  4842. Clark's expat parser. Expat's behavior for parsing XML encoded string can 
  4843. affect processing messages that have lot of encoded entities, like XML 
  4844. fragments, encoded as strings. Providing low-level details, parser will call 
  4845. char() callback for every portion of processed stream, but individually for 
  4846. every processed entity or newline. It can lead to lot of calls and additional
  4847. memory manager expenses even for small messages. By contrast, XML messages
  4848. which are encoded as base64, don't have this problem and difference in 
  4849. processing time can be significant. For XML encoded string that has about 20 
  4850. lines and 30 tags, number of call could be about 100 instead of one for
  4851. the same string encoded as base64.
  4852.  
  4853. Since it is parser's feature there is NO fix for this behavior (let me know
  4854. if you find one), especially because you need to parse message you already
  4855. got (and you cannot control content of this message), however, if your are
  4856. in charge for both ends of processing you can switch encoding to base64 on
  4857. sender's side. It will definitely work with SOAP::Lite and it B<may> work with 
  4858. other toolkits/implementations also, but obviously I cannot guarantee that.
  4859.  
  4860. If you want to encode specific string as base64, just do 
  4861. C<< SOAP::Data->type(base64 => $string) >> either on client or on server
  4862. side. If you want change behavior for specific instance of SOAP::Lite, you 
  4863. may subclass C<SOAP::Serializer>, override C<as_string()> method that is 
  4864. responsible for string encoding (take a look into C<as_base64()>) and 
  4865. specify B<new> serializer class for your SOAP::Lite object with:
  4866.  
  4867.   my $soap = new SOAP::Lite
  4868.     serializer => My::Serializer->new,
  4869.     ..... other parameters
  4870.  
  4871. or on server side:
  4872.  
  4873.   my $server = new SOAP::Transport::HTTP::Daemon # or any other server
  4874.     serializer => My::Serializer->new,
  4875.     ..... other parameters
  4876.  
  4877. If you want to change this behavior for B<all> instances of SOAP::Lite, just
  4878. substitute C<as_string()> method with C<as_base64()> somewhere in your 
  4879. code B<after> C<use SOAP::Lite> and B<before> actual processing/sending:
  4880.  
  4881.   *SOAP::Serializer::as_string = \&SOAP::Serializer::as_base64;
  4882.  
  4883. Be warned that last two methods will affect B<all> strings and convert them
  4884. into base64 encoded. It doesn't make any difference for SOAP::Lite, but it
  4885. B<may> make a difference for other toolkits.
  4886.  
  4887. =back
  4888.  
  4889. =head2 WEBHOSTING INSTALLATION
  4890.  
  4891. As soon as you have telnet access to the box and XML::Parser is already
  4892. installed there (or you have Perl 5.6 and can use XML::Parser::Lite) you 
  4893. may install your own copy of SOAP::Lite even if hosting provider doesn't 
  4894. want to do it.
  4895.  
  4896. Setup C<PERL5LIB> environment variable. Depending on your shell it may 
  4897. look like:
  4898.  
  4899.   PERL5LIB=/you/home/directory/lib; export PERL5LIB
  4900.  
  4901. C<lib> here is the name of directory where all libraries will be installed 
  4902. under your home directory.
  4903.  
  4904. Run CPAN module with
  4905.  
  4906.   perl -MCPAN -e shell
  4907.  
  4908. and run three commands from CPAN shell
  4909.  
  4910.   > o conf make_arg -I~/lib
  4911.   > o conf make_install_arg -I~/lib
  4912.   > o conf makepl_arg LIB=~/lib PREFIX=~ INSTALLMAN1DIR=~/man/man1 INSTALLMAN3DIR=~/man/man3
  4913.  
  4914. C<LIB> will specify directory where all libraries will reside. 
  4915.  
  4916. C<PREFIX> will specify prefix for all directories (like F<lib>, F<bin>, F<man>, 
  4917. though it doesn't work in all cases for some reason).
  4918.  
  4919. C<INSTALLMAN1DIR> and C<INSTALLMAN3DIR> specify directories for manuals 
  4920. (if you don't specify them, install will fail because it'll try to setup 
  4921. it in default directory and you don't have permissions for that).
  4922.  
  4923. Then run:
  4924.  
  4925.   > install SOAP::Lite
  4926.  
  4927. Now in your scripts you need to specify:
  4928.  
  4929.   use lib '/your/home/directory/lib';
  4930.  
  4931. somewhere before C<'use SOAP::Lite;'>
  4932.  
  4933. =head1 BUGS AND LIMITATIONS
  4934.  
  4935. =over 4
  4936.  
  4937. =item *
  4938.  
  4939. No support for multidimensional, partially transmitted and sparse arrays 
  4940. (however arrays of arrays are supported, as well as any other data 
  4941. structures, and you can add your own implementation with SOAP::Data). 
  4942.  
  4943. =item *
  4944.  
  4945. Limited support for WSDL schema. 
  4946.  
  4947. =item *
  4948.  
  4949. XML::Parser::Lite relies on Unicode support in Perl and doesn't do 
  4950. entity decoding. 
  4951.  
  4952. =item *
  4953.  
  4954. Limited support for mustUnderstand and Actor attributes. 
  4955.  
  4956. =back
  4957.  
  4958. =head1 PLATFORMS
  4959.  
  4960. =over 4
  4961.  
  4962. =item MacOS
  4963.  
  4964. Information about XML::Parser for MacPerl could be found here:
  4965. http://bumppo.net/lists/macperl-modules/1999/07/msg00047.html
  4966.  
  4967. Compiled XML::Parser for MacOS could be found here:
  4968. http://www.perl.com/CPAN-local/authors/id/A/AS/ASANDSTRM/XML-Parser-2.27-bin-1-MacOS.tgz
  4969.  
  4970. =back
  4971.  
  4972. =head1 AVAILABILITY
  4973.  
  4974. You can download the latest version SOAP::Lite for Unix or SOAP::Lite for Win32 from http://soaplite.com/ .
  4975. SOAP::Lite is available also from CPAN ( http://search.cpan.org/search?dist=SOAP-Lite ).  
  4976. You are very welcome to write mail to the author (paulclinger@yahoo.com) 
  4977. with your comments, suggestions, bug reports and complaints.
  4978.  
  4979. =head1 SEE ALSO
  4980.  
  4981. L<SOAP> SOAP/Perl library from Keith Brown ( http://www.develop.com/soap/ ) or
  4982. ( http://search.cpan.org/search?dist=SOAP )
  4983.  
  4984. =head1 ACKNOWLEDGMENTS
  4985.  
  4986. A lot of thanks to
  4987.   Tony Hong <thong@xmethods.net>,
  4988.   Petr Janata <petr.janata@i.cz>,
  4989.   Murray Nesbitt <murray@ActiveState.com>,
  4990.   Robert Barta <rho@bigpond.net.au>,
  4991.   Gisle Aas <gisle@ActiveState.com>,
  4992.   Carl K. Cunningham <cc@roberts.de>,
  4993.   Graham Glass <graham-glass@mindspring.com>,
  4994.   Chris Radcliff <chris@velocigen.com>, 
  4995.   Arun Kumar <u_arunkumar@yahoo.com>,
  4996.   and many many others 
  4997. for provided help, feedback, support, patches and comments. 
  4998.  
  4999. =head1 COPYRIGHT
  5000.  
  5001. Copyright (C) 2000-2001 Paul Kulchenko. All rights reserved.
  5002.  
  5003. This library is free software; you can redistribute it and/or modify
  5004. it under the same terms as Perl itself.
  5005.  
  5006. =head1 AUTHOR
  5007.  
  5008. Paul Kulchenko (paulclinger@yahoo.com)
  5009.  
  5010. =cut
  5011.