[ Index ]

PHP Cross Reference of Joomla 1.5.26 DE

title

Body

[close]

/libraries/phpxmlrpc/ -> xmlrpcs.php (source)

   1  <?php
   2  // by Edd Dumbill (C) 1999-2002
   3  // <edd@usefulinc.com>
   4  // $Id: xmlrpcs.inc,v 1.67 2007/05/22 21:31:58 ggiunta 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  // Do not allow direct access
  39  defined( '_JEXEC' ) or die( 'Restricted access' );
  40  
  41      // XML RPC Server class
  42      // requires: xmlrpc.inc
  43  
  44      $GLOBALS['xmlrpcs_capabilities'] = array(
  45          // xmlrpc spec: always supported
  46          'xmlrpc' => new xmlrpcval(array(
  47              'specUrl' => new xmlrpcval('http://www.xmlrpc.com/spec', 'string'),
  48              'specVersion' => new xmlrpcval(1, 'int')
  49          ), 'struct'),
  50          // if we support system.xxx functions, we always support multicall, too...
  51          // Note that, as of 2006/09/17, the following URL does not respond anymore
  52          'system.multicall' => new xmlrpcval(array(
  53              'specUrl' => new xmlrpcval('http://www.xmlrpc.com/discuss/msgReader$1208', 'string'),
  54              'specVersion' => new xmlrpcval(1, 'int')
  55          ), 'struct'),
  56          // introspection: version 2! we support 'mixed', too
  57          'introspection' => new xmlrpcval(array(
  58              'specUrl' => new xmlrpcval('http://phpxmlrpc.sourceforge.net/doc-2/ch10.html', 'string'),
  59              'specVersion' => new xmlrpcval(2, 'int')
  60          ), 'struct')
  61      );
  62  
  63      /* Functions that implement system.XXX methods of xmlrpc servers */
  64      $_xmlrpcs_getCapabilities_sig=array(array($GLOBALS['xmlrpcStruct']));
  65      $_xmlrpcs_getCapabilities_doc='This method lists all the capabilites that the XML-RPC server has: the (more or less standard) extensions to the xmlrpc spec that it adheres to';
  66      $_xmlrpcs_getCapabilities_sdoc=array(array('list of capabilities, described as structs with a version number and url for the spec'));
  67  	function _xmlrpcs_getCapabilities($server, $m=null)
  68      {
  69          $outAr = $GLOBALS['xmlrpcs_capabilities'];
  70          // NIL extension
  71          if ($GLOBALS['xmlrpc_null_extension']) {
  72              $outAr['nil'] = new xmlrpcval(array(
  73                  'specUrl' => new xmlrpcval('http://www.ontosys.com/xml-rpc/extensions.php', 'string'),
  74                  'specVersion' => new xmlrpcval(1, 'int')
  75              ), 'struct');
  76          }
  77          return new xmlrpcresp(new xmlrpcval($outAr, 'struct'));
  78      }
  79  
  80      // listMethods: signature was either a string, or nothing.
  81      // The useless string variant has been removed
  82      $_xmlrpcs_listMethods_sig=array(array($GLOBALS['xmlrpcArray']));
  83      $_xmlrpcs_listMethods_doc='This method lists all the methods that the XML-RPC server knows how to dispatch';
  84      $_xmlrpcs_listMethods_sdoc=array(array('list of method names'));
  85  	function _xmlrpcs_listMethods($server, $m=null) // if called in plain php values mode, second param is missing
  86      {
  87  
  88          $outAr=array();
  89          foreach($server->dmap as $key => $val)
  90          {
  91              $outAr[]=&new xmlrpcval($key, 'string');
  92          }
  93          if($server->allow_system_funcs)
  94          {
  95              foreach($GLOBALS['_xmlrpcs_dmap'] as $key => $val)
  96              {
  97                  $outAr[]=&new xmlrpcval($key, 'string');
  98              }
  99          }
 100          return new xmlrpcresp(new xmlrpcval($outAr, 'array'));
 101      }
 102  
 103      $_xmlrpcs_methodSignature_sig=array(array($GLOBALS['xmlrpcArray'], $GLOBALS['xmlrpcString']));
 104      $_xmlrpcs_methodSignature_doc='Returns an array of known signatures (an array of arrays) for the method name passed. If no signatures are known, returns a none-array (test for type != array to detect missing signature)';
 105      $_xmlrpcs_methodSignature_sdoc=array(array('list of known signatures, each sig being an array of xmlrpc type names', 'name of method to be described'));
 106  	function _xmlrpcs_methodSignature($server, $m)
 107      {
 108          // let accept as parameter both an xmlrpcval or string
 109          if (is_object($m))
 110          {
 111              $methName=$m->getParam(0);
 112              $methName=$methName->scalarval();
 113          }
 114          else
 115          {
 116              $methName=$m;
 117          }
 118          if(strpos($methName, "system.") === 0)
 119          {
 120              $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1;
 121          }
 122          else
 123          {
 124              $dmap=$server->dmap; $sysCall=0;
 125          }
 126          if(isset($dmap[$methName]))
 127          {
 128              if(isset($dmap[$methName]['signature']))
 129              {
 130                  $sigs=array();
 131                  foreach($dmap[$methName]['signature'] as $inSig)
 132                  {
 133                      $cursig=array();
 134                      foreach($inSig as $sig)
 135                      {
 136                          $cursig[]=&new xmlrpcval($sig, 'string');
 137                      }
 138                      $sigs[]=&new xmlrpcval($cursig, 'array');
 139                  }
 140                  $r=&new xmlrpcresp(new xmlrpcval($sigs, 'array'));
 141              }
 142              else
 143              {
 144                  // NB: according to the official docs, we should be returning a
 145                  // "none-array" here, which means not-an-array
 146                  $r=&new xmlrpcresp(new xmlrpcval('undef', 'string'));
 147              }
 148          }
 149          else
 150          {
 151              $r=&new xmlrpcresp(0,$GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']);
 152          }
 153          return $r;
 154      }
 155  
 156      $_xmlrpcs_methodHelp_sig=array(array($GLOBALS['xmlrpcString'], $GLOBALS['xmlrpcString']));
 157      $_xmlrpcs_methodHelp_doc='Returns help text if defined for the method passed, otherwise returns an empty string';
 158      $_xmlrpcs_methodHelp_sdoc=array(array('method description', 'name of the method to be described'));
 159  	function _xmlrpcs_methodHelp($server, $m)
 160      {
 161          // let accept as parameter both an xmlrpcval or string
 162          if (is_object($m))
 163          {
 164              $methName=$m->getParam(0);
 165              $methName=$methName->scalarval();
 166          }
 167          else
 168          {
 169              $methName=$m;
 170          }
 171          if(strpos($methName, "system.") === 0)
 172          {
 173              $dmap=$GLOBALS['_xmlrpcs_dmap']; $sysCall=1;
 174          }
 175          else
 176          {
 177              $dmap=$server->dmap; $sysCall=0;
 178          }
 179          if(isset($dmap[$methName]))
 180          {
 181              if(isset($dmap[$methName]['docstring']))
 182              {
 183                  $r=&new xmlrpcresp(new xmlrpcval($dmap[$methName]['docstring']), 'string');
 184              }
 185              else
 186              {
 187                  $r=&new xmlrpcresp(new xmlrpcval('', 'string'));
 188              }
 189          }
 190          else
 191          {
 192              $r=&new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['introspect_unknown'], $GLOBALS['xmlrpcstr']['introspect_unknown']);
 193          }
 194          return $r;
 195      }
 196  
 197      $_xmlrpcs_multicall_sig = array(array($GLOBALS['xmlrpcArray'], $GLOBALS['xmlrpcArray']));
 198      $_xmlrpcs_multicall_doc = 'Boxcar multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details';
 199      $_xmlrpcs_multicall_sdoc = array(array('list of response structs, where each struct has the usual members', 'list of calls, with each call being represented as a struct, with members "methodname" and "params"'));
 200  	function _xmlrpcs_multicall_error($err)
 201      {
 202          if(is_string($err))
 203          {
 204              $str = $GLOBALS['xmlrpcstr']["multicall_$err}"];
 205              $code = $GLOBALS['xmlrpcerr']["multicall_$err}"];
 206          }
 207          else
 208          {
 209              $code = $err->faultCode();
 210              $str = $err->faultString();
 211          }
 212          $struct = array();
 213          $struct['faultCode'] =& new xmlrpcval($code, 'int');
 214          $struct['faultString'] =& new xmlrpcval($str, 'string');
 215          return new xmlrpcval($struct, 'struct');
 216      }
 217  
 218  	function _xmlrpcs_multicall_do_call($server, $call)
 219      {
 220          if($call->kindOf() != 'struct')
 221          {
 222              return _xmlrpcs_multicall_error('notstruct');
 223          }
 224          $methName = @$call->structmem('methodName');
 225          if(!$methName)
 226          {
 227              return _xmlrpcs_multicall_error('nomethod');
 228          }
 229          if($methName->kindOf() != 'scalar' || $methName->scalartyp() != 'string')
 230          {
 231              return _xmlrpcs_multicall_error('notstring');
 232          }
 233          if($methName->scalarval() == 'system.multicall')
 234          {
 235              return _xmlrpcs_multicall_error('recursion');
 236          }
 237  
 238          $params = @$call->structmem('params');
 239          if(!$params)
 240          {
 241              return _xmlrpcs_multicall_error('noparams');
 242          }
 243          if($params->kindOf() != 'array')
 244          {
 245              return _xmlrpcs_multicall_error('notarray');
 246          }
 247          $numParams = $params->arraysize();
 248  
 249          $msg =& new xmlrpcmsg($methName->scalarval());
 250          for($i = 0; $i < $numParams; $i++)
 251          {
 252              if(!$msg->addParam($params->arraymem($i)))
 253              {
 254                  $i++;
 255                  return _xmlrpcs_multicall_error(new xmlrpcresp(0,
 256                      $GLOBALS['xmlrpcerr']['incorrect_params'],
 257                      $GLOBALS['xmlrpcstr']['incorrect_params'] . ": probable xml error in param " . $i));
 258              }
 259          }
 260  
 261          $result = $server->execute($msg);
 262  
 263          if($result->faultCode() != 0)
 264          {
 265              return _xmlrpcs_multicall_error($result);        // Method returned fault.
 266          }
 267  
 268          return new xmlrpcval(array($result->value()), 'array');
 269      }
 270  
 271  	function _xmlrpcs_multicall_do_call_phpvals($server, $call)
 272      {
 273          if(!is_array($call))
 274          {
 275              return _xmlrpcs_multicall_error('notstruct');
 276          }
 277          if(!array_key_exists('methodName', $call))
 278          {
 279              return _xmlrpcs_multicall_error('nomethod');
 280          }
 281          if (!is_string($call['methodName']))
 282          {
 283              return _xmlrpcs_multicall_error('notstring');
 284          }
 285          if($call['methodName'] == 'system.multicall')
 286          {
 287              return _xmlrpcs_multicall_error('recursion');
 288          }
 289          if(!array_key_exists('params', $call))
 290          {
 291              return _xmlrpcs_multicall_error('noparams');
 292          }
 293          if(!is_array($call['params']))
 294          {
 295              return _xmlrpcs_multicall_error('notarray');
 296          }
 297  
 298          // this is a real dirty and simplistic hack, since we might have received a
 299          // base64 or datetime values, but they will be listed as strings here...
 300          $numParams = count($call['params']);
 301          $pt = array();
 302          foreach($call['params'] as $val)
 303              $pt[] = php_2_xmlrpc_type(gettype($val));
 304  
 305          $result = $server->execute($call['methodName'], $call['params'], $pt);
 306  
 307          if($result->faultCode() != 0)
 308          {
 309              return _xmlrpcs_multicall_error($result);        // Method returned fault.
 310          }
 311  
 312          return new xmlrpcval(array($result->value()), 'array');
 313      }
 314  
 315  	function _xmlrpcs_multicall($server, $m)
 316      {
 317          $result = array();
 318          // let accept a plain list of php parameters, beside a single xmlrpc msg object
 319          if (is_object($m))
 320          {
 321              $calls = $m->getParam(0);
 322              $numCalls = $calls->arraysize();
 323              for($i = 0; $i < $numCalls; $i++)
 324              {
 325                  $call = $calls->arraymem($i);
 326                  $result[$i] = _xmlrpcs_multicall_do_call($server, $call);
 327              }
 328          }
 329          else
 330          {
 331              $numCalls=count($m);
 332              for($i = 0; $i < $numCalls; $i++)
 333              {
 334                  $result[$i] = _xmlrpcs_multicall_do_call_phpvals($server, $m[$i]);
 335              }
 336          }
 337  
 338          return new xmlrpcresp(new xmlrpcval($result, 'array'));
 339      }
 340  
 341      $GLOBALS['_xmlrpcs_dmap']=array(
 342          'system.listMethods' => array(
 343              'function' => '_xmlrpcs_listMethods',
 344              'signature' => $_xmlrpcs_listMethods_sig,
 345              'docstring' => $_xmlrpcs_listMethods_doc,
 346              'signature_docs' => $_xmlrpcs_listMethods_sdoc),
 347          'system.methodHelp' => array(
 348              'function' => '_xmlrpcs_methodHelp',
 349              'signature' => $_xmlrpcs_methodHelp_sig,
 350              'docstring' => $_xmlrpcs_methodHelp_doc,
 351              'signature_docs' => $_xmlrpcs_methodHelp_sdoc),
 352          'system.methodSignature' => array(
 353              'function' => '_xmlrpcs_methodSignature',
 354              'signature' => $_xmlrpcs_methodSignature_sig,
 355              'docstring' => $_xmlrpcs_methodSignature_doc,
 356              'signature_docs' => $_xmlrpcs_methodSignature_sdoc),
 357          'system.multicall' => array(
 358              'function' => '_xmlrpcs_multicall',
 359              'signature' => $_xmlrpcs_multicall_sig,
 360              'docstring' => $_xmlrpcs_multicall_doc,
 361              'signature_docs' => $_xmlrpcs_multicall_sdoc),
 362          'system.getCapabilities' => array(
 363              'function' => '_xmlrpcs_getCapabilities',
 364              'signature' => $_xmlrpcs_getCapabilities_sig,
 365              'docstring' => $_xmlrpcs_getCapabilities_doc,
 366              'signature_docs' => $_xmlrpcs_getCapabilities_sdoc)
 367      );
 368  
 369      $GLOBALS['_xmlrpcs_occurred_errors'] = '';
 370      $GLOBALS['_xmlrpcs_prev_ehandler'] = '';
 371      /**
 372      * Error handler used to track errors that occur during server-side execution of PHP code.
 373      * This allows to report back to the client whether an internal error has occurred or not
 374      * using an xmlrpc response object, instead of letting the client deal with the html junk
 375      * that a PHP execution error on the server generally entails.
 376      *
 377      * NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors.
 378      *
 379      */
 380  	function _xmlrpcs_errorHandler($errcode, $errstring, $filename=null, $lineno=null, $context=null)
 381      {
 382          // obey the @ protocol
 383          if (error_reporting() == 0)
 384              return;
 385  
 386          //if($errcode != E_NOTICE && $errcode != E_WARNING && $errcode != E_USER_NOTICE && $errcode != E_USER_WARNING)
 387          if($errcode != 2048) // do not use E_STRICT by name, since on PHP 4 it will not be defined
 388          {
 389              $GLOBALS['_xmlrpcs_occurred_errors'] = $GLOBALS['_xmlrpcs_occurred_errors'] . $errstring . "\n";
 390          }
 391          // Try to avoid as much as possible disruption to the previous error handling
 392          // mechanism in place
 393          if($GLOBALS['_xmlrpcs_prev_ehandler'] == '')
 394          {
 395              // The previous error handler was the default: all we should do is log error
 396              // to the default error log (if level high enough)
 397              if(ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errcode))
 398              {
 399                  error_log($errstring);
 400              }
 401          }
 402          else
 403          {
 404              // Pass control on to previous error handler, trying to avoid loops...
 405              if($GLOBALS['_xmlrpcs_prev_ehandler'] != '_xmlrpcs_errorHandler')
 406              {
 407                  // NB: this code will NOT work on php < 4.0.2: only 2 params were used for error handlers
 408                  if(is_array($GLOBALS['_xmlrpcs_prev_ehandler']))
 409                  {
 410                      $GLOBALS['_xmlrpcs_prev_ehandler'][0]->$GLOBALS['_xmlrpcs_prev_ehandler'][1]($errcode, $errstring, $filename, $lineno, $context);
 411                  }
 412                  else
 413                  {
 414                      $GLOBALS['_xmlrpcs_prev_ehandler']($errcode, $errstring, $filename, $lineno, $context);
 415                  }
 416              }
 417          }
 418      }
 419  
 420      $GLOBALS['_xmlrpc_debuginfo']='';
 421  
 422      /**
 423      * Add a string to the debug info that can be later seralized by the server
 424      * as part of the response message.
 425      * Note that for best compatbility, the debug string should be encoded using
 426      * the $GLOBALS['xmlrpc_internalencoding'] character set.
 427      * @param string $m
 428      * @access public
 429      */
 430  	function xmlrpc_debugmsg($m)
 431      {
 432          $GLOBALS['_xmlrpc_debuginfo'] .= $m . "\n";
 433      }
 434  
 435      class xmlrpc_server
 436      {
 437          /// array defining php functions exposed as xmlrpc methods by this server
 438          var $dmap=array();
 439          /**
 440          * Defines how functions in dmap will be invokde: either using an xmlrpc msg object
 441          * or plain php values.
 442          * valid strings are 'xmlrpcvals', 'phpvals' or 'epivals'
 443          */
 444          var $functions_parameters_type='xmlrpcvals';
 445          /// controls wether the server is going to echo debugging messages back to the client as comments in response body. valid values: 0,1,2,3
 446          var $debug = 1;
 447          /**
 448          * When set to true, it will enable HTTP compression of the response, in case
 449          * the client has declared its support for compression in the request.
 450          */
 451          var $compress_response = false;
 452          /**
 453          * List of http compression methods accepted by the server for requests.
 454          * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib
 455          */
 456          var $accepted_compression = array();
 457          /// shall we serve calls to system.* methods?
 458          var $allow_system_funcs = true;
 459          /// list of charset encodings natively accepted for requests
 460          var $accepted_charset_encodings = array();
 461          /**
 462          * charset encoding to be used for response.
 463          * NB: if we can, we will convert the generated response from internal_encoding to the intended one.
 464          * can be: a supported xml encoding (only UTF-8 and ISO-8859-1 at present, unless mbstring is enabled),
 465          * null (leave unspecified in response, convert output stream to US_ASCII),
 466          * 'default' (use xmlrpc library default as specified in xmlrpc.inc, convert output stream if needed),
 467          * or 'auto' (use client-specified charset encoding or same as request if request headers do not specify it (unless request is US-ASCII: then use library default anyway).
 468          * NB: pretty dangerous if you accept every charset and do not have mbstring enabled)
 469          */
 470          var $response_charset_encoding = '';
 471          /// storage for internal debug info
 472          var $debug_info = '';
 473          /// extra data passed at runtime to method handling functions. Used only by EPI layer
 474          var $user_data = null;
 475  
 476          /**
 477          * @param array $dispmap the dispatch map withd efinition of exposed services
 478          * @param boolean $servicenow set to false to prevent the server from runnung upon construction
 479          */
 480  		function xmlrpc_server($dispMap=null, $serviceNow=true)
 481          {
 482              // if ZLIB is enabled, let the server by default accept compressed requests,
 483              // and compress responses sent to clients that support them
 484              if(function_exists('gzinflate'))
 485              {
 486                  $this->accepted_compression = array('gzip', 'deflate');
 487                  $this->compress_response = true;
 488              }
 489  
 490              // by default the xml parser can support these 3 charset encodings
 491              $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
 492  
 493              // dispMap is a dispatch array of methods
 494              // mapped to function names and signatures
 495              // if a method
 496              // doesn't appear in the map then an unknown
 497              // method error is generated
 498              /* milosch - changed to make passing dispMap optional.
 499               * instead, you can use the class add_to_map() function
 500               * to add functions manually (borrowed from SOAPX4)
 501               */
 502              if($dispMap)
 503              {
 504                  $this->dmap = $dispMap;
 505                  if($serviceNow)
 506                  {
 507                      $this->service();
 508                  }
 509              }
 510          }
 511  
 512          /**
 513          * Set debug level of server.
 514          * @param integer $in debug lvl: determines info added to xmlrpc responses (as xml comments)
 515          * 0 = no debug info,
 516          * 1 = msgs set from user with debugmsg(),
 517          * 2 = add complete xmlrpc request (headers and body),
 518          * 3 = add also all processing warnings happened during method processing
 519          * (NB: this involves setting a custom error handler, and might interfere
 520          * with the standard processing of the php function exposed as method. In
 521          * particular, triggering an USER_ERROR level error will not halt script
 522          * execution anymore, but just end up logged in the xmlrpc response)
 523          * Note that info added at elevel 2 and 3 will be base64 encoded
 524          * @access public
 525          */
 526  		function setDebug($in)
 527          {
 528              $this->debug=$in;
 529          }
 530  
 531          /**
 532          * Return a string with the serialized representation of all debug info
 533          * @param string $charset_encoding the target charset encoding for the serialization
 534          * @return string an XML comment (or two)
 535          */
 536  		function serializeDebug($charset_encoding='')
 537          {
 538              // Tough encoding problem: which internal charset should we assume for debug info?
 539              // It might contain a copy of raw data received from client, ie with unknown encoding,
 540              // intermixed with php generated data and user generated data...
 541              // so we split it: system debug is base 64 encoded,
 542              // user debug info should be encoded by the end user using the INTERNAL_ENCODING
 543              $out = '';
 544              if ($this->debug_info != '')
 545              {
 546                  $out .= "<!-- SERVER DEBUG INFO (BASE64 ENCODED):\n".base64_encode($this->debug_info)."\n-->\n";
 547              }
 548              if($GLOBALS['_xmlrpc_debuginfo']!='')
 549              {
 550  
 551                  $out .= "<!-- DEBUG INFO:\n" . xmlrpc_encode_entitites(str_replace('--', '_-', $GLOBALS['_xmlrpc_debuginfo']), $GLOBALS['xmlrpc_internalencoding'], $charset_encoding) . "\n-->\n";
 552                  // NB: a better solution MIGHT be to use CDATA, but we need to insert it
 553                  // into return payload AFTER the beginning tag
 554                  //$out .= "<![CDATA[ DEBUG INFO:\n\n" . str_replace(']]>', ']_]_>', $GLOBALS['_xmlrpc_debuginfo']) . "\n]]>\n";
 555              }
 556              return $out;
 557          }
 558  
 559          /**
 560          * Execute the xmlrpc request, printing the response
 561          * @param string $data the request body. If null, the http POST request will be examined
 562          * @return xmlrpcresp the response object (usually not used by caller...)
 563          * @access public
 564          */
 565  		function service($data=null, $return_payload=false)
 566          {
 567              if ($data === null)
 568              {
 569                  // workaround for a known bug in php ver. 5.2.2 that broke $HTTP_RAW_POST_DATA
 570                  $ver = phpversion();
 571                  if ($ver[0] >= 5)
 572                  {
 573                      $data = file_get_contents('php://input');
 574                  }
 575                  else
 576                  {
 577                      // Check if it has a value, if it doesn't have a value try and read php://input but supress the error
 578                      // this will mimic returning an empty string, without a "cant find wrapper error" and allow backwards compat
 579                      // php docs are unclear as to when this was added, works on php 4.4 at least, and probably 4.3
 580                      $data = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : @file_get_contents('php://input');
 581                  }
 582              }
 583              $raw_data = $data;
 584  
 585              // reset internal debug info
 586              $this->debug_info = '';
 587  
 588              // Echo back what we received, before parsing it
 589              if($this->debug > 1)
 590              {
 591                  $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++");
 592              }
 593  
 594              $r = $this->parseRequestHeaders($data, $req_charset, $resp_charset, $resp_encoding);
 595              if (!$r)
 596              {
 597                  $r=$this->parseRequest($data, $req_charset);
 598              }
 599  
 600              // save full body of request into response, for more debugging usages
 601              $r->raw_data = $raw_data;
 602  
 603              if($this->debug > 2 && $GLOBALS['_xmlrpcs_occurred_errors'])
 604              {
 605                  $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" .
 606                      $GLOBALS['_xmlrpcs_occurred_errors'] . "+++END+++");
 607              }
 608  
 609              $payload=$this->xml_header($resp_charset);
 610              if($this->debug > 0)
 611              {
 612                  $payload = $payload . $this->serializeDebug($resp_charset);
 613              }
 614  
 615              // G. Giunta 2006-01-27: do not create response serialization if it has
 616              // already happened. Helps building json magic
 617              if (empty($r->payload))
 618              {
 619                  $r->serialize($resp_charset);
 620              }
 621              $payload = $payload . $r->payload;
 622  
 623              if ($return_payload)
 624              {
 625                  return $payload;
 626              }
 627  
 628              // if we get a warning/error that has output some text before here, then we cannot
 629              // add a new header. We cannot say we are sending xml, either...
 630              if(!headers_sent())
 631              {
 632                  header('Content-Type: '.$r->content_type);
 633                  // we do not know if client actually told us an accepted charset, but if he did
 634                  // we have to tell him what we did
 635                  header("Vary: Accept-Charset");
 636  
 637                  // http compression of output: only
 638                  // if we can do it, and we want to do it, and client asked us to,
 639                  // and php ini settings do not force it already
 640                  $php_no_self_compress = ini_get('zlib.output_compression') == '' && (ini_get('output_handler') != 'ob_gzhandler');
 641                  if($this->compress_response && function_exists('gzencode') && $resp_encoding != ''
 642                      && $php_no_self_compress)
 643                  {
 644                      if(strpos($resp_encoding, 'gzip') !== false)
 645                      {
 646                          $payload = gzencode($payload);
 647                          header("Content-Encoding: gzip");
 648                          header("Vary: Accept-Encoding");
 649                      }
 650                      elseif (strpos($resp_encoding, 'deflate') !== false)
 651                      {
 652                          $payload = gzcompress($payload);
 653                          header("Content-Encoding: deflate");
 654                          header("Vary: Accept-Encoding");
 655                      }
 656                  }
 657  
 658                  // do not ouput content-length header if php is compressing output for us:
 659                  // it will mess up measurements
 660                  if($php_no_self_compress)
 661                  {
 662                      header('Content-Length: ' . (int)strlen($payload));
 663                  }
 664              }
 665              else
 666              {
 667                  error_log('XML-RPC: xmlrpc_server::service: http headers already sent before response is fully generated. Check for php warning or error messages');
 668              }
 669  
 670              print $payload;
 671  
 672              // return request, in case subclasses want it
 673              return $r;
 674          }
 675  
 676          /**
 677          * Add a method to the dispatch map
 678          * @param string $methodname the name with which the method will be made available
 679          * @param string $function the php function that will get invoked
 680          * @param array $sig the array of valid method signatures
 681          * @param string $doc method documentation
 682          * @access public
 683          */
 684  		function add_to_map($methodname,$function,$sig=null,$doc='')
 685          {
 686              $this->dmap[$methodname] = array(
 687                  'function'    => $function,
 688                  'docstring' => $doc
 689              );
 690              if ($sig)
 691              {
 692                  $this->dmap[$methodname]['signature'] = $sig;
 693              }
 694          }
 695  
 696          /**
 697          * Verify type and number of parameters received against a list of known signatures
 698          * @param array $in array of either xmlrpcval objects or xmlrpc type definitions
 699          * @param array $sig array of known signatures to match against
 700          * @access private
 701          */
 702  		function verifySignature($in, $sig)
 703          {
 704              // check each possible signature in turn
 705              if (is_object($in))
 706              {
 707                  $numParams = $in->getNumParams();
 708              }
 709              else
 710              {
 711                  $numParams = count($in);
 712              }
 713              foreach($sig as $cursig)
 714              {
 715                  if(count($cursig)==$numParams+1)
 716                  {
 717                      $itsOK=1;
 718                      for($n=0; $n<$numParams; $n++)
 719                      {
 720                          if (is_object($in))
 721                          {
 722                              $p=$in->getParam($n);
 723                              if($p->kindOf() == 'scalar')
 724                              {
 725                                  $pt=$p->scalartyp();
 726                              }
 727                              else
 728                              {
 729                                  $pt=$p->kindOf();
 730                              }
 731                          }
 732                          else
 733                          {
 734                              $pt= $in[$n] == 'i4' ? 'int' : $in[$n]; // dispatch maps never use i4...
 735                          }
 736  
 737                          // param index is $n+1, as first member of sig is return type
 738                          if($pt != $cursig[$n+1] && $cursig[$n+1] != $GLOBALS['xmlrpcValue'])
 739                          {
 740                              $itsOK=0;
 741                              $pno=$n+1;
 742                              $wanted=$cursig[$n+1];
 743                              $got=$pt;
 744                              break;
 745                          }
 746                      }
 747                      if($itsOK)
 748                      {
 749                          return array(1,'');
 750                      }
 751                  }
 752              }
 753              if(isset($wanted))
 754              {
 755                  return array(0, "Wanted $wanted}, got $got} at param $pno}");
 756              }
 757              else
 758              {
 759                  return array(0, "No method signature matches number of parameters");
 760              }
 761          }
 762  
 763          /**
 764          * Parse http headers received along with xmlrpc request. If needed, inflate request
 765          * @return null on success or an xmlrpcresp
 766          * @access private
 767          */
 768  		function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, &$resp_compression)
 769          {
 770              // Play nice to PHP 4.0.x: superglobals were not yet invented...
 771              if(!isset($_SERVER))
 772              {
 773                  $_SERVER = $GLOBALS['HTTP_SERVER_VARS'];
 774              }
 775  
 776              if($this->debug > 1)
 777              {
 778                  if(function_exists('getallheaders'))
 779                  {
 780                      $this->debugmsg(''); // empty line
 781                      foreach(getallheaders() as $name => $val)
 782                      {
 783                          $this->debugmsg("HEADER: $name: $val");
 784                      }
 785                  }
 786  
 787              }
 788  
 789              if(isset($_SERVER['HTTP_CONTENT_ENCODING']))
 790              {
 791                  $content_encoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']);
 792              }
 793              else
 794              {
 795                  $content_encoding = '';
 796              }
 797  
 798              // check if request body has been compressed and decompress it
 799              if($content_encoding != '' && strlen($data))
 800              {
 801                  if($content_encoding == 'deflate' || $content_encoding == 'gzip')
 802                  {
 803                      // if decoding works, use it. else assume data wasn't gzencoded
 804                      if(function_exists('gzinflate') && in_array($content_encoding, $this->accepted_compression))
 805                      {
 806                          if($content_encoding == 'deflate' && $degzdata = @gzuncompress($data))
 807                          {
 808                              $data = $degzdata;
 809                              if($this->debug > 1)
 810                              {
 811                                  $this->debugmsg("\n+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++");
 812                              }
 813                          }
 814                          elseif($content_encoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
 815                          {
 816                              $data = $degzdata;
 817                              if($this->debug > 1)
 818                                  $this->debugmsg("+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++");
 819                          }
 820                          else
 821                          {
 822                              $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_decompress_fail'], $GLOBALS['xmlrpcstr']['server_decompress_fail']);
 823                              return $r;
 824                          }
 825                      }
 826                      else
 827                      {
 828                          //error_log('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
 829                          $r =& new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_cannot_decompress'], $GLOBALS['xmlrpcstr']['server_cannot_decompress']);
 830                          return $r;
 831                      }
 832                  }
 833              }
 834  
 835              // check if client specified accepted charsets, and if we know how to fulfill
 836              // the request
 837              if ($this->response_charset_encoding == 'auto')
 838              {
 839                  $resp_encoding = '';
 840                  if (isset($_SERVER['HTTP_ACCEPT_CHARSET']))
 841                  {
 842                      // here we should check if we can match the client-requested encoding
 843                      // with the encodings we know we can generate.
 844                      /// @todo we should parse q=0.x preferences instead of getting first charset specified...
 845                      $client_accepted_charsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET']));
 846                      // Give preference to internal encoding
 847                      $known_charsets = array($this->internal_encoding, 'UTF-8', 'ISO-8859-1', 'US-ASCII');
 848                      foreach ($known_charsets as $charset)
 849                      {
 850                          foreach ($client_accepted_charsets as $accepted)
 851                              if (strpos($accepted, $charset) === 0)
 852                              {
 853                                  $resp_encoding = $charset;
 854                                  break;
 855                              }
 856                          if ($resp_encoding)
 857                              break;
 858                      }
 859                  }
 860              }
 861              else
 862              {
 863                  $resp_encoding = $this->response_charset_encoding;
 864              }
 865  
 866              if (isset($_SERVER['HTTP_ACCEPT_ENCODING']))
 867              {
 868                  $resp_compression = $_SERVER['HTTP_ACCEPT_ENCODING'];
 869              }
 870              else
 871              {
 872                  $resp_compression = '';
 873              }
 874  
 875              // 'guestimate' request encoding
 876              /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check???
 877              $req_encoding = guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '',
 878                  $data);
 879  
 880              return null;
 881          }
 882  
 883          /**
 884          * Parse an xml chunk containing an xmlrpc request and execute the corresponding
 885          * php function registered with the server
 886          * @param string $data the xml request
 887          * @param string $req_encoding (optional) the charset encoding of the xml request
 888          * @return xmlrpcresp
 889          * @access private
 890          */
 891  		function parseRequest($data, $req_encoding='')
 892          {
 893              // 2005/05/07 commented and moved into caller function code
 894              //if($data=='')
 895              //{
 896              //    $data=$GLOBALS['HTTP_RAW_POST_DATA'];
 897              //}
 898  
 899              // G. Giunta 2005/02/13: we do NOT expect to receive html entities
 900              // so we do not try to convert them into xml character entities
 901              //$data = xmlrpc_html_entity_xlate($data);
 902  
 903              $GLOBALS['_xh']=array();
 904              $GLOBALS['_xh']['ac']='';
 905              $GLOBALS['_xh']['stack']=array();
 906              $GLOBALS['_xh']['valuestack'] = array();
 907              $GLOBALS['_xh']['params']=array();
 908              $GLOBALS['_xh']['pt']=array();
 909              $GLOBALS['_xh']['isf']=0;
 910              $GLOBALS['_xh']['isf_reason']='';
 911              $GLOBALS['_xh']['method']=false; // so we can check later if we got a methodname or not
 912              $GLOBALS['_xh']['rt']='';
 913  
 914              // decompose incoming XML into request structure
 915              if ($req_encoding != '')
 916              {
 917                  if (!in_array($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
 918                  // the following code might be better for mb_string enabled installs, but
 919                  // makes the lib about 200% slower...
 920                  //if (!is_valid_charset($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
 921                  {
 922                      error_log('XML-RPC: xmlrpc_server::parseRequest: invalid charset encoding of received request: '.$req_encoding);
 923                      $req_encoding = $GLOBALS['xmlrpc_defencoding'];
 924                  }
 925                  /// @BUG this will fail on PHP 5 if charset is not specified in the xml prologue,
 926                  // the encoding is not UTF8 and there are non-ascii chars in the text...
 927                  $parser = xml_parser_create($req_encoding);
 928              }
 929              else
 930              {
 931                  $parser = xml_parser_create();
 932              }
 933  
 934              xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
 935              // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
 936              // the xml parser to give us back data in the expected charset
 937              xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);
 938  
 939              if ($this->functions_parameters_type != 'xmlrpcvals')
 940                  xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
 941              else
 942                  xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
 943              xml_set_character_data_handler($parser, 'xmlrpc_cd');
 944              xml_set_default_handler($parser, 'xmlrpc_dh');
 945              if(!xml_parse($parser, $data, 1))
 946              {
 947                  // return XML error as a faultCode
 948                  $r=&new xmlrpcresp(0,
 949                  $GLOBALS['xmlrpcerrxml']+xml_get_error_code($parser),
 950                  sprintf('XML error: %s at line %d, column %d',
 951                      xml_error_string(xml_get_error_code($parser)),
 952                      xml_get_current_line_number($parser), xml_get_current_column_number($parser)));
 953                  xml_parser_free($parser);
 954              }
 955              elseif ($GLOBALS['_xh']['isf'])
 956              {
 957                  xml_parser_free($parser);
 958                  $r=&new xmlrpcresp(0,
 959                      $GLOBALS['xmlrpcerr']['invalid_request'],
 960                      $GLOBALS['xmlrpcstr']['invalid_request'] . ' ' . $GLOBALS['_xh']['isf_reason']);
 961              }
 962              else
 963              {
 964                  xml_parser_free($parser);
 965                  if ($this->functions_parameters_type != 'xmlrpcvals')
 966                  {
 967                      if($this->debug > 1)
 968                      {
 969                          $this->debugmsg("\n+++PARSED+++\n".var_export($GLOBALS['_xh']['params'], true)."\n+++END+++");
 970                      }
 971                      $r = $this->execute($GLOBALS['_xh']['method'], $GLOBALS['_xh']['params'], $GLOBALS['_xh']['pt']);
 972                  }
 973                  else
 974                  {
 975                      // build an xmlrpcmsg object with data parsed from xml
 976                      $m=&new xmlrpcmsg($GLOBALS['_xh']['method']);
 977                      // now add parameters in
 978                      for($i=0; $i<count($GLOBALS['_xh']['params']); $i++)
 979                      {
 980                          $m->addParam($GLOBALS['_xh']['params'][$i]);
 981                      }
 982  
 983                      if($this->debug > 1)
 984                      {
 985                          $this->debugmsg("\n+++PARSED+++\n".var_export($m, true)."\n+++END+++");
 986                      }
 987  
 988                      $r = $this->execute($m);
 989                  }
 990              }
 991              return $r;
 992          }
 993  
 994          /**
 995          * Execute a method invoked by the client, checking parameters used
 996          * @param mixed $m either an xmlrpcmsg obj or a method name
 997          * @param array $params array with method parameters as php types (if m is method name only)
 998          * @param array $paramtypes array with xmlrpc types of method parameters (if m is method name only)
 999          * @return xmlrpcresp
1000          * @access private
1001          */
1002  		function execute($m, $params=null, $paramtypes=null)
1003          {
1004              if (is_object($m))
1005              {
1006                  $methName = $m->method();
1007              }
1008              else
1009              {
1010                  $methName = $m;
1011              }
1012              $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0);
1013              $dmap = $sysCall ? $GLOBALS['_xmlrpcs_dmap'] : $this->dmap;
1014  
1015              if(!isset($dmap[$methName]['function']))
1016              {
1017                  // No such method
1018                  return new xmlrpcresp(0,
1019                      $GLOBALS['xmlrpcerr']['unknown_method'],
1020                      $GLOBALS['xmlrpcstr']['unknown_method']);
1021              }
1022  
1023              // Check signature
1024              if(isset($dmap[$methName]['signature']))
1025              {
1026                  $sig = $dmap[$methName]['signature'];
1027                  if (is_object($m))
1028                  {
1029                      list($ok, $errstr) = $this->verifySignature($m, $sig);
1030                  }
1031                  else
1032                  {
1033                      list($ok, $errstr) = $this->verifySignature($paramtypes, $sig);
1034                  }
1035                  if(!$ok)
1036                  {
1037                      // Didn't match.
1038                      return new xmlrpcresp(
1039                          0,
1040                          $GLOBALS['xmlrpcerr']['incorrect_params'],
1041                          $GLOBALS['xmlrpcstr']['incorrect_params'] . ": $errstr}"
1042                      );
1043                  }
1044              }
1045  
1046              $func = $dmap[$methName]['function'];
1047              // let the 'class::function' syntax be accepted in dispatch maps
1048              if(is_string($func) && strpos($func, '::'))
1049              {
1050                  $func = explode('::', $func);
1051              }
1052              // verify that function to be invoked is in fact callable
1053              if(!is_callable($func))
1054              {
1055                  error_log("XML-RPC: xmlrpc_server::execute: function $func registered as method handler is not callable");
1056                  return new xmlrpcresp(
1057                      0,
1058                      $GLOBALS['xmlrpcerr']['server_error'],
1059                      $GLOBALS['xmlrpcstr']['server_error'] . ": no function matches method"
1060                  );
1061              }
1062  
1063              // If debug level is 3, we should catch all errors generated during
1064              // processing of user function, and log them as part of response
1065              if($this->debug > 2)
1066              {
1067                  $GLOBALS['_xmlrpcs_prev_ehandler'] = set_error_handler('_xmlrpcs_errorHandler');
1068              }
1069              if (is_object($m))
1070              {
1071                  if($sysCall)
1072                  {
1073                      $r = call_user_func($func, $this, $m);
1074                  }
1075                  else
1076                  {
1077                      $r = call_user_func($func, $m);
1078                  }
1079                  if (!is_a($r, 'xmlrpcresp'))
1080                  {
1081                      error_log("XML-RPC: xmlrpc_server::execute: function $func registered as method handler does not return an xmlrpcresp object");
1082                      if (is_a($r, 'xmlrpcval'))
1083                      {
1084                          $r =& new xmlrpcresp($r);
1085                      }
1086                      else
1087                      {
1088                          $r =& new xmlrpcresp(
1089                              0,
1090                              $GLOBALS['xmlrpcerr']['server_error'],
1091                              $GLOBALS['xmlrpcstr']['server_error'] . ": function does not return xmlrpcresp object"
1092                          );
1093                      }
1094                  }
1095              }
1096              else
1097              {
1098                  // call a 'plain php' function
1099                  if($sysCall)
1100                  {
1101                      array_unshift($params, $this);
1102                      $r = call_user_func_array($func, $params);
1103                  }
1104                  else
1105                  {
1106                      // 3rd API convention for method-handling functions: EPI-style
1107                      if ($this->functions_parameters_type == 'epivals')
1108                      {
1109                          $r = call_user_func_array($func, array($methName, $params, $this->user_data));
1110                          // mimic EPI behaviour: if we get an array that looks like an error, make it
1111                          // an eror response
1112                          if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r))
1113                          {
1114                              $r =& new xmlrpcresp(0, (integer)$r['faultCode'], (string)$r['faultString']);
1115                          }
1116                          else
1117                          {
1118                              // functions using EPI api should NOT return resp objects,
1119                              // so make sure we encode the return type correctly
1120                              $r =& new xmlrpcresp(php_xmlrpc_encode($r, array('extension_api')));
1121                          }
1122                      }
1123                      else
1124                      {
1125                          $r = call_user_func_array($func, $params);
1126                      }
1127                  }
1128                  // the return type can be either an xmlrpcresp object or a plain php value...
1129                  if (!is_a($r, 'xmlrpcresp'))
1130                  {
1131                      // what should we assume here about automatic encoding of datetimes
1132                      // and php classes instances???
1133                      $r =& new xmlrpcresp(php_xmlrpc_encode($r, array('auto_dates')));
1134                  }
1135              }
1136              if($this->debug > 2)
1137              {
1138                  // note: restore the error handler we found before calling the
1139                  // user func, even if it has been changed inside the func itself
1140                  if($GLOBALS['_xmlrpcs_prev_ehandler'])
1141                  {
1142                      set_error_handler($GLOBALS['_xmlrpcs_prev_ehandler']);
1143                  }
1144                  else
1145                  {
1146                      restore_error_handler();
1147                  }
1148              }
1149              return $r;
1150          }
1151  
1152          /**
1153          * add a string to the 'internal debug message' (separate from 'user debug message')
1154          * @param string $strings
1155          * @access private
1156          */
1157  		function debugmsg($string)
1158          {
1159              $this->debug_info .= $string."\n";
1160          }
1161  
1162          /**
1163          * @access private
1164          */
1165  		function xml_header($charset_encoding='')
1166          {
1167              if ($charset_encoding != '')
1168              {
1169                  return "<?xml version=\"1.0\" encoding=\"$charset_encoding\"?" . ">\n";
1170              }
1171              else
1172              {
1173                  return "<?xml version=\"1.0\"?" . ">\n";
1174              }
1175          }
1176  
1177          /**
1178          * A debugging routine: just echoes back the input packet as a string value
1179          * DEPRECATED!
1180          */
1181  		function echoInput()
1182          {
1183              $r=&new xmlrpcresp(new xmlrpcval( "'Aha said I: '" . $GLOBALS['HTTP_RAW_POST_DATA'], 'string'));
1184              print $r->serialize();
1185          }
1186      }
1187  ?>


Generated: Wed Mar 28 15:54:07 2012 Cross-referenced by PHPXref 0.7.1