Request.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. <?php
  2. namespace PhpXmlRpc;
  3. use PhpXmlRpc\Exception\HttpException;
  4. use PhpXmlRpc\Helper\Http;
  5. use PhpXmlRpc\Helper\XMLParser;
  6. use PhpXmlRpc\Traits\CharsetEncoderAware;
  7. use PhpXmlRpc\Traits\DeprecationLogger;
  8. use PhpXmlRpc\Traits\ParserAware;
  9. use PhpXmlRpc\Traits\PayloadBearer;
  10. /**
  11. * This class provides the representation of a request to an XML-RPC server.
  12. * A client sends a PhpXmlrpc\Request to a server, and receives back an PhpXmlrpc\Response.
  13. *
  14. * @todo feature creep - add a protected $httpRequest member, in the same way the Response has one
  15. *
  16. * @property string $methodname deprecated - public access left in purely for BC. Access via method()/__construct()
  17. * @property Value[] $params deprecated - public access left in purely for BC. Access via getParam()/__construct()
  18. * @property int $debug deprecated - public access left in purely for BC. Access via .../setDebug()
  19. * @property string $payload deprecated - public access left in purely for BC. Access via getPayload()/setPayload()
  20. * @property string $content_type deprecated - public access left in purely for BC. Access via getContentType()/setPayload()
  21. */
  22. class Request
  23. {
  24. use CharsetEncoderAware;
  25. use DeprecationLogger;
  26. use ParserAware;
  27. use PayloadBearer;
  28. /** @var string */
  29. protected $methodname;
  30. /** @var Value[] */
  31. protected $params = array();
  32. /** @var int */
  33. protected $debug = 0;
  34. /**
  35. * holds data while parsing the response. NB: Not a full Response object
  36. * @deprecated will be removed in a future release; still accessible by subclasses for the moment
  37. */
  38. private $httpResponse = array();
  39. /**
  40. * @param string $methodName the name of the method to invoke
  41. * @param Value[] $params array of parameters to be passed to the method (NB: Value objects, not plain php values)
  42. */
  43. public function __construct($methodName, $params = array())
  44. {
  45. $this->methodname = $methodName;
  46. foreach ($params as $param) {
  47. $this->addParam($param);
  48. }
  49. }
  50. /**
  51. * Gets/sets the xml-rpc method to be invoked.
  52. *
  53. * @param string $methodName the method to be set (leave empty not to set it)
  54. * @return string the method that will be invoked
  55. */
  56. public function method($methodName = '')
  57. {
  58. if ($methodName != '') {
  59. $this->methodname = $methodName;
  60. }
  61. return $this->methodname;
  62. }
  63. /**
  64. * Add a parameter to the list of parameters to be used upon method invocation.
  65. * Checks that $params is actually a Value object and not a plain php value.
  66. *
  67. * @param Value $param
  68. * @return boolean false on failure
  69. */
  70. public function addParam($param)
  71. {
  72. // check: do not add to self params which are not xml-rpc values
  73. if (is_object($param) && is_a($param, 'PhpXmlRpc\Value')) {
  74. $this->params[] = $param;
  75. return true;
  76. } else {
  77. $this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': value passed in must be a PhpXmlRpc\Value');
  78. return false;
  79. }
  80. }
  81. /**
  82. * Returns the nth parameter in the request. The index zero-based.
  83. *
  84. * @param integer $i the index of the parameter to fetch (zero based)
  85. * @return Value the i-th parameter
  86. */
  87. public function getParam($i)
  88. {
  89. return $this->params[$i];
  90. }
  91. /**
  92. * Returns the number of parameters in the message.
  93. *
  94. * @return integer the number of parameters currently set
  95. */
  96. public function getNumParams()
  97. {
  98. return count($this->params);
  99. }
  100. /**
  101. * Returns xml representation of the message, XML prologue included. Sets `payload` and `content_type` properties
  102. *
  103. * @param string $charsetEncoding
  104. * @return string the xml representation of the message, xml prologue included
  105. */
  106. public function serialize($charsetEncoding = '')
  107. {
  108. $this->createPayload($charsetEncoding);
  109. return $this->payload;
  110. }
  111. /**
  112. * @internal this function will become protected in the future (and be folded into serialize)
  113. *
  114. * @param string $charsetEncoding
  115. * @return void
  116. */
  117. public function createPayload($charsetEncoding = '')
  118. {
  119. $this->logDeprecationUnlessCalledBy('serialize');
  120. if ($charsetEncoding != '') {
  121. $this->content_type = 'text/xml; charset=' . $charsetEncoding;
  122. } else {
  123. $this->content_type = 'text/xml';
  124. }
  125. $result = $this->xml_header($charsetEncoding);
  126. $result .= '<methodName>' . $this->getCharsetEncoder()->encodeEntities(
  127. $this->methodname, PhpXmlRpc::$xmlrpc_internalencoding, $charsetEncoding) . "</methodName>\n";
  128. $result .= "<params>\n";
  129. foreach ($this->params as $p) {
  130. $result .= "<param>\n" . $p->serialize($charsetEncoding) .
  131. "</param>\n";
  132. }
  133. $result .= "</params>\n";
  134. $result .= $this->xml_footer();
  135. $this->payload = $result;
  136. }
  137. /**
  138. * @internal this function will become protected in the future (and be folded into serialize)
  139. *
  140. * @param string $charsetEncoding
  141. * @return string
  142. */
  143. public function xml_header($charsetEncoding = '')
  144. {
  145. $this->logDeprecationUnlessCalledBy('createPayload');
  146. if ($charsetEncoding != '') {
  147. return "<?xml version=\"1.0\" encoding=\"$charsetEncoding\" ?" . ">\n<methodCall>\n";
  148. } else {
  149. return "<?xml version=\"1.0\"?" . ">\n<methodCall>\n";
  150. }
  151. }
  152. /**
  153. * @internal this function will become protected in the future (and be folded into serialize)
  154. *
  155. * @return string
  156. */
  157. public function xml_footer()
  158. {
  159. $this->logDeprecationUnlessCalledBy('createPayload');
  160. return '</methodCall>';
  161. }
  162. /**
  163. * Given an open file handle, read all data available and parse it as an xml-rpc response.
  164. *
  165. * NB: the file handle is not closed by this function.
  166. * NNB: might have trouble in rare cases to work on network streams, as we check for a read of 0 bytes instead of
  167. * feof($fp). But since checking for feof(null) returns false, we would risk an infinite loop in that case,
  168. * because we cannot trust the caller to give us a valid pointer to an open file...
  169. *
  170. * @param resource $fp stream pointer
  171. * @param bool $headersProcessed
  172. * @param string $returnType
  173. * @return Response
  174. *
  175. * @todo arsing Responses is not really the responsibility of the Request class. Maybe of the Client...
  176. * @todo feature creep - add a flag to disable trying to parse the http headers
  177. */
  178. public function parseResponseFile($fp, $headersProcessed = false, $returnType = 'xmlrpcvals')
  179. {
  180. $ipd = '';
  181. // q: is there an optimal buffer size? Is there any value in making the buffer size a tuneable?
  182. while ($data = fread($fp, 32768)) {
  183. $ipd .= $data;
  184. }
  185. return $this->parseResponse($ipd, $headersProcessed, $returnType);
  186. }
  187. /**
  188. * Parse the xml-rpc response contained in the string $data and return a Response object.
  189. *
  190. * When $this->debug has been set to a value greater than 0, will echo debug messages to screen while decoding.
  191. *
  192. * @param string $data the xml-rpc response, possibly including http headers
  193. * @param bool $headersProcessed when true prevents parsing HTTP headers for interpretation of content-encoding and
  194. * consequent decoding
  195. * @param string $returnType decides return type, i.e. content of response->value(). Either 'xmlrpcvals', 'xml' or
  196. * 'phpvals'
  197. * @return Response
  198. *
  199. * @todo parsing Responses is not really the responsibility of the Request class. Maybe of the Client...
  200. * @todo what about only populating 'raw_data' in httpResponse when debug mode is > 0?
  201. * @todo feature creep - allow parsing data gotten from a stream pointer instead of a string: read it piecewise,
  202. * looking first for separation between headers and body, then for charset indicators, server debug info and
  203. * </methodResponse>. That would require a notable increase in code complexity...
  204. */
  205. public function parseResponse($data = '', $headersProcessed = false, $returnType = XMLParser::RETURN_XMLRPCVALS)
  206. {
  207. if ($this->debug > 0) {
  208. $this->getLogger()->debug("---GOT---\n$data\n---END---");
  209. }
  210. $this->httpResponse = array('raw_data' => $data, 'headers' => array(), 'cookies' => array());
  211. if ($data == '') {
  212. $this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': no response received from server.');
  213. return new Response(0, PhpXmlRpc::$xmlrpcerr['no_data'], PhpXmlRpc::$xmlrpcstr['no_data']);
  214. }
  215. // parse the HTTP headers of the response, if present, and separate them from data
  216. if (substr($data, 0, 4) == 'HTTP') {
  217. $httpParser = new Http();
  218. try {
  219. $httpResponse = $httpParser->parseResponseHeaders($data, $headersProcessed, $this->debug > 0);
  220. } catch (HttpException $e) {
  221. // failed processing of HTTP response headers
  222. // save into response obj the full payload received, for debugging
  223. return new Response(0, $e->getCode(), $e->getMessage(), '', array('raw_data' => $data, 'status_code', $e->statusCode()));
  224. } catch(\Exception $e) {
  225. return new Response(0, $e->getCode(), $e->getMessage(), '', array('raw_data' => $data));
  226. }
  227. } else {
  228. $httpResponse = $this->httpResponse;
  229. }
  230. // be tolerant of extra whitespace in response body
  231. $data = trim($data);
  232. /// @todo optimization creep - return an error msg if $data == ''
  233. // be tolerant of junk after methodResponse (e.g. javascript ads automatically inserted by free hosts)
  234. // idea from Luca Mariano, originally in PEARified version of the lib
  235. $pos = strrpos($data, '</methodResponse>');
  236. if ($pos !== false) {
  237. $data = substr($data, 0, $pos + 17);
  238. }
  239. // try to 'guestimate' the character encoding of the received response
  240. $respEncoding = XMLParser::guessEncoding(
  241. isset($httpResponse['headers']['content-type']) ? $httpResponse['headers']['content-type'] : '',
  242. $data
  243. );
  244. if ($this->debug >= 0) {
  245. $this->httpResponse = $httpResponse;
  246. } else {
  247. $httpResponse = null;
  248. }
  249. if ($this->debug > 0) {
  250. $start = strpos($data, '<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
  251. if ($start) {
  252. $start += strlen('<!-- SERVER DEBUG INFO (BASE64 ENCODED):');
  253. /// @todo what if there is no end tag?
  254. $end = strpos($data, '-->', $start);
  255. $comments = substr($data, $start, $end - $start);
  256. $this->getLogger()->debug("---SERVER DEBUG INFO (DECODED)---\n\t" .
  257. str_replace("\n", "\n\t", base64_decode($comments)) . "\n---END---", array('encoding' => $respEncoding));
  258. }
  259. }
  260. // if the user wants back raw xml, give it to her
  261. if ($returnType == 'xml') {
  262. return new Response($data, 0, '', 'xml', $httpResponse);
  263. }
  264. /// @todo move this block of code into the XMLParser
  265. if ($respEncoding != '') {
  266. // Since parsing will fail if charset is not specified in the xml declaration,
  267. // the encoding is not UTF8 and there are non-ascii chars in the text, we try to work round that...
  268. // The following code might be better for mb_string enabled installs, but makes the lib about 200% slower...
  269. //if (!is_valid_charset($respEncoding, array('UTF-8')))
  270. if (!in_array($respEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($data)) {
  271. if (function_exists('mb_convert_encoding')) {
  272. $data = mb_convert_encoding($data, 'UTF-8', $respEncoding);
  273. } else {
  274. if ($respEncoding == 'ISO-8859-1') {
  275. $data = utf8_encode($data);
  276. } else {
  277. $this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': unsupported charset encoding of received response: ' . $respEncoding);
  278. }
  279. }
  280. }
  281. }
  282. // PHP internally might use ISO-8859-1, so we have to tell the xml parser to give us back data in the expected charset.
  283. // What if internal encoding is not in one of the 3 allowed? We use the broadest one, i.e. utf8
  284. if (in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
  285. $options = array(XML_OPTION_TARGET_ENCODING => PhpXmlRpc::$xmlrpc_internalencoding);
  286. } else {
  287. $options = array(XML_OPTION_TARGET_ENCODING => 'UTF-8', 'target_charset' => PhpXmlRpc::$xmlrpc_internalencoding);
  288. }
  289. $xmlRpcParser = $this->getParser();
  290. $_xh = $xmlRpcParser->parse($data, $returnType, XMLParser::ACCEPT_RESPONSE, $options);
  291. // BC
  292. if (!is_array($_xh)) {
  293. $_xh = $xmlRpcParser->_xh;
  294. }
  295. // first error check: xml not well-formed
  296. if ($_xh['isf'] == 3) {
  297. // BC break: in the past for some cases we used the error message: 'XML error at line 1, check URL'
  298. // Q: should we give back an error with variable error number, as we do server-side? But if we do, will
  299. // we be able to tell apart the two cases? In theory, we never emit invalid xml on our end, but
  300. // there could be proxies meddling with the request, or network data corruption...
  301. $r = new Response(0, PhpXmlRpc::$xmlrpcerr['invalid_xml'],
  302. PhpXmlRpc::$xmlrpcstr['invalid_xml'] . ' ' . $_xh['isf_reason'], '', $httpResponse);
  303. if ($this->debug > 0) {
  304. $this->getLogger()->debug($_xh['isf_reason']);
  305. }
  306. }
  307. // second error check: xml well-formed but not xml-rpc compliant
  308. elseif ($_xh['isf'] == 2) {
  309. $r = new Response(0, PhpXmlRpc::$xmlrpcerr['xml_not_compliant'],
  310. PhpXmlRpc::$xmlrpcstr['xml_not_compliant'] . ' ' . $_xh['isf_reason'], '', $httpResponse);
  311. /// @todo echo something for the user? check if it was already done by the parser...
  312. //if ($this->debug > 0) {
  313. // $this->getLogger()->debug($_xh['isf_reason']);
  314. //}
  315. }
  316. // third error check: parsing of the response has somehow gone boink.
  317. /// @todo shall we omit this check, since we trust the parsing code?
  318. elseif ($_xh['isf'] > 3 || ($returnType == XMLParser::RETURN_XMLRPCVALS && !is_object($_xh['value']))) {
  319. // something odd has happened and it's time to generate a client side error indicating something odd went on
  320. $r = new Response(0, PhpXmlRpc::$xmlrpcerr['xml_parsing_error'], PhpXmlRpc::$xmlrpcstr['xml_parsing_error'],
  321. '', $httpResponse
  322. );
  323. /// @todo echo something for the user?
  324. } else {
  325. if ($this->debug > 1) {
  326. $this->getLogger()->debug(
  327. "---PARSED---\n".var_export($_xh['value'], true)."\n---END---"
  328. );
  329. }
  330. $v = $_xh['value'];
  331. if ($_xh['isf']) {
  332. /// @todo we should test (here or preferably in the parser) if server sent an int and a string, and/or
  333. /// coerce them into such...
  334. if ($returnType == XMLParser::RETURN_XMLRPCVALS) {
  335. $errNo_v = $v['faultCode'];
  336. $errStr_v = $v['faultString'];
  337. $errNo = $errNo_v->scalarVal();
  338. $errStr = $errStr_v->scalarVal();
  339. } else {
  340. $errNo = $v['faultCode'];
  341. $errStr = $v['faultString'];
  342. }
  343. if ($errNo == 0) {
  344. // FAULT returned, errno needs to reflect that
  345. /// @todo feature creep - add this code to PhpXmlRpc::$xmlrpcerr
  346. $this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': fault response received with faultCode 0 or null. Converted it to -1');
  347. /// @todo in Encoder::decodeXML, we use PhpXmlRpc::$xmlrpcerr['invalid_return'] for this case (see
  348. /// also the todo 17 lines above)
  349. $errNo = -1;
  350. }
  351. $r = new Response(0, $errNo, $errStr, '', $httpResponse);
  352. } else {
  353. $r = new Response($v, 0, '', $returnType, $httpResponse);
  354. }
  355. }
  356. return $r;
  357. }
  358. /**
  359. * Kept the old name even if Request class was renamed, for BC.
  360. *
  361. * @return string
  362. */
  363. public function kindOf()
  364. {
  365. return 'msg';
  366. }
  367. /**
  368. * Enables/disables the echoing to screen of the xml-rpc responses received.
  369. *
  370. * @param integer $level values <0, 0, 1, >1 are supported
  371. * @return $this
  372. */
  373. public function setDebug($level)
  374. {
  375. $this->debug = $level;
  376. return $this;
  377. }
  378. // *** BC layer ***
  379. // we have to make this return by ref in order to allow calls such as `$resp->_cookies['name'] = ['value' => 'something'];`
  380. public function &__get($name)
  381. {
  382. switch ($name) {
  383. case 'me':
  384. case 'mytype':
  385. case '_php_class':
  386. case 'payload':
  387. case 'content_type':
  388. $this->logDeprecation('Getting property Request::' . $name . ' is deprecated');
  389. return $this->$name;
  390. case 'httpResponse':
  391. // manually implement the 'protected property' behaviour
  392. $canAccess = false;
  393. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  394. if (isset($trace[1]) && isset($trace[1]['class'])) {
  395. if (is_subclass_of($trace[1]['class'], 'PhpXmlRpc\Request')) {
  396. $canAccess = true;
  397. }
  398. }
  399. if ($canAccess) {
  400. $this->logDeprecation('Getting property Request::' . $name . ' is deprecated');
  401. return $this->httpResponse;
  402. } else {
  403. trigger_error("Cannot access protected property Request::httpResponse in " . __FILE__, E_USER_ERROR);
  404. }
  405. break;
  406. default:
  407. /// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
  408. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
  409. trigger_error('Undefined property via __get(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
  410. $result = null;
  411. return $result;
  412. }
  413. }
  414. public function __set($name, $value)
  415. {
  416. switch ($name) {
  417. case 'methodname':
  418. case 'params':
  419. case 'debug':
  420. case 'payload':
  421. case 'content_type':
  422. $this->logDeprecation('Setting property Request::' . $name . ' is deprecated');
  423. $this->$name = $value;
  424. break;
  425. case 'httpResponse':
  426. // manually implement the 'protected property' behaviour
  427. $canAccess = false;
  428. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  429. if (isset($trace[1]) && isset($trace[1]['class'])) {
  430. if (is_subclass_of($trace[1]['class'], 'PhpXmlRpc\Request')) {
  431. $canAccess = true;
  432. }
  433. }
  434. if ($canAccess) {
  435. $this->logDeprecation('Setting property Request::' . $name . ' is deprecated');
  436. $this->httpResponse = $value;
  437. } else {
  438. trigger_error("Cannot access protected property Request::httpResponse in " . __FILE__, E_USER_ERROR);
  439. }
  440. break;
  441. default:
  442. /// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
  443. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
  444. trigger_error('Undefined property via __set(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
  445. }
  446. }
  447. public function __isset($name)
  448. {
  449. switch ($name) {
  450. case 'methodname':
  451. case 'params':
  452. case 'debug':
  453. case 'payload':
  454. case 'content_type':
  455. $this->logDeprecation('Checking property Request::' . $name . ' is deprecated');
  456. return isset($this->$name);
  457. case 'httpResponse':
  458. // manually implement the 'protected property' behaviour
  459. $canAccess = false;
  460. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  461. if (isset($trace[1]) && isset($trace[1]['class'])) {
  462. if (is_subclass_of($trace[1]['class'], 'PhpXmlRpc\Request')) {
  463. $canAccess = true;
  464. }
  465. }
  466. if ($canAccess) {
  467. $this->logDeprecation('Checking property Request::' . $name . ' is deprecated');
  468. return isset($this->httpResponse);
  469. }
  470. // break through voluntarily
  471. default:
  472. return false;
  473. }
  474. }
  475. public function __unset($name)
  476. {
  477. switch ($name) {
  478. case 'methodname':
  479. case 'params':
  480. case 'debug':
  481. case 'payload':
  482. case 'content_type':
  483. $this->logDeprecation('Unsetting property Request::' . $name . ' is deprecated');
  484. unset($this->$name);
  485. break;
  486. case 'httpResponse':
  487. // manually implement the 'protected property' behaviour
  488. $canAccess = false;
  489. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  490. if (isset($trace[1]) && isset($trace[1]['class'])) {
  491. if (is_subclass_of($trace[1]['class'], 'PhpXmlRpc\Request')) {
  492. $canAccess = true;
  493. }
  494. }
  495. if ($canAccess) {
  496. $this->logDeprecation('Unsetting property Request::' . $name . ' is deprecated');
  497. unset($this->httpResponse);
  498. } else {
  499. trigger_error("Cannot access protected property Request::httpResponse in " . __FILE__, E_USER_ERROR);
  500. }
  501. break;
  502. default:
  503. /// @todo throw instead? There are very few other places where the lib trigger errors which can potentially reach stdout...
  504. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
  505. trigger_error('Undefined property via __unset(): ' . $name . ' in ' . $trace[0]['file'] . ' on line ' . $trace[0]['line'], E_USER_WARNING);
  506. }
  507. }
  508. }