b2evolution PHP Cross Reference Blogging Systems

Source: /inc/_ext/xmlrpc/_xmlrpcs.inc.php - 1288 lines - 42002 bytes - Summary - Text - Print

   1  <?php
   2  // b2evo mods: added logIO() calls
   3  
   4  // by Edd Dumbill (C) 1999-2002
   5  // <edd@usefulinc.com>
   6  // $Id: _xmlrpcs.inc.php 4148 2013-07-05 22:24:06Z fplanque $
   7  
   8  // Copyright (c) 1999,2000,2002 Edd Dumbill.
   9  // All rights reserved.
  10  //
  11  // Redistribution and use in source and binary forms, with or without
  12  // modification, are permitted provided that the following conditions
  13  // are met:
  14  //
  15  //    * Redistributions of source code must retain the above copyright
  16  //      notice, this list of conditions and the following disclaimer.
  17  //
  18  //    * Redistributions in binary form must reproduce the above
  19  //      copyright notice, this list of conditions and the following
  20  //      disclaimer in the documentation and/or other materials provided
  21  //      with the distribution.
  22  //
  23  //    * Neither the name of the "XML-RPC for PHP" nor the names of its
  24  //      contributors may be used to endorse or promote products derived
  25  //      from this software without specific prior written permission.
  26  //
  27  // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  28  // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  29  // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  30  // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  31  // REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  32  // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  33  // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  34  // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  35  // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  36  // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  37  // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  38  // OF THE POSSIBILITY OF SUCH DAMAGE.
  39  if( !defined('EVO_MAIN_INIT') ) die( 'Please, do not access this page directly.' );
  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              if( count($m->params) > 1 )
 322              {    // One call per param
 323                  foreach( $m->params as $call )
 324                  {
 325                      if( $call->kindOf('struct') )
 326                      {
 327                          $result[] = _xmlrpcs_multicall_do_call($server, $call);
 328                      }
 329                  }
 330              }
 331              else
 332              {    // Array of calls in a single param
 333                  $calls = $m->getParam(0);
 334                  if( is_array($calls) )
 335                  {
 336                      $numCalls = $calls->arraysize();
 337                      for($i = 0; $i < $numCalls; $i++)
 338                      {
 339                          $call = $calls->arraymem($i);
 340                          $result[$i] = _xmlrpcs_multicall_do_call($server, $call);
 341                      }
 342                  }
 343              }
 344          }
 345          else
 346          {
 347              $numCalls=count($m);
 348              for($i = 0; $i < $numCalls; $i++)
 349              {
 350                  $result[$i] = _xmlrpcs_multicall_do_call_phpvals($server, $m[$i]);
 351              }
 352          }
 353  
 354          return new xmlrpcresp(new xmlrpcval($result, 'array'));
 355      }
 356  
 357      $GLOBALS['_xmlrpcs_dmap']=array(
 358          'system.listMethods' => array(
 359              'function' => '_xmlrpcs_listMethods',
 360              'signature' => $_xmlrpcs_listMethods_sig,
 361              'docstring' => $_xmlrpcs_listMethods_doc,
 362              'signature_docs' => $_xmlrpcs_listMethods_sdoc),
 363          'system.methodHelp' => array(
 364              'function' => '_xmlrpcs_methodHelp',
 365              'signature' => $_xmlrpcs_methodHelp_sig,
 366              'docstring' => $_xmlrpcs_methodHelp_doc,
 367              'signature_docs' => $_xmlrpcs_methodHelp_sdoc),
 368          'system.methodSignature' => array(
 369              'function' => '_xmlrpcs_methodSignature',
 370              'signature' => $_xmlrpcs_methodSignature_sig,
 371              'docstring' => $_xmlrpcs_methodSignature_doc,
 372              'signature_docs' => $_xmlrpcs_methodSignature_sdoc),
 373          'system.multicall' => array(
 374              'function' => '_xmlrpcs_multicall',
 375              //'signature' => $_xmlrpcs_multicall_sig, // Do not check signature, every app sends its own params
 376              'docstring' => $_xmlrpcs_multicall_doc,
 377              'signature_docs' => $_xmlrpcs_multicall_sdoc),
 378          'system.getCapabilities' => array(
 379              'function' => '_xmlrpcs_getCapabilities',
 380              'signature' => $_xmlrpcs_getCapabilities_sig,
 381              'docstring' => $_xmlrpcs_getCapabilities_doc,
 382              'signature_docs' => $_xmlrpcs_getCapabilities_sdoc)
 383      );
 384  
 385      $GLOBALS['_xmlrpcs_occurred_errors'] = '';
 386      $GLOBALS['_xmlrpcs_prev_ehandler'] = '';
 387  
 388      /**
 389      * Error handler used to track errors that occur during server-side execution of PHP code.
 390      * This allows to report back to the client whether an internal error has occurred or not
 391      * using an xmlrpc response object, instead of letting the client deal with the html junk
 392      * that a PHP execution error on the server generally entails.
 393      *
 394      * NB: in fact a user defined error handler can only handle WARNING, NOTICE and USER_* errors.
 395      *
 396      */
 397  	function _xmlrpcs_errorHandler($errcode, $errstring, $filename=null, $lineno=null, $context=null)
 398      {
 399          // obey the @ protocol
 400          if (error_reporting() == 0)
 401              return;
 402  
 403          //if($errcode != E_NOTICE && $errcode != E_WARNING && $errcode != E_USER_NOTICE && $errcode != E_USER_WARNING)
 404          if($errcode != E_STRICT)
 405          {
 406              $GLOBALS['_xmlrpcs_occurred_errors'] = $GLOBALS['_xmlrpcs_occurred_errors'] . $errstring . "\n";
 407          }
 408          // Try to avoid as much as possible disruption to the previous error handling
 409          // mechanism in place
 410          if($GLOBALS['_xmlrpcs_prev_ehandler'] == '')
 411          {
 412              // The previous error handler was the default: all we should do is log error
 413              // to the default error log (if level high enough)
 414              if(ini_get('log_errors') && (intval(ini_get('error_reporting')) & $errcode))
 415              {
 416                  error_log($errstring);
 417              }
 418          }
 419          else
 420          {
 421              // Pass control on to previous error handler, trying to avoid loops...
 422              if($GLOBALS['_xmlrpcs_prev_ehandler'] != '_xmlrpcs_errorHandler')
 423              {
 424                  // NB: this code will NOT work on php < 4.0.2: only 2 params were used for error handlers
 425                  if(is_array($GLOBALS['_xmlrpcs_prev_ehandler']))
 426                  {
 427                      // the following works both with static class methods and plain object methods as error handler
 428                      call_user_func_array($GLOBALS['_xmlrpcs_prev_ehandler'], array($errcode, $errstring, $filename, $lineno, $context));
 429                  }
 430                  else
 431                  {
 432                      $GLOBALS['_xmlrpcs_prev_ehandler']($errcode, $errstring, $filename, $lineno, $context);
 433                  }
 434              }
 435          }
 436      }
 437  
 438      $GLOBALS['_xmlrpc_debuginfo']='';
 439  
 440      /**
 441      * Add a string to the debug info that can be later seralized by the server
 442      * as part of the response message.
 443      * Note that for best compatbility, the debug string should be encoded using
 444      * the $GLOBALS['xmlrpc_internalencoding'] character set.
 445      * @param string $m
 446      * @access public
 447      */
 448  	function xmlrpc_debugmsg($m)
 449      {
 450          $GLOBALS['_xmlrpc_debuginfo'] .= $m . "\n";
 451      }
 452  
 453      class xmlrpc_server
 454      {
 455          /**
 456          * Array defining php functions exposed as xmlrpc methods by this server
 457          * @access private
 458          */
 459          var $dmap=array();
 460          /**
 461          * Defines how functions in dmap will be invoked: either using an xmlrpc msg object
 462          * or plain php values.
 463          * valid strings are 'xmlrpcvals', 'phpvals' or 'epivals'
 464          */
 465          var $functions_parameters_type='xmlrpcvals';
 466          /**
 467          * Option used for fine-tuning the encoding the php values returned from
 468          * functions registered in the dispatch map when the functions_parameters_types
 469          * member is set to 'phpvals'
 470          * @see php_xmlrpc_encode for a list of values
 471          */
 472          var $phpvals_encoding_options = array( 'auto_dates' );
 473          /// 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
 474          var $debug = 1;
 475          /**
 476          * Controls behaviour of server when invoked user function throws an exception:
 477          * 0 = catch it and return an 'internal error' xmlrpc response (default)
 478          * 1 = catch it and return an xmlrpc response with the error corresponding to the exception
 479          * 2 = allow the exception to float to the upper layers
 480          */
 481          var $exception_handling = 0;
 482          /**
 483          * When set to true, it will enable HTTP compression of the response, in case
 484          * the client has declared its support for compression in the request.
 485          */
 486          var $compress_response = false;
 487          /**
 488          * List of http compression methods accepted by the server for requests.
 489          * NB: PHP supports deflate, gzip compressions out of the box if compiled w. zlib
 490          */
 491          var $accepted_compression = array();
 492          /// shall we serve calls to system.* methods?
 493          var $allow_system_funcs = true;
 494          /// list of charset encodings natively accepted for requests
 495          var $accepted_charset_encodings = array();
 496          /**
 497          * charset encoding to be used for response.
 498          * NB: if we can, we will convert the generated response from internal_encoding to the intended one.
 499          * can be: a supported xml encoding (only UTF-8 and ISO-8859-1 at present, unless mbstring is enabled),
 500          * null (leave unspecified in response, convert output stream to US_ASCII),
 501          * 'default' (use xmlrpc library default as specified in xmlrpc.inc, convert output stream if needed),
 502          * 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).
 503          * NB: pretty dangerous if you accept every charset and do not have mbstring enabled)
 504          */
 505          var $response_charset_encoding = '';
 506          /**
 507          * Storage for internal debug info
 508          * @access private
 509          */
 510          var $debug_info = '';
 511          /**
 512          * Extra data passed at runtime to method handling functions. Used only by EPI layer
 513          */
 514          var $user_data = null;
 515  
 516          /**
 517          * @param array $dispmap the dispatch map withd efinition of exposed services
 518          * @param boolean $servicenow set to false to prevent the server from runnung upon construction
 519          */
 520  		function xmlrpc_server($dispMap=null, $serviceNow=true)
 521          {
 522              // if ZLIB is enabled, let the server by default accept compressed requests,
 523              // and compress responses sent to clients that support them
 524              if(function_exists('gzinflate'))
 525              {
 526                  if( version_compare( phpversion(), '5.4', '<' ) ||version_compare( phpversion(), '5.5', '>=' ) )
 527                   { //fplanque: disabling this in PHP 5.4 because it bugs...
 528                       // Note: the task of compressing will fall back to Apache
 529                      $this->accepted_compression = array('gzip', 'deflate');
 530                      $this->compress_response = true;
 531                  }
 532              }
 533  
 534              // by default the xml parser can support these 3 charset encodings
 535              $this->accepted_charset_encodings = array('UTF-8', 'ISO-8859-1', 'US-ASCII');
 536  
 537              // dispMap is a dispatch array of methods
 538              // mapped to function names and signatures
 539              // if a method
 540              // doesn't appear in the map then an unknown
 541              // method error is generated
 542              /* milosch - changed to make passing dispMap optional.
 543               * instead, you can use the class add_to_map() function
 544               * to add functions manually (borrowed from SOAPX4)
 545               */
 546              if($dispMap)
 547              {
 548                  $this->dmap = $dispMap;
 549                  if($serviceNow)
 550                  {
 551                      $this->service();
 552                  }
 553              }
 554          }
 555  
 556          /**
 557          * Set debug level of server.
 558          * @param integer $in debug lvl: determines info added to xmlrpc responses (as xml comments)
 559          * 0 = no debug info,
 560          * 1 = msgs set from user with debugmsg(),
 561          * 2 = add complete xmlrpc request (headers and body),
 562          * 3 = add also all processing warnings happened during method processing
 563          * (NB: this involves setting a custom error handler, and might interfere
 564          * with the standard processing of the php function exposed as method. In
 565          * particular, triggering an USER_ERROR level error will not halt script
 566          * execution anymore, but just end up logged in the xmlrpc response)
 567          * Note that info added at elevel 2 and 3 will be base64 encoded
 568          * @access public
 569          */
 570  		function setDebug($in)
 571          {
 572              $this->debug=$in;
 573          }
 574  
 575          /**
 576          * Return a string with the serialized representation of all debug info
 577          * @param string $charset_encoding the target charset encoding for the serialization
 578          * @return string an XML comment (or two)
 579          */
 580  		function serializeDebug($charset_encoding='')
 581          {
 582              // Tough encoding problem: which internal charset should we assume for debug info?
 583              // It might contain a copy of raw data received from client, ie with unknown encoding,
 584              // intermixed with php generated data and user generated data...
 585              // so we split it: system debug is base 64 encoded,
 586              // user debug info should be encoded by the end user using the INTERNAL_ENCODING
 587              $out = '';
 588              if ($this->debug_info != '')
 589              {
 590                  $out .= "<!-- SERVER DEBUG INFO (BASE64 ENCODED):\n".base64_encode($this->debug_info)."\n-->\n";
 591              }
 592              if($GLOBALS['_xmlrpc_debuginfo']!='')
 593              {
 594  
 595                  $out .= "<!-- DEBUG INFO:\n" . xmlrpc_encode_entitites(str_replace('--', '_-', $GLOBALS['_xmlrpc_debuginfo']), $GLOBALS['xmlrpc_internalencoding'], $charset_encoding) . "\n-->\n";
 596                  // NB: a better solution MIGHT be to use CDATA, but we need to insert it
 597                  // into return payload AFTER the beginning tag
 598                  //$out .= "<![CDATA[ DEBUG INFO:\n\n" . str_replace(']]>', ']_]_>', $GLOBALS['_xmlrpc_debuginfo']) . "\n]]>\n";
 599              }
 600              return $out;
 601          }
 602  
 603          /**
 604          * Execute the xmlrpc request, printing the response
 605          * @param string $data the request body. If null, the http POST request will be examined
 606          * @return xmlrpcresp the response object (usually not used by caller...)
 607          * @access public
 608          */
 609  		function service($data=null, $return_payload=false)
 610          {
 611              if ($data === null)
 612              {
 613                  // workaround for a known bug in php ver. 5.2.2 that broke $HTTP_RAW_POST_DATA
 614                  $ver = phpversion();
 615                  if ($ver[0] >= 5)
 616                  {
 617                      $data = file_get_contents('php://input');
 618                  }
 619                  else
 620                  {
 621                      $data = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
 622                  }
 623              }
 624              $raw_data = $data;
 625  
 626              // reset internal debug info
 627              $this->debug_info = '';
 628  
 629              // Echo back what we received, before parsing it
 630              if($this->debug > 1)
 631              {
 632                  $this->debugmsg("+++GOT+++\n" . $data . "\n+++END+++");
 633              }
 634  
 635              $r = $this->parseRequestHeaders($data, $req_charset, $resp_charset, $resp_encoding);
 636              if (!$r)
 637              {
 638                  $r=$this->parseRequest($data, $req_charset);
 639              }
 640  
 641              // save full body of request into response, for more debugging usages
 642              $r->raw_data = $raw_data;
 643  
 644              if($this->debug > 2 && $GLOBALS['_xmlrpcs_occurred_errors'])
 645              {
 646                  $this->debugmsg("+++PROCESSING ERRORS AND WARNINGS+++\n" .
 647                      $GLOBALS['_xmlrpcs_occurred_errors'] . "+++END+++");
 648              }
 649  
 650              $payload=$this->xml_header($resp_charset);
 651              if($this->debug > 0)
 652              {
 653                  $payload = $payload . $this->serializeDebug($resp_charset);
 654              }
 655  
 656              // G. Giunta 2006-01-27: do not create response serialization if it has
 657              // already happened. Helps building json magic
 658              if (empty($r->payload))
 659              {
 660                  $r->serialize($resp_charset);
 661              }
 662              $payload = $payload . $r->payload;
 663  
 664              if ($return_payload)
 665              {
 666                  return $payload;
 667              }
 668  
 669              // if we get a warning/error that has output some text before here, then we cannot
 670              // add a new header. We cannot say we are sending xml, either...
 671              if(!headers_sent())
 672              {
 673                  header('Content-Type: '.$r->content_type);
 674                  // we do not know if client actually told us an accepted charset, but if he did
 675                  // we have to tell him what we did
 676                  header("Vary: Accept-Charset");
 677  
 678                  // http compression of output: only
 679                  // if we can do it, and we want to do it, and client asked us to,
 680                  // and php ini settings do not force it already
 681                  $php_no_self_compress = !ini_get('zlib.output_compression') && (ini_get('output_handler') != 'ob_gzhandler');
 682                  if($this->compress_response && function_exists('gzencode') && $resp_encoding != ''
 683                      && $php_no_self_compress)
 684                  {
 685                      if(strpos($resp_encoding, 'gzip') !== false)
 686                      {
 687                          $payload = gzencode($payload);
 688                          header("Content-Encoding: gzip");
 689                          header("Vary: Accept-Encoding");
 690                      }
 691                      elseif (strpos($resp_encoding, 'deflate') !== false)
 692                      {
 693                          $payload = gzcompress($payload);
 694                          header("Content-Encoding: deflate");
 695                          header("Vary: Accept-Encoding");
 696                      }
 697                  }
 698  
 699                  // do not ouput content-length header if php is compressing output for us:
 700                  // it will mess up measurements
 701                  if($php_no_self_compress)
 702                  {
 703                      header('Content-Length: ' . (int)strlen($payload));
 704                  }
 705              }
 706              else
 707              {
 708                  error_log('XML-RPC: '.__METHOD__.': http headers already sent before response is fully generated. Check for php warning or error messages');
 709              }
 710  
 711              print $payload;
 712  
 713              // return request, in case subclasses want it
 714              return $r;
 715          }
 716  
 717          /**
 718          * Add a method to the dispatch map
 719          * @param string $methodname the name with which the method will be made available
 720          * @param string $function the php function that will get invoked
 721          * @param array $sig the array of valid method signatures
 722          * @param string $doc method documentation
 723          * @param array $sigdoc the array of valid method signatures docs (one string per param, one for return type)
 724          * @access public
 725          */
 726  		function add_to_map($methodname,$function,$sig=null,$doc=false,$sigdoc=false)
 727          {
 728              $this->dmap[$methodname] = array(
 729                  'function'    => $function,
 730                  'docstring' => $doc
 731              );
 732              if ($sig)
 733              {
 734                  $this->dmap[$methodname]['signature'] = $sig;
 735              }
 736              if ($sigdoc)
 737              {
 738                  $this->dmap[$methodname]['signature_docs'] = $sigdoc;
 739              }
 740          }
 741  
 742          /**
 743          * Verify type and number of parameters received against a list of known signatures
 744          * @param array $in array of either xmlrpcval objects or xmlrpc type definitions
 745          * @param array $sig array of known signatures to match against
 746          * @access private
 747          */
 748  		function verifySignature($in, $sig)
 749          {
 750              // check each possible signature in turn
 751              if (is_object($in))
 752              {
 753                  $numParams = $in->getNumParams();
 754              }
 755              else
 756              {
 757                  $numParams = count($in);
 758              }
 759              foreach($sig as $cursig)
 760              {
 761                  // save the number of cexpected params for each signature
 762                  $exp_p[] = count($cursig)-1;
 763  
 764                  if(count($cursig)==$numParams+1)
 765                  {
 766                      $itsOK=1;
 767                      for($n=0; $n<$numParams; $n++)
 768                      {
 769                          if (is_object($in))
 770                          {
 771                              $p=$in->getParam($n);
 772                              if($p->kindOf() == 'scalar')
 773                              {
 774                                  $pt=$p->scalartyp();
 775                              }
 776                              else
 777                              {
 778                                  $pt=$p->kindOf();
 779                              }
 780                          }
 781                          else
 782                          {
 783                              $pt= $in[$n] == 'i4' ? 'int' : strtolower($in[$n]); // dispatch maps never use i4...
 784                          }
 785                          logIO( 'Param #'.($n+1).' is: '.$pt );
 786  
 787                          // param index is $n+1, as first member of sig is return type
 788                          if($pt != $cursig[$n+1] && $cursig[$n+1] != $GLOBALS['xmlrpcValue'])
 789                          {
 790                              $itsOK=0;
 791                              $pno=$n+1;
 792                              $wanted=$cursig[$n+1];
 793                              $got=$pt;
 794                              break;
 795                          }
 796                      }
 797                      if($itsOK)
 798                      {
 799                          return array(1,'');
 800                      }
 801                  }
 802              }
 803              if(isset($wanted))
 804              {
 805                  $msg = "Wanted $wanted}, got $got} at param $pno}";
 806                  logIO($msg);
 807                  logIO( 'Method signatures: '.var_export($sig, true) );
 808  
 809                  return array(0, $msg);
 810              }
 811              else
 812              {
 813                  $msg = "No method signature matches number of parameters, got $numParams} expected ".implode(' or ', $exp_p);
 814                  logIO($msg);
 815                  logIO( 'Method signatures: '.var_export($sig, true) );
 816  
 817                  return array( 0, $msg );
 818              }
 819          }
 820  
 821          /**
 822          * Parse http headers received along with xmlrpc request. If needed, inflate request
 823          * @return null on success or an xmlrpcresp
 824          * @access private
 825          */
 826  		function parseRequestHeaders(&$data, &$req_encoding, &$resp_encoding, &$resp_compression)
 827          {
 828              // check if $_SERVER is populated: it might have been disabled via ini file
 829              // (this is true even when in CLI mode)
 830              if (count($_SERVER) == 0)
 831              {
 832                  error_log('XML-RPC: '.__METHOD__.': cannot parse request headers as $_SERVER is not populated');
 833              }
 834  
 835              if($this->debug > 1)
 836              {
 837                  if(function_exists('getallheaders'))
 838                  {
 839                      $this->debugmsg(''); // empty line
 840                      foreach(getallheaders() as $name => $val)
 841                      {
 842                          $this->debugmsg("HEADER: $name: $val");
 843                      }
 844                  }
 845  
 846              }
 847  
 848              if(isset($_SERVER['HTTP_CONTENT_ENCODING']))
 849              {
 850                  $content_encoding = str_replace('x-', '', $_SERVER['HTTP_CONTENT_ENCODING']);
 851              }
 852              else
 853              {
 854                  $content_encoding = '';
 855              }
 856  
 857              // check if request body has been compressed and decompress it
 858              if($content_encoding != '' && strlen($data))
 859              {
 860                  if($content_encoding == 'deflate' || $content_encoding == 'gzip')
 861                  {
 862                      // if decoding works, use it. else assume data wasn't gzencoded
 863                      if(function_exists('gzinflate') && in_array($content_encoding, $this->accepted_compression))
 864                      {
 865                          if($content_encoding == 'deflate' && $degzdata = @gzuncompress($data))
 866                          {
 867                              $data = $degzdata;
 868                              if($this->debug > 1)
 869                              {
 870                                  $this->debugmsg("\n+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++");
 871                              }
 872                          }
 873                          elseif($content_encoding == 'gzip' && $degzdata = @gzinflate(substr($data, 10)))
 874                          {
 875                              $data = $degzdata;
 876                              if($this->debug > 1)
 877                                  $this->debugmsg("+++INFLATED REQUEST+++[".strlen($data)." chars]+++\n" . $data . "\n+++END+++");
 878                          }
 879                          else
 880                          {
 881                              $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_decompress_fail'], $GLOBALS['xmlrpcstr']['server_decompress_fail']);
 882                              return $r;
 883                          }
 884                      }
 885                      else
 886                      {
 887                          //error_log('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');
 888                          $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_cannot_decompress'], $GLOBALS['xmlrpcstr']['server_cannot_decompress']);
 889                          return $r;
 890                      }
 891                  }
 892              }
 893  
 894              // check if client specified accepted charsets, and if we know how to fulfill
 895              // the request
 896              if ($this->response_charset_encoding == 'auto')
 897              {
 898                  $resp_encoding = '';
 899                  if (isset($_SERVER['HTTP_ACCEPT_CHARSET']))
 900                  {
 901                      // here we should check if we can match the client-requested encoding
 902                      // with the encodings we know we can generate.
 903                      /// @todo we should parse q=0.x preferences instead of getting first charset specified...
 904                      $client_accepted_charsets = explode(',', strtoupper($_SERVER['HTTP_ACCEPT_CHARSET']));
 905                      // Give preference to internal encoding
 906                      $known_charsets = array($GLOBALS['xmlrpc_internalencoding'], 'UTF-8', 'ISO-8859-1', 'US-ASCII');
 907                      foreach ($known_charsets as $charset)
 908                      {
 909                          foreach ($client_accepted_charsets as $accepted)
 910                              if (strpos($accepted, $charset) === 0)
 911                              {
 912                                  $resp_encoding = $charset;
 913                                  break;
 914                              }
 915                          if ($resp_encoding)
 916                              break;
 917                      }
 918                  }
 919              }
 920              else
 921              {
 922                  $resp_encoding = $this->response_charset_encoding;
 923              }
 924  
 925              if (isset($_SERVER['HTTP_ACCEPT_ENCODING']))
 926              {
 927                  $resp_compression = $_SERVER['HTTP_ACCEPT_ENCODING'];
 928              }
 929              else
 930              {
 931                  $resp_compression = '';
 932              }
 933  
 934              // 'guestimate' request encoding
 935              /// @todo check if mbstring is enabled and automagic input conversion is on: it might mingle with this check???
 936              $req_encoding = guess_encoding(isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '',
 937                  $data);
 938  
 939              return null;
 940          }
 941  
 942          /**
 943          * Parse an xml chunk containing an xmlrpc request and execute the corresponding
 944          * php function registered with the server
 945          * @param string $data the xml request
 946          * @param string $req_encoding (optional) the charset encoding of the xml request
 947          * @return xmlrpcresp
 948          * @access private
 949          */
 950  		function parseRequest($data, $req_encoding='')
 951          {
 952              // 2005/05/07 commented and moved into caller function code
 953              //if($data=='')
 954              //{
 955              //    $data=$GLOBALS['HTTP_RAW_POST_DATA'];
 956              //}
 957  
 958              // G. Giunta 2005/02/13: we do NOT expect to receive html entities
 959              // so we do not try to convert them into xml character entities
 960              //$data = xmlrpc_html_entity_xlate($data);
 961  
 962              $GLOBALS['_xh']=array();
 963              $GLOBALS['_xh']['ac']='';
 964              $GLOBALS['_xh']['stack']=array();
 965              $GLOBALS['_xh']['valuestack'] = array();
 966              $GLOBALS['_xh']['params']=array();
 967              $GLOBALS['_xh']['pt']=array();
 968              $GLOBALS['_xh']['isf']=0;
 969              $GLOBALS['_xh']['isf_reason']='';
 970              $GLOBALS['_xh']['method']=false; // so we can check later if we got a methodname or not
 971              $GLOBALS['_xh']['rt']='';
 972  
 973              // decompose incoming XML into request structure
 974              if ($req_encoding != '')
 975              {
 976                  if (!in_array($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
 977                  // the following code might be better for mb_string enabled installs, but
 978                  // makes the lib about 200% slower...
 979                  //if (!is_valid_charset($req_encoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
 980                  {
 981                      error_log('XML-RPC: '.__METHOD__.': invalid charset encoding of received request: '.$req_encoding);
 982                      $req_encoding = $GLOBALS['xmlrpc_defencoding'];
 983                  }
 984                  /// @BUG this will fail on PHP 5 if charset is not specified in the xml prologue,
 985                  // the encoding is not UTF8 and there are non-ascii chars in the text...
 986                  /// @todo use an ampty string for php 5 ???
 987                  $parser = xml_parser_create($req_encoding);
 988              }
 989              else
 990              {
 991                  $parser = xml_parser_create();
 992              }
 993  
 994              xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, true);
 995              // G. Giunta 2005/02/13: PHP internally uses ISO-8859-1, so we have to tell
 996              // the xml parser to give us back data in the expected charset
 997              // What if internal encoding is not in one of the 3 allowed?
 998              // we use the broadest one, ie. utf8
 999              // This allows to send data which is native in various charset,
1000              // by extending xmlrpc_encode_entitites() and setting xmlrpc_internalencoding
1001              if (!in_array($GLOBALS['xmlrpc_internalencoding'], array('UTF-8', 'ISO-8859-1', 'US-ASCII')))
1002              {
1003                  xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
1004              }
1005              else
1006              {
1007                  xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $GLOBALS['xmlrpc_internalencoding']);
1008              }
1009  
1010              if ($this->functions_parameters_type != 'xmlrpcvals')
1011                  xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee_fast');
1012              else
1013                  xml_set_element_handler($parser, 'xmlrpc_se', 'xmlrpc_ee');
1014              xml_set_character_data_handler($parser, 'xmlrpc_cd');
1015              xml_set_default_handler($parser, 'xmlrpc_dh');
1016              if(!xml_parse($parser, $data, 1))
1017              {
1018                  // return XML error as a faultCode
1019                  $r = new xmlrpcresp(0,
1020                  $GLOBALS['xmlrpcerrxml']+xml_get_error_code($parser),
1021                  sprintf('XML error: %s at line %d, column %d',
1022                      xml_error_string(xml_get_error_code($parser)),
1023                      xml_get_current_line_number($parser), xml_get_current_column_number($parser)));
1024                  xml_parser_free($parser);
1025              }
1026              elseif ($GLOBALS['_xh']['isf'])
1027              {
1028                  xml_parser_free($parser);
1029                  $r = new xmlrpcresp(0,
1030                      $GLOBALS['xmlrpcerr']['invalid_request'],
1031                      $GLOBALS['xmlrpcstr']['invalid_request'] . ' ' . $GLOBALS['_xh']['isf_reason']);
1032              }
1033              else
1034              {
1035                  xml_parser_free($parser);
1036                  // small layering violation in favor of speed and memory usage:
1037                  // we should allow the 'execute' method handle this, but in the
1038                  // most common scenario (xmlrpcvals type server with some methods
1039                  // registered as phpvals) that would mean a useless encode+decode pass
1040                  if ($this->functions_parameters_type != 'xmlrpcvals' || (isset($this->dmap[$GLOBALS['_xh']['method']]['parameters_type']) && ($this->dmap[$GLOBALS['_xh']['method']]['parameters_type'] == 'phpvals')))
1041                  {
1042                      if($this->debug > 1)
1043                      {
1044                          $this->debugmsg("\n+++PARSED+++\n".var_export($GLOBALS['_xh']['params'], true)."\n+++END+++");
1045                      }
1046                      $r = $this->execute($GLOBALS['_xh']['method'], $GLOBALS['_xh']['params'], $GLOBALS['_xh']['pt']);
1047                  }
1048                  else
1049                  {
1050                      // build an xmlrpcmsg object with data parsed from xml
1051                      $m = new xmlrpcmsg($GLOBALS['_xh']['method']);
1052                      // now add parameters in
1053                      for($i=0; $i<count($GLOBALS['_xh']['params']); $i++)
1054                      {
1055                          $m->addParam($GLOBALS['_xh']['params'][$i]);
1056                      }
1057  
1058                      if($this->debug > 1)
1059                      {
1060                          $this->debugmsg("\n+++PARSED+++\n".var_export($m, true)."\n+++END+++");
1061                      }
1062                      $r = $this->execute($m);
1063                  }
1064              }
1065              return $r;
1066          }
1067  
1068          /**
1069          * Execute a method invoked by the client, checking parameters used
1070          * @param mixed $m either an xmlrpcmsg obj or a method name
1071          * @param array $params array with method parameters as php types (if m is method name only)
1072          * @param array $paramtypes array with xmlrpc types of method parameters (if m is method name only)
1073          * @return xmlrpcresp
1074          * @access private
1075          */
1076  		function execute($m, $params=null, $paramtypes=null)
1077          {
1078              if (is_object($m))
1079              {
1080                  $methName = $m->method();
1081              }
1082              else
1083              {
1084                  $methName = $m;
1085              }
1086              logIO( $methName, true );
1087  
1088              $sysCall = $this->allow_system_funcs && (strpos($methName, "system.") === 0);
1089              $dmap = $sysCall ? $GLOBALS['_xmlrpcs_dmap'] : $this->dmap;
1090  
1091              if(!isset($dmap[$methName]['function']))
1092              {
1093                  // No such method
1094                  logIO( 'No such method:'.$methName );
1095                  return new xmlrpcresp(0,
1096                      $GLOBALS['xmlrpcerr']['unknown_method'],
1097                      $GLOBALS['xmlrpcstr']['unknown_method']);
1098              }
1099  
1100              // Check signature
1101              if(isset($dmap[$methName]['signature']))
1102              {
1103                  $sig = $dmap[$methName]['signature'];
1104                  if (is_object($m))
1105                  {
1106                      list($ok, $errstr) = $this->verifySignature($m, $sig);
1107                  }
1108                  else
1109                  {
1110                      list($ok, $errstr) = $this->verifySignature($paramtypes, $sig);
1111                  }
1112                  if(!$ok)
1113                  {
1114                      // Didn't match.
1115                      logIO( 'Invalid signature.');
1116                      logIO( 'Passed params: '.var_export($m->params, true));
1117  
1118                      return new xmlrpcresp(
1119                          0,
1120                          $GLOBALS['xmlrpcerr']['incorrect_params'],
1121                          $GLOBALS['xmlrpcstr']['incorrect_params'] . ": $errstr}"
1122                      );
1123                  }
1124              }
1125  
1126              $func = $dmap[$methName]['function'];
1127              // let the 'class::function' syntax be accepted in dispatch maps
1128              if(is_string($func) && strpos($func, '::'))
1129              {
1130                  $func = explode('::', $func);
1131              }
1132              // verify that function to be invoked is in fact callable
1133              if(!is_callable($func))
1134              {
1135                  error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler is not callable");
1136                  return new xmlrpcresp(
1137                      0,
1138                      $GLOBALS['xmlrpcerr']['server_error'],
1139                      $GLOBALS['xmlrpcstr']['server_error'] . ": no function matches method"
1140                  );
1141              }
1142  
1143              // If debug level is 3, we should catch all errors generated during
1144              // processing of user function, and log them as part of response
1145              if($this->debug > 2)
1146              {
1147                  $GLOBALS['_xmlrpcs_prev_ehandler'] = set_error_handler('_xmlrpcs_errorHandler');
1148              }
1149              try
1150              {
1151                  // Allow mixed-convention servers
1152                  if (is_object($m))
1153                  {
1154                      if($sysCall)
1155                      {
1156                          $r = call_user_func($func, $this, $m);
1157                      }
1158                      else
1159                      {
1160                          $r = call_user_func($func, $m);
1161                      }
1162                      if (!is_a($r, 'xmlrpcresp'))
1163                      {
1164                          error_log("XML-RPC: ".__METHOD__.": function $func registered as method handler does not return an xmlrpcresp object");
1165                          if (is_a($r, 'xmlrpcval'))
1166                          {
1167                              $r = new xmlrpcresp($r);
1168                          }
1169                          else
1170                          {
1171                              $r = new xmlrpcresp(
1172                                  0,
1173                                  $GLOBALS['xmlrpcerr']['server_error'],
1174                                  $GLOBALS['xmlrpcstr']['server_error'] . ": function does not return xmlrpcresp object"
1175                              );
1176                          }
1177                      }
1178                  }
1179                  else
1180                  {
1181                      // call a 'plain php' function
1182                      if($sysCall)
1183                      {
1184                          array_unshift($params, $this);
1185                          $r = call_user_func_array($func, $params);
1186                      }
1187                      else
1188                      {
1189                          // 3rd API convention for method-handling functions: EPI-style
1190                          if ($this->functions_parameters_type == 'epivals')
1191                          {
1192                              $r = call_user_func_array($func, array($methName, $params, $this->user_data));
1193                              // mimic EPI behaviour: if we get an array that looks like an error, make it
1194                              // an eror response
1195                              if (is_array($r) && array_key_exists('faultCode', $r) && array_key_exists('faultString', $r))
1196                              {
1197                                  $r = new xmlrpcresp(0, (integer)$r['faultCode'], (string)$r['faultString']);
1198                              }
1199                              else
1200                              {
1201                                  // functions using EPI api should NOT return resp objects,
1202                                  // so make sure we encode the return type correctly
1203                                  $r = new xmlrpcresp(php_xmlrpc_encode($r, array('extension_api')));
1204                              }
1205                          }
1206                          else
1207                          {
1208                              $r = call_user_func_array($func, $params);
1209                          }
1210                      }
1211                      // the return type can be either an xmlrpcresp object or a plain php value...
1212                      if (!is_a($r, 'xmlrpcresp'))
1213                      {
1214                          // what should we assume here about automatic encoding of datetimes
1215                          // and php classes instances???
1216                          $r = new xmlrpcresp(php_xmlrpc_encode($r, $this->phpvals_encoding_options));
1217                      }
1218                  }
1219              }
1220              catch(Exception $e)
1221              {
1222                  // (barring errors in the lib) an uncatched exception happened
1223                  // in the called function, we wrap it in a proper error-response
1224                  switch($this->exception_handling)
1225                  {
1226                      case 2:
1227                          throw $e;
1228                          break;
1229                      case 1:
1230                          $r = new xmlrpcresp(0, $e->getCode(), $e->getMessage());
1231                          break;
1232                      default:
1233                          $r = new xmlrpcresp(0, $GLOBALS['xmlrpcerr']['server_error'], $GLOBALS['xmlrpcstr']['server_error']);
1234                  }
1235              }
1236              if($this->debug > 2)
1237              {
1238                  // note: restore the error handler we found before calling the
1239                  // user func, even if it has been changed inside the func itself
1240                  if($GLOBALS['_xmlrpcs_prev_ehandler'])
1241                  {
1242                      set_error_handler($GLOBALS['_xmlrpcs_prev_ehandler']);
1243                  }
1244                  else
1245                  {
1246                      restore_error_handler();
1247                  }
1248              }
1249              return $r;
1250          }
1251  
1252          /**
1253          * add a string to the 'internal debug message' (separate from 'user debug message')
1254          * @param string $strings
1255          * @access private
1256          */
1257  		function debugmsg($string)
1258          {
1259              $this->debug_info .= $string."\n";
1260          }
1261  
1262          /**
1263          * @access private
1264          */
1265  		function xml_header($charset_encoding='')
1266          {
1267              if ($charset_encoding != '')
1268              {
1269                  return "<?xml version=\"1.0\" encoding=\"$charset_encoding\"?" . ">\n";
1270              }
1271              else
1272              {
1273                  return "<?xml version=\"1.0\"?" . ">\n";
1274              }
1275          }
1276  
1277          /**
1278          * A debugging routine: just echoes back the input packet as a string value
1279          * DEPRECATED!
1280          */
1281  		function echoInput()
1282          {
1283              $r=new xmlrpcresp(new xmlrpcval( "'Aha said I: '" . $GLOBALS['HTTP_RAW_POST_DATA'], 'string'));
1284              print $r->serialize();
1285          }
1286      }
1287  
1288  ?>

title

Description

title

Description

title

Description

title

title

Body