You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

625 lines
16 KiB

7 years ago
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
  33. * @license http://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 1.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. if ( ! function_exists('xml_parser_create'))
  40. {
  41. show_error('Your PHP installation does not support XML');
  42. }
  43. if ( ! class_exists('CI_Xmlrpc', FALSE))
  44. {
  45. show_error('You must load the Xmlrpc class before loading the Xmlrpcs class in order to create a server.');
  46. }
  47. // ------------------------------------------------------------------------
  48. /**
  49. * XML-RPC server class
  50. *
  51. * @package CodeIgniter
  52. * @subpackage Libraries
  53. * @category XML-RPC
  54. * @author EllisLab Dev Team
  55. * @link https://codeigniter.com/user_guide/libraries/xmlrpc.html
  56. */
  57. class CI_Xmlrpcs extends CI_Xmlrpc {
  58. /**
  59. * Array of methods mapped to function names and signatures
  60. *
  61. * @var array
  62. */
  63. public $methods = array();
  64. /**
  65. * Debug Message
  66. *
  67. * @var string
  68. */
  69. public $debug_msg = '';
  70. /**
  71. * XML RPC Server methods
  72. *
  73. * @var array
  74. */
  75. public $system_methods = array();
  76. /**
  77. * Configuration object
  78. *
  79. * @var object
  80. */
  81. public $object = FALSE;
  82. /**
  83. * Initialize XMLRPC class
  84. *
  85. * @param array $config
  86. * @return void
  87. */
  88. public function __construct($config = array())
  89. {
  90. parent::__construct();
  91. $this->set_system_methods();
  92. if (isset($config['functions']) && is_array($config['functions']))
  93. {
  94. $this->methods = array_merge($this->methods, $config['functions']);
  95. }
  96. log_message('info', 'XML-RPC Server Class Initialized');
  97. }
  98. // --------------------------------------------------------------------
  99. /**
  100. * Initialize Prefs and Serve
  101. *
  102. * @param mixed
  103. * @return void
  104. */
  105. public function initialize($config = array())
  106. {
  107. if (isset($config['functions']) && is_array($config['functions']))
  108. {
  109. $this->methods = array_merge($this->methods, $config['functions']);
  110. }
  111. if (isset($config['debug']))
  112. {
  113. $this->debug = $config['debug'];
  114. }
  115. if (isset($config['object']) && is_object($config['object']))
  116. {
  117. $this->object = $config['object'];
  118. }
  119. if (isset($config['xss_clean']))
  120. {
  121. $this->xss_clean = $config['xss_clean'];
  122. }
  123. }
  124. // --------------------------------------------------------------------
  125. /**
  126. * Setting of System Methods
  127. *
  128. * @return void
  129. */
  130. public function set_system_methods()
  131. {
  132. $this->methods = array(
  133. 'system.listMethods' => array(
  134. 'function' => 'this.listMethods',
  135. 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcString), array($this->xmlrpcArray)),
  136. 'docstring' => 'Returns an array of available methods on this server'),
  137. 'system.methodHelp' => array(
  138. 'function' => 'this.methodHelp',
  139. 'signature' => array(array($this->xmlrpcString, $this->xmlrpcString)),
  140. 'docstring' => 'Returns a documentation string for the specified method'),
  141. 'system.methodSignature' => array(
  142. 'function' => 'this.methodSignature',
  143. 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcString)),
  144. 'docstring' => 'Returns an array describing the return type and required parameters of a method'),
  145. 'system.multicall' => array(
  146. 'function' => 'this.multicall',
  147. 'signature' => array(array($this->xmlrpcArray, $this->xmlrpcArray)),
  148. 'docstring' => 'Combine multiple RPC calls in one request. See http://www.xmlrpc.com/discuss/msgReader$1208 for details')
  149. );
  150. }
  151. // --------------------------------------------------------------------
  152. /**
  153. * Main Server Function
  154. *
  155. * @return void
  156. */
  157. public function serve()
  158. {
  159. $r = $this->parseRequest();
  160. $payload = '<?xml version="1.0" encoding="'.$this->xmlrpc_defencoding.'"?'.'>'."\n".$this->debug_msg.$r->prepare_response();
  161. header('Content-Type: text/xml');
  162. header('Content-Length: '.strlen($payload));
  163. exit($payload);
  164. }
  165. // --------------------------------------------------------------------
  166. /**
  167. * Add Method to Class
  168. *
  169. * @param string method name
  170. * @param string function
  171. * @param string signature
  172. * @param string docstring
  173. * @return void
  174. */
  175. public function add_to_map($methodname, $function, $sig, $doc)
  176. {
  177. $this->methods[$methodname] = array(
  178. 'function' => $function,
  179. 'signature' => $sig,
  180. 'docstring' => $doc
  181. );
  182. }
  183. // --------------------------------------------------------------------
  184. /**
  185. * Parse Server Request
  186. *
  187. * @param string data
  188. * @return object xmlrpc response
  189. */
  190. public function parseRequest($data = '')
  191. {
  192. //-------------------------------------
  193. // Get Data
  194. //-------------------------------------
  195. if ($data === '')
  196. {
  197. $CI =& get_instance();
  198. if ($CI->input->method() === 'post')
  199. {
  200. $data = $CI->input->raw_input_stream;
  201. }
  202. }
  203. //-------------------------------------
  204. // Set up XML Parser
  205. //-------------------------------------
  206. $parser = xml_parser_create($this->xmlrpc_defencoding);
  207. $parser_object = new XML_RPC_Message('filler');
  208. $pname = (string) $parser;
  209. $parser_object->xh[$pname] = array(
  210. 'isf' => 0,
  211. 'isf_reason' => '',
  212. 'params' => array(),
  213. 'stack' => array(),
  214. 'valuestack' => array(),
  215. 'method' => ''
  216. );
  217. xml_set_object($parser, $parser_object);
  218. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, TRUE);
  219. xml_set_element_handler($parser, 'open_tag', 'closing_tag');
  220. xml_set_character_data_handler($parser, 'character_data');
  221. //xml_set_default_handler($parser, 'default_handler');
  222. //-------------------------------------
  223. // PARSE + PROCESS XML DATA
  224. //-------------------------------------
  225. if ( ! xml_parse($parser, $data, 1))
  226. {
  227. // Return XML error as a faultCode
  228. $r = new XML_RPC_Response(0,
  229. $this->xmlrpcerrxml + xml_get_error_code($parser),
  230. sprintf('XML error: %s at line %d',
  231. xml_error_string(xml_get_error_code($parser)),
  232. xml_get_current_line_number($parser)));
  233. xml_parser_free($parser);
  234. }
  235. elseif ($parser_object->xh[$pname]['isf'])
  236. {
  237. return new XML_RPC_Response(0, $this->xmlrpcerr['invalid_return'], $this->xmlrpcstr['invalid_return']);
  238. }
  239. else
  240. {
  241. xml_parser_free($parser);
  242. $m = new XML_RPC_Message($parser_object->xh[$pname]['method']);
  243. $plist = '';
  244. for ($i = 0, $c = count($parser_object->xh[$pname]['params']); $i < $c; $i++)
  245. {
  246. if ($this->debug === TRUE)
  247. {
  248. $plist .= $i.' - '.print_r(get_object_vars($parser_object->xh[$pname]['params'][$i]), TRUE).";\n";
  249. }
  250. $m->addParam($parser_object->xh[$pname]['params'][$i]);
  251. }
  252. if ($this->debug === TRUE)
  253. {
  254. echo "<pre>---PLIST---\n".$plist."\n---PLIST END---\n\n</pre>";
  255. }
  256. $r = $this->_execute($m);
  257. }
  258. //-------------------------------------
  259. // SET DEBUGGING MESSAGE
  260. //-------------------------------------
  261. if ($this->debug === TRUE)
  262. {
  263. $this->debug_msg = "<!-- DEBUG INFO:\n\n".$plist."\n END DEBUG-->\n";
  264. }
  265. return $r;
  266. }
  267. // --------------------------------------------------------------------
  268. /**
  269. * Executes the Method
  270. *
  271. * @param object
  272. * @return mixed
  273. */
  274. protected function _execute($m)
  275. {
  276. $methName = $m->method_name;
  277. // Check to see if it is a system call
  278. $system_call = (strpos($methName, 'system') === 0);
  279. if ($this->xss_clean === FALSE)
  280. {
  281. $m->xss_clean = FALSE;
  282. }
  283. //-------------------------------------
  284. // Valid Method
  285. //-------------------------------------
  286. if ( ! isset($this->methods[$methName]['function']))
  287. {
  288. return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']);
  289. }
  290. //-------------------------------------
  291. // Check for Method (and Object)
  292. //-------------------------------------
  293. $method_parts = explode('.', $this->methods[$methName]['function']);
  294. $objectCall = ! empty($method_parts[1]);
  295. if ($system_call === TRUE)
  296. {
  297. if ( ! is_callable(array($this, $method_parts[1])))
  298. {
  299. return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']);
  300. }
  301. }
  302. elseif (($objectCall && ! is_callable(array($method_parts[0], $method_parts[1])))
  303. OR ( ! $objectCall && ! is_callable($this->methods[$methName]['function']))
  304. )
  305. {
  306. return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']);
  307. }
  308. //-------------------------------------
  309. // Checking Methods Signature
  310. //-------------------------------------
  311. if (isset($this->methods[$methName]['signature']))
  312. {
  313. $sig = $this->methods[$methName]['signature'];
  314. for ($i = 0, $c = count($sig); $i < $c; $i++)
  315. {
  316. $current_sig = $sig[$i];
  317. if (count($current_sig) === count($m->params)+1)
  318. {
  319. for ($n = 0, $mc = count($m->params); $n < $mc; $n++)
  320. {
  321. $p = $m->params[$n];
  322. $pt = ($p->kindOf() === 'scalar') ? $p->scalarval() : $p->kindOf();
  323. if ($pt !== $current_sig[$n+1])
  324. {
  325. $pno = $n+1;
  326. $wanted = $current_sig[$n+1];
  327. return new XML_RPC_Response(0,
  328. $this->xmlrpcerr['incorrect_params'],
  329. $this->xmlrpcstr['incorrect_params'] .
  330. ': Wanted '.$wanted.', got '.$pt.' at param '.$pno.')');
  331. }
  332. }
  333. }
  334. }
  335. }
  336. //-------------------------------------
  337. // Calls the Function
  338. //-------------------------------------
  339. if ($objectCall === TRUE)
  340. {
  341. if ($method_parts[0] === 'this' && $system_call === TRUE)
  342. {
  343. return call_user_func(array($this, $method_parts[1]), $m);
  344. }
  345. elseif ($this->object === FALSE)
  346. {
  347. return get_instance()->{$method_parts[1]}($m);
  348. }
  349. else
  350. {
  351. return $this->object->{$method_parts[1]}($m);
  352. }
  353. }
  354. else
  355. {
  356. return call_user_func($this->methods[$methName]['function'], $m);
  357. }
  358. }
  359. // --------------------------------------------------------------------
  360. /**
  361. * Server Function: List Methods
  362. *
  363. * @param mixed
  364. * @return object
  365. */
  366. public function listMethods($m)
  367. {
  368. $v = new XML_RPC_Values();
  369. $output = array();
  370. foreach ($this->methods as $key => $value)
  371. {
  372. $output[] = new XML_RPC_Values($key, 'string');
  373. }
  374. foreach ($this->system_methods as $key => $value)
  375. {
  376. $output[] = new XML_RPC_Values($key, 'string');
  377. }
  378. $v->addArray($output);
  379. return new XML_RPC_Response($v);
  380. }
  381. // --------------------------------------------------------------------
  382. /**
  383. * Server Function: Return Signature for Method
  384. *
  385. * @param mixed
  386. * @return object
  387. */
  388. public function methodSignature($m)
  389. {
  390. $parameters = $m->output_parameters();
  391. $method_name = $parameters[0];
  392. if (isset($this->methods[$method_name]))
  393. {
  394. if ($this->methods[$method_name]['signature'])
  395. {
  396. $sigs = array();
  397. $signature = $this->methods[$method_name]['signature'];
  398. for ($i = 0, $c = count($signature); $i < $c; $i++)
  399. {
  400. $cursig = array();
  401. $inSig = $signature[$i];
  402. for ($j = 0, $jc = count($inSig); $j < $jc; $j++)
  403. {
  404. $cursig[]= new XML_RPC_Values($inSig[$j], 'string');
  405. }
  406. $sigs[] = new XML_RPC_Values($cursig, 'array');
  407. }
  408. return new XML_RPC_Response(new XML_RPC_Values($sigs, 'array'));
  409. }
  410. return new XML_RPC_Response(new XML_RPC_Values('undef', 'string'));
  411. }
  412. return new XML_RPC_Response(0, $this->xmlrpcerr['introspect_unknown'], $this->xmlrpcstr['introspect_unknown']);
  413. }
  414. // --------------------------------------------------------------------
  415. /**
  416. * Server Function: Doc String for Method
  417. *
  418. * @param mixed
  419. * @return object
  420. */
  421. public function methodHelp($m)
  422. {
  423. $parameters = $m->output_parameters();
  424. $method_name = $parameters[0];
  425. if (isset($this->methods[$method_name]))
  426. {
  427. $docstring = isset($this->methods[$method_name]['docstring']) ? $this->methods[$method_name]['docstring'] : '';
  428. return new XML_RPC_Response(new XML_RPC_Values($docstring, 'string'));
  429. }
  430. else
  431. {
  432. return new XML_RPC_Response(0, $this->xmlrpcerr['introspect_unknown'], $this->xmlrpcstr['introspect_unknown']);
  433. }
  434. }
  435. // --------------------------------------------------------------------
  436. /**
  437. * Server Function: Multi-call
  438. *
  439. * @param mixed
  440. * @return object
  441. */
  442. public function multicall($m)
  443. {
  444. // Disabled
  445. return new XML_RPC_Response(0, $this->xmlrpcerr['unknown_method'], $this->xmlrpcstr['unknown_method']);
  446. $parameters = $m->output_parameters();
  447. $calls = $parameters[0];
  448. $result = array();
  449. foreach ($calls as $value)
  450. {
  451. $m = new XML_RPC_Message($value[0]);
  452. $plist = '';
  453. for ($i = 0, $c = count($value[1]); $i < $c; $i++)
  454. {
  455. $m->addParam(new XML_RPC_Values($value[1][$i], 'string'));
  456. }
  457. $attempt = $this->_execute($m);
  458. if ($attempt->faultCode() !== 0)
  459. {
  460. return $attempt;
  461. }
  462. $result[] = new XML_RPC_Values(array($attempt->value()), 'array');
  463. }
  464. return new XML_RPC_Response(new XML_RPC_Values($result, 'array'));
  465. }
  466. // --------------------------------------------------------------------
  467. /**
  468. * Multi-call Function: Error Handling
  469. *
  470. * @param mixed
  471. * @return object
  472. */
  473. public function multicall_error($err)
  474. {
  475. $str = is_string($err) ? $this->xmlrpcstr["multicall_${err}"] : $err->faultString();
  476. $code = is_string($err) ? $this->xmlrpcerr["multicall_${err}"] : $err->faultCode();
  477. $struct['faultCode'] = new XML_RPC_Values($code, 'int');
  478. $struct['faultString'] = new XML_RPC_Values($str, 'string');
  479. return new XML_RPC_Values($struct, 'struct');
  480. }
  481. // --------------------------------------------------------------------
  482. /**
  483. * Multi-call Function: Processes method
  484. *
  485. * @param mixed
  486. * @return object
  487. */
  488. public function do_multicall($call)
  489. {
  490. if ($call->kindOf() !== 'struct')
  491. {
  492. return $this->multicall_error('notstruct');
  493. }
  494. elseif ( ! $methName = $call->me['struct']['methodName'])
  495. {
  496. return $this->multicall_error('nomethod');
  497. }
  498. list($scalar_value, $scalar_type) = array(reset($methName->me), key($methName->me));
  499. $scalar_type = $scalar_type === $this->xmlrpcI4 ? $this->xmlrpcInt : $scalar_type;
  500. if ($methName->kindOf() !== 'scalar' OR $scalar_type !== 'string')
  501. {
  502. return $this->multicall_error('notstring');
  503. }
  504. elseif ($scalar_value === 'system.multicall')
  505. {
  506. return $this->multicall_error('recursion');
  507. }
  508. elseif ( ! $params = $call->me['struct']['params'])
  509. {
  510. return $this->multicall_error('noparams');
  511. }
  512. elseif ($params->kindOf() !== 'array')
  513. {
  514. return $this->multicall_error('notarray');
  515. }
  516. list($b, $a) = array(reset($params->me), key($params->me));
  517. $msg = new XML_RPC_Message($scalar_value);
  518. for ($i = 0, $numParams = count($b); $i < $numParams; $i++)
  519. {
  520. $msg->params[] = $params->me['array'][$i];
  521. }
  522. $result = $this->_execute($msg);
  523. if ($result->faultCode() !== 0)
  524. {
  525. return $this->multicall_error($result);
  526. }
  527. return new XML_RPC_Values(array($result->value()), 'array');
  528. }
  529. }