Encoder.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. <?php
  2. namespace PhpXmlRpc;
  3. use PhpXmlRpc\Helper\XMLParser;
  4. use PhpXmlRpc\Traits\LoggerAware;
  5. use PhpXmlRpc\Traits\ParserAware;
  6. /**
  7. * A helper class to easily convert between Value objects and php native values.
  8. *
  9. * @todo implement an interface
  10. * @todo add class constants for the options values
  11. */
  12. class Encoder
  13. {
  14. use LoggerAware;
  15. use ParserAware;
  16. /**
  17. * Takes an xml-rpc Value in object instance and translates it into native PHP types, recursively.
  18. * Works with xml-rpc Request objects as input, too.
  19. * Xmlrpc dateTime values will be converted to strings or DateTime objects depending on an $options parameter
  20. * Supports i8 and NIL xml-rpc values without the need for specific options.
  21. * Both xml-rpc arrays and structs are decoded into PHP arrays, with the exception described below:
  22. * Given proper options parameter, can rebuild generic php object instances (provided those have been encoded to
  23. * xml-rpc format using a corresponding option in php_xmlrpc_encode()).
  24. * PLEASE NOTE that rebuilding php objects involves calling their constructor function.
  25. * This means that the remote communication end can decide which php code will get executed on your server, leaving
  26. * the door possibly open to 'php-injection' style of attacks (provided you have some classes defined on your server
  27. * that might wreak havoc if instances are built outside an appropriate context).
  28. * Make sure you trust the remote server/client before enabling this!
  29. *
  30. * @author Dan Libby
  31. *
  32. * @param Value|Request $xmlrpcVal
  33. * @param array $options accepted elements:
  34. * - 'decode_php_objs': if set in the options array, xml-rpc structs can be decoded into php
  35. * objects, see the details above;
  36. * - 'dates_as_objects': when set xml-rpc dateTimes are decoded as php DateTime objects
  37. * - 'extension_api': reserved for usage by phpxmlrpc-polyfill
  38. * @return mixed
  39. *
  40. * Feature creep -- add an option to allow converting xml-rpc dateTime values to unix timestamps (integers)
  41. */
  42. public function decode($xmlrpcVal, $options = array())
  43. {
  44. switch ($xmlrpcVal->kindOf()) {
  45. case 'scalar':
  46. if (in_array('extension_api', $options)) {
  47. $val = $xmlrpcVal->scalarVal();
  48. $typ = $xmlrpcVal->scalarTyp();
  49. switch ($typ) {
  50. case 'dateTime.iso8601':
  51. $xmlrpcVal = array(
  52. 'xmlrpc_type' => 'datetime',
  53. 'scalar' => $val,
  54. 'timestamp' => \PhpXmlRpc\Helper\Date::iso8601Decode($val)
  55. );
  56. return (object)$xmlrpcVal;
  57. case 'base64':
  58. $xmlrpcVal = array(
  59. 'xmlrpc_type' => 'base64',
  60. 'scalar' => $val
  61. );
  62. return (object)$xmlrpcVal;
  63. case 'string':
  64. if (isset($options['extension_api_encoding'])) {
  65. // if iconv is not available, we use mb_convert_encoding
  66. if (function_exists('iconv')) {
  67. $dval = @iconv('UTF-8', $options['extension_api_encoding'], $val);
  68. } elseif (function_exists('mb_convert_encoding')) {
  69. /// @todo check for discrepancies between the supported charset names
  70. $dval = @mb_convert_encoding($val, $options['extension_api_encoding'], 'UTF-8');
  71. } else {
  72. $dval = false;
  73. }
  74. if ($dval !== false) {
  75. return $dval;
  76. }
  77. }
  78. // break through voluntarily
  79. default:
  80. return $val;
  81. }
  82. }
  83. if (in_array('dates_as_objects', $options) && $xmlrpcVal->scalarTyp() == 'dateTime.iso8601') {
  84. // we return a Datetime object instead of a string; since now the constructor of xml-rpc value accepts
  85. // safely string, int and DateTimeInterface, we cater to all 3 cases here
  86. $out = $xmlrpcVal->scalarVal();
  87. if (is_string($out)) {
  88. $out = strtotime($out);
  89. // NB: if the string does not convert into a timestamp, this will return false.
  90. // We avoid logging an error here, as we presume it was already done when parsing the xml
  91. /// @todo we could return null, to be more in line with what the XMLParser does...
  92. }
  93. if (is_int($out)) {
  94. $result = new \DateTime();
  95. $result->setTimestamp($out);
  96. return $result;
  97. } elseif (is_a($out, 'DateTimeInterface') || is_a($out, 'DateTime')) {
  98. return $out;
  99. }
  100. }
  101. return $xmlrpcVal->scalarVal();
  102. case 'array':
  103. $arr = array();
  104. foreach ($xmlrpcVal as $value) {
  105. $arr[] = $this->decode($value, $options);
  106. }
  107. return $arr;
  108. case 'struct':
  109. // If user said so, try to rebuild php objects for specific struct vals.
  110. /// @todo should we raise a warning for class not found?
  111. // shall we check for proper subclass of xml-rpc value instead of presence of _php_class to detect
  112. // what we can do?
  113. if (in_array('decode_php_objs', $options) && $xmlrpcVal->_php_class != ''
  114. && class_exists($xmlrpcVal->_php_class)
  115. ) {
  116. $obj = @new $xmlrpcVal->_php_class();
  117. foreach ($xmlrpcVal as $key => $value) {
  118. $obj->$key = $this->decode($value, $options);
  119. }
  120. return $obj;
  121. } else {
  122. $arr = array();
  123. foreach ($xmlrpcVal as $key => $value) {
  124. $arr[$key] = $this->decode($value, $options);
  125. }
  126. return $arr;
  127. }
  128. case 'msg':
  129. $paramCount = $xmlrpcVal->getNumParams();
  130. $arr = array();
  131. for ($i = 0; $i < $paramCount; $i++) {
  132. $arr[] = $this->decode($xmlrpcVal->getParam($i), $options);
  133. }
  134. return $arr;
  135. /// @todo throw on unsupported type
  136. }
  137. }
  138. /**
  139. * Takes native php types and encodes them into xml-rpc Value objects, recursively.
  140. * PHP strings, integers, floats and booleans have a straightforward encoding - note that integers will _not_ be
  141. * converted to xml-rpc <i8> elements, even if they exceed the 32-bit range.
  142. * PHP arrays will be encoded to either xml-rpc structs or arrays, depending on whether they are hashes
  143. * or plain 0..N integer indexed.
  144. * PHP objects will be encoded into xml-rpc structs, except if they implement DateTimeInterface, in which case they
  145. * will be encoded as dateTime values.
  146. * PhpXmlRpc\Value objects will not be double-encoded - which makes it possible to pass in a pre-created base64 Value
  147. * as part of a php array.
  148. * If given a proper $options parameter, php object instances will be encoded into 'special' xml-rpc values, that can
  149. * later be decoded into php object instances by calling php_xmlrpc_decode() with a corresponding option.
  150. * PHP resource and NULL variables will be converted into uninitialized Value objects (which will lead to invalid
  151. * xml-rpc when later serialized); to support encoding of the latter use the appropriate $options parameter.
  152. *
  153. * @author Dan Libby
  154. *
  155. * @param mixed $phpVal the value to be converted into an xml-rpc value object
  156. * @param array $options can include:
  157. * - 'encode_php_objs' when set, some out-of-band info will be added to the xml produced by
  158. * serializing the built Value, which can later be decoced by this library to rebuild an
  159. * instance of the same php object
  160. * - 'auto_dates': when set, any string which respects the xml-rpc datetime format will be converted to a dateTime Value
  161. * - 'null_extension': when set, php NULL values will be converted to an xml-rpc <NIL> (or <EX:NIL>) Value
  162. * - 'extension_api': reserved for usage by phpxmlrpc-polyfill
  163. * @return Value
  164. *
  165. * Feature creep -- could support more types via optional type argument (string => datetime support has been added,
  166. * ??? => base64 not yet). Also: allow auto-encoding of integers to i8 when too-big to fit into i4
  167. */
  168. public function encode($phpVal, $options = array())
  169. {
  170. $type = gettype($phpVal);
  171. switch ($type) {
  172. case 'string':
  173. if (in_array('auto_dates', $options) && preg_match(PhpXmlRpc::$xmlrpc_datetime_format, $phpVal)) {
  174. $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDateTime);
  175. } else {
  176. $xmlrpcVal = new Value($phpVal, Value::$xmlrpcString);
  177. }
  178. break;
  179. case 'integer':
  180. $xmlrpcVal = new Value($phpVal, Value::$xmlrpcInt);
  181. break;
  182. case 'double':
  183. $xmlrpcVal = new Value($phpVal, Value::$xmlrpcDouble);
  184. break;
  185. case 'boolean':
  186. $xmlrpcVal = new Value($phpVal, Value::$xmlrpcBoolean);
  187. break;
  188. case 'array':
  189. // A shorter one-liner would be
  190. // $tmp = array_diff(array_keys($phpVal), range(0, count($phpVal)-1));
  191. // but execution time skyrockets!
  192. $j = 0;
  193. $arr = array();
  194. $ko = false;
  195. foreach ($phpVal as $key => $val) {
  196. $arr[$key] = $this->encode($val, $options);
  197. if (!$ko && $key !== $j) {
  198. $ko = true;
  199. }
  200. $j++;
  201. }
  202. if ($ko) {
  203. $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
  204. } else {
  205. $xmlrpcVal = new Value($arr, Value::$xmlrpcArray);
  206. }
  207. break;
  208. case 'object':
  209. if (is_a($phpVal, 'PhpXmlRpc\Value')) {
  210. $xmlrpcVal = $phpVal;
  211. // DateTimeInterface is not present in php 5.4...
  212. } elseif (is_a($phpVal, 'DateTimeInterface') || is_a($phpVal, 'DateTime')) {
  213. $xmlrpcVal = new Value($phpVal->format('Ymd\TH:i:s'), Value::$xmlrpcDateTime);
  214. } elseif (in_array('extension_api', $options) && $phpVal instanceof \stdClass && isset($phpVal->xmlrpc_type)) {
  215. // Handle the 'pre-converted' base64 and datetime values
  216. if (isset($phpVal->scalar)) {
  217. switch ($phpVal->xmlrpc_type) {
  218. case 'base64':
  219. $xmlrpcVal = new Value($phpVal->scalar, Value::$xmlrpcBase64);
  220. break;
  221. case 'datetime':
  222. $xmlrpcVal = new Value($phpVal->scalar, Value::$xmlrpcDateTime);
  223. break;
  224. default:
  225. $xmlrpcVal = new Value();
  226. }
  227. } else {
  228. $xmlrpcVal = new Value();
  229. }
  230. } else {
  231. $arr = array();
  232. foreach ($phpVal as $k => $v) {
  233. $arr[$k] = $this->encode($v, $options);
  234. }
  235. $xmlrpcVal = new Value($arr, Value::$xmlrpcStruct);
  236. if (in_array('encode_php_objs', $options)) {
  237. // let's save original class name into xml-rpc value: it might be useful later on...
  238. $xmlrpcVal->_php_class = get_class($phpVal);
  239. }
  240. }
  241. break;
  242. case 'NULL':
  243. if (in_array('extension_api', $options)) {
  244. $xmlrpcVal = new Value('', Value::$xmlrpcString);
  245. } elseif (in_array('null_extension', $options)) {
  246. $xmlrpcVal = new Value('', Value::$xmlrpcNull);
  247. } else {
  248. $xmlrpcVal = new Value();
  249. }
  250. break;
  251. case 'resource':
  252. if (in_array('extension_api', $options)) {
  253. $xmlrpcVal = new Value((int)$phpVal, Value::$xmlrpcInt);
  254. } else {
  255. $xmlrpcVal = new Value();
  256. }
  257. break;
  258. // catch "user function", "unknown type"
  259. default:
  260. // it has to return an empty object in case, not a boolean. (giancarlo pinerolo)
  261. $xmlrpcVal = new Value();
  262. break;
  263. }
  264. return $xmlrpcVal;
  265. }
  266. /**
  267. * Convert the xml representation of a method response, method request or single
  268. * xml-rpc value into the appropriate object (a.k.a. deserialize).
  269. *
  270. * @param string $xmlVal
  271. * @param array $options unused atm
  272. * @return Value|Request|Response|false false on error, or an instance of either Value, Request or Response
  273. *
  274. * @todo is this a good name/class for this method? It does something quite different from 'decode' after all
  275. * (returning objects vs returns plain php values)... In fact, it belongs rather to a Parser class
  276. * @todo feature creep -- we should allow an option to return php native types instead of PhpXmlRpc objects instances
  277. * @todo feature creep -- allow source charset to be passed in as an option, in case the xml misses its declaration
  278. * @todo feature creep -- allow expected type (val/req/resp) to be passed in as an option
  279. */
  280. public function decodeXml($xmlVal, $options = array())
  281. {
  282. // 'guestimate' encoding
  283. $valEncoding = XMLParser::guessEncoding('', $xmlVal);
  284. if ($valEncoding != '') {
  285. // Since parsing will fail if
  286. // - charset is not specified in the xml declaration,
  287. // - the encoding is not UTF8 and
  288. // - there are non-ascii chars in the text,
  289. // we try to work round that...
  290. // The following code might be better for mb_string enabled installs, but makes the lib about 200% slower...
  291. //if (!is_valid_charset($valEncoding, array('UTF-8'))
  292. if (!in_array($valEncoding, array('UTF-8', 'US-ASCII')) && !XMLParser::hasEncoding($xmlVal)) {
  293. if (function_exists('mb_convert_encoding')) {
  294. $xmlVal = mb_convert_encoding($xmlVal, 'UTF-8', $valEncoding);
  295. } else {
  296. if ($valEncoding == 'ISO-8859-1') {
  297. $xmlVal = utf8_encode($xmlVal);
  298. } else {
  299. $this->getLogger()->error('XML-RPC: ' . __METHOD__ . ': invalid charset encoding of xml text: ' . $valEncoding);
  300. }
  301. }
  302. }
  303. }
  304. // What if internal encoding is not in one of the 3 allowed? We use the broadest one, i.e. utf8!
  305. /// @todo with php < 5.6, this does not work. We should add a manual conversion of the xml string to UTF8
  306. if (in_array(PhpXmlRpc::$xmlrpc_internalencoding, array('UTF-8', 'ISO-8859-1', 'US-ASCII'))) {
  307. $parserOptions = array(XML_OPTION_TARGET_ENCODING => PhpXmlRpc::$xmlrpc_internalencoding);
  308. } else {
  309. $parserOptions = array(XML_OPTION_TARGET_ENCODING => 'UTF-8', 'target_charset' => PhpXmlRpc::$xmlrpc_internalencoding);
  310. }
  311. $xmlRpcParser = $this->getParser();
  312. $_xh = $xmlRpcParser->parse(
  313. $xmlVal,
  314. XMLParser::RETURN_XMLRPCVALS,
  315. XMLParser::ACCEPT_REQUEST | XMLParser::ACCEPT_RESPONSE | XMLParser::ACCEPT_VALUE | XMLParser::ACCEPT_FAULT,
  316. $parserOptions
  317. );
  318. // BC
  319. if (!is_array($_xh)) {
  320. $_xh = $xmlRpcParser->_xh;
  321. }
  322. if ($_xh['isf'] > 1) {
  323. // test that $_xh['value'] is an obj, too???
  324. $this->getLogger()->error('XML-RPC: ' . $_xh['isf_reason']);
  325. return false;
  326. }
  327. switch ($_xh['rt']) {
  328. case 'methodresponse':
  329. $v = $_xh['value'];
  330. if ($_xh['isf'] == 1) {
  331. /** @var Value $vc */
  332. $vc = $v['faultCode'];
  333. /** @var Value $vs */
  334. $vs = $v['faultString'];
  335. $r = new Response(0, $vc->scalarVal(), $vs->scalarVal());
  336. } else {
  337. $r = new Response($v);
  338. }
  339. return $r;
  340. case 'methodcall':
  341. $req = new Request($_xh['method']);
  342. for ($i = 0; $i < count($_xh['params']); $i++) {
  343. $req->addParam($_xh['params'][$i]);
  344. }
  345. return $req;
  346. case 'value':
  347. return $_xh['value'];
  348. case 'fault':
  349. // EPI api emulation
  350. $v = $_xh['value'];
  351. // use a known error code
  352. /** @var Value $vc */
  353. $vc = isset($v['faultCode']) ? $v['faultCode']->scalarVal() : PhpXmlRpc::$xmlrpcerr['invalid_return'];
  354. /** @var Value $vs */
  355. $vs = isset($v['faultString']) ? $v['faultString']->scalarVal() : '';
  356. if (!is_int($vc) || $vc == 0) {
  357. $vc = PhpXmlRpc::$xmlrpcerr['invalid_return'];
  358. }
  359. return new Response(0, $vc, $vs);
  360. default:
  361. return false;
  362. }
  363. }
  364. }