b2evolution

Multilingual multiuser multiblog engine

b2evolution Technical Documentation (Version 2.4) [ class tree: main ] [ index: main ] [ all elements ]

Source for file _xmlrpc.inc.php

Documentation is available at _xmlrpc.inc.php

  1. <?php
  2. // by Edd Dumbill (C) 1999-2002
  3. // <edd@usefulinc.com>
  4. // $Id: _xmlrpc.inc.php,v 1.1 2008/01/14 07:17:31 fplanque Exp $
  5.  
  6. // Copyright (c) 1999,2000,2002 Edd Dumbill.
  7. // All rights reserved.
  8. //
  9. // Redistribution and use in source and binary forms, with or without
  10. // modification, are permitted provided that the following conditions
  11. // are met:
  12. //
  13. //    * Redistributions of source code must retain the above copyright
  14. //      notice, this list of conditions and the following disclaimer.
  15. //
  16. //    * Redistributions in binary form must reproduce the above
  17. //      copyright notice, this list of conditions and the following
  18. //      disclaimer in the documentation and/or other materials provided
  19. //      with the distribution.
  20. //
  21. //    * Neither the name of the "XML-RPC for PHP" nor the names of its
  22. //      contributors may be used to endorse or promote products derived
  23. //      from this software without specific prior written permission.
  24. //
  25. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  26. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  27. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  28. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  29. // REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  30. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  31. // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  32. // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  33. // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  34. // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  35. // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  36. // OF THE POSSIBILITY OF SUCH DAMAGE.
  37.  
  38.     // G. Giunta 2005/01/29: declare global these variables,
  39.     // so that xmlrpc.inc will work even if included from within a function
  40.     // Milosch: 2005/08/07 - explicitly request these via $GLOBALS where used.
  41.     $GLOBALS['xmlrpcI4']='i4';
  42.     $GLOBALS['xmlrpcInt']='int';
  43.     $GLOBALS['xmlrpcBoolean']='boolean';
  44.     $GLOBALS['xmlrpcDouble']='double';
  45.     $GLOBALS['xmlrpcString']='string';
  46.     $GLOBALS['xmlrpcDateTime']='dateTime.iso8601';
  47.     $GLOBALS['xmlrpcBase64']='base64';
  48.     $GLOBALS['xmlrpcArray']='array';
  49.     $GLOBALS['xmlrpcStruct']='struct';
  50.     $GLOBALS['xmlrpcValue']='undefined';
  51.  
  52.     $GLOBALS['xmlrpcTypes']=array(
  53.         $GLOBALS['xmlrpcI4']       => 1,
  54.         $GLOBALS['xmlrpcInt']      => 1,
  55.         $GLOBALS['xmlrpcBoolean']  => 1,
  56.         $GLOBALS['xmlrpcString']   => 1,
  57.         $GLOBALS['xmlrpcDouble']   => 1,
  58.         $GLOBALS['xmlrpcDateTime'=> 1,
  59.         $GLOBALS['xmlrpcBase64']   => 1,
  60.         $GLOBALS['xmlrpcArray']    => 2,
  61.         $GLOBALS['xmlrpcStruct']   => 3
  62.     );
  63.  
  64.     $GLOBALS['xmlrpc_valid_parents'array(
  65.         'VALUE' => array('MEMBER''DATA''PARAM''FAULT'),
  66.         'BOOLEAN' => array('VALUE'),
  67.         'I4' => array('VALUE'),
  68.         'INT' => array('VALUE'),
  69.         'STRING' => array('VALUE'),
  70.         'DOUBLE' => array('VALUE'),
  71.         'DATETIME.ISO8601' => array('VALUE'),
  72.         'BASE64' => array('VALUE'),
  73.         'MEMBER' => array('STRUCT'),
  74.         'NAME' => array('MEMBER'),
  75.         'DATA' => array('ARRAY'),
  76.         'ARRAY' => array('VALUE'),
  77.         'STRUCT' => array('VALUE'),
  78.         'PARAM' => array('PARAMS'),
  79.         'METHODNAME' => array('METHODCALL'),
  80.         'PARAMS' => array('METHODCALL''METHODRESPONSE'),
  81.         'FAULT' => array('METHODRESPONSE'),
  82.         'NIL' => array('VALUE'// only used when extension activated
  83.     );
  84.  
  85.     // define extra types for supporting NULL (useful for json or <NIL/>)
  86.     $GLOBALS['xmlrpcNull']='null';
  87.     $GLOBALS['xmlrpcTypes']['null']=1;
  88.  
  89.     // Not in use anymore since 2.0. Shall we remove it?
  90.     /// @deprecated
  91.     $GLOBALS['xmlEntities']=array(
  92.         'amp'  => '&',
  93.         'quot' => '"',
  94.         'lt'   => '<',
  95.         'gt'   => '>',
  96.         'apos' => "'"
  97.     );
  98.  
  99.     // tables used for transcoding different charsets into us-ascii xml
  100.  
  101.     $GLOBALS['xml_iso88591_Entities']=array();
  102.     $GLOBALS['xml_iso88591_Entities']['in'array();
  103.     $GLOBALS['xml_iso88591_Entities']['out'array();
  104.     for ($i 0$i 32$i++)
  105.     {
  106.         $GLOBALS['xml_iso88591_Entities']['in'][chr($i);
  107.         $GLOBALS['xml_iso88591_Entities']['out']['&#'.$i.';';
  108.     }
  109.     for ($i 160$i 256$i++)
  110.     {
  111.         $GLOBALS['xml_iso88591_Entities']['in'][chr($i);
  112.         $GLOBALS['xml_iso88591_Entities']['out']['&#'.$i.';';
  113.     }
  114.  
  115.     /// @todo add to iso table the characters from cp_1252 range, i.e. 128 to 159.
  116.     /// These will NOT be present in true ISO-8859-1, but will save the unwary
  117.     /// windows user from sending junk.
  118. /*
  119. $cp1252_to_xmlent =
  120.   array(
  121.    '\x80'=>'&#x20AC;', '\x81'=>'?', '\x82'=>'&#x201A;', '\x83'=>'&#x0192;',
  122.    '\x84'=>'&#x201E;', '\x85'=>'&#x2026;', '\x86'=>'&#x2020;', \x87'=>'&#x2021;',
  123.    '\x88'=>'&#x02C6;', '\x89'=>'&#x2030;', '\x8A'=>'&#x0160;', '\x8B'=>'&#x2039;',
  124.    '\x8C'=>'&#x0152;', '\x8D'=>'?', '\x8E'=>'&#x017D;', '\x8F'=>'?',
  125.    '\x90'=>'?', '\x91'=>'&#x2018;', '\x92'=>'&#x2019;', '\x93'=>'&#x201C;',
  126.    '\x94'=>'&#x201D;', '\x95'=>'&#x2022;', '\x96'=>'&#x2013;', '\x97'=>'&#x2014;',
  127.    '\x98'=>'&#x02DC;', '\x99'=>'&#x2122;', '\x9A'=>'&#x0161;', '\x9B'=>'&#x203A;',
  128.    '\x9C'=>'&#x0153;', '\x9D'=>'?', '\x9E'=>'&#x017E;', '\x9F'=>'&#x0178;'
  129.   );
  130. */
  131.  
  132.     $GLOBALS['xmlrpcerr']['unknown_method']=1;
  133.     $GLOBALS['xmlrpcstr']['unknown_method']='Unknown method';
  134.     $GLOBALS['xmlrpcerr']['invalid_return']=2;
  135.     $GLOBALS['xmlrpcstr']['invalid_return']='Invalid return payload: enable debugging to examine incoming payload';
  136.     $GLOBALS['xmlrpcerr']['incorrect_params']=3;
  137.     $GLOBALS['xmlrpcstr']['incorrect_params']='Incorrect parameters passed to method';
  138.     $GLOBALS['xmlrpcerr']['introspect_unknown']=4;
  139.     $GLOBALS['xmlrpcstr']['introspect_unknown']="Can't introspect: method unknown";
  140.     $GLOBALS['xmlrpcerr']['http_error']=5;
  141.     $GLOBALS['xmlrpcstr']['http_error']="Didn't receive 200 OK from remote server.";
  142.     $GLOBALS['xmlrpcerr']['no_data']=6;
  143.     $GLOBALS['xmlrpcstr']['no_data']='No data received from server.';
  144.     $GLOBALS['xmlrpcerr']['no_ssl']=7;
  145.     $GLOBALS['xmlrpcstr']['no_ssl']='No SSL support compiled in.';
  146.     $GLOBALS['xmlrpcerr']['curl_fail']=8;
  147.     $GLOBALS['xmlrpcstr']['curl_fail']='CURL error';
  148.     $GLOBALS['xmlrpcerr']['invalid_request']=15;
  149.     $GLOBALS['xmlrpcstr']['invalid_request']='Invalid request payload';
  150.     $GLOBALS['xmlrpcerr']['no_curl']=16;
  151.     $GLOBALS['xmlrpcstr']['no_curl']='No CURL support compiled in.';
  152.     $GLOBALS['xmlrpcerr']['server_error']=17;
  153.     $GLOBALS['xmlrpcstr']['server_error']='Internal server error';
  154.     $GLOBALS['xmlrpcerr']['multicall_error']=18;
  155.     $GLOBALS['xmlrpcstr']['multicall_error']='Received from server invalid multicall response';
  156.  
  157.     $GLOBALS['xmlrpcerr']['multicall_notstruct'9;
  158.     $GLOBALS['xmlrpcstr']['multicall_notstruct''system.multicall expected struct';
  159.     $GLOBALS['xmlrpcerr']['multicall_nomethod']  10;
  160.     $GLOBALS['xmlrpcstr']['multicall_nomethod']  'missing methodName';
  161.     $GLOBALS['xmlrpcerr']['multicall_notstring'11;
  162.     $GLOBALS['xmlrpcstr']['multicall_notstring''methodName is not a string';
  163.     $GLOBALS['xmlrpcerr']['multicall_recursion'12;
  164.     $GLOBALS['xmlrpcstr']['multicall_recursion''recursive system.multicall forbidden';
  165.     $GLOBALS['xmlrpcerr']['multicall_noparams']  13;
  166.     $GLOBALS['xmlrpcstr']['multicall_noparams']  'missing params';
  167.     $GLOBALS['xmlrpcerr']['multicall_notarray']  14;
  168.     $GLOBALS['xmlrpcstr']['multicall_notarray']  'params is not an array';
  169.  
  170.     $GLOBALS['xmlrpcerr']['cannot_decompress']=103;
  171.     $GLOBALS['xmlrpcstr']['cannot_decompress']='Received from server compressed HTTP and cannot decompress';
  172.     $GLOBALS['xmlrpcerr']['decompress_fail']=104;
  173.     $GLOBALS['xmlrpcstr']['decompress_fail']='Received from server invalid compressed HTTP';
  174.     $GLOBALS['xmlrpcerr']['dechunk_fail']=105;
  175.     $GLOBALS['xmlrpcstr']['dechunk_fail']='Received from server invalid chunked HTTP';
  176.     $GLOBALS['xmlrpcerr']['server_cannot_decompress']=106;
  177.     $GLOBALS['xmlrpcstr']['server_cannot_decompress']='Received from client compressed HTTP request and cannot decompress';
  178.     $GLOBALS['xmlrpcerr']['server_decompress_fail']=107;
  179.     $GLOBALS['xmlrpcstr']['server_decompress_fail']='Received from client invalid compressed HTTP request';
  180.  
  181.     // The charset encoding used by the server for received messages and
  182.     // by the client for received responses when received charset cannot be determined
  183.     // or is not supported
  184.     $GLOBALS['xmlrpc_defencoding']='UTF-8';
  185.  
  186.     // The encoding used internally by PHP.
  187.     // String values received as xml will be converted to this, and php strings will be converted to xml
  188.     // as if having been coded with this
  189.     $GLOBALS['xmlrpc_internalencoding']='ISO-8859-1';
  190.  
  191.     $GLOBALS['xmlrpcName']='XML-RPC for PHP';
  192.     $GLOBALS['xmlrpcVersion']='2.2';
  193.  
  194.     // let user errors start at 800
  195.     $GLOBALS['xmlrpcerruser']=800;
  196.     // let XML parse errors start at 100
  197.     $GLOBALS['xmlrpcerrxml']=100;
  198.  
  199.     // formulate backslashes for escaping regexp
  200.     // Not in use anymore since 2.0. Shall we remove it?
  201.     /// @deprecated
  202.     $GLOBALS['xmlrpc_backslash']=chr(92).chr(92);
  203.  
  204.     // set to TRUE to enable correct decoding of <NIL/> values
  205.     $GLOBALS['xmlrpc_null_extension']=false;
  206.  
  207.     // used to store state during parsing
  208.     // quick explanation of components:
  209.     //   ac - used to accumulate values
  210.     //   isf - used to indicate a parsing fault (2) or xmlrpcresp fault (1)
  211.     //   isf_reason - used for storing xmlrpcresp fault string
  212.     //   lv - used to indicate "looking for a value": implements
  213.     //        the logic to allow values with no types to be strings
  214.     //   params - used to store parameters in method calls
  215.     //   method - used to store method name
  216.     //   stack - array with genealogy of xml elements names:
  217.     //           used to validate nesting of xmlrpc elements
  218.     $GLOBALS['_xh']=null;
  219.  
  220.     /**
  221.     * Convert a string to the correct XML representation in a target charset
  222.     * To help correct communication of non-ascii chars inside strings, regardless
  223.     * of the charset used when sending requests, parsing them, sending responses
  224.     * and parsing responses, an option is to convert all non-ascii chars present in the message
  225.     * into their equivalent 'charset entity'. Charset entities enumerated this way
  226.     * are independent of the charset encoding used to transmit them, and all XML
  227.     * parsers are bound to understand them.
  228.     * Note that in the std case we are not sending a charset encoding mime type
  229.     * along with http headers, so we are bound by RFC 3023 to emit strict us-ascii.
  230.     *
  231.     * @todo do a bit of basic benchmarking (strtr vs. str_replace)
  232.     * @todo    make usage of iconv() or recode_string() or mb_string() where available
  233.     */
  234.     function xmlrpc_encode_entitites($data$src_encoding=''$dest_encoding='')
  235.     {
  236.         if ($src_encoding == '')
  237.         {
  238.             // lame, but we know no better...
  239.             $src_encoding $GLOBALS['xmlrpc_internalencoding'];
  240.         }
  241.  
  242.         switch(strtoupper($src_encoding.'_'.$dest_encoding))
  243.         {
  244.             case 'ISO-8859-1_':
  245.             case 'ISO-8859-1_US-ASCII':
  246.                 $escaped_data str_replace(array('&''"'"'"'<''>')array('&amp;''&quot;''&apos;''&lt;''&gt;')$data);
  247.                 $escaped_data str_replace($GLOBALS['xml_iso88591_Entities']['in']$GLOBALS['xml_iso88591_Entities']['out']$escaped_data);
  248.                 break;
  249.             case 'ISO-8859-1_UTF-8':
  250.                 $escaped_data str_replace(array('&''"'"'"'<''>')array('&amp;''&quot;''&apos;''&lt;''&gt;')$data);
  251.                 $escaped_data utf8_encode($escaped_data);
  252.                 break;
  253.             case 'ISO-8859-1_ISO-8859-1':
  254.             case 'US-ASCII_US-ASCII':
  255.             case 'US-ASCII_UTF-8':
  256.             case 'US-ASCII_':
  257.             case 'US-ASCII_ISO-8859-1':
  258.             case 'UTF-8_UTF-8':
  259.                 $escaped_data str_replace(array('&''"'"'"'<''>')array('&amp;''&quot;''&apos;''&lt;''&gt;')$data);
  260.                 break;
  261.             case 'UTF-8_':
  262.             case 'UTF-8_US-ASCII':
  263.             case 'UTF-8_ISO-8859-1':
  264.     // NB: this will choke on invalid UTF-8, going most likely beyond EOF
  265.     $escaped_data '';
  266.     // be kind to users creating string xmlrpcvals out of different php types
  267.     $data = (string) $data;
  268.     $ns strlen ($data);
  269.     for ($nn 0$nn $ns$nn++)
  270.     {
  271.         $ch $data[$nn];
  272.         $ii ord($ch);
  273.         //1 7 0bbbbbbb (127)
  274.         if ($ii 128)
  275.         {
  276.             /// @todo shall we replace this with a (supposedly) faster str_replace?
  277.             switch($ii){
  278.                 case 34:
  279.                     $escaped_data .= '&quot;';
  280.                     break;
  281.                 case 38:
  282.                     $escaped_data .= '&amp;';
  283.                     break;
  284.                 case 39:
  285.                     $escaped_data .= '&apos;';
  286.                     break;
  287.                 case 60:
  288.                     $escaped_data .= '&lt;';
  289.                     break;
  290.                 case 62:
  291.                     $escaped_data .= '&gt;';
  292.                     break;
  293.                 default:
  294.                     $escaped_data .= $ch;
  295.             // switch
  296.         }
  297.         //2 11 110bbbbb 10bbbbbb (2047)
  298.         else if ($ii>>== 6)
  299.         {
  300.             $b1 ($ii 31);
  301.             $ii ord($data[$nn+1]);
  302.             $b2 ($ii 63);
  303.             $ii ($b1 64$b2;
  304.             $ent sprintf ('&#%d;'$ii);
  305.             $escaped_data .= $ent;
  306.             $nn += 1;
  307.         }
  308.         //3 16 1110bbbb 10bbbbbb 10bbbbbb
  309.         else if ($ii>>== 14)
  310.         {
  311.             $b1 ($ii 31);
  312.             $ii ord($data[$nn+1]);
  313.             $b2 ($ii 63);
  314.             $ii ord($data[$nn+2]);
  315.             $b3 ($ii 63);
  316.             $ii ((($b1 64$b264$b3;
  317.             $ent sprintf ('&#%d;'$ii);
  318.             $escaped_data .= $ent;
  319.             $nn += 2;
  320.         }
  321.         //4 21 11110bbb 10bbbbbb 10bbbbbb 10bbbbbb
  322.         else if ($ii>>== 30)
  323.         {
  324.             $b1 ($ii 31);
  325.             $ii ord($data[$nn+1]);
  326.             $b2 ($ii 63);
  327.             $ii ord($data[$nn+2]);
  328.             $b3 ($ii 63);
  329.             $ii ord($data[$nn+3]);
  330.             $b4 ($ii 63);
  331.             $ii ((((($b1 64$b264$b364$b4;
  332.             $ent sprintf ('&#%d;'$ii);
  333.             $escaped_data .= $ent;
  334.             $nn += 3;
  335.         }
  336.     }
  337.                 break;
  338.             default:
  339.                 $escaped_data '';
  340.                 error_log("Converting from $src_encoding to $dest_encoding: not supported...");
  341.         }
  342.         return $escaped_data;
  343.     }
  344.  
  345.     /// xml parser handler function for opening element tags
  346.     function xmlrpc_se($parser$name$attrs$accept_single_vals=false)
  347.     {
  348.         // if invalid xmlrpc already detected, skip all processing
  349.         if ($GLOBALS['_xh']['isf'2)
  350.         {
  351.             // check for correct element nesting
  352.             // top level element can only be of 2 types
  353.             /// @todo optimization creep: save this check into a bool variable, instead of using count() every time:
  354.             ///       there is only a single top level element in xml anyway
  355.             if (count($GLOBALS['_xh']['stack']== 0)
  356.             {
  357.                 if ($name != 'METHODRESPONSE' && $name != 'METHODCALL' && (
  358.                     $name != 'VALUE' && !$accept_single_vals))
  359.                 {
  360.                     $GLOBALS['_xh']['isf'2;
  361.                     $GLOBALS['_xh']['isf_reason''missing top level xmlrpc element';
  362.                     return;
  363.                 }
  364.                 else
  365.                 {
  366.                     $GLOBALS['_xh']['rt'strtolower($name);
  367.                 }
  368.             }
  369.             else
  370.             {
  371.                 // not top level element: see if parent is OK
  372.                 $parent end($GLOBALS['_xh']['stack']);
  373.                 if (!array_key_exists($name$GLOBALS['xmlrpc_valid_parents']|| !in_array($parent$GLOBALS['xmlrpc_valid_parents'][$name]))
  374.                 {
  375.                     $GLOBALS['_xh']['isf'2;
  376.                     $GLOBALS['_xh']['isf_reason'"xmlrpc element $name cannot be child of $parent";
  377.                     return;
  378.                 }
  379.             }
  380.  
  381.             switch($name)
  382.             {
  383.                 // optimize for speed switch cases: most common cases first
  384.                 case 'VALUE':
  385.                     /// @todo we could check for 2 VALUE elements inside a MEMBER or PARAM element
  386.                     $GLOBALS['_xh']['vt']='value'// indicator: no value found yet
  387.                     $GLOBALS['_xh']['ac']='';
  388.                     $GLOBALS['_xh']['lv']=1;
  389.                     $GLOBALS['_xh']['php_class']=null;
  390.                     break;
  391.                 case 'I4':
  392.                 case 'INT':
  393.                 case 'STRING':
  394.                 case 'BOOLEAN':
  395.                 case 'DOUBLE':
  396.                 case 'DATETIME.ISO8601':
  397.                 case 'BASE64':
  398.                     if ($GLOBALS['_xh']['vt']!='value')
  399.                     {
  400.                         //two data elements inside a value: an error occurred!
  401.                         $GLOBALS['_xh']['isf'2;
  402.                         $GLOBALS['_xh']['isf_reason'"$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
  403.                         return;
  404.                     }
  405.                     $GLOBALS['_xh']['ac']=''// reset the accumulator
  406.                     break;
  407.                 case 'STRUCT':
  408.                 case 'ARRAY':
  409.                     if ($GLOBALS['_xh']['vt']!='value')
  410.                     {
  411.                         //two data elements inside a value: an error occurred!
  412.                         $GLOBALS['_xh']['isf'2;
  413.                         $GLOBALS['_xh']['isf_reason'"$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
  414.                         return;
  415.                     }
  416.                     // create an empty array to hold child values, and push it onto appropriate stack
  417.                     $cur_val array();
  418.                     $cur_val['values'array();
  419.                     $cur_val['type'$name;
  420.                     // check for out-of-band information to rebuild php objs
  421.                     // and in case it is found, save it
  422.                     if (@isset($attrs['PHP_CLASS']))
  423.                     {
  424.                         $cur_val['php_class'$attrs['PHP_CLASS'];
  425.                     }
  426.                     $GLOBALS['_xh']['valuestack'][$cur_val;
  427.                     $GLOBALS['_xh']['vt']='data'// be prepared for a data element next
  428.                     break;
  429.                 case 'DATA':
  430.                     if ($GLOBALS['_xh']['vt']!='data')
  431.                     {
  432.                         //two data elements inside a value: an error occurred!
  433.                         $GLOBALS['_xh']['isf'2;
  434.                         $GLOBALS['_xh']['isf_reason'"found two data elements inside an array element";
  435.                         return;
  436.                     }
  437.                 case 'METHODCALL':
  438.                 case 'METHODRESPONSE':
  439.                 case 'PARAMS':
  440.                     // valid elements that add little to processing
  441.                     break;
  442.                 case 'METHODNAME':
  443.                 case 'NAME':
  444.                     /// @todo we could check for 2 NAME elements inside a MEMBER element
  445.                     $GLOBALS['_xh']['ac']='';
  446.                     break;
  447.                 case 'FAULT':
  448.                     $GLOBALS['_xh']['isf']=1;
  449.                     break;
  450.                 case 'MEMBER':
  451.                     $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name']=''// set member name to null, in case we do not find in the xml later on
  452.                     //$GLOBALS['_xh']['ac']='';
  453.                     // Drop trough intentionally
  454.                 case 'PARAM':
  455.                     // clear value type, so we can check later if no value has been passed for this param/member
  456.                     $GLOBALS['_xh']['vt']=null;
  457.                     break;
  458.                 case 'NIL':
  459.                     if ($GLOBALS['xmlrpc_null_extension'])
  460.                     {
  461.                         if ($GLOBALS['_xh']['vt']!='value')
  462.                         {
  463.                             //two data elements inside a value: an error occurred!
  464.                             $GLOBALS['_xh']['isf'2;
  465.                             $GLOBALS['_xh']['isf_reason'"$name element following a {$GLOBALS['_xh']['vt']} element inside a single value";
  466.                             return;
  467.                         }
  468.                         $GLOBALS['_xh']['ac']=''// reset the accumulator
  469.                         break;
  470.                     }
  471.                     // we do not support the <NIL/> extension, so
  472.                     // drop through intentionally
  473.                 default:
  474.                     /// INVALID ELEMENT: RAISE ISF so that it is later recognized!!!
  475.                     $GLOBALS['_xh']['isf'2;
  476.                     $GLOBALS['_xh']['isf_reason'"found not-xmlrpc xml element $name";
  477.                     break;
  478.             }
  479.  
  480.             // Save current element name to stack, to validate nesting
  481.             $GLOBALS['_xh']['stack'][$name;
  482.  
  483.             /// @todo optimization creep: move this inside the big switch() above
  484.             if($name!='VALUE')
  485.             {
  486.                 $GLOBALS['_xh']['lv']=0;
  487.             }
  488.         }
  489.     }
  490.  
  491.     /// Used in decoding xml chunks that might represent single xmlrpc values
  492.     function xmlrpc_se_any($parser$name$attrs)
  493.     {
  494.         xmlrpc_se($parser$name$attrstrue);
  495.     }
  496.  
  497.     /// xml parser handler function for close element tags
  498.     function xmlrpc_ee($parser$name$rebuild_xmlrpcvals true)
  499.     {
  500.         if ($GLOBALS['_xh']['isf'2)
  501.         {
  502.             // push this element name from stack
  503.             // NB: if XML validates, correct opening/closing is guaranteed and
  504.             // we do not have to check for $name == $curr_elem.
  505.             // we also checked for proper nesting at start of elements...
  506.             $curr_elem array_pop($GLOBALS['_xh']['stack']);
  507.  
  508.             switch($name)
  509.             {
  510.                 case 'VALUE':
  511.                     // This if() detects if no scalar was inside <VALUE></VALUE>
  512.                     if ($GLOBALS['_xh']['vt']=='value')
  513.                     {
  514.                         $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];
  515.                         $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcString'];
  516.                     }
  517.  
  518.                     if ($rebuild_xmlrpcvals)
  519.                     {
  520.                         // build the xmlrpc val out of the data received, and substitute it
  521.                         $temp =new xmlrpcval($GLOBALS['_xh']['value']$GLOBALS['_xh']['vt']);
  522.                         // in case we got info about underlying php class, save it
  523.                         // in the object we're rebuilding
  524.                         if (isset($GLOBALS['_xh']['php_class']))
  525.                             $temp->_php_class $GLOBALS['_xh']['php_class'];
  526.                         // check if we are inside an array or struct:
  527.                         // if value just built is inside an array, let's move it into array on the stack
  528.                         $vscount count($GLOBALS['_xh']['valuestack']);
  529.                         if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY')
  530.                         {
  531.                             $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][$temp;
  532.                         }
  533.                         else
  534.                         {
  535.                             $GLOBALS['_xh']['value'$temp;
  536.                         }
  537.                     }
  538.                     else
  539.                     {
  540.                         /// @todo this needs to treat correctly php-serialized objects,
  541.                         /// since std deserializing is done by php_xmlrpc_decode,
  542.                         /// which we will not be calling...
  543.                         if (isset($GLOBALS['_xh']['php_class']))
  544.                         {
  545.                         }
  546.  
  547.                         // check if we are inside an array or struct:
  548.                         // if value just built is inside an array, let's move it into array on the stack
  549.                         $vscount count($GLOBALS['_xh']['valuestack']);
  550.                         if ($vscount && $GLOBALS['_xh']['valuestack'][$vscount-1]['type']=='ARRAY')
  551.                         {
  552.                             $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][$GLOBALS['_xh']['value'];
  553.                         }
  554.                     }
  555.                     break;
  556.                 case 'BOOLEAN':
  557.                 case 'I4':
  558.                 case 'INT':
  559.                 case 'STRING':
  560.                 case 'DOUBLE':
  561.                 case 'DATETIME.ISO8601':
  562.                 case 'BASE64':
  563.                     $GLOBALS['_xh']['vt']=strtolower($name);
  564.                     /// @todo: optimization creep - remove the if/elseif cycle below
  565.                     /// since the case() in which we are already did that
  566.                     if ($name=='STRING')
  567.                     {
  568.                         $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];
  569.                     }
  570.                     elseif ($name=='DATETIME.ISO8601')
  571.                     {
  572.                         if (!preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/'$GLOBALS['_xh']['ac']))
  573.                         {
  574.                             error_log('XML-RPC: invalid value received in DATETIME: '.$GLOBALS['_xh']['ac']);
  575.                         }
  576.                         $GLOBALS['_xh']['vt']=$GLOBALS['xmlrpcDateTime'];
  577.                         $GLOBALS['_xh']['value']=$GLOBALS['_xh']['ac'];
  578.                     }
  579.                     elseif ($name=='BASE64')
  580.                     {
  581.                         /// @todo check for failure of base64 decoding / catch warnings
  582.                         $GLOBALS['_xh']['value']=base64_decode($GLOBALS['_xh']['ac']);
  583.                     }
  584.                     elseif ($name=='BOOLEAN')
  585.                     {
  586.                         // special case here: we translate boolean 1 or 0 into PHP
  587.                         // constants true or false.
  588.                         // Strings 'true' and 'false' are accepted, even though the
  589.                         // spec never mentions them (see eg. Blogger api docs)
  590.                         // NB: this simple checks helps a lot sanitizing input, ie no
  591.                         // security problems around here
  592.                         if ($GLOBALS['_xh']['ac']=='1' || strcasecmp($GLOBALS['_xh']['ac']'true'== 0)
  593.                         {
  594.                             $GLOBALS['_xh']['value']=true;
  595.                         }
  596.                         else
  597.                         {
  598.                             // log if receiveing something strange, even though we set the value to false anyway
  599.                             if ($GLOBALS['_xh']['ac']!='0' && strcasecmp($_xh[$parser]['ac']'false'!= 0)
  600.                                 error_log('XML-RPC: invalid value received in BOOLEAN: '.$GLOBALS['_xh']['ac']);
  601.                             $GLOBALS['_xh']['value']=false;
  602.                         }
  603.                     }
  604.                     elseif ($name=='DOUBLE')
  605.                     {
  606.                         // we have a DOUBLE
  607.                         // we must check that only 0123456789-.<space> are characters here
  608.                         if (!preg_match('/^[+-]?[eE0123456789 \t.]+$/'$GLOBALS['_xh']['ac']))
  609.                         {
  610.                             /// @todo: find a better way of throwing an error
  611.                             // than this!
  612.                             error_log('XML-RPC: non numeric value received in DOUBLE: '.$GLOBALS['_xh']['ac']);
  613.                             $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND';
  614.                         }
  615.                         else
  616.                         {
  617.                             // it's ok, add it on
  618.                             $GLOBALS['_xh']['value']=(double)$GLOBALS['_xh']['ac'];
  619.                         }
  620.                     }
  621.                     else
  622.                     {
  623.                         // we have an I4/INT
  624.                         // we must check that only 0123456789-<space> are characters here
  625.                         if (!preg_match('/^[+-]?[0123456789 \t]+$/'$GLOBALS['_xh']['ac']))
  626.                         {
  627.                             /// @todo find a better way of throwing an error
  628.                             // than this!
  629.                             error_log('XML-RPC: non numeric value received in INT: '.$GLOBALS['_xh']['ac']);
  630.                             $GLOBALS['_xh']['value']='ERROR_NON_NUMERIC_FOUND';
  631.                         }
  632.                         else
  633.                         {
  634.                             // it's ok, add it on
  635.                             $GLOBALS['_xh']['value']=(int)$GLOBALS['_xh']['ac'];
  636.                         }
  637.                     }
  638.                     //$GLOBALS['_xh']['ac']=''; // is this necessary?
  639.                     $GLOBALS['_xh']['lv']=3// indicate we've found a value
  640.                     break;
  641.                 case 'NAME':
  642.                     $GLOBALS['_xh']['valuestack'][count($GLOBALS['_xh']['valuestack'])-1]['name'$GLOBALS['_xh']['ac'];
  643.                     break;
  644.                 case 'MEMBER':
  645.                     //$GLOBALS['_xh']['ac']=''; // is this necessary?
  646.                     // add to array in the stack the last element built,
  647.                     // unless no VALUE was found
  648.                     if ($GLOBALS['_xh']['vt'])
  649.                     {
  650.                         $vscount count($GLOBALS['_xh']['valuestack']);
  651.                         $GLOBALS['_xh']['valuestack'][$vscount-1]['values'][$GLOBALS['_xh']['valuestack'][$vscount-1]['name']] $GLOBALS['_xh']['value'];
  652.                     else
  653.                         error_log('XML-RPC: missing VALUE inside STRUCT in received xml');
  654.                     break;
  655.                 case 'DATA':
  656.                     //$GLOBALS['_xh']['ac']=''; // is this necessary?
  657.                     $GLOBALS['_xh']['vt']=null// reset this to check for 2 data elements in a row - even if they're empty
  658.                     break;
  659.                 case 'STRUCT':
  660.                 case 'ARRAY':
  661.                     // fetch out of stack array of values, and promote it to current value
  662.                     $curr_val array_pop($GLOBALS['_xh']['valuestack']);
  663.                     $GLOBALS['_xh']['value'$curr_val['values'];
  664.                     $GLOBALS['_xh']['vt']=strtolower($name);
  665.                     if (isset($curr_val['php_class']))
  666.                     {
  667.                         $GLOBALS['_xh']['php_class'$curr_val['php_class'];
  668.                     }
  669.                     break;
  670.                 case 'PARAM':
  671.                     // add to array of params the current value,
  672.                     // unless no VALUE was found
  673.                     if ($GLOBALS['_xh']['vt'])
  674.                     {
  675.                         $GLOBALS['_xh']['params'][]=$GLOBALS['_xh']['value'];
  676.                         $GLOBALS['_xh']['pt'][]=$GLOBALS['_xh']['vt'];
  677.                     }
  678.                     else
  679.                         error_log('XML-RPC: missing VALUE inside PARAM in received xml');
  680.                     break;
  681.                 case 'METHODNAME':
  682.                     $GLOBALS['_xh']['method']=preg_replace('/^[\n\r\t ]+/'''$GLOBALS['_xh']['ac']);
  683.                     break;
  684.                 case 'NIL':
  685.                     if ($GLOBALS['xmlrpc_null_extension'])
  686.                     {
  687.                         $GLOBALS['_xh']['vt']='null';
  688.                         $GLOBALS['_xh']['value']=null;
  689.                         $GLOBALS['_xh']['lv']=3;
  690.                         break;
  691.                     }
  692.                     // drop through intentionally if nil extension not enabled
  693.                 case 'PARAMS':
  694.                 case 'FAULT':
  695.                 case 'METHODCALL':
  696.                 case 'METHORESPONSE':
  697.                     break;
  698.                 default:
  699.                     // End of INVALID ELEMENT!
  700.                     // shall we add an assert here for unreachable code???
  701.                     break;
  702.             }
  703.         }
  704.     }
  705.  
  706.     /// Used in decoding xmlrpc requests/responses without rebuilding xmlrpc values
  707.     function xmlrpc_ee_fast($parser$name)
  708.     {
  709.         xmlrpc_ee($parser$namefalse);
  710.     }
  711.  
  712.     /// xml parser handler function for character data
  713.     function xmlrpc_cd($parser$data)
  714.     {
  715.         // skip processing if xml fault already detected
  716.         if ($GLOBALS['_xh']['isf'2)
  717.         {
  718.             // "lookforvalue==3" means that we've found an entire value
  719.             // and should discard any further character data
  720.             if($GLOBALS['_xh']['lv']!=3)
  721.             {
  722.                 // G. Giunta 2006-08-23: useless change of 'lv' from 1 to 2
  723.                 //if($GLOBALS['_xh']['lv']==1)
  724.                 //{
  725.                     // if we've found text and we're just in a <value> then
  726.                     // say we've found a value
  727.                     //$GLOBALS['_xh']['lv']=2;
  728.                 //}
  729.                 // we always initialize the accumulator before starting parsing, anyway...
  730.                 //if(!@isset($GLOBALS['_xh']['ac']))
  731.                 //{
  732.                 //    $GLOBALS['_xh']['ac'] = '';
  733.                 //}
  734.                 $GLOBALS['_xh']['ac'].=$data;
  735.             }
  736.         }
  737.     }
  738.  
  739.     /// xml parser handler function for 'other stuff', ie. not char data or
  740.     /// element start/end tag. In fact it only gets called on unknown entities...
  741.     function xmlrpc_dh($parser$data)
  742.     {
  743.         // skip processing if xml fault already detected
  744.         if ($GLOBALS['_xh']['isf'2)
  745.         {
  746.             if(substr($data01== '&' && substr($data-11== ';')
  747.             {
  748.                 // G. Giunta 2006-08-25: useless change of 'lv' from 1 to 2
  749.                 //if($GLOBALS['_xh']['lv']==1)
  750.                 //{
  751.                 //    $GLOBALS['_xh']['lv']=2;
  752.                 //}
  753.                 $GLOBALS['_xh']['ac'].=$data;
  754.             }
  755.         }
  756.         return true;
  757.     }
  758.  
  759.     class xmlrpc_client
  760.     {
  761.         var $path;
  762.         var $server;
  763.         var $port=0;
  764.         var $method='http';
  765.         var $errno;
  766.         var $errstr;
  767.         var $debug=0;
  768.         var $username='';
  769.         var $password='';
  770.         var $authtype=1;
  771.         var $cert='';
  772.         var $certpass='';
  773.         var $cacert='';
  774.         var $cacertdir='';
  775.         var $key='';
  776.         var $keypass='';
  777.         var $verifypeer=true;
  778.         var $verifyhost=1;
  779.         var $no_multicall=false;
  780.         var $proxy='';
  781.         var $proxyport=0;
  782.         var $proxy_user='';
  783.         var $proxy_pass='';
  784.         var $proxy_authtype=1;
  785.         var $cookies=array();
  786.         /**
  787.         * List of http compression methods accepted by the client for responses.
  788.         * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib
  789.         *
  790.         * NNB: you can set it to any non-empty array for HTTP11 and HTTPS, since
  791.         * in those cases it will be up to CURL to decide the compression methods
  792.         * it supports. You might check for the presence of 'zlib' in the output of
  793.         * curl_version() to determine wheter compression is supported or not
  794.         */
  795.         var $accepted_compression = array();
  796.         /**
  797.         * Name of compression scheme to be used for sending requests.
  798.         * Either null, gzip or deflate
  799.         */
  800.         var $request_compression = '';
  801.         /**
  802.         * CURL handle: used for keep-alive connections (PHP 4.3.8 up, see:
  803.         * http://curl.haxx.se/docs/faq.html#7.3)
  804.         */
  805.         var $xmlrpc_curl_handle = null;
  806.         /// Wheter to use persistent connections for http 1.1 and https
  807.         var $keepalive = false;
  808.         /// Charset encodings that can be decoded without problems by the client
  809.         var $accepted_charset_encodings = array();
  810.         /// Charset encoding to be used in serializing request. NULL = use ASCII
  811.         var $request_charset_encoding = '';
  812.         /**
  813.         * Decides the content of xmlrpcresp objects returned by calls to send()
  814.         * valid strings are 'xmlrpcvals', 'phpvals' or 'xml'
  815.         */
  816.         var $return_type = 'xmlrpcvals';
  817.  
  818.         /**
  819.         * @param string $path either the complete server URL or the PATH part of the xmlrc server URL, e.g. /xmlrpc/server.php
  820.         * @param string $server the server name / ip address
  821.         * @param integer $port the port the server is listening on, defaults to 80 or 443 depending on protocol used
  822.         * @param string $method the http protocol variant: defaults to 'http', 'https' and 'http11' can be used if CURL is installed
  823.         */
  824.         function xmlrpc_client($path$server=''$port=''$method='')
  825.         {
  826.             // allow user to specify all params in $path
  827.             if($server == '' and $port == '' and $method == '')
  828.             {
  829.                 $parts parse_url($path);
  830.                 $server $parts['host'];
  831.                 $path $parts['path'];
  832.                 if(isset($parts['query']))
  833.                 {
  834.                     $path .= '?'.$parts['query'];
  835.                 }
  836.                 if(isset($parts['fragment']))
  837.                 {
  838.                     $path .= '#'.$parts['fragment'];
  839.                 }
  840.                 if(isset($parts['port']))
  841.                 {
  842.                     $port $parts['port'];
  843.                 }
  844.                 if(isset($parts['scheme']))
  845.                 {
  846.                     $method $parts['scheme'];
  847.                 }
  848.                 if(isset($parts['user']))
  849.                 {
  850.                     $this->username = $parts['user'];
  851.                 }
  852.                 if(isset($parts['pass']))
  853.                 {
  854.                     $this->password = $parts['pass'];
  855.                 }
  856.             }
  857.             if($path == '' || $path[0!= '/')
  858.             {
  859.                 $this->path='/'.$path;
  860.             }
  861.             else
  862.             {
  863.                 $this->path=$path;
  864.             }
  865.             $this->server=$server;
  866.             if($port != '')
  867.             {
  868.                 $this->port=$port;
  869.             }
  870.             if($method != '')
  871.             {
  872.                 $this->method=$method;
  873.             }
  874.  
  875.             // if ZLIB is enabled, let the client by default accept compressed responses
  876.             if(function_exists('gzinflate'|| (
  877.                 function_exists('curl_init'&& (($info curl_version()) &&
  878.                 ((is_string($info&& strpos($info'zlib'!== null|| isset($info['libz_version'])))
  879.             ))
  880.             {
  881.                 $this->accepted_compression = array('gzip''deflate');
  882.             }
  883.  
  884.             // keepalives: enabled by default ONLY for PHP >= 4.3.8
  885.             // (see http://curl.haxx.se/docs/faq.html#7.3)
  886.             if(version_compare(phpversion()'4.3.8'>= 0)
  887.             {
  888.                 $this->keepalive = true;
  889.             }
  890.  
  891.             // by default the xml parser can support these 3 charset encodings
  892.             $this->accepted_charset_encodings = array('UTF-8''ISO-8859-1''US-ASCII');
  893.         }
  894.  
  895.         /**
  896.         * Enables/disables the echoing to screen of the xmlrpc responses received
  897.         * @param integer $debug values 0, 1 and 2 are supported (2 = echo sent msg too, before received response)
  898.         * @access public
  899.         */
  900.         function setDebug($in)
  901.         {
  902.             $this->debug=$in;
  903.         }
  904.  
  905.         /**
  906.         * Add some http BASIC AUTH credentials, used by the client to authenticate
  907.         * @param string $u username
  908.         * @param string $p password
  909.         * @param integer $t auth type. See curl_setopt man page for supported auth types. Defaults to CURLAUTH_BASIC (basic auth)
  910.         * @access public
  911.         */
  912.         function setCredentials($u$p$t=1)
  913.         {
  914.             $this->username=$u;
  915.             $this->password=$p;
  916.             $this->authtype=$t;
  917.         }
  918.  
  919.         /**
  920.         * Add a client-side https certificate
  921.         * @param string $cert 
  922.         * @param string $certpass 
  923.         * @access public
  924.         */
  925.         function setCertificate($cert$certpass)
  926.         {
  927.             $this->cert = $cert;
  928.             $this->certpass = $certpass;
  929.         }
  930.  
  931.         /**
  932.         * Add a CA certificate to verify server with (see man page about
  933.         * CURLOPT_CAINFO for more details
  934.         * @param string $cacert certificate file name (or dir holding certificates)
  935.         * @param bool $is_dir set to true to indicate cacert is a dir. defaults to false
  936.         * @access public
  937.         */
  938.         function setCaCertificate($cacert$is_dir=false)
  939.         {
  940.             if ($is_dir)
  941.             {
  942.                 $this->cacert = $cacert;
  943.             }
  944.             else
  945.             {
  946.                 $this->cacertdir = $cacert;
  947.             }
  948.         }
  949.  
  950.         /**
  951.         * Set attributes for SSL communication: private SSL key
  952.         * @param string $key The name of a file containing a private SSL key
  953.         * @param string $keypass The secret password needed to use the private SSL key
  954.         * @access public
  955.         *  NB: does not work in older php/curl installs
  956.         *  Thanks to Daniel Convissor
  957.         */
  958.         function setKey($key$keypass)
  959.         {
  960.             $this->key = $key;
  961.             $this->keypass = $keypass;
  962.         }
  963.  
  964.         /**
  965.         * Set attributes for SSL communication: verify server certificate
  966.         * @param bool $i enable/disable verification of peer certificate
  967.         * @access public
  968.         */
  969.         function setSSLVerifyPeer($i)
  970.         {
  971.             $this->verifypeer = $i;
  972.         }
  973.  
  974.         /**
  975.         * Set attributes for SSL communication: verify match of server cert w. hostname
  976.         * @param int $i 
  977.         * @access public
  978.         */
  979.         function setSSLVerifyHost($i)
  980.         {
  981.             $this->verifyhost = $i;
  982.         }
  983.  
  984.         /**
  985.         * Set proxy info
  986.         * @param string $proxyhost 
  987.         * @param string $proxyport Defaults to 8080 for HTTP and 443 for HTTPS
  988.         * @param string $proxyusername Leave blank if proxy has public access
  989.         * @param string $proxypassword Leave blank if proxy has public access
  990.         * @param int $proxyauthtype set to constant CURLAUTH_NTLM to use NTLM auth with proxy
  991.         * @access public
  992.         */
  993.         function setProxy($proxyhost$proxyport$proxyusername ''$proxypassword ''$proxyauthtype 1)
  994.         {
  995.             $this->proxy = $proxyhost;
  996.             $this->proxyport = $proxyport;
  997.             $this->proxy_user = $proxyusername;
  998.             $this->proxy_pass = $proxypassword;
  999.             $this->proxy_authtype = $proxyauthtype;
  1000.         }
  1001.  
  1002.         /**
  1003.         * Enables/disables reception of compressed xmlrpc responses.
  1004.         * Note that enabling reception of compressed responses merely adds some standard
  1005.         * http headers to xmlrpc requests. It is up to the xmlrpc server to return
  1006.         * compressed responses when receiving such requests.
  1007.         * @param string $compmethod either 'gzip', 'deflate', 'any' or ''
  1008.         * @access public
  1009.         */
  1010.         function setAcceptedCompression($compmethod)
  1011.         {
  1012.             if ($compmethod == 'any')
  1013.                 $this->accepted_compression = array('gzip''deflate');
  1014.             else
  1015.                 $this->accepted_compression = array($compmethod);
  1016.         }
  1017.  
  1018.         /**
  1019.         * Enables/disables http compression of xmlrpc request.
  1020.         * Take care when sending compressed requests: servers might not support them
  1021.         * (and automatic fallback to uncompressed requests is not yet implemented)
  1022.         * @param string $compmethod either 'gzip', 'deflate' or ''
  1023.         * @access public
  1024.         */
  1025.         function setRequestCompression($compmethod)
  1026.         {
  1027.             $this->request_compression = $compmethod;
  1028.         }
  1029.  
  1030.         /**
  1031.         * Adds a cookie to list of cookies that will be sent to server.
  1032.         * NB: setting any param but name and value will turn the cookie into a 'version 1' cookie:
  1033.         * do not do it unless you know what you are doing
  1034.         * @param string $name 
  1035.         * @param string $value 
  1036.         * @param string $path 
  1037.         * @param string $domain 
  1038.         * @param int $port 
  1039.         * @access public
  1040.         *
  1041.         * @todo check correctness of urlencoding cookie value (copied from php way of doing it...)
  1042.         */
  1043.         function setCookie($name$value=''$path=''$domain=''$port=null)
  1044.         {
  1045.             $this->cookies[$name]['value'urlencode($value);
  1046.             if ($path || $domain || $port)
  1047.             {
  1048.                 $this->cookies[$name]['path'$path;
  1049.                 $this->cookies[$name]['domain'$domain;
  1050.                 $this->cookies[$name]['port'$port;
  1051.                 $this->cookies[$name]['version'1;
  1052.             }
  1053.             else
  1054.             {
  1055.                 $this->cookies[$name]['version'0;
  1056.             }
  1057.         }
  1058.  
  1059.         /**
  1060.         * Send an xmlrpc request
  1061.         * @param mixed $msg The message object, or an array of messages for using multicall, or the complete xml representation of a request
  1062.         * @param integer $timeout Connection timeout, in seconds, If unspecified, a platform specific timeout will apply
  1063.         * @param string $method if left unspecified, the http protocol chosen during creation of the object will be used
  1064.         * @return xmlrpcresp 
  1065.         * @access public
  1066.         */
  1067.         functionsend($msg$timeout=0$method='')
  1068.         {
  1069.             // if user deos not specify http protocol, use native method of this client
  1070.             // (i.e. method set during call to constructor)
  1071.             if($method == '')
  1072.             {
  1073.                 $method $this->method;
  1074.             }
  1075.  
  1076.             if(is_array($msg))
  1077.             {
  1078.                 // $msg is an array of xmlrpcmsg's
  1079.                 $r $this->multicall($msg$timeout$method);
  1080.                 return $r;
  1081.             }
  1082.             elseif(is_string($msg))
  1083.             {
  1084.                 $n =new xmlrpcmsg('');
  1085.                 $n->payload $msg;
  1086.                 $msg $n;
  1087.             }
  1088.  
  1089.             // where msg is an xmlrpcmsg
  1090.             $msg->debug=$this->debug;
  1091.  
  1092.             if($method == 'https')
  1093.             {
  1094.                 $r =$this->sendPayloadHTTPS(
  1095.                     $msg,
  1096.                     $this->server,
  1097.                     $this->port,
  1098.                     $timeout,
  1099.                     $this->username,
  1100.                     $this->password,
  1101.                     $this->authtype,
  1102.                     $this->cert,
  1103.                     $this->certpass,
  1104.                     $this->cacert,
  1105.                     $this->cacertdir,
  1106.                     $this->proxy,
  1107.                     $this->proxyport,
  1108.                     $this->proxy_user,
  1109.                     $this->proxy_pass,
  1110.                     $this->proxy_authtype,
  1111.                     $this->keepalive,
  1112.                     $this->key,
  1113.                     $this->keypass
  1114.                 );
  1115.             }
  1116.             elseif($method == 'http11')
  1117.             {
  1118.                 $r =$this->sendPayloadCURL(
  1119.                     $msg,
  1120.                     $this->server,
  1121.                     $this->port,
  1122.                     $timeout,
  1123.                     $this->username,
  1124.                     $this->password,
  1125.                     $this->authtype,
  1126.                     null,
  1127.                     null,
  1128.                     null,
  1129.                     null,
  1130.                     $this->proxy,
  1131.                     $this->proxyport,
  1132.                     $this->proxy_user,
  1133.                     $this->proxy_pass,
  1134.                     $this->proxy_authtype,
  1135.                     'http',
  1136.                     $this->keepalive
  1137.                 );
  1138.             }
  1139.             else
  1140.             {
  1141.                 $r =$this->sendPayloadHTTP10(
  1142.                     $msg,
  1143.                     $this->server,
  1144.                     $this->port,
  1145.                     $timeout,
  1146.                     $this->username,
  1147.                     $this->password,
  1148.                     $this->authtype,
  1149.                     $this->proxy,
  1150.                     $this->proxyport,
  1151.                     $this->proxy_user,
  1152.                     $this->proxy_pass,
  1153.                     $this->proxy_authtype
  1154.                 );
  1155.             }
  1156.  
  1157.             return $r;
  1158.         }
  1159.  
  1160.         /**
  1161.         * @access private
  1162.         */
  1163.         function &sendPayloadHTTP10($msg$server$port$timeout=0,
  1164.             $username=''$password=''$authtype=1$proxyhost='',
  1165.             $proxyport=0$proxyusername=''$proxypassword=''$proxyauthtype=1)
  1166.         {
  1167.             if($port==0)
  1168.             {
  1169.                 $port=80;
  1170.             }
  1171.  
  1172.             // Only create the payload if it was not created previously
  1173.             if(empty($msg->payload))
  1174.             {
  1175.                 $msg->createPayload($this->request_charset_encoding);
  1176.             }
  1177.  
  1178.             $payload $msg->payload;
  1179.             // Deflate request body and set appropriate request headers
  1180.             if(function_exists('gzdeflate'&& ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))
  1181.             {
  1182.                 if($this->request_compression == 'gzip')
  1183.                 {
  1184.                     $a @gzencode($payload);
  1185.                     if($a)
  1186.                     {
  1187.                         $payload $a;
  1188.                         $encoding_hdr "Content-Encoding: gzip\r\n";
  1189.                     }
  1190.                 }
  1191.                 else
  1192.                 {
  1193.                     $a @gzcompress($payload);
  1194.                     if($a)
  1195.                     {
  1196.                         $payload $a;
  1197.                         $encoding_hdr "Content-Encoding: deflate\r\n";
  1198.                     }
  1199.                 }
  1200.             }
  1201.             else
  1202.             {
  1203.                 $encoding_hdr '';
  1204.             }
  1205.  
  1206.             // thanks to Grant Rauscher <grant7@firstworld.net> for this
  1207.             $credentials='';
  1208.             if($username!='')
  1209.             {
  1210.                 $credentials='Authorization: Basic ' base64_encode($username ':' $password"\r\n";
  1211.                 if ($authtype != 1)
  1212.                 {
  1213.                     error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth is supported with HTTP 1.0');
  1214.                 }
  1215.             }
  1216.  
  1217.             $accepted_encoding '';
  1218.             if(is_array($this->accepted_compression&& count($this->accepted_compression))
  1219.             {
  1220.                 $accepted_encoding 'Accept-Encoding: ' implode(', '$this->accepted_compression"\r\n";
  1221.             }
  1222.  
  1223.             $proxy_credentials '';
  1224.             if($proxyhost)
  1225.             {
  1226.                 if($proxyport == 0)
  1227.                 {
  1228.                     $proxyport 8080;
  1229.                 }
  1230.                 $connectserver $proxyhost;
  1231.                 $connectport $proxyport;
  1232.                 $uri 'http://'.$server.':'.$port.$this->path;
  1233.                 if($proxyusername != '')
  1234.                 {
  1235.                     if ($proxyauthtype != 1)
  1236.                     {
  1237.                         error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth to proxy is supported with HTTP 1.0');
  1238.                     }
  1239.                     $proxy_credentials 'Proxy-Authorization: Basic ' base64_encode($proxyusername.':'.$proxypassword"\r\n";
  1240.                 }
  1241.             }
  1242.             else
  1243.             {
  1244.                 $connectserver $server;
  1245.                 $connectport $port;
  1246.                 $uri $this->path;
  1247.             }
  1248.  
  1249.             // Cookie generation, as per rfc2965 (version 1 cookies) or
  1250.             // netscape's rules (version 0 cookies)
  1251.             $cookieheader='';
  1252.             foreach ($this->cookies as $name => $cookie)
  1253.             {
  1254.                 if ($cookie['version'])
  1255.                 {
  1256.                     $cookieheader .= 'Cookie: $Version="' $cookie['version''"; ';
  1257.                     $cookieheader .= $name '="' $cookie['value''";';
  1258.                     if ($cookie['path'])
  1259.                         $cookieheader .= ' $Path="' $cookie['path''";';
  1260.                     if ($cookie['domain'])
  1261.                         $cookieheader .= ' $Domain="' $cookie['domain''";';
  1262.                     if ($cookie['port'])
  1263.                         $cookieheader .= ' $Port="' $cookie['domain''";';
  1264.                     $cookieheader substr($cookieheader0-1"\r\n";
  1265.                 }
  1266.                 else
  1267.                 {
  1268.                     $cookieheader .= 'Cookie: ' $name '=' $cookie['value'"\r\n";
  1269.                 }
  1270.             }
  1271.  
  1272.             $op'POST ' $uri" HTTP/1.0\r\n" .
  1273.                 'User-Agent: ' $GLOBALS['xmlrpcName'' ' $GLOBALS['xmlrpcVersion'"\r\n" .
  1274.                 'Host: '$server ':' $port "\r\n" .
  1275.                 $credentials .
  1276.                 $proxy_credentials .
  1277.                 $accepted_encoding .
  1278.                 $encoding_hdr .
  1279.                 'Accept-Charset: ' implode(','$this->accepted_charset_encodings"\r\n" .
  1280.                 $cookieheader .
  1281.                 'Content-Type: ' $msg->content_type "\r\nContent-Length: " .
  1282.                 strlen($payload"\r\n\r\n" .
  1283.                 $payload;
  1284.  
  1285.             if($this->debug > 1)
  1286.             {
  1287.                 print "<PRE>\n---SENDING---\n" htmlentities($op"\n---END---\n</PRE>";
  1288.                 // let the client see this now in case http times out...
  1289.                 flush();
  1290.             }
  1291.  
  1292.             if($timeout>0)
  1293.             {
  1294.                 $fp=@fsockopen($connectserver$connectport$this->errno$this->errstr$timeout);
  1295.             }
  1296.             else
  1297.             {
  1298.                 $fp=@fsockopen($connectserver$connectport$this->errno$this->errstr);
  1299.             }
  1300.             if($fp)
  1301.             {
  1302.                 if($timeout>&& function_exists('stream_set_timeout'))
  1303.                 {
  1304.                     stream_set_timeout($fp$timeout);
  1305.                 }
  1306.             }
  1307.             else
  1308.             {
  1309.                 $this->errstr='Connect error: '.$this->errstr;
  1310.                 $r=&new xmlrpcresp(0$GLOBALS['xmlrpcerr']['http_error']$this->errstr . ' (' $this->errno . ')');
  1311.                 return $r;
  1312.             }
  1313.  
  1314.             if(!fputs($fp$opstrlen($op)))
  1315.             {
  1316.                 $this->errstr='Write error';
  1317.                 $r=&new xmlrpcresp(0$GLOBALS['xmlrpcerr']['http_error']$this->errstr);
  1318.                 return $r;
  1319.             }
  1320.             else
  1321.             {
  1322.                 // reset errno and errstr on succesful socket connection
  1323.                 $this->errstr = '';
  1324.             }
  1325.             // G. Giunta 2005/10/24: close socket before parsing.
  1326.             // should yeld slightly better execution times, and make easier recursive calls (e.g. to follow http redirects)
  1327.             $ipd='';
  1328.             while($data=fread($fp32768))
  1329.             {
  1330.                 // shall we check for $data === FALSE?
  1331.                 // as per the manual, it signals an error
  1332.                 $ipd.=$data;
  1333.             }
  1334.             fclose($fp);
  1335.             $r =$msg->parseResponse($ipdfalse$this->return_type);
  1336.             return $r;
  1337.  
  1338.         }
  1339.  
  1340.         /**
  1341.         * @access private
  1342.         */
  1343.         function &sendPayloadHTTPS($msg$server$port$timeout=0$username='',
  1344.             $password=''$authtype=1$cert='',$certpass=''$cacert=''$cacertdir='',
  1345.             $proxyhost=''$proxyport=0$proxyusername=''$proxypassword=''$proxyauthtype=1,
  1346.             $keepalive=false$key=''$keypass='')
  1347.         {
  1348.             $r =$this->sendPayloadCURL($msg$server$port$timeout$username,
  1349.                 $password$authtype$cert$certpass$cacert$cacertdir$proxyhost$proxyport,
  1350.                 $proxyusername$proxypassword$proxyauthtype'https'$keepalive$key$keypass);
  1351.             return $r;
  1352.         }
  1353.  
  1354.         /**
  1355.         * Contributed by Justin Miller <justin@voxel.net>
  1356.         * Requires curl to be built into PHP
  1357.         * NB: CURL versions before 7.11.10 cannot use proxy to talk to https servers!
  1358.         * @access private
  1359.         */
  1360.         function &sendPayloadCURL($msg$server$port$timeout=0$username='',
  1361.             $password=''$authtype=1$cert=''$certpass=''$cacert=''$cacertdir='',
  1362.             $proxyhost=''$proxyport=0$proxyusername=''$proxypassword=''$proxyauthtype=1$method='https',
  1363.             $keepalive=false$key=''$keypass='')
  1364.         {
  1365.             if(!function_exists('curl_init'))
  1366.             {
  1367.                 $this->errstr='CURL unavailable on this install';
  1368.                 $r=&new xmlrpcresp(0$GLOBALS['xmlrpcerr']['no_curl']$GLOBALS['xmlrpcstr']['no_curl']);
  1369.                 return $r;
  1370.             }
  1371.             if($method == 'https')
  1372.             {
  1373.                 if(($info curl_version()) &&
  1374.                     ((is_string($info&& strpos($info'OpenSSL'=== null|| (is_array($info&& !isset($info['ssl_version']))))
  1375.                 {
  1376.                     $this->errstr='SSL unavailable on this install';
  1377.                     $r=&new xmlrpcresp(0$GLOBALS['xmlrpcerr']['no_ssl']$GLOBALS['xmlrpcstr']['no_ssl']);
  1378.                     return $r;
  1379.                 }
  1380.             }
  1381.  
  1382.             if($port == 0)
  1383.             {
  1384.                 if($method == 'http')
  1385.                 {
  1386.                     $port 80;
  1387.                 }
  1388.                 else
  1389.                 {
  1390.                     $port 443;
  1391.                 }
  1392.             }
  1393.  
  1394.             // Only create the payload if it was not created previously
  1395.             if(empty($msg->payload))
  1396.             {
  1397.                 $msg->createPayload($this->request_charset_encoding);
  1398.             }
  1399.  
  1400.             // Deflate request body and set appropriate request headers
  1401.             $payload $msg->payload;
  1402.             if(function_exists('gzdeflate'&& ($this->request_compression == 'gzip' || $this->request_compression == 'deflate'))
  1403.             {
  1404.                 if($this->request_compression == 'gzip')
  1405.                 {
  1406.                     $a @gzencode($payload);
  1407.                     if($a)
  1408.                     {
  1409.                         $payload $a;
  1410.                         $encoding_hdr 'Content-Encoding: gzip';
  1411.                     }
  1412.                 }
  1413.                 else
  1414.                 {
  1415.                     $a @gzcompress($payload);
  1416.                     if($a)
  1417.                     {
  1418.                         $payload $a;
  1419.                         $encoding_hdr 'Content-Encoding: deflate';
  1420.                     }
  1421.                 }
  1422.             }
  1423.             else
  1424.             {
  1425.                 $encoding_hdr '';
  1426.             }
  1427.  
  1428.             if($this->debug > 1)
  1429.             {
  1430.                 print "<PRE>\n---SENDING---\n" htmlentities($payload"\n---END---\n</PRE>";
  1431.                 // let the client see this now in case http times out...
  1432.                 flush();
  1433.             }
  1434.  
  1435.             if(!$keepalive || !$this->xmlrpc_curl_handle)
  1436.             {
  1437.                 $curl curl_init($method '://' $server ':' $port $this->path);
  1438.                 if($keepalive)
  1439.                 {
  1440.                     $this->xmlrpc_curl_handle = $curl;
  1441.                 }
  1442.             }
  1443.             else
  1444.             {
  1445.                 $curl $this->xmlrpc_curl_handle;
  1446.             }
  1447.  
  1448.             // results into variable
  1449.             curl_setopt($curlCURLOPT_RETURNTRANSFER1);
  1450.  
  1451.             if($this->debug)
  1452.             {
  1453.                 curl_setopt($curlCURLOPT_VERBOSE1);
  1454.             }
  1455.             curl_setopt($curlCURLOPT_USERAGENT$GLOBALS['xmlrpcName'].' '.$GLOBALS['xmlrpcVersion']);
  1456.             // required for XMLRPC: post the data
  1457.             curl_setopt($curlCURLOPT_POST1);
  1458.             // the data
  1459.             curl_setopt($curlCURLOPT_POSTFIELDS$payload);
  1460.  
  1461.             // return the header too
  1462.             curl_setopt($curlCURLOPT_HEADER1);
  1463.  
  1464.             // will only work with PHP >= 5.0
  1465.             // NB: if we set an empty string, CURL will add http header indicating
  1466.             // ALL methods it is supporting. This is possibly a better option than
  1467.             // letting the user tell what curl can / cannot do...
  1468.             if(is_array($this->accepted_compression&& count($this->accepted_compression))
  1469.             {
  1470.                 //curl_setopt($curl, CURLOPT_ENCODING, implode(',', $this->accepted_compression));
  1471.                 // empty string means 'any supported by CURL' (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
  1472.                 if (count($this->accepted_compression== 1)
  1473.                 {
  1474.                     curl_setopt($curlCURLOPT_ENCODING$this->accepted_compression[0]);
  1475.                 }
  1476.                 else
  1477.                     curl_setopt($curlCURLOPT_ENCODING'');
  1478.             }
  1479.             // extra headers
  1480.             $headers array('Content-Type: ' $msg->content_type 'Accept-Charset: ' implode(','$this->accepted_charset_encodings));
  1481.             // if no keepalive is wanted, let the server know it in advance
  1482.             if(!$keepalive)
  1483.             {
  1484.                 $headers['Connection: close';
  1485.             }
  1486.             // request compression header
  1487.             if($encoding_hdr)
  1488.             {
  1489.                 $headers[$encoding_hdr;
  1490.             }
  1491.  
  1492.             curl_setopt($curlCURLOPT_HTTPHEADER$headers);
  1493.             // timeout is borked
  1494.             if($timeout)
  1495.             {
  1496.                 curl_setopt($curlCURLOPT_TIMEOUT$timeout == $timeout 1);
  1497.             }
  1498.  
  1499.             if($username && $password)
  1500.             {
  1501.                 curl_setopt($curlCURLOPT_USERPWD$username.':'.$password);
  1502.                 if (defined('CURLOPT_HTTPAUTH'))
  1503.                 {
  1504.                     curl_setopt($curlCURLOPT_HTTPAUTH$authtype);
  1505.                 }
  1506.                 else if ($authtype != 1)
  1507.                 {
  1508.                     error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth is supported by the current PHP/curl install');
  1509.                 }
  1510.             }
  1511.  
  1512.             if($method == 'https')
  1513.             {
  1514.                 // set cert file
  1515.                 if($cert)
  1516.                 {
  1517.                     curl_setopt($curlCURLOPT_SSLCERT$cert);
  1518.                 }
  1519.                 // set cert password
  1520.                 if($certpass)
  1521.                 {
  1522.                     curl_setopt($curlCURLOPT_SSLCERTPASSWD$certpass);
  1523.                 }
  1524.                 // whether to verify remote host's cert
  1525.                 curl_setopt($curlCURLOPT_SSL_VERIFYPEER$this->verifypeer);
  1526.                 // set ca certificates file/dir
  1527.                 if($cacert)
  1528.                 {
  1529.                     curl_setopt($curlCURLOPT_CAINFO$cacert);
  1530.                 }
  1531.                 if($cacertdir)
  1532.                 {
  1533.                     curl_setopt($curlCURLOPT_CAPATH$cacertdir);
  1534.                 }
  1535.                 // set key file (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
  1536.                 if($key)
  1537.                 {
  1538.                     curl_setopt($curlCURLOPT_SSLKEY$key);
  1539.                 }
  1540.                 // set key password (shall we catch errors in case CURLOPT_SSLKEY undefined ?)
  1541.                 if($keypass)
  1542.                 {
  1543.                     curl_setopt($curlCURLOPT_SSLKEYPASSWD$keypass);
  1544.                 }
  1545.                 // whether to verify cert's common name (CN); 0 for no, 1 to verify that it exists, and 2 to verify that it matches the hostname used
  1546.                 curl_setopt($curlCURLOPT_SSL_VERIFYHOST$this->verifyhost);
  1547.             }
  1548.  
  1549.             // proxy info
  1550.             if($proxyhost)
  1551.             {
  1552.                 if($proxyport == 0)
  1553.                 {
  1554.                     $proxyport 8080// NB: even for HTTPS, local connection is on port 8080
  1555.                 }
  1556.                 curl_setopt($curlCURLOPT_PROXY,$proxyhost.':'.$proxyport);
  1557.                 //curl_setopt($curl, CURLOPT_PROXYPORT,$proxyport);
  1558.                 if($proxyusername)
  1559.                 {
  1560.                     curl_setopt($curlCURLOPT_PROXYUSERPWD$proxyusername.':'.$proxypassword);
  1561.                     if (defined('CURLOPT_PROXYAUTH'))
  1562.                     {
  1563.                         curl_setopt($curlCURLOPT_PROXYAUTH$proxyauthtype);
  1564.                     }
  1565.                     else if ($proxyauthtype != 1)
  1566.                     {
  1567.                         error_log('XML-RPC: xmlrpc_client::send: warning. Only Basic auth to proxy is supported by the current PHP/curl install');
  1568.                     }
  1569.                 }
  1570.             }
  1571.  
  1572.             // NB: should we build cookie http headers by hand rather than let CURL do it?
  1573.             // the following code does not honour 'expires', 'path' and 'domain' cookie attributes
  1574.             // set to clint obj the the user...
  1575.             if (count($this->cookies))
  1576.             {
  1577.                 $cookieheader '';
  1578.                 foreach ($this->cookies as $name => $cookie)
  1579.                 {
  1580.                     $cookieheader .= $name '=' $cookie['value'', ';
  1581.                 }
  1582.                 curl_setopt($curlCURLOPT_COOKIEsubstr($cookieheader0-2));
  1583.             }
  1584.  
  1585.             $result curl_exec($curl);
  1586.  
  1587.             if(!$result)
  1588.             {
  1589.                 $this->errstr='no response';
  1590.                 $resp=&new xmlrpcresp(0$GLOBALS['xmlrpcerr']['curl_fail']$GLOBALS['xmlrpcstr']['curl_fail']': 'curl_error($curl));
  1591.                 if(!$keepalive)
  1592.                 {
  1593.                     curl_close($curl);
  1594.                 }
  1595.             }
  1596.             else
  1597.             {
  1598.                 if(!$keepalive)
  1599.                 {
  1600.                     curl_close($curl);
  1601.                 }
  1602.                 $resp =$msg->parseResponse($resulttrue$this->return_type);
  1603.             }
  1604.             return $resp;
  1605.         }
  1606.  
  1607.         /**
  1608.         * Send an array of request messages and return an array of responses.
  1609.         * Unless $this->no_multicall has been set to true, it will try first
  1610.         * to use one single xmlrpc call to server method system.multicall, and
  1611.         * revert to sending many successive calls in case of failure.
  1612.         * This failure is also stored in $this->no_multicall for subsequent calls.
  1613.         * Unfortunately, there is no server error code universally used to denote
  1614.         * the fact that multicall is unsupported, so there is no way to reliably
  1615.         * distinguish between that and a temporary failure.
  1616.         * If you are sure that server supports multicall and do not want to
  1617.         * fallback to using many single calls, set the fourth parameter to FALSE.
  1618.         *
  1619.         * NB: trying to shoehorn extra functionality into existing syntax has resulted
  1620.         * in pretty much convoluted code...
  1621.         *
  1622.         * @param array $msgs an array of xmlrpcmsg objects
  1623.         * @param integer $timeout connection timeout (in seconds)
  1624.         * @param string $method the http protocol variant to be used
  1625.         * @param boolean fallback When true, upon receiveing an error during multicall, multiple single calls will be attempted
  1626.         * @return array 
  1627.         * @access public
  1628.         */
  1629.         function multicall($msgs$timeout=0$method=''$fallback=true)
  1630.         {
  1631.             if ($method == '')
  1632.             {
  1633.                 $method $this->method;
  1634.             }
  1635.             if(!$this->no_multicall)
  1636.             {
  1637.                 $results $this->_try_multicall($msgs$timeout$method);
  1638.                 if(is_array($results))
  1639.                 {
  1640.                     // System.multicall succeeded
  1641.                     return $results;
  1642.                 }
  1643.                 else
  1644.                 {
  1645.                     // either system.multicall is unsupported by server,
  1646.                     // or call failed for some other reason.
  1647.                     if ($fallback)
  1648.                     {
  1649.                         // Don't try it next time...
  1650.                         $this->no_multicall = true;
  1651.                     }
  1652.                     else
  1653.                     {
  1654.                         if (is_a($results'xmlrpcresp'))
  1655.                         {
  1656.                             $result $results;
  1657.                         }
  1658.                         else
  1659.                         {
  1660.                             $result =new xmlrpcresp(0$GLOBALS['xmlrpcerr']['multicall_error']$GLOBALS['xmlrpcstr']['multicall_error']);
  1661.                         }
  1662.                     }
  1663.                 }
  1664.             }
  1665.             else
  1666.             {
  1667.                 // override fallback, in case careless user tries to do two
  1668.                 // opposite things at the same time
  1669.                 $fallback true;
  1670.             }
  1671.  
  1672.             $results array();
  1673.             if ($fallback)
  1674.             {
  1675.                 // system.multicall is (probably) unsupported by server:
  1676.                 // emulate multicall via multiple requests
  1677.                 foreach($msgs as $msg)
  1678.                 {
  1679.                     $results[=$this->send($msg$timeout$method);
  1680.                 }
  1681.             }
  1682.             else
  1683.             {
  1684.                 // user does NOT want to fallback on many single calls:
  1685.                 // since we should always return an array of responses,
  1686.                 // return an array with the same error repeated n times
  1687.                 foreach($msgs as $msg)
  1688.                 {
  1689.                     $results[$result;
  1690.                 }
  1691.             }
  1692.             return $results;
  1693.         }
  1694.  
  1695.         /**
  1696.         * Attempt to boxcar $msgs via system.multicall.
  1697.         * Returns either an array of xmlrpcreponses, an xmlrpc error response
  1698.         * or false (when received response does not respect valid multicall syntax)
  1699.         * @access private
  1700.         */
  1701.         function _try_multicall($msgs$timeout$method)
  1702.         {
  1703.             // Construct multicall message
  1704.             $calls array();
  1705.             foreach($msgs as $msg)
  1706.             {
  1707.                 $call['methodName'=new xmlrpcval($msg->method(),'string');
  1708.                 $numParams $msg->getNumParams();
  1709.                 $params array();
  1710.                 for($i 0$i $numParams$i++)
  1711.                 {
  1712.                     $params[$i$msg->getParam($i);
  1713.                 }
  1714.                 $call['params'=new xmlrpcval($params'array');
  1715.                 $calls[=new xmlrpcval($call'struct');
  1716.             }
  1717.             $multicall =new xmlrpcmsg('system.multicall');
  1718.             $multicall->addParam(new xmlrpcval($calls'array'));
  1719.  
  1720.             // Attempt RPC call
  1721.             $result =$this->send($multicall$timeout$method);
  1722.  
  1723.             if($result->faultCode(!= 0)
  1724.             {
  1725.                 // call to system.multicall failed
  1726.                 return $result;
  1727.             }
  1728.  
  1729.             // Unpack responses.
  1730.             $rets $result->value();
  1731.  
  1732.             if ($this->return_type == 'xml')
  1733.             {
  1734.                     return $rets;
  1735.             }
  1736.             else if ($this->return_type == 'phpvals')
  1737.             {
  1738.                 ///@todo test this code branch...
  1739.                 $rets $result->value();
  1740.                 if(!is_array($rets))
  1741.                 {
  1742.                     return false;        // bad return type from system.multicall
  1743.                 }
  1744.                 $numRets count($rets);
  1745.                 if($numRets != count($msgs))
  1746.                 {
  1747.                     return false;        // wrong number of return values.
  1748.                 }
  1749.  
  1750.                 $response array();
  1751.                 for($i 0$i $numRets$i++)
  1752.                 {
  1753.                     $val $rets[$i];
  1754.                     if (!is_array($val)) {
  1755.                         return false;
  1756.                     }
  1757.                     switch(count($val))
  1758.                     {
  1759.                         case 1:
  1760.                             if(!isset($val[0]))
  1761.                             {
  1762.                                 return false;        // Bad value
  1763.                             }
  1764.                             // Normal return value
  1765.                             $response[$i=new xmlrpcresp($val[0]0'''phpvals');
  1766.                             break;
  1767.                         case 2:
  1768.                             ///    @todo remove usage of @: it is apparently quite slow
  1769.                             $code @$val['faultCode'];
  1770.                             if(!is_int($code))
  1771.                             {
  1772.                                 return false;
  1773.                             }
  1774.                             $str @$val['faultString'];
  1775.                             if(!is_string($str))
  1776.                             {
  1777.                                 return false;
  1778.                             }
  1779.                             $response[$i=new xmlrpcresp(0$code$str);
  1780.                             break;
  1781.                         default:
  1782.                             return false;
  1783.                     }
  1784.                 }
  1785.                 return $response;
  1786.             }
  1787.             else // return type == 'xmlrpcvals'
  1788.             {
  1789.                 $rets $result->value();
  1790.                 if($rets->kindOf(!= 'array')
  1791.                 {
  1792.                     return false;        // bad return type from system.multicall
  1793.                 }
  1794.                 $numRets $rets->arraysize();
  1795.                 if($numRets != count($msgs))
  1796.                 {
  1797.                     return false;        // wrong number of return values.
  1798.                 }
  1799.  
  1800.                 $response array();
  1801.                 for($i 0$i $numRets$i++)
  1802.                 {
  1803.                     $val $rets->arraymem($i);
  1804.                     switch($val->kindOf())
  1805.                     {
  1806.                         case 'array':
  1807.                             if($val->arraysize(!= 1)
  1808.                             {
  1809.                                 return false;        // Bad value
  1810.                             }
  1811.                             // Normal return value
  1812.                             $response[$i=new xmlrpcresp($val->arraymem(0));
  1813.                             break;
  1814.                         case 'struct':
  1815.                             $code $val->structmem('faultCode');
  1816.                             if($code->kindOf(!= 'scalar' || $code->scalartyp(!= 'int')
  1817.                             {
  1818.                                 return false;
  1819.                             }
  1820.                             $str $val->structmem('faultString');
  1821.                             if($str->kindOf(!= 'scalar' || $str->scalartyp(!= 'string')
  1822.                             {
  1823.                                 return false;
  1824.                             }
  1825.                             $response[$i=new xmlrpcresp(0$code->scalarval()$str->scalarval());
  1826.                             break;
  1827.                         default:
  1828.                             return false;
  1829.                     }
  1830.                 }
  1831.                 return $response;
  1832.             }
  1833.         }
  1834.     // end class xmlrpc_client
  1835.  
  1836.     class xmlrpcresp
  1837.     {
  1838.         var $val = 0;
  1839.         var $valtyp;
  1840.         var $errno = 0;
  1841.         var $errstr = '';
  1842.         var $payload;
  1843.         var $hdrs = array();
  1844.         var $_cookies = array();
  1845.         var $content_type = 'text/xml';
  1846.         var $raw_data = '';
  1847.  
  1848.         /**
  1849.         * @param mixed $val either an xmlrpcval obj, a php value or the xml serialization of an xmlrpcval (a string)
  1850.         * @param integer $fcode set it to anything but 0 to create an error response
  1851.         * @param string $fstr the error string, in case of an error response
  1852.         * @param string $valtyp either 'xmlrpcvals', 'phpvals' or 'xml'
  1853.         *
  1854.         * @todo add check that $val / $fcode / $fstr is of correct type???
  1855.         *  NB: as of now we do not do it, since it might be either an xmlrpcval or a plain
  1856.         *  php val, or a complete xml chunk, depending on usage of xmlrpc_client::send() inside which creator is called...
  1857.         */
  1858.         function xmlrpcresp($val$fcode 0$fstr ''$valtyp='')
  1859.         {
  1860.             if($fcode != 0)
  1861.             {
  1862.                 // error response
  1863.                 $this->errno = $fcode;
  1864.                 $this->errstr = $fstr;
  1865.                 //$this->errstr = htmlspecialchars($fstr); // XXX: encoding probably shouldn't be done here; fix later.
  1866.             }
  1867.             else
  1868.             {
  1869.                 // successful response
  1870.                 $this->val = $val;
  1871.                 if ($valtyp == '')
  1872.                 {
  1873.                     // user did not declare type of response value: try to guess it
  1874.                     if (is_object($this->val&& is_a($this->val'xmlrpcval'))
  1875.                     {
  1876.                         $this->valtyp = 'xmlrpcvals';
  1877.                     }
  1878.                     else if (is_string($this->val))
  1879.                     {
  1880.                         $this->valtyp = 'xml';
  1881.  
  1882.                     }
  1883.                     else
  1884.                     {
  1885.                         $this->valtyp = 'phpvals';
  1886.                     }
  1887.                 }
  1888.                 else
  1889.                 {
  1890.                     // user declares type of resp value: believe him
  1891.                     $this->valtyp = $valtyp;
  1892.                 }
  1893.             }
  1894.         }
  1895.  
  1896.         /**
  1897.         * Returns the error code of the response.
  1898.         * @return integer the error code of this response (0 for not-error responses)
  1899.         * @access public
  1900.         */
  1901.         function faultCode()
  1902.         {
  1903.             return $this->errno;
  1904.         }
  1905.  
  1906.         /**
  1907.         * Returns the error code of the response.
  1908.         * @return string the error string of this response ('' for not-error responses)
  1909.         * @access public
  1910.         */
  1911.         function faultString()
  1912.         {
  1913.             return $this->errstr;
  1914.         }
  1915.  
  1916.         /**
  1917.         * Returns the value received by the server.
  1918.         * @return mixed the xmlrpcval object returned by the server. Might be an xml string or php value if the response has been created by specially configured xmlrpc_client objects
  1919.         * @access public
  1920.         */
  1921.         function value()
  1922.         {
  1923.             return $this->val;
  1924.         }
  1925.  
  1926.         /**
  1927.         * Returns an array with the cookies received from the server.
  1928.         * Array has the form: $cookiename => array ('value' => $val, $attr1 => $val1, $attr2 = $val2, ...)
  1929.         * with attributes being e.g. 'expires', 'path', domain'.
  1930.         * NB: cookies sent as 'expired' by the server (i.e. with an expiry date in the past)
  1931.         * are still present in the array. It is up to the user-defined code to decide
  1932.         * how to use the received cookies, and wheter they have to be sent back with the next
  1933.         * request to the server (using xmlrpc_client::setCookie) or not
  1934.         * @return array array of cookies received from the server
  1935.         * @access public
  1936.         */
  1937.         function cookies()
  1938.         {
  1939.             return $this->_cookies;
  1940.         }
  1941.  
  1942.         /**
  1943.         * Returns xml representation of the response. XML prologue not included
  1944.         * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed
  1945.         * @return string the xml representation of the response
  1946.         * @access public
  1947.         */
  1948.         function serialize($charset_encoding='')
  1949.         {
  1950.             if ($charset_encoding != '')
  1951.                 $this->content_type = 'text/xml; charset=' $charset_encoding;
  1952.             else
  1953.                 $this->content_type = 'text/xml';
  1954.             $result "<methodResponse>\n";
  1955.             if($this->errno)
  1956.             {
  1957.                 // G. Giunta 2005/2/13: let non-ASCII response messages be tolerated by clients
  1958.                 // by xml-encoding non ascii chars
  1959.                 $result .= "<fault>\n" .
  1960. "<value>\n<struct><member><name>faultCode</name>\n<value><int>" $this->errno .
  1961. "</int></value>\n</member>\n<member>\n<name>faultString</name>\n<value><string>" .
  1962. xmlrpc_encode_entitites($this->errstr$GLOBALS['xmlrpc_internalencoding']$charset_encoding"</string></value>\n</member>\n" .
  1963. "</struct>\n</value>\n</fault>";
  1964.             }
  1965.             else
  1966.             {
  1967.                 if(!is_object($this->val|| !is_a($this->val'xmlrpcval'))
  1968.                 {
  1969.                     if (is_string($this->val&& $this->valtyp == 'xml')
  1970.                     {
  1971.                         $result .= "<params>\n<param>\n" .
  1972.                             $this->val .
  1973.                             "</param>\n</params>";
  1974.                     }
  1975.                     else
  1976.                     {
  1977.                         /// @todo try to build something serializable?
  1978.                         die('cannot serialize xmlrpcresp objects whose content is native php values');
  1979.                     }
  1980.                 }
  1981.                 else
  1982.                 {
  1983.                     $result .= "<params>\n<param>\n" .
  1984.                         $this->val->serialize($charset_encoding.
  1985.                         "</param>\n</params>";
  1986.                 }
  1987.             }
  1988.             $result .= "\n</methodResponse>";
  1989.             $this->payload = $result;
  1990.             return $result;
  1991.         }
  1992.     }
  1993.  
  1994.     class xmlrpcmsg
  1995.     {
  1996.         var $payload;
  1997.         var $methodname;
  1998.         var $params=array();
  1999.         var $debug=0;
  2000.         var $content_type = 'text/xml';
  2001.  
  2002.         /**
  2003.         * @param string $meth the name of the method to invoke
  2004.         * @param array $pars array of parameters to be paased to the method (xmlrpcval objects)
  2005.         */
  2006.         function xmlrpcmsg($meth$pars=0)
  2007.         {
  2008.             $this->methodname=$meth;
  2009.             if(is_array($pars&& count($pars)>0)
  2010.             {
  2011.                 for($i=0$i<count($pars)$i++)
  2012.                 {
  2013.                     $this->addParam($pars[$i]);
  2014.                 }
  2015.             }
  2016.         }
  2017.  
  2018.         /**
  2019.         * @access private
  2020.         */
  2021.         function xml_header($charset_encoding='')
  2022.         {
  2023.             if ($charset_encoding != '')
  2024.             {
  2025.                 return "<?xml version=\"1.0\" encoding=\"$charset_encoding\" ?">\n<methodCall>\n";
  2026.             }
  2027.             else
  2028.             {
  2029.                 return "<?xml version=\"1.0\"?" ">\n<methodCall>\n";
  2030.             }
  2031.         }
  2032.  
  2033.         /**
  2034.         * @access private
  2035.         */
  2036.         function xml_footer()
  2037.         {
  2038.             return '</methodCall>';
  2039.         }
  2040.  
  2041.         /**
  2042.         * @access private
  2043.         */
  2044.         function kindOf()
  2045.         {
  2046.             return 'msg';
  2047.         }
  2048.  
  2049.         /**
  2050.         * @access private
  2051.         */
  2052.         function createPayload($charset_encoding='')
  2053.         {
  2054.             if ($charset_encoding != '')
  2055.                 $this->content_type = 'text/xml; charset=' $charset_encoding;
  2056.             else
  2057.                 $this->content_type = 'text/xml';
  2058.             $this->payload=$this->xml_header($charset_encoding);
  2059.             $this->payload.='<methodName>' $this->methodname . "</methodName>\n";
  2060.             $this->payload.="<params>\n";
  2061.             for($i=0$i<count($this->params)$i++)
  2062.             {
  2063.                 $p=$this->params[$i];
  2064.                 $this->payload.="<param>\n" $p->serialize($charset_encoding.
  2065.                 "</param>\n";
  2066.             }
  2067.             $this->payload.="</params>\n";
  2068.             $this->payload.=$this->xml_footer();
  2069.         }
  2070.  
  2071.         /**
  2072.         * Gets/sets the xmlrpc method to be invoked
  2073.         * @param string $meth the method to be set (leave empty not to set it)
  2074.         * @return string the method that will be invoked
  2075.         * @access public
  2076.         */
  2077.         function method($meth='')
  2078.         {
  2079.             if($meth!='')
  2080.             {
  2081.                 $this->methodname=$meth;
  2082.             }
  2083.             return $this->methodname;
  2084.         }
  2085.  
  2086.         /**
  2087.         * Returns xml representation of the message. XML prologue included
  2088.         * @return string the xml representation of the message, xml prologue included
  2089.         * @access public
  2090.         */
  2091.         function serialize($charset_encoding='')
  2092.         {
  2093.             $this->createPayload($charset_encoding);
  2094.             return $this->payload;
  2095.         }
  2096.  
  2097.         /**
  2098.         * Add a parameter to the list of parameters to be used upon method invocation
  2099.         * @param xmlrpcval $par 
  2100.         * @return boolean false on failure
  2101.         * @access public
  2102.         */
  2103.         function addParam($par)
  2104.         {
  2105.             // add check: do not add to self params which are not xmlrpcvals
  2106.             if(is_object($par&& is_a($par'xmlrpcval'))
  2107.             {
  2108.                 $this->params[]=$par;
  2109.                 return true;
  2110.             }
  2111.             else
  2112.             {
  2113.                 return false;
  2114.             }
  2115.         }
  2116.  
  2117.         /**
  2118.         * Returns the nth parameter in the message. The index zero-based.
  2119.         * @param integer $i the index of the parameter to fetch (zero based)
  2120.         * @return xmlrpcval the i-th parameter
  2121.         * @access public
  2122.         */
  2123.         function getParam($ireturn $this->params[$i]}
  2124.  
  2125.         /**
  2126.         * Returns the number of parameters in the messge.
  2127.         * @return integer the number of parameters currently set
  2128.         * @access public
  2129.         */
  2130.         function getNumParams(return count($this->params)}
  2131.  
  2132.         /**
  2133.         * Given an open file handle, read all data available and parse it as axmlrpc response.
  2134.         * NB: the file handle is not closed by this function.
  2135.         * @access public
  2136.         * @return xmlrpcresp 
  2137.         * @todo add 2nd & 3rd param to be passed to ParseResponse() ???
  2138.         */
  2139.         function &parseResponseFile($fp)
  2140.         {
  2141.             $ipd='';
  2142.             while($data=fread($fp32768))
  2143.             {
  2144.                 $ipd.=$data;
  2145.             }
  2146.             //fclose($fp);
  2147.             $r =$this->parseResponse($ipd);
  2148.             return $r;
  2149.         }
  2150.  
  2151.         /**
  2152.         * Parses HTTP headers and separates them from data.
  2153.         * @access private
  2154.         */
  2155.         function &parseResponseHeaders(&$data$headers_processed=false)
  2156.         {
  2157.                 // Support "web-proxy-tunelling" connections for https through proxies
  2158.                 if(preg_match('/^HTTP\/1\.[0-1] 200 Connection established/'$data))
  2159.                 {
  2160.                     // Look for CR/LF or simple LF as line separator,
  2161.                     // (even though it is not valid http)
  2162.                     $pos strpos($data,"\r\n\r\n");
  2163.                     if($pos || is_int($pos))
  2164.                     {
  2165.                         $bd $pos+4;
  2166.                     }
  2167.                     else
  2168.                     {
  2169.                         $pos strpos($data,"\n\n");
  2170.                         if($pos || is_int($pos))
  2171.                         {
  2172.                             $bd $pos+2;
  2173.                         }
  2174.                         else
  2175.                         {
  2176.                             // No separation between response headers and body: fault?
  2177.                             $bd 0;
  2178.                         }
  2179.                     }
  2180.                     if ($bd)
  2181.                     {
  2182.                         // this filters out all http headers from proxy.
  2183.                         // maybe we could take them into account, too?
  2184.                         $data substr($data$bd);
  2185.                     }
  2186.                     else
  2187.                     {
  2188.                         error_log('XML-RPC: xmlrpcmsg::parseResponse: HTTPS via proxy error, tunnel connection possibly failed');
  2189.                         $r=&new xmlrpcresp(0$GLOBALS['xmlrpcerr']['http_error']$GLOBALS['xmlrpcstr']['http_error']' (HTTPS via proxy error, tunnel connection possibly failed)');
  2190.                         return $r;
  2191.                     }
  2192.                 }
  2193.  
  2194.                 // Strip HTTP 1.1 100 Continue header if present
  2195.                 while(preg_match('/^HTTP\/1\.1 1[0-9]{2} /'$data))
  2196.                 {
  2197.                     $pos strpos($data'HTTP'12);
  2198.                     // server sent a Continue header without any (valid) content following...
  2199.                     // give the client a chance to know it
  2200.                     if(!$pos && !is_int($pos)) // works fine in php 3, 4 and 5
  2201.                     {
  2202.                         break;
  2203.                     }
  2204.                     $data substr($data$pos);
  2205.                 }
  2206.                 if(!preg_match('/^HTTP\/[0-9.]+ 200 /'$data))
  2207.                 {
  2208.                     $errstrsubstr($data0strpos($data"\n")-1);
  2209.                     error_log('XML-RPC: xmlrpcmsg::parseResponse: HTTP error, got response: ' .$errstr);
  2210.                     $r=&new xmlrpcresp(0$GLOBALS['xmlrpcerr']['http_error']$GLOBALS['xmlrpcstr']['http_error']' (' $errstr ')');
  2211.                     return $r;
  2212.                 }
  2213.  
  2214.                 $GLOBALS['_xh']['headers'array();
  2215.                 $GLOBALS['_xh']['cookies'array();
  2216.  
  2217.                 // be tolerant to usage of \n instead of \r\n to separate headers and data
  2218.                 // (even though it is not valid http)
  2219.                 $pos strpos($data,"\r\n\r\n");
  2220.                 if($pos || is_int($pos))
  2221.                 {
  2222.                     $bd $pos+4;
  2223.                 }
  2224.                 else
  2225.                 {
  2226.                     $pos strpos($data,"\n\n");
  2227.                     if($pos || is_int($pos))
  2228.                     {
  2229.                         $bd $pos+2;
  2230.                     }
  2231.                     else
  2232.                     {
  2233.                         // No separation between response headers and body: fault?
  2234.                         // we could take some action here instead of going on...
  2235.                         $bd 0;
  2236.                     }
  2237.                 }
  2238.                 // be tolerant to line endings, and extra empty lines
  2239.                 $ar split("\r?\n"trim(substr($data0$pos)));
  2240.                 while(list(,$line@each($ar))
  2241.                 {
  2242.                     // take care of multi-line headers and cookies
  2243.                     $arr explode(':',$line,2);
  2244.                     if(count($arr1)
  2245.                     {
  2246.                         $header_name strtolower(trim($arr[0]));
  2247.                         /// @todo some other headers (the ones that allow a CSV list of values)
  2248.                         /// do allow many values to be passed using multiple header lines.
  2249.                         /// We should add content to $GLOBALS['_xh']['headers'][$header_name]
  2250.                         /// instead of replacing it for those...
  2251.                         if ($header_name == 'set-cookie' || $header_name == 'set-cookie2')
  2252.                         {
  2253.                             if ($header_name == 'set-cookie2')
  2254.                             {
  2255.                                 // version 2 cookies:
  2256.                                 // there could be many cookies on one line, comma separated
  2257.                                 $cookies explode(','$arr[1]);
  2258.                             }
  2259.                             else
  2260.                             {
  2261.                                 $cookies array($arr[1]);
  2262.                             }
  2263.                             foreach ($cookies as $cookie)
  2264.                             {
  2265.                                 // glue together all received cookies, using a comma to separate them
  2266.                                 // (same as php does with getallheaders())
  2267.                                 if (isset($GLOBALS['_xh']['headers'][$header_name]))
  2268.                                     $GLOBALS['_xh']['headers'][$header_name.= ', ' trim($cookie);
  2269.                                 else
  2270.                                     $GLOBALS['_xh']['headers'][$header_nametrim($cookie);
  2271.                                 // parse cookie attributes, in case user wants to correctly honour them
  2272.                                 // feature creep: only allow rfc-compliant cookie attributes?
  2273.                                 $cookie explode(';'$cookie);
  2274.                                 foreach ($cookie as $pos => $val)
  2275.                                 {
  2276.                                     $val explode('='$val2);
  2277.                                     $tag trim($val[0]);
  2278.                                     $val trim(@$val[1]);
  2279.                                     /// @todo with version 1 cookies, we should strip leading and trailing " chars
  2280.                                     if ($pos == 0)
  2281.                                     {
  2282.                                         $cookiename $tag;
  2283.                                         $GLOBALS['_xh']['cookies'][$tagarray();
  2284.                                         $GLOBALS['_xh']['cookies'][$cookiename]['value'urldecode($val);
  2285.                                     }
  2286.                                     else
  2287.                                     {
  2288.                                         $GLOBALS['_xh']['cookies'][$cookiename][$tag$val;
  2289.                                     }
  2290.                                 }
  2291.                             }
  2292.                         }
  2293.                         else
  2294.                         {
  2295.                             $GLOBALS['_xh']['headers'][$header_nametrim($arr[1]);
  2296.                         }
  2297.                     }
  2298.                     elseif(isset($header_name))
  2299.                     {
  2300.                         ///    @todo version1 cookies might span multiple lines, thus breaking the parsing above
  2301.                         $GLOBALS['_xh']['headers'][$header_name.= ' ' trim($line);
  2302.                     }
  2303.                 }
  2304.  
  2305.                 $data substr($data$bd);
  2306.  
  2307.                 if($this->debug && count($GLOBALS['_xh']['headers']))
  2308.                 {
  2309.                     print '<PRE>';
  2310.                     foreach($GLOBALS['_xh']['headers'as $header => $value)
  2311.                     {
  2312.                         print htmlentities("HEADER: $header$value\n");
  2313.                     }
  2314.                     foreach($GLOBALS['_xh']['cookies'as $header => $value)
  2315.                     {
  2316.                         print htmlentities("COOKIE: $header={$value['value']}\n");
  2317.                     }
  2318.                     print "</PRE>\n";
  2319.                 }
  2320.  
  2321.                 // if CURL was used for the call, http headers have been processed,
  2322.                 // and dechunking + reinflating have been carried out
  2323.                 if(!$headers_processed)
  2324.                 {
  2325.                     // Decode chunked encoding sent by http 1.1 servers
  2326.                     if(isset($GLOBALS['_xh']['headers']['transfer-encoding']&& $GLOBALS['_xh']['headers']['transfer-encoding'== 'chunked')
  2327.                     {
  2328.                         if(!$data decode_chunked($data))
  2329.                         {
  2330.                             error_log('XML-RPC: xmlrpcmsg::parseResponse: errors occurred when trying to rebuild the chunked data received from server');
  2331.                             $r =new xmlrpcresp(0$GLOBALS['xmlrpcerr']['dechunk_fail']$GLOBALS['xmlrpcstr']['dechunk_fail']);
  2332.                             return $r;
  2333.                         }
  2334.                     }
  2335.  
  2336.                     // Decode gzip-compressed stuff
  2337.                     // code shamelessly inspired from nusoap library by Dietrich Ayala
  2338.                     if(isset($GLOBALS['_xh']['headers']['content-encoding']))
  2339.                     {
  2340.                         $GLOBALS['_xh']['headers']['content-encoding'str_replace('x-'''$GLOBALS['_xh']['headers']['content-encoding']);
  2341.                         if($GLOBALS['_xh']['headers']['content-encoding'== 'deflate' || $GLOBALS['_xh']['headers']['content-encoding'== 'gzip')
  2342.                         {
  2343.                             // if decoding works, use it. else assume data wasn't gzencoded
  2344.                             if(function_exists('gzinflate'))
  2345.                             {
  2346.                                 if($GLOBALS['_xh']['headers']['content-encoding'== 'deflate' && $degzdata @gzuncompress($data))
  2347.                                 {
  2348.                                     $data $degzdata;
  2349.                                     if($this->debug)
  2350.                                     print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" htmlentities($data"\n---END---</PRE>";
  2351.                                 }
  2352.                                 elseif($GLOBALS['_xh']['headers']['content-encoding'== 'gzip' && $degzdata @gzinflate(substr($data10)))
  2353.                                 {
  2354.                                     $data $degzdata;
  2355.                                     if($this->debug)
  2356.                                     print "<PRE>---INFLATED RESPONSE---[".strlen($data)." chars]---\n" htmlentities($data"\n---END---</PRE>";
  2357.                                 }
  2358.                                 else
  2359.                                 {
  2360.                                     error_log('XML-RPC: xmlrpcmsg::parseResponse: errors occurred when trying to decode the deflated data received from server');
  2361.                                     $r =new xmlrpcresp(0$GLOBALS['xmlrpcerr']['decompress_fail']$GLOBALS['xmlrpcstr']['decompress_fail']);
  2362.                                     return $r;
  2363.                                 }
  2364.                             }
  2365.                             else
  2366.                             {
  2367.                                 error_log('XML-RPC: xmlrpcmsg::parseResponse: the server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
  2368.                                 $r =new xmlrpcresp(0$GLOBALS['xmlrpcerr']['cannot_decompress']$GLOBALS['xmlrpcstr']['cannot_decompress']);
  2369.                                 return $r;
  2370.                             }
  2371.                         }
  2372.                     }
  2373.                 // end of 'if needed, de-chunk, re-inflate response'
  2374.  
  2375.                 // real stupid hack to avoid PHP 4 complaining about returning NULL by ref
  2376.                 $r null;
  2377.                 $r =$r;
  2378.                 return $r;
  2379.         }
  2380.  
  2381.         /**
  2382.         * Parse the xmlrpc response contained in the string $data and return an xmlrpcresp object.
  2383.         * @param string $data the xmlrpc response, eventually including http headers
  2384.         * @param bool $headers_processed when true prevents parsing HTTP headers for interpretation of content-encoding and consequent decoding
  2385.         * @param string $return_type decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or 'phpvals'
  2386.         * @return xmlrpcresp 
  2387.         * @access public
  2388.         */
  2389.         function &parseResponse($data=''$headers_processed=false$return_type='xmlrpcvals')
  2390.         {
  2391.             if($this->debug)
  2392.             {
  2393.                 //by maHo, replaced htmlspecialchars with htmlentities
  2394.                 print "<PRE>---GOT---\n" htmlentities($data"\n---END---\n</PRE>";
  2395.             }
  2396.  
  2397.             if($data == '')
  2398.             {
  2399.                 error_log('XML-RPC: xmlrpcmsg::parseResponse: no response received from server.');
  2400.                 $r =new xmlrpcresp(0$GLOBALS['xmlrpcerr']['no_data']$GLOBALS['xmlrpcstr']['no_data']);
  2401.                 return $r;
  2402.             }
  2403.  
  2404.             $GLOBALS['_xh']=array();
  2405.  
  2406.             $raw_data $data;
  2407.             // parse the HTTP headers of the response, if present, and separate them from data
  2408.             if(substr($data04== 'HTTP')
  2409.             {
  2410.                 $r =$this->parseResponseHeaders($data$headers_processed);
  2411.                 if ($r)
  2412.                 {
  2413.                     // failed processing of HTTP response headers
  2414.                     // save into response obj the full payload received, for debugging
  2415.                     $r->raw_data $data;
  2416.                     return $r;
  2417.                 }
  2418.             }
  2419.             else
  2420.             {
  2421.                 $GLOBALS['_xh']['headers'array();
  2422.                 $GLOBALS['_xh']['cookies'array();
  2423.             }
  2424.  
  2425.             if($this->debug)
  2426.             {
  2427.                 $start strpos($data'<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
  2428.                 if ($start)
  2429.                 {
  2430.                     $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
  2431.                     $end strpos($data'-->'$start);
  2432.                     $comments substr($data$start$end-$start);
  2433.                     print "<PRE>---SERVER DEBUG INFO (DECODED) ---\n\t".htmlentities(str_replace("\n""\n\t"base64_decode($comments)))."\n---END---\n</PRE>";
  2434.                 }
  2435.             }
  2436.  
  2437.             // be tolerant of extra whitespace in response body
  2438.             $data trim($data);
  2439.  
  2440.             /// @todo return an error msg if $data=='' ?
  2441.  
  2442.             // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
  2443.             // idea from Luca Mariano <luca.mariano@email.it> originally in PEARified version of the lib
  2444.             $bd false;
  2445.             // Poor man's version of strrpos for php 4...
  2446.             $pos strpos($data'</methodResponse>');
  2447.             while($pos || is_int($pos))
  2448.             {
  2449.                 $bd $pos+17;
  2450.                 $pos strpos($data'</methodResponse>'$bd);
  2451.             }
  2452.             if($bd)
  2453.             {
  2454.                 $data substr($data0$bd);
  2455.             }
  2456.  
  2457.             // if user wants back raw xml, give it to him
  2458.             if ($return_type == 'xml')
  2459.             {
  2460.                 $r =new xmlrpcresp($data0'''xml');
  2461.                 $r->hdrs $GLOBALS['_xh']['headers'];
  2462.                 $r->_cookies $GLOBALS['_xh']['cookies'];
  2463.                 $r->raw_data $raw_data;
  2464.                 return $r;
  2465.             }
  2466.  
  2467.             // try to 'guestimate' the character encoding of the received response
  2468.             $resp_encoding guess_encoding(@$GLOBALS['_xh']['headers']['content-type']$data);
  2469.  
  2470.             $GLOBALS['_xh']['ac']='';
  2471.             //$GLOBALS['_xh']['qt']=''; //unused...
  2472.             $GLOBALS['_xh']['stack'array();
  2473.             $GLOBALS['_xh']['valuestack'array();
  2474.             $GLOBALS['_xh']['isf']=0// 0 = OK, 1 for xmlrpc fault responses, 2 = invalid xmlrpc
  2475.             $GLOBALS['_xh']['isf_reason']='';
  2476.             $GLOBALS['_xh']['rt']=''// 'methodcall or 'methodresponse'
  2477.  
  2478.             // if response charset encoding is not known / supported, try to use
  2479.             // the default encoding and parse the xml anyway, but log a warning...
  2480.             if (!in_array($resp_encodingarray('UTF-8''ISO-8859-1''US-ASCII')))
  2481.             // the following code might be better for mb_string enabled installs, but
  2482.             // makes the lib about 200% slower...
  2483.             //if (!is_valid_charset($resp_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
  2484.             {
  2485.                 error_log('XML-RPC: xmlrpcmsg::parseResponse: invalid charset encoding of received response: '.$resp_encoding);
  2486.                 $resp_encoding $GLOBALS['xmlrpc_defencoding'];
  2487.             }
  2488.             $parser xml_parser_create($resp_encoding);
  2489.             xml_parser_set_option($parserXML_OPTION_CASE_FOLDINGtrue);
  2490.             // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
  2491.             // the xml parser to give us back data in the expected charset
  2492.             xml_parser_set_option($parserXML_OPTION_TARGET_ENCODING$GLOBALS['xmlrpc_internalencoding']);
  2493.  
  2494.             if ($return_type == 'phpvals')
  2495.             {
  2496.                 xml_set_element_handler($parser'xmlrpc_se''xmlrpc_ee_fast');
  2497.             }
  2498.             else
  2499.             {
  2500.                 xml_set_element_handler($parser'xmlrpc_se''xmlrpc_ee');
  2501.             }
  2502.  
  2503.             xml_set_character_data_handler($parser'xmlrpc_cd');
  2504.             xml_set_default_handler($parser'xmlrpc_dh');
  2505.  
  2506.             // first error check: xml not well formed
  2507.             if(!xml_parse($parser$datacount($data)))
  2508.             {
  2509.                 // thanks to Peter Kocks <peter.kocks@baygate.com>
  2510.                 if((xml_get_current_line_number($parser)) == 1)
  2511.                 {
  2512.                     $errstr 'XML error at line 1, check URL';
  2513.                 }
  2514.                 else
  2515.                 {
  2516.                     $errstr sprintf('XML error: %s at line %d, column %d',
  2517.                         xml_error_string(xml_get_error_code($parser)),
  2518.                         xml_get_current_line_number($parser)xml_get_current_column_number($parser));
  2519.                 }
  2520.                 error_log($errstr);
  2521.                 $r=&new xmlrpcresp(0$GLOBALS['xmlrpcerr']['invalid_return']$GLOBALS['xmlrpcstr']['invalid_return'].' ('.$errstr.')');
  2522.                 xml_parser_free($parser);
  2523.                 if($this->debug)
  2524.                 {
  2525.                     print $errstr;
  2526.                 }
  2527.                 $r->hdrs $GLOBALS['_xh']['headers'];
  2528.                 $r->_cookies $GLOBALS['_xh']['cookies'];
  2529.                 $r->raw_data $raw_data;
  2530.                 return $r;
  2531.             }
  2532.             xml_parser_free($parser);
  2533.             // second error check: xml well formed but not xml-rpc compliant
  2534.             if ($GLOBALS['_xh']['isf'1)
  2535.             {
  2536.                 if ($this->debug)
  2537.                 {
  2538.                     /// @todo echo something for user?
  2539.                 }
  2540.  
  2541.                 $r =new xmlrpcresp(0$GLOBALS['xmlrpcerr']['invalid_return'],
  2542.                 $GLOBALS['xmlrpcstr']['invalid_return'' ' $GLOBALS['_xh']['isf_reason']);
  2543.             }
  2544.             // third error check: parsing of the response has somehow gone boink.
  2545.             // NB: shall we omit this check, since we trust the parsing code?
  2546.             elseif ($return_type == 'xmlrpcvals' && !is_object($GLOBALS['_xh']['value']))
  2547.             {
  2548.                 // something odd has happened
  2549.                 // and it's time to generate a client side error
  2550.                 // indicating something odd went on
  2551.                 $r=&new xmlrpcresp(0$GLOBALS['xmlrpcerr']['invalid_return'],
  2552.                     $GLOBALS['xmlrpcstr']['invalid_return']);
  2553.             }
  2554.             else
  2555.             {
  2556.                 if ($this->debug)
  2557.                 {
  2558.                     print "<PRE>---PARSED---\n";
  2559.                     // somehow htmlentities chokes on var_export, and some full html string...
  2560.                     //print htmlentitites(var_export($GLOBALS['_xh']['value'], true));
  2561.                     print htmlspecialchars(var_export($GLOBALS['_xh']['value']true));
  2562.                     print "\n---END---</PRE>";
  2563.                 }
  2564.  
  2565.                 // note that using =& will raise an error if $GLOBALS['_xh']['st'] does not generate an object.
  2566.                 $v =$GLOBALS['_xh']['value'];
  2567.  
  2568.                 if($GLOBALS['_xh']['isf'])
  2569.                 {
  2570.                     /// @todo we should test here if server sent an int and a string,
  2571.                     /// and/or coerce them into such...
  2572.                     if ($return_type == 'xmlrpcvals')
  2573.                     {
  2574.                         $errno_v $v->structmem('faultCode');
  2575.                         $errstr_v $v->structmem('faultString');
  2576.                         $errno $errno_v->scalarval();
  2577.                         $errstr $errstr_v->scalarval();
  2578.                     }
  2579.                     else
  2580.                     {
  2581.                         $errno $v['faultCode'];
  2582.                         $errstr $v['faultString'];
  2583.                     }
  2584.  
  2585.                     if($errno == 0)
  2586.                     {
  2587.                         // FAULT returned, errno needs to reflect that
  2588.                         $errno = -1;
  2589.                     }
  2590.  
  2591.                     $r =new xmlrpcresp(0$errno$errstr);
  2592.                 }
  2593.                 else
  2594.                 {
  2595.                     $r=&new xmlrpcresp($v0''$return_type);
  2596.                 }
  2597.             }
  2598.  
  2599.             $r->hdrs $GLOBALS['_xh']['headers'];
  2600.             $r->_cookies $GLOBALS['_xh']['cookies'];
  2601.             $r->raw_data $raw_data;
  2602.             return $r;
  2603.         }
  2604.     }
  2605.  
  2606.     class xmlrpcval
  2607.     {
  2608.         var $me=array();
  2609.         var $mytype=0;
  2610.         var $_php_class=null;
  2611.  
  2612.         /**
  2613.         * @param mixed $val 
  2614.         * @param string $type any valid xmlrpc type name (lowercase). If null, 'string' is assumed
  2615.         */
  2616.         function xmlrpcval($val=-1$type='')
  2617.         {
  2618.             /// @todo: optimization creep - do not call addXX, do it all inline.
  2619.             /// downside: booleans will not be coerced anymore
  2620.             if($val!==-|| $type!='')
  2621.             {
  2622.                 // optimization creep: inlined all work done by constructor
  2623.                 switch($type)
  2624.                 {
  2625.                     case '':
  2626.                         $this->mytype=1;
  2627.                         $this->me['string']=$val;
  2628.                         break;
  2629.                     case 'i4':
  2630.                     case 'int':
  2631.                     case 'double':
  2632.                     case 'string':
  2633.                     case 'boolean':
  2634.                     case 'dateTime.iso8601':
  2635.                     case 'base64':
  2636.                     case 'null':
  2637.                         $this->mytype=1;
  2638.                         $this->me[$type]=$val;
  2639.                         break;
  2640.                     case 'array':
  2641.                         $this->mytype=2;
  2642.                         $this->me['array']=$val;
  2643.                         break;
  2644.                     case 'struct':
  2645.                         $this->mytype=3;
  2646.                         $this->me['struct']=$val;
  2647.                         break;
  2648.                     default:
  2649.                         error_log("XML-RPC: xmlrpcval::xmlrpcval: not a known type ($type)");
  2650.                 }
  2651.                 /*if($type=='')
  2652.                 {
  2653.                     $type='string';
  2654.                 }
  2655.                 if($GLOBALS['xmlrpcTypes'][$type]==1)
  2656.                 {
  2657.                     $this->addScalar($val,$type);
  2658.                 }
  2659.                 elseif($GLOBALS['xmlrpcTypes'][$type]==2)
  2660.                 {
  2661.                     $this->addArray($val);
  2662.                 }
  2663.                 elseif($GLOBALS['xmlrpcTypes'][$type]==3)
  2664.                 {
  2665.                     $this->addStruct($val);
  2666.                 }*/
  2667.             }
  2668.         }
  2669.  
  2670.         /**
  2671.         * Add a single php value to an (unitialized) xmlrpcval
  2672.         * @param mixed $val 
  2673.         * @param string $type 
  2674.         * @return int 1 or 0 on failure
  2675.         */
  2676.         function addScalar($val$type='string')
  2677.         {
  2678.             $typeof=@$GLOBALS['xmlrpcTypes'][$type];
  2679.             if($typeof!=1)
  2680.             {
  2681.                 error_log("XML-RPC: xmlrpcval::addScalar: not a scalar type ($type)");
  2682.                 return 0;
  2683.             }
  2684.  
  2685.             // coerce booleans into correct values
  2686.             // NB: we should iether do it for datetimes, integers and doubles, too,
  2687.             // or just plain remove this check, implemnted on booleans only...
  2688.             if($type==$GLOBALS['xmlrpcBoolean'])
  2689.             {
  2690.                 if(strcasecmp($val,'true')==|| $val==|| ($val==true && strcasecmp($val,'false')))
  2691.                 {
  2692.                     $val=true;
  2693.                 }
  2694.                 else
  2695.                 {
  2696.                     $val=false;
  2697.                 }
  2698.             }
  2699.  
  2700.             switch($this->mytype)
  2701.             {
  2702.                 case 1:
  2703.                     error_log('XML-RPC: xmlrpcval::addScalar: scalar xmlrpcval can have only one value');
  2704.                     return 0;
  2705.                 case 3:
  2706.                     error_log('XML-RPC: xmlrpcval::addScalar: cannot add anonymous scalar to struct xmlrpcval');
  2707.                     return 0;
  2708.                 case 2:
  2709.                     // we're adding a scalar value to an array here
  2710.                     //$ar=$this->me['array'];
  2711.                     //$ar[]=&new xmlrpcval($val, $type);
  2712.                     //$this->me['array']=$ar;
  2713.                     // Faster (?) avoid all the costly array-copy-by-val done here...
  2714.                     $this->me['array'][]=&new xmlrpcval($val$type);
  2715.                     return 1;
  2716.                 default:
  2717.                     // a scalar, so set the value and remember we're scalar
  2718.                     $this->me[$type]=$val;
  2719.                     $this->mytype=$typeof;
  2720.                     return 1;
  2721.             }
  2722.         }
  2723.  
  2724.         /**
  2725.         * Add an array of xmlrpcval objects to an xmlrpcval
  2726.         * @param array $vals 
  2727.         * @return int 1 or 0 on failure
  2728.         * @access public
  2729.         *
  2730.         * @todo add some checking for $vals to be an array of xmlrpcvals?
  2731.         */
  2732.         function addArray($vals)
  2733.         {
  2734.             if($this->mytype==0)
  2735.             {
  2736.                 $this->mytype=$GLOBALS['xmlrpcTypes']['array'];
  2737.                 $this->me['array']=$vals;
  2738.                 return 1;
  2739.             }
  2740.             elseif($this->mytype==2)
  2741.             {
  2742.                 // we're adding to an array here
  2743.                 $this->me['array'array_merge($this->me['array']$vals);
  2744.                 return 1;
  2745.             }
  2746.             else
  2747.             {
  2748.                 error_log('XML-RPC: xmlrpcval::addArray: already initialized as a [' $this->kindOf(']');
  2749.                 return 0;
  2750.             }
  2751.         }
  2752.  
  2753.         /**
  2754.         * Add an array of named xmlrpcval objects to an xmlrpcval
  2755.         * @param array $vals 
  2756.         * @return int 1 or 0 on failure
  2757.         * @access public
  2758.         *
  2759.         * @todo add some checking for $vals to be an array?
  2760.         */
  2761.         function addStruct($vals)
  2762.         {
  2763.             if($this->mytype==0)
  2764.             {
  2765.                 $this->mytype=$GLOBALS['xmlrpcTypes']['struct'];
  2766.                 $this->me['struct']=$vals;
  2767.                 return 1;
  2768.             }
  2769.             elseif($this->mytype==3)
  2770.             {
  2771.                 // we're adding to a struct here
  2772.                 $this->me['struct'array_merge($this->me['struct']$vals);
  2773.                 return 1;
  2774.             }
  2775.             else
  2776.             {
  2777.                 error_log('XML-RPC: xmlrpcval::addStruct: already initialized as a [' $this->kindOf(']');
  2778.                 return 0;
  2779.             }
  2780.         }
  2781.  
  2782.         // poor man's version of print_r ???
  2783.         // DEPRECATED!
  2784.         function dump($ar)
  2785.         {
  2786.             foreach($ar as $key => $val)
  2787.             {
  2788.                 echo "$key => $val<br />";
  2789.                 if($key == 'array')
  2790.                 {
  2791.                     while(list($key2$val2each($val))
  2792.                     {
  2793.                         echo "-- $key2 => $val2<br />";
  2794.                     }
  2795.                 }
  2796.             }
  2797.         }
  2798.  
  2799.         /**
  2800.         * Returns a string containing "struct", "array" or "scalar" describing the base type of the value
  2801.         * @return string 
  2802.         * @access public
  2803.         */
  2804.         function kindOf()
  2805.         {
  2806.             switch($this->mytype)
  2807.             {
  2808.                 case 3:
  2809.                     return 'struct';
  2810.                     break;
  2811.                 case 2:
  2812.                     return 'array';
  2813.                     break;
  2814.                 case 1:
  2815.                     return 'scalar';
  2816.                     break;
  2817.                 default:
  2818.                     return 'undef';
  2819.             }
  2820.         }
  2821.  
  2822.         /**
  2823.         * @access private
  2824.         */
  2825.         function serializedata($typ$val$charset_encoding='')
  2826.         {
  2827.             $rs='';
  2828.             switch(@$GLOBALS['xmlrpcTypes'][$typ])
  2829.             {
  2830.                 case 1:
  2831.                     switch($typ)
  2832.                     {
  2833.                         case $GLOBALS['xmlrpcBase64']:
  2834.                             $rs.="<${typ}>base64_encode($val"</${typ}>";
  2835.                             break;
  2836.                         case $GLOBALS['xmlrpcBoolean']:
  2837.                             $rs.="<${typ}>($val '1' '0'"</${typ}>";
  2838.                             break;
  2839.                         case $GLOBALS['xmlrpcString']:
  2840.                             // G. Giunta 2005/2/13: do NOT use htmlentities, since
  2841.                             // it will produce named html entities, which are invalid xml
  2842.                             $rs.="<${typ}>xmlrpc_encode_entitites($val$GLOBALS['xmlrpc_internalencoding']$charset_encoding)"</${typ}>";
  2843.                             break;
  2844.                         case $GLOBALS['xmlrpcInt']:
  2845.                         case $GLOBALS['xmlrpcI4']:
  2846.                             $rs.="<${typ}>".(int)$val."</${typ}>";
  2847.                             break;
  2848.                         case $GLOBALS['xmlrpcDouble']:
  2849.                             $rs.="<${typ}>".(double)$val."</${typ}>";
  2850.                             break;
  2851.                         case $GLOBALS['xmlrpcNull']:
  2852.                             $rs.="<nil/>";
  2853.                             break;
  2854.                         default:
  2855.                             // no standard type value should arrive here, but provide a possibility
  2856.                             // for xmlrpcvals of unknown type...
  2857.                             $rs.="<${typ}>${val}</${typ}>";
  2858.                     }
  2859.                     break;
  2860.                 case 3:
  2861.                     // struct
  2862.                     if ($this->_php_class)
  2863.                     {
  2864.                         $rs.='<struct php_class="' $this->_php_class . "\">\n";
  2865.                     }
  2866.                     else
  2867.                     {
  2868.                         $rs.="<struct>\n";
  2869.                     }
  2870.                     foreach($val as $key2 => $val2)
  2871.                     {
  2872.                         $rs.='<member><name>'.xmlrpc_encode_entitites($key2$GLOBALS['xmlrpc_internalencoding']$charset_encoding)."</name>\n";
  2873.                         //$rs.=$this->serializeval($val2);
  2874.                         $rs.=$val2->serialize($charset_encoding);
  2875.                         $rs.="</member>\n";
  2876.                     }
  2877.                     $rs.='</struct>';
  2878.                     break;
  2879.                 case 2:
  2880.                     // array
  2881.                     $rs.="<array>\n<data>\n";
  2882.                     for($i=0$i<count($val)$i++)
  2883.                     {
  2884.                         //$rs.=$this->serializeval($val[$i]);
  2885.                         $rs.=$val[$i]->serialize($charset_encoding);
  2886.                     }
  2887.                     $rs.="</data>\n</array>";
  2888.                     break;
  2889.                 default:
  2890.                     break;
  2891.             }
  2892.             return $rs;
  2893.         }
  2894.  
  2895.         /**
  2896.         * Returns xml representation of the value. XML prologue not included
  2897.         * @param string $charset_encoding the charset to be used for serialization. if null, US-ASCII is assumed
  2898.         * @return string 
  2899.         * @access public
  2900.         */
  2901.         function serialize($charset_encoding='')
  2902.         {
  2903.             // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...
  2904.             //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
  2905.             //{
  2906.                 reset($this->me);
  2907.                 list($typ$valeach($this->me);
  2908.                 return '<value>' $this->serializedata($typ$val$charset_encoding"</value>\n";
  2909.             //}
  2910.         }
  2911.  
  2912.         // DEPRECATED
  2913.         function serializeval($o)
  2914.         {
  2915.             // add check? slower, but helps to avoid recursion in serializing broken xmlrpcvals...
  2916.             //if (is_object($o) && (get_class($o) == 'xmlrpcval' || is_subclass_of($o, 'xmlrpcval')))
  2917.             //{
  2918.                 $ar=$o->me;
  2919.                 reset($ar);
  2920.                 list($typ$valeach($ar);
  2921.                 return '<value>' $this->serializedata($typ$val"</value>\n";
  2922.             //}
  2923.         }
  2924.  
  2925.         /**
  2926.         * Checks wheter a struct member with a given name is present.
  2927.         * Works only on xmlrpcvals of type struct.
  2928.         * @param string $m the name of the struct member to be looked up
  2929.         * @return boolean 
  2930.         * @access public
  2931.         */
  2932.         function structmemexists($m)
  2933.         {
  2934.             return array_key_exists($m$this->me['struct']);
  2935.         }
  2936.  
  2937.         /**
  2938.         * Returns the value of a given struct member (an xmlrpcval object in itself).
  2939.         * Will raise a php warning if struct member of given name does not exist
  2940.         * @param string $m the name of the struct member to be looked up
  2941.         * @return xmlrpcval 
  2942.         * @access public
  2943.         */
  2944.         function structmem($m)
  2945.         {
  2946.             return $this->me['struct'][$m];
  2947.         }
  2948.  
  2949.         /**
  2950.         * Reset internal pointer for xmlrpcvals of type struct.
  2951.         * @access public
  2952.         */
  2953.         function structreset()
  2954.         {
  2955.             reset($this->me['struct']);
  2956.         }
  2957.  
  2958.         /**
  2959.         * Return next member element for xmlrpcvals of type struct.
  2960.         * @return xmlrpcval 
  2961.         * @access public
  2962.         */
  2963.         function structeach()
  2964.         {
  2965.             return each($this->me['struct']);
  2966.         }
  2967.  
  2968.         // DEPRECATED! this code looks like it is very fragile and has not been fixed
  2969.         // for a long long time. Shall we remove it for 2.0?
  2970.         function getval()
  2971.         {
  2972.             // UNSTABLE
  2973.             reset($this->me);
  2974.             list($a,$b)=each($this->me);
  2975.             // contributed by I Sofer, 2001-03-24
  2976.             // add support for nested arrays to scalarval
  2977.             // i've created a new method here, so as to
  2978.             // preserve back compatibility
  2979.  
  2980.             if(is_array($b))
  2981.             {
  2982.                 @reset($b);
  2983.                 while(list($id,$cont@each($b))
  2984.                 {
  2985.                     $b[$id$cont->scalarval();
  2986.                 }
  2987.             }
  2988.  
  2989.             // add support for structures directly encoding php objects
  2990.             if(is_object($b))
  2991.             {
  2992.                 $t get_object_vars($b);
  2993.                 @reset($t);
  2994.                 while(list($id,$cont@each($t))
  2995.                 {
  2996.                     $t[$id$cont->scalarval();
  2997.                 }
  2998.                 @reset($t);
  2999.                 while(list($id,$cont@each($t))
  3000.                 {
  3001.                     @$b->$id $cont;
  3002.                 }
  3003.             }
  3004.             // end contrib
  3005.             return $b;
  3006.         }
  3007.  
  3008.         /**
  3009.         * Returns the value of a scalar xmlrpcval
  3010.         * @return mixed 
  3011.         * @access public
  3012.         */
  3013.         function scalarval()
  3014.         {
  3015.             reset($this->me);
  3016.             list(,$b)=each($this->me);
  3017.             return $b;
  3018.         }
  3019.  
  3020.         /**
  3021.         * Returns the type of the xmlrpcval.
  3022.         * For integers, 'int' is always returned in place of 'i4'
  3023.         * @return string 
  3024.         * @access public
  3025.         */
  3026.         function scalartyp()
  3027.         {
  3028.             reset($this->me);
  3029.             list($a,)=each($this->me);
  3030.             if($a==$GLOBALS['xmlrpcI4'])
  3031.             {
  3032.                 $a=$GLOBALS['xmlrpcInt'];
  3033.             }
  3034.             return $a;
  3035.         }
  3036.  
  3037.         /**
  3038.         * Returns the m-th member of an xmlrpcval of struct type
  3039.         * @param integer $m the index of the value to be retrieved (zero based)
  3040.         * @return xmlrpcval 
  3041.         * @access public
  3042.         */
  3043.         function arraymem($m)
  3044.         {
  3045.             return $this->me['array'][$m];
  3046.         }
  3047.  
  3048.         /**
  3049.         * Returns the number of members in an xmlrpcval of array type
  3050.         * @return integer 
  3051.         * @access public
  3052.         */
  3053.         function arraysize()
  3054.         {
  3055.             return count($this->me['array']);
  3056.         }
  3057.  
  3058.         /**
  3059.         * Returns the number of members in an xmlrpcval of struct type
  3060.         * @return integer 
  3061.         * @access public
  3062.         */
  3063.         function structsize()
  3064.         {
  3065.             return count($this->me['struct']);
  3066.         }
  3067.     }
  3068.  
  3069.  
  3070.     // date helpers
  3071.  
  3072.     /**
  3073.     * Given a timestamp, return the corresponding ISO8601 encoded string.
  3074.     *
  3075.     * Really, timezones ought to be supported
  3076.     * but the XML-RPC spec says:
  3077.     *
  3078.     * "Don't assume a timezone. It should be specified by the server in its
  3079.     * documentation what assumptions it makes about timezones."
  3080.     *
  3081.     * These routines always assume localtime unless
  3082.     * $utc is set to 1, in which case UTC is assumed
  3083.     * and an adjustment for locale is made when encoding
  3084.     *
  3085.     * @param int $timet (timestamp)
  3086.     * @param int $utc (0 or 1)
  3087.     * @return string 
  3088.     */
  3089.     function iso8601_encode($timet$utc=0)
  3090.     {
  3091.         if(!$utc)
  3092.         {
  3093.             $t=strftime("%Y%m%dT%H:%M:%S"$timet);
  3094.         }
  3095.         else
  3096.         {
  3097.             if(function_exists('gmstrftime'))
  3098.             {
  3099.                 // gmstrftime doesn't exist in some versions
  3100.                 // of PHP
  3101.                 $t=gmstrftime("%Y%m%dT%H:%M:%S"$timet);
  3102.             }
  3103.             else
  3104.             {
  3105.                 $t=strftime("%Y%m%dT%H:%M:%S"$timet-date('Z'));
  3106.             }
  3107.         }
  3108.         return $t;
  3109.     }
  3110.  
  3111.     /**
  3112.     * Given an ISO8601 date string, return a timet in the localtime, or UTC
  3113.     * @param string $idate 
  3114.     * @param int $utc either 0 or 1
  3115.     * @return int (datetime)
  3116.     */
  3117.     function iso8601_decode($idate$utc=0)
  3118.     {
  3119.         $t=0;
  3120.         if(preg_match('/([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})/'$idate$regs))
  3121.         {
  3122.             if($utc)
  3123.             {
  3124.                 $t=gmmktime($regs[4]$regs[5]$regs[6]$regs[2]$regs[3]$regs[1]);
  3125.             }
  3126.             else
  3127.             {
  3128.                 $t=mktime($regs[4]$regs[5]$regs[6]$regs[2]$regs[3]$regs[1]);
  3129.             }
  3130.         }
  3131.         return $t;
  3132.     }
  3133.  
  3134.     /**
  3135.     * Takes an xmlrpc value in PHP xmlrpcval object format and translates it into native PHP types.
  3136.     *
  3137.     * Works with xmlrpc message objects as input, too.
  3138.     *
  3139.     * Given proper options parameter, can rebuild generic php object instances
  3140.     * (provided those have been encoded to xmlrpc format using a corresponding
  3141.     * option in php_xmlrpc_encode())
  3142.     * PLEASE NOTE that rebuilding php objects involves calling their constructor function.
  3143.     * This means that the remote communication end can decide which php code will
  3144.     * get executed on your server, leaving the door possibly open to 'php-injection'
  3145.     * style of attacks (provided you have some classes defined on your server that
  3146.     * might wreak havoc if instances are built outside an appropriate context).
  3147.     * Make sure you trust the remote server/client before eanbling this!
  3148.     *
  3149.     * @author Dan Libby (dan@libby.com)
  3150.     *
  3151.     * @param xmlrpcval $xmlrpc_val 
  3152.     * @param array $options if 'decode_php_objs' is set in the options array, xmlrpc structs can be decoded into php objects
  3153.     * @return mixed 
  3154.     */
  3155.     function php_xmlrpc_decode($xmlrpc_val$options=array())
  3156.     {
  3157.         switch($xmlrpc_val->kindOf())
  3158.         {
  3159.             case 'scalar':
  3160.                 if (in_array('extension_api'$options))
  3161.                 {
  3162.                     reset($xmlrpc_val->me);
  3163.                     list($typ,$valeach($xmlrpc_val->me);
  3164.                     switch ($typ)
  3165.                     {
  3166.                         case 'dateTime.iso8601':
  3167.                             $xmlrpc_val->scalar $val;
  3168.                             $xmlrpc_val->xmlrpc_type 'datetime';
  3169.                             $xmlrpc_val->timestamp iso8601_decode($val);
  3170.                             return $xmlrpc_val;
  3171.                         case 'base64':
  3172.                             $xmlrpc_val->scalar $val;
  3173.                             $xmlrpc_val->type $typ;
  3174.                             return $xmlrpc_val;
  3175.                         default:
  3176.                             return $xmlrpc_val->scalarval();
  3177.                     }
  3178.                 }
  3179.                 return $xmlrpc_val->scalarval();
  3180.             case 'array':
  3181.                 $size $xmlrpc_val->arraysize();
  3182.                 $arr array();
  3183.                 for($i 0$i $size$i++)
  3184.                 {
  3185.                     $arr[php_xmlrpc_decode($xmlrpc_val->arraymem($i)$options);
  3186.                 }
  3187.                 return $arr;
  3188.             case 'struct':
  3189.                 $xmlrpc_val->structreset();
  3190.                 // If user said so, try to rebuild php objects for specific struct vals.
  3191.                 /// @todo should we raise a warning for class not found?
  3192.                 // shall we check for proper subclass of xmlrpcval instead of
  3193.                 // presence of _php_class to detect what we can do?
  3194.                 if (in_array('decode_php_objs'$options&& $xmlrpc_val->_php_class != ''
  3195.                     && class_exists($xmlrpc_val->_php_class))
  3196.                 {
  3197.                     $obj @new $xmlrpc_val->_php_class;
  3198.                     while(list($key,$value)=$xmlrpc_val->structeach())
  3199.                     {
  3200.                         $obj->$key php_xmlrpc_decode($value$options);
  3201.                     }
  3202.                     return $obj;
  3203.                 }
  3204.                 else
  3205.                 {
  3206.                     $arr array();
  3207.                     while(list($key,$value)=$xmlrpc_val->structeach())
  3208.                     {
  3209.                         $arr[$keyphp_xmlrpc_decode($value$options);
  3210.                     }
  3211.                     return $arr;
  3212.                 }
  3213.             case 'msg':
  3214.                 $paramcount $xmlrpc_val->getNumParams();
  3215.                 $arr array();
  3216.                 for($i 0$i $paramcount$i++)
  3217.                 {
  3218.                     $arr[php_xmlrpc_decode($xmlrpc_val->getParam($i));
  3219.                 }
  3220.                 return $arr;
  3221.             }
  3222.     }
  3223.  
  3224.     // This constant left here only for historical reasons...
  3225.     // it was used to decide if we have to define xmlrpc_encode on our own, but
  3226.     // we do not do it anymore
  3227.     if(function_exists('xmlrpc_decode'))
  3228.     {
  3229.         define('XMLRPC_EPI_ENABLED','1');
  3230.     }
  3231.     else
  3232.     {
  3233.         define('XMLRPC_EPI_ENABLED','0');
  3234.     }
  3235.  
  3236.     /**
  3237.     * Takes native php types and encodes them into xmlrpc PHP object format.
  3238.     * It will not re-encode xmlrpcval objects.
  3239.     *
  3240.     * Feature creep -- could support more types via optional type argument
  3241.     * (string => datetime support has been added, ??? => base64 not yet)
  3242.     *
  3243.     * If given a proper options parameter, php object instances will be encoded
  3244.     * into 'special' xmlrpc values, that can later be decoded into php objects
  3245.     * by calling php_xmlrpc_decode() with a corresponding option
  3246.     *
  3247.     * @author Dan Libby (dan@libby.com)
  3248.     *
  3249.     * @param mixed $php_val the value to be converted into an xmlrpcval object
  3250.     * @param array $options    can include 'encode_php_objs', 'auto_dates', 'null_extension' or 'extension_api'
  3251.     * @return xmlrpcval 
  3252.     */
  3253.     function &php_xmlrpc_encode($php_val$options=array())
  3254.     {
  3255.         $type gettype($php_val);
  3256.         switch($type)
  3257.         {
  3258.             case 'string':
  3259.                 if (in_array('auto_dates'$options&& preg_match('/^[0-9]{8}T[0-9]{2}:[0-9]{2}:[0-9]{2}$/'$php_val))
  3260.                     $xmlrpc_val =new xmlrpcval($php_val$GLOBALS['xmlrpcDateTime']);
  3261.                 else
  3262.                     $xmlrpc_val =new xmlrpcval($php_val$GLOBALS['xmlrpcString']);
  3263.                 break;
  3264.             case 'integer':
  3265.                 $xmlrpc_val =new xmlrpcval($php_val$GLOBALS['xmlrpcInt']);
  3266.                 break;
  3267.             case 'double':
  3268.                 $xmlrpc_val =new xmlrpcval($php_val$GLOBALS['xmlrpcDouble']);
  3269.                 break;
  3270.                 // <G_Giunta_2001-02-29>
  3271.                 // Add support for encoding/decoding of booleans, since they are supported in PHP
  3272.             case 'boolean':
  3273.                 $xmlrpc_val =new xmlrpcval($php_val$GLOBALS['xmlrpcBoolean']);
  3274.                 break;
  3275.                 // </G_Giunta_2001-02-29>
  3276.             case 'array':
  3277.                 // PHP arrays can be encoded to either xmlrpc structs or arrays,
  3278.                 // depending on wheter they are hashes or plain 0..n integer indexed
  3279.                 // A shorter one-liner would be
  3280.                 // $tmp = array_diff(array_keys($php_val), range(0, count($php_val)-1));
  3281.                 // but execution time skyrockets!
  3282.                 $j 0;
  3283.                 $arr array();
  3284.                 $ko false;
  3285.                 foreach($php_val as $key => $val)
  3286.                 {
  3287.                     $arr[$key=php_xmlrpc_encode($val$options);
  3288.                     if(!$ko && $key !== $j)
  3289.                     {
  3290.                         $ko true;
  3291.                     }
  3292.                     $j++;
  3293.                 }
  3294.                 if($ko)
  3295.                 {
  3296.                     $xmlrpc_val =new xmlrpcval($arr$GLOBALS['xmlrpcStruct']);
  3297.                 }
  3298.                 else
  3299.                 {
  3300.                     $xmlrpc_val =new xmlrpcval($arr$GLOBALS['xmlrpcArray']);
  3301.                 }
  3302.                 break;
  3303.             case 'object':
  3304.                 if(is_a($php_val'xmlrpcval'))
  3305.                 {
  3306.                     $xmlrpc_val $php_val;
  3307.                 }
  3308.                 else
  3309.                 {
  3310.                     $arr array();
  3311.                     while(list($k,$veach($php_val))
  3312.                     {
  3313.                         $arr[$kphp_xmlrpc_encode($v$options);
  3314.                     }
  3315.                     $xmlrpc_val =new xmlrpcval($arr$GLOBALS['xmlrpcStruct']);
  3316.                     if (in_array('encode_php_objs'$options))
  3317.                     {
  3318.                         // let's save original class name into xmlrpcval:
  3319.                         // might be useful later on...
  3320.                         $xmlrpc_val->_php_class get_class($php_val);
  3321.                     }
  3322.                 }
  3323.                 break;
  3324.             case 'NULL':
  3325.                 if (in_array('extension_api'$options))
  3326.                 {
  3327.                     $xmlrpc_val =new xmlrpcval(''$GLOBALS['xmlrpcString']);
  3328.                 }
  3329.                 if (in_array('null_extension'$options))
  3330.                 {
  3331.                     $xmlrpc_val =new xmlrpcval(''$GLOBALS['xmlrpcNull']);
  3332.                 }
  3333.                 else
  3334.                 {
  3335.                     $xmlrpc_val =new xmlrpcval();
  3336.                 }
  3337.                 break;
  3338.             case 'resource':
  3339.                 if (in_array('extension_api'$options))
  3340.                 {
  3341.                     $xmlrpc_val =new xmlrpcval((int)$php_val$GLOBALS['xmlrpcInt']);
  3342.                 }
  3343.                 else
  3344.                 {
  3345.                     $xmlrpc_val =new xmlrpcval();
  3346.                 }
  3347.             // catch "user function", "unknown type"
  3348.             default:
  3349.                 // giancarlo pinerolo <ping@alt.it>
  3350.                 // it has to return
  3351.                 // an empty object in case, not a boolean.
  3352.                 $xmlrpc_val =new xmlrpcval();
  3353.                 break;
  3354.             }
  3355.             return $xmlrpc_val;
  3356.     }
  3357.  
  3358.     /**
  3359.     * Convert the xml representation of a method response, method request or single
  3360.     * xmlrpc value into the appropriate object (a.k.a. deserialize)
  3361.     * @param string $xml_val 
  3362.     * @param array $options 
  3363.     * @return mixed false on error, or an instance of either xmlrpcval, xmlrpcmsg or xmlrpcresp
  3364.     */
  3365.     function php_xmlrpc_decode_xml($xml_val$options=array())
  3366.     {
  3367.         $GLOBALS['_xh'array();
  3368.         $GLOBALS['_xh']['ac''';
  3369.         $GLOBALS['_xh']['stack'array();
  3370.         $GLOBALS['_xh']['valuestack'array();
  3371.         $GLOBALS['_xh']['params'array();
  3372.         $GLOBALS['_xh']['pt'array();
  3373.         $GLOBALS['_xh']['isf'0;
  3374.         $GLOBALS['_xh']['isf_reason''';
  3375.         $GLOBALS['_xh']['method'false;
  3376.         $GLOBALS['_xh']['rt''';
  3377.         /// @todo 'guestimate' encoding
  3378.         $parser xml_parser_create();
  3379.         xml_parser_set_option($parserXML_OPTION_CASE_FOLDINGtrue);
  3380.         xml_parser_set_option($parserXML_OPTION_TARGET_ENCODING$GLOBALS['xmlrpc_internalencoding']);
  3381.         xml_set_element_handler($parser'xmlrpc_se_any''xmlrpc_ee');
  3382.         xml_set_character_data_handler($parser'xmlrpc_cd');
  3383.         xml_set_default_handler($parser'xmlrpc_dh');
  3384.         if(!xml_parse($parser$xml_val1))
  3385.         {
  3386.             $errstr sprintf('XML error: %s at line %d, column %d',
  3387.                         xml_error_string(xml_get_error_code($parser)),
  3388.                         xml_get_current_line_number($parser)xml_get_current_column_number($parser));
  3389.             error_log($errstr);
  3390.             xml_parser_free($parser);
  3391.             return false;
  3392.         }
  3393.         xml_parser_free($parser);
  3394.         if ($GLOBALS['_xh']['isf'1// test that $GLOBALS['_xh']['value'] is an obj, too???
  3395.         {
  3396.             error_log($GLOBALS['_xh']['isf_reason']);
  3397.             return false;
  3398.         }
  3399.         switch ($GLOBALS['_xh']['rt'])
  3400.         {
  3401.             case 'methodresponse':
  3402.                 $v =$GLOBALS['_xh']['value'];
  3403.                 if ($GLOBALS['_xh']['isf'== 1)
  3404.                 {
  3405.                     $vc $v->structmem('faultCode');
  3406.                     $vs $v->structmem('faultString');
  3407.                     $r =new xmlrpcresp(0$vc->scalarval()$vs->scalarval());
  3408.                 }
  3409.                 else
  3410.                 {
  3411.                     $r =new xmlrpcresp($v);
  3412.                 }
  3413.                 return $r;
  3414.             case 'methodcall':
  3415.                 $m =new xmlrpcmsg($GLOBALS['_xh']['method']);
  3416.                 for($i=0$i count($GLOBALS['_xh']['params'])$i++)
  3417.                 {
  3418.                     $m->addParam($GLOBALS['_xh']['params'][$i]);
  3419.                 }
  3420.                 return $m;
  3421.             case 'value':
  3422.                 return $GLOBALS['_xh']['value'];
  3423.             default:
  3424.                 return false;
  3425.         }
  3426.     }
  3427.  
  3428.     /**
  3429.     * decode a string that is encoded w/ "chunked" transfer encoding
  3430.     * as defined in rfc2068 par. 19.4.6
  3431.     * code shamelessly stolen from nusoap library by Dietrich Ayala
  3432.     *
  3433.     * @param string $buffer the string to be decoded
  3434.     * @return string 
  3435.     */
  3436.     function decode_chunked($buffer)
  3437.     {
  3438.         // length := 0
  3439.         $length 0;
  3440.         $new '';
  3441.  
  3442.         // read chunk-size, chunk-extension (if any) and crlf
  3443.         // get the position of the linebreak
  3444.         $chunkend strpos($buffer,"\r\n"2;
  3445.         $temp substr($buffer,0,$chunkend);
  3446.         $chunk_size hexdectrim($temp) );
  3447.         $chunkstart $chunkend;
  3448.         while($chunk_size 0)
  3449.         {
  3450.             $chunkend strpos($buffer"\r\n"$chunkstart $chunk_size);
  3451.  
  3452.             // just in case we got a broken connection
  3453.             if($chunkend == false)
  3454.             {
  3455.                 $chunk substr($buffer,$chunkstart);
  3456.                 // append chunk-data to entity-body
  3457.                 $new .= $chunk;
  3458.                 $length += strlen($chunk);
  3459.                 break;
  3460.             }
  3461.  
  3462.             // read chunk-data and crlf
  3463.             $chunk substr($buffer,$chunkstart,$chunkend-$chunkstart);
  3464.             // append chunk-data to entity-body
  3465.             $new .= $chunk;
  3466.             // length := length + chunk-size
  3467.             $length += strlen($chunk);
  3468.             // read chunk-size and crlf
  3469.             $chunkstart $chunkend 2;
  3470.  
  3471.             $chunkend strpos($buffer,"\r\n",$chunkstart)+2;
  3472.             if($chunkend == false)
  3473.             {
  3474.                 break//just in case we got a broken connection
  3475.             }
  3476.             $temp substr($buffer,$chunkstart,$chunkend-$chunkstart);
  3477.             $chunk_size hexdectrim($temp) );
  3478.             $chunkstart $chunkend;
  3479.         }
  3480.         return $new;
  3481.     }
  3482.  
  3483.     /**
  3484.     * xml charset encoding guessing helper function.
  3485.     * Tries to determine the charset encoding of an XML chunk
  3486.     * received over HTTP.
  3487.     * NB: according to the spec (RFC 3023, if text/xml content-type is received over HTTP without a content-type,
  3488.     * we SHOULD assume it is strictly US-ASCII. But we try to be more tolerant of unconforming (legacy?) clients/servers,
  3489.     * which will be most probably using UTF-8 anyway...
  3490.     *
  3491.     * @param string $httpheaders the http Content-type header
  3492.     * @param string $xmlchunk xml content buffer
  3493.     * @param string $encoding_prefs comma separated list of character encodings to be used as default (when mb extension is enabled)
  3494.     *
  3495.     * @todo explore usage of mb_http_input(): does it detect http headers + post data? if so, use it instead of hand-detection!!!
  3496.     */
  3497.     function guess_encoding($httpheader=''$xmlchunk=''$encoding_prefs=null)
  3498.     {
  3499.         // discussion: see http://www.yale.edu/pclt/encoding/
  3500.         // 1 - test if encoding is specified in HTTP HEADERS
  3501.  
  3502.         //Details:
  3503.         // LWS:           (\13\10)?( |\t)+
  3504.         // token:         (any char but excluded stuff)+
  3505.         // header:        Content-type = ...; charset=value(; ...)*
  3506.         //   where value is of type token, no LWS allowed between 'charset' and value
  3507.         // Note: we do not check for invalid chars in VALUE:
  3508.         //   this had better be done using pure ereg as below
  3509.  
  3510.         /// @todo this test will pass if ANY header has charset specification, not only Content-Type. Fix it?
  3511.         $matches array();
  3512.         if(preg_match('/;\s*charset=([^;]+)/i'$httpheader$matches))
  3513.         {
  3514.             return strtoupper(trim($matches[1]));
  3515.         }
  3516.  
  3517.         // 2 - scan the first bytes of the data for a UTF-16 (or other) BOM pattern
  3518.         //     (source: http://www.w3.org/TR/2000/REC-xml-20001006)
  3519.         //     NOTE: actually, according to the spec, even if we find the BOM and determine
  3520.         //     an encoding, we should check if there is an encoding specified
  3521.         //     in the xml declaration, and verify if they match.
  3522.         /// @todo implement check as described above?
  3523.         /// @todo implement check for first bytes of string even without a BOM? (It sure looks harder than for cases WITH a BOM)
  3524.         if(preg_match('/^(\x00\x00\xFE\xFF|\xFF\xFE\x00\x00|\x00\x00\xFF\xFE|\xFE\xFF\x00\x00)/'$xmlchunk))
  3525.         {
  3526.             return 'UCS-4';
  3527.         }
  3528.         elseif(preg_match('/^(\xFE\xFF|\xFF\xFE)/'$xmlchunk))
  3529.         {
  3530.             return 'UTF-16';
  3531.         }
  3532.         elseif(preg_match('/^(\xEF\xBB\xBF)/'$xmlchunk))
  3533.         {
  3534.             return 'UTF-8';
  3535.         }
  3536.  
  3537.         // 3 - test if encoding is specified in the xml declaration
  3538.         // Details:
  3539.         // SPACE:         (#x20 | #x9 | #xD | #xA)+ === [ \x9\xD\xA]+
  3540.         // EQ:            SPACE?=SPACE? === [ \x9\xD\xA]*=[ \x9\xD\xA]*
  3541.         if (preg_match('/^<\?xml\s+version\s*=\s*'"((?:\"[a-zA-Z0-9_.:-]+\")|(?:'[a-zA-Z0-9_.:-]+'))".
  3542.             '\s+encoding\s*=\s*' "((?:\"[A-Za-z][A-Za-z0-9._-]*\")|(?:'[A-Za-z][A-Za-z0-9._-]*'))/",
  3543.             $xmlchunk$matches))
  3544.         {
  3545.             return strtoupper(substr($matches[2]1-1));
  3546.         }
  3547.  
  3548.         // 4 - if mbstring is available, let it do the guesswork
  3549.         // NB: we favour finding an encoding that is compatible with what we can process
  3550.         if(extension_loaded('mbstring'))
  3551.         {
  3552.             if($encoding_prefs)
  3553.             {
  3554.                 $enc mb_detect_encoding($xmlchunk$encoding_prefs);
  3555.             }
  3556.             else
  3557.             {
  3558.                 $enc mb_detect_encoding($xmlchunk);
  3559.             }
  3560.             // NB: mb_detect likes to call it ascii, xml parser likes to call it US_ASCII...
  3561.             // IANA also likes better US-ASCII, so go with it
  3562.             if($enc == 'ASCII')
  3563.             {
  3564.                 $enc 'US-'.$enc;
  3565.             }
  3566.             return $enc;
  3567.         }
  3568.         else
  3569.         {
  3570.             // no encoding specified: as per HTTP1.1 assume it is iso-8859-1?
  3571.             // Both RFC 2616 (HTTP 1.1) and 1945(http 1.0) clearly state that for text/xxx content types
  3572.             // this should be the standard. And we should be getting text/xml as request and response.
  3573.             // BUT we have to be backward compatible with the lib, which always used UTF-8 as default...
  3574.             return $GLOBALS['xmlrpc_defencoding'];
  3575.         }
  3576.     }
  3577.  
  3578.     /**
  3579.     * Checks if a given charset encoding is present in a list of encodings or
  3580.     * if it is a valid subset of any encoding in the list
  3581.     * @param string $encoding charset to be tested
  3582.     * @param mixed $validlist comma separated list of valid charsets (or array of charsets)
  3583.     */
  3584.     function is_valid_charset($encoding$validlist)
  3585.     {
  3586.         $charset_supersets array(
  3587.             'US-ASCII' => array ('ISO-8859-1''ISO-8859-2''ISO-8859-3''ISO-8859-4',
  3588.                 'ISO-8859-5''ISO-8859-6''ISO-8859-7''ISO-8859-8',
  3589.                 'ISO-8859-9''ISO-8859-10''ISO-8859-11''ISO-8859-12',
  3590.                 'ISO-8859-13''ISO-8859-14''ISO-8859-15''UTF-8',
  3591.                 'EUC-JP''EUC-''EUC-KR''EUC-CN')
  3592.         );
  3593.         if (is_string($validlist))
  3594.             $validlist explode(','$validlist);
  3595.         if (@in_array(strtoupper($encoding)$validlist))
  3596.             return true;
  3597.         else
  3598.         {
  3599.             if (array_key_exists($encoding$charset_supersets))
  3600.                 foreach ($validlist as $allowed)
  3601.                     if (in_array($allowed$charset_supersets[$encoding]))
  3602.                         return true;
  3603.                 return false;
  3604.         }
  3605.     }
  3606.  
  3607. /*
  3608.  * $Log: _xmlrpc.inc.php,v $
  3609.  * Revision 1.1  2008/01/14 07:17:31  fplanque
  3610.  * Upgraded XML-RPC for PHP library
  3611.  *
  3612.  */
  3613. ?>

Documentation generated on Sat, 06 Mar 2010 03:43:18 +0100 by phpDocumentor 1.4.2. This site is hosted and maintained by Daniel HAHLER (Contact).