Advertisement
Guest User

MulticraftAPI - Told ya :P

a guest
Jul 9th, 2015
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 33.19 KB | None | 0 0
  1. <?php
  2. /**
  3. *
  4. * Copyright © 2010-2012 by xhost.ch GmbH
  5. *
  6. * All rights reserved.
  7. *
  8. **/
  9. /**
  10. * Sample Multicraft API implementation. Includes the Yii framework CJSON class for
  11. * systems lacking the PHP JSON extension.
  12. *
  13. * For examples and function reference, please see:
  14. * http://www.multicraft.org/site/page?view=api-doc
  15. *
  16. **/
  17. class MulticraftAPI
  18. {
  19. private $key = '';
  20. private $url = '';
  21.  
  22. private $lastResponse = '';
  23.  
  24. private $methods = array(
  25. //User functions
  26. 'listUsers' => array(),
  27. 'findUsers' => array(array('name'=>'field', 'type'=>'array'), array('name'=>'value', 'type'=>'array')),
  28. 'getUser' => array('id'),
  29. 'updateUser' => array('id', array('name'=>'field', 'type'=>'array'), array('name'=>'value', 'type'=>'array'), array('name'=>'send_mail', 'default'=>0)),
  30. 'createUser' => array('name', 'email', 'password', array('name'=>'lang', 'default'=>''), array('name'=>'send_mail', 'default'=>0)),
  31. 'deleteUser' => array('id'),
  32. 'getUserRole' => array('user_id', 'server_id'),
  33. 'setUserRole' => array('user_id', 'server_id', 'role'),
  34. 'getUserFtpAccess' => array('user_id', 'server_id'),
  35. 'setUserFtpAccess' => array('user_id', 'server_id', 'mode'),
  36. 'getUserId' => array('name'),
  37. //Player functions
  38. 'listPlayers' => array('server_id'),
  39. 'findPlayers' => array('server_id', array('name'=>'field', 'type'=>'array'), array('name'=>'value', 'type'=>'array')),
  40. 'getPlayer' => array('id'),
  41. 'updatePlayer' => array('id', array('name'=>'field', 'type'=>'array'), array('name'=>'value', 'type'=>'array')),
  42. 'createPlayer' => array('server_id', 'name'),
  43. 'deletePlayer' => array('id'),
  44. 'assignPlayerToUser' => array('player_id', 'user_id'),
  45. //Command functions
  46. 'listCommands' => array('server_id'),
  47. 'findCommands' => array('server_id', array('name'=>'field', 'type'=>'array'), array('name'=>'value', 'type'=>'array')),
  48. 'getCommand' => array('id'),
  49. 'updateCommand' => array('id', array('name'=>'field', 'type'=>'array'), array('name'=>'value', 'type'=>'array')),
  50. 'createCommand' => array('server_id', 'name', 'role', 'chat', 'response', 'run'),
  51. 'deleteCommand' => array('id'),
  52. //Server functions
  53. 'listServers' => array(),
  54. 'findServers' => array(array('name'=>'field', 'type'=>'array'), array('name'=>'value', 'type'=>'array')),
  55. 'listServersByConnection' => array('connection_id'),
  56. 'listServersByOwner' => array('user_id'),
  57. 'getServer' => array('id'),
  58. 'updateServer' => array('id', array('name'=>'field', 'type'=>'array'), array('name'=>'value', 'type'=>'array')),
  59. 'createServerOn' => array(array('name'=>'daemon_id', 'default'=>0), array('name'=>'no_commands', 'default'=>0), array('name'=>'no_setup_script', 'default'=>0)),
  60. 'createServer' => array(array('name'=>'name', 'default'=>''), array('name'=>'port', 'default'=>0), array('name'=>'base', 'default'=>''), array('name'=>'players', 'default'=>0), array('name'=>'no_commands', 'default'=>0), array('name'=>'no_setup_script', 'default'=>0)),
  61. 'suspendServer' => array('id', array('name'=>'stop', 'default'=>1)),
  62. 'resumeServer' => array('id', array('name'=>'start', 'default'=>1)),
  63. 'deleteServer' => array('id', array('name'=>'delete_dir', 'default'=>'no')),
  64. 'getServerStatus' => array('id', array('name'=>'player_list', 'default'=>0)),
  65. 'getServerOwner' => array('server_id'),
  66. 'setServerOwner' => array('server_id', 'user_id', array('name'=>'send_mail', 'default'=>0)),
  67. 'getServerConfig' => array('id'),
  68. 'updateServerConfig' => array('id', array('name'=>'field', 'type'=>'array'), array('name'=>'value', 'type'=>'array')),
  69. 'startServerBackup' => array('id'),
  70. 'getServerBackupStatus' => array('id'),
  71. 'startServer' => array('id'),
  72. 'stopServer' => array('id'),
  73. 'restartServer' => array('id'),
  74. 'startAllServers' => array(),
  75. 'stopAllServers' => array(),
  76. 'restartAllServers' => array(),
  77. 'sendConsoleCommand' => array('server_id', 'command'),
  78. 'sendAllConsoleCommand' => array('command'),
  79. 'runCommand' => array('server_id', 'command_id', array('name'=>'run_for', 'default'=>0)),
  80. 'getServerLog' => array('id'),
  81. 'clearServerLog' => array('id'),
  82. 'getServerChat' => array('id'),
  83. 'clearServerChat' => array('id'),
  84. 'sendServerControl' => array('id', 'command'),
  85. 'getServerResources' => array('id'),
  86. //Daemon functions
  87. 'listConnections' => array(),
  88. 'findConnections' => array(array('name'=>'field', 'type'=>'array'), array('name'=>'value', 'type'=>'array')),
  89. 'getConnection' => array('id'),
  90. 'removeConnection' => array('id'),
  91. 'getConnectionStatus' => array('id'),
  92. 'getConnectionMemory' => array('id', array('name'=>'include_suspended', 'default'=>0)),
  93. //Settings functions
  94. 'listSettings' => array(),
  95. 'getSetting' => array('key'),
  96. 'setSetting' => array('key', 'value'),
  97. 'deleteSetting' => array('key'),
  98. //Schedule functions
  99. 'listSchedules' => array('server_id'),
  100. 'findSchedules' => array('server_id', array('name'=>'field', 'type'=>'array'), array('name'=>'value', 'type'=>'array')),
  101. 'getSchedule' => array('id'),
  102. 'updateSchedule' => array('id', array('name'=>'field', 'type'=>'array'), array('name'=>'value', 'type'=>'array')),
  103. 'createSchedule' => array('server_id', 'name', 'ts', 'interval', 'cmd', 'status', 'for'),
  104. 'deleteSchedule' => array('id'),
  105. );
  106.  
  107. public function __construct($url, $user, $key)
  108. {
  109. $this->url = $url;
  110. $this->user = $user;
  111. $this->key = $key;
  112. }
  113.  
  114. public function __call($function, $args)
  115. {
  116. $argnames = @$this->methods[$function];
  117. if (!is_array($argnames))
  118. return array('success'=>false, 'errors'=>array('Unknown API method "'.$function.'()"'), 'data'=>array());
  119. $callargs = array();
  120. $name = ''; $value = '';
  121. for ($i = 0; $i < count($argnames); $i++)
  122. {
  123. if (is_array($argnames[$i]))
  124. $name = $argnames[$i]['name'];
  125. else
  126. $name = $argnames[$i];
  127.  
  128. if ($i < count($args))
  129. {
  130. $value = $args[$i];
  131. }
  132. else if (is_array($argnames[$i]) && isset($argnames[$i]['default']))
  133. {
  134. if ($i >= count($args))
  135. $value = $argnames[$i]['default'];
  136. else
  137. $value = $args[$i];
  138. }
  139. else
  140. return array('success'=>false, 'errors'=>array('"'.$function.'()": Not enough arguments ('.count($args).')'), 'data'=>array());
  141.  
  142. if (is_array($argnames[$i]) && isset($argnames[$i]['type']))
  143. {
  144. if ($argnames[$i]['type'] == 'array')
  145. $value = CJSON::encode($value);
  146. }
  147. $callargs[$name] = $value;
  148. }
  149. return $this->call($function, $callargs);
  150. }
  151.  
  152.  
  153. public function call($method, $params = array())
  154. {
  155. if (!$this->url)
  156. return array('success'=>false, 'errors'=>array('Invalid target URL'));
  157. if (!$this->key)
  158. return array('success'=>false, 'errors'=>array('Invalid API key'));
  159.  
  160. $url = $this->url;
  161. $query = '?';
  162.  
  163. $str = '';
  164. if (!is_array($params))
  165. $params = array($params=>$params);
  166. $params['_MulticraftAPIMethod'] = $method;
  167. $params['_MulticraftAPIUser'] = $this->user;
  168. foreach ($params as $p)
  169. $str .= $p;
  170. $params['_MulticraftAPIKey'] = md5($this->key.$str);
  171.  
  172. foreach ($params as $k=>$v)
  173. $query .= '&'.urlencode($k).'='.urlencode($v);
  174.  
  175. return $this->send($url, $query);
  176. }
  177.  
  178. public function send($url, $query)
  179. {
  180. $response = '';
  181. $error = '';
  182. if (function_exists('curl_init'))
  183. {
  184. $curl = curl_init($url);
  185.  
  186. curl_setopt ($curl, CURLOPT_POST, true);
  187. curl_setopt ($curl, CURLOPT_POSTFIELDS, $query);
  188.  
  189. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  190. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  191.  
  192. $response = curl_exec($curl);
  193. //echo $response;
  194. $error = curl_error($curl);
  195. curl_close($curl);
  196. }
  197. else
  198. $response = file_get_contents($url.$query);
  199.  
  200. if (!$response)
  201. {
  202. if (!$error)
  203. $error = 'Empty response (wrong API URL or connection problem)';
  204. return array('success'=>false, 'errors'=>array($error), 'data'=>'');
  205. }
  206. $this->lastResponse = $response;
  207. $ret = CJSON::decode($response);
  208. if (!is_array($ret))
  209. {
  210. return array('success'=>false, 'errors'=>array($ret), 'data'=>array());
  211. }
  212. return $ret;
  213. }
  214.  
  215. public function rawResponse()
  216. {
  217. return $this->lastResponse;
  218. }
  219. }
  220. /*?>
  221. <?php
  222. /**
  223. * JSON (JavaScript Object Notation) is a lightweight data-interchange
  224. * format. It is easy for humans to read and write. It is easy for machines
  225. * to parse and generate. It is based on a subset of the JavaScript
  226. * Programming Language, Standard ECMA-262 3rd Edition - December 1999.
  227. * This feature can also be found in Python. JSON is a text format that is
  228. * completely language independent but uses conventions that are familiar
  229. * to programmers of the C-family of languages, including C, C++, C#, Java,
  230. * JavaScript, Perl, TCL, and many others. These properties make JSON an
  231. * ideal data-interchange language.
  232. *
  233. * This package provides a simple encoder and decoder for JSON notation. It
  234. * is intended for use with client-side Javascript applications that make
  235. * use of HTTPRequest to perform server communication functions - data can
  236. * be encoded into JSON notation for use in a client-side javascript, or
  237. * decoded from incoming Javascript requests. JSON format is native to
  238. * Javascript, and can be directly eval()'ed with no further parsing
  239. * overhead
  240. *
  241. * All strings should be in ASCII or UTF-8 format!
  242. *
  243. * LICENSE: Redistribution and use in source and binary forms, with or
  244. * without modification, are permitted provided that the following
  245. * conditions are met: Redistributions of source code must retain the
  246. * above copyright notice, this list of conditions and the following
  247. * disclaimer. Redistributions in binary form must reproduce the above
  248. * copyright notice, this list of conditions and the following disclaimer
  249. * in the documentation and/or other materials provided with the
  250. * distribution.
  251. *
  252. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
  253. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  254. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
  255. * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  256. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  257. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  258. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  259. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  260. * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  261. * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  262. * DAMAGE.
  263. *
  264. * @author Michal Migurski <mike-json@teczno.com>
  265. * @author Matt Knapp <mdknapp[at]gmail[dot]com>
  266. * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
  267. * @copyright 2005 Michal Migurski
  268. * @license http://www.opensource.org/licenses/bsd-license.php
  269. * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
  270. */
  271.  
  272. /**
  273. * CJSON converts PHP data to and from JSON format.
  274. *
  275. * @author Michal Migurski <mike-json@teczno.com>
  276. * @author Matt Knapp <mdknapp[at]gmail[dot]com>
  277. * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
  278. * @version $Id$
  279. * @package system.web.helpers
  280. * @since 1.0
  281. */
  282. class CJSON
  283. {
  284. /**
  285. * Marker constant for JSON::decode(), used to flag stack state
  286. */
  287. const JSON_SLICE = 1;
  288.  
  289. /**
  290. * Marker constant for JSON::decode(), used to flag stack state
  291. */
  292. const JSON_IN_STR = 2;
  293.  
  294. /**
  295. * Marker constant for JSON::decode(), used to flag stack state
  296. */
  297. const JSON_IN_ARR = 4;
  298.  
  299. /**
  300. * Marker constant for JSON::decode(), used to flag stack state
  301. */
  302. const JSON_IN_OBJ = 8;
  303.  
  304. /**
  305. * Marker constant for JSON::decode(), used to flag stack state
  306. */
  307. const JSON_IN_CMT = 16;
  308.  
  309. /**
  310. * Encodes an arbitrary variable into JSON format
  311. *
  312. * @param mixed $var any number, boolean, string, array, or object to be encoded.
  313. * If var is a string, it will be converted to UTF-8 format first before being encoded.
  314. * @return string JSON string representation of input var
  315. */
  316. public static function encode($var)
  317. {
  318. switch (gettype($var)) {
  319. case 'boolean':
  320. return $var ? 'true' : 'false';
  321.  
  322. case 'NULL':
  323. return 'null';
  324.  
  325. case 'integer':
  326. return (int) $var;
  327.  
  328. case 'double':
  329. case 'float':
  330. return str_replace(',','.',(float)$var); // locale-independent representation
  331.  
  332. case 'string':
  333. if (substr($var,0,3) == pack('CCC',0xEF,0xBB,0xBF))
  334. $var = substr($var, 3);
  335. if (function_exists('json_encode'))
  336. {
  337. if (function_exists('iconv'))
  338. return json_encode(iconv("UTF-8","UTF-8//IGNORE",$var));
  339. else
  340. return json_encode($var);
  341. }
  342.  
  343. if (($enc=strtoupper(Yii::app()->charset))!=='UTF-8')
  344. $var=iconv($enc, 'UTF-8', $var);
  345.  
  346. // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
  347. $ascii = '';
  348. $strlen_var = strlen($var);
  349.  
  350. /*
  351. * Iterate over every character in the string,
  352. * escaping with a slash or encoding to UTF-8 where necessary
  353. */
  354. for ($c = 0; $c < $strlen_var; ++$c) {
  355.  
  356. $ord_var_c = ord($var{$c});
  357.  
  358. switch (true) {
  359. case $ord_var_c == 0x08:
  360. $ascii .= '\b';
  361. break;
  362. case $ord_var_c == 0x09:
  363. $ascii .= '\t';
  364. break;
  365. case $ord_var_c == 0x0A:
  366. $ascii .= '\n';
  367. break;
  368. case $ord_var_c == 0x0C:
  369. $ascii .= '\f';
  370. break;
  371. case $ord_var_c == 0x0D:
  372. $ascii .= '\r';
  373. break;
  374.  
  375. case $ord_var_c == 0x22:
  376. case $ord_var_c == 0x2F:
  377. case $ord_var_c == 0x5C:
  378. // double quote, slash, slosh
  379. $ascii .= '\\'.$var{$c};
  380. break;
  381.  
  382. case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
  383. // characters U-00000000 - U-0000007F (same as ASCII)
  384. $ascii .= $var{$c};
  385. break;
  386.  
  387. case (($ord_var_c & 0xE0) == 0xC0):
  388. // characters U-00000080 - U-000007FF, mask 110XXXXX
  389. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  390. $char = pack('C*', $ord_var_c, ord($var{$c+1}));
  391. $c+=1;
  392. $utf16 = self::utf8ToUTF16BE($char);
  393. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  394. break;
  395.  
  396. case (($ord_var_c & 0xF0) == 0xE0):
  397. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  398. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  399. $char = pack('C*', $ord_var_c,
  400. ord($var{$c+1}),
  401. ord($var{$c+2}));
  402. $c+=2;
  403. $utf16 = self::utf8ToUTF16BE($char);
  404. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  405. break;
  406.  
  407. case (($ord_var_c & 0xF8) == 0xF0):
  408. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  409. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  410. $char = pack('C*', $ord_var_c,
  411. ord($var{$c+1}),
  412. ord($var{$c+2}),
  413. ord($var{$c+3}));
  414. $c+=3;
  415. $utf16 = self::utf8ToUTF16BE($char);
  416. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  417. break;
  418.  
  419. case (($ord_var_c & 0xFC) == 0xF8):
  420. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  421. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  422. $char = pack('C*', $ord_var_c,
  423. ord($var{$c+1}),
  424. ord($var{$c+2}),
  425. ord($var{$c+3}),
  426. ord($var{$c+4}));
  427. $c+=4;
  428. $utf16 = self::utf8ToUTF16BE($char);
  429. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  430. break;
  431.  
  432. case (($ord_var_c & 0xFE) == 0xFC):
  433. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  434. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  435. $char = pack('C*', $ord_var_c,
  436. ord($var{$c+1}),
  437. ord($var{$c+2}),
  438. ord($var{$c+3}),
  439. ord($var{$c+4}),
  440. ord($var{$c+5}));
  441. $c+=5;
  442. $utf16 = self::utf8ToUTF16BE($char);
  443. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  444. break;
  445. }
  446. }
  447.  
  448. return '"'.$ascii.'"';
  449.  
  450. case 'array':
  451. /*
  452. * As per JSON spec if any array key is not an integer
  453. * we must treat the the whole array as an object. We
  454. * also try to catch a sparsely populated associative
  455. * array with numeric keys here because some JS engines
  456. * will create an array with empty indexes up to
  457. * max_index which can cause memory issues and because
  458. * the keys, which may be relevant, will be remapped
  459. * otherwise.
  460. *
  461. * As per the ECMA and JSON specification an object may
  462. * have any string as a property. Unfortunately due to
  463. * a hole in the ECMA specification if the key is a
  464. * ECMA reserved word or starts with a digit the
  465. * parameter is only accessible using ECMAScript's
  466. * bracket notation.
  467. */
  468.  
  469. // treat as a JSON object
  470. if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
  471. return '{' .
  472. join(',', array_map(array('CJSON', 'nameValue'),
  473. array_keys($var),
  474. array_values($var)))
  475. . '}';
  476. }
  477.  
  478. // treat it like a regular array
  479. return '[' . join(',', array_map(array('CJSON', 'encode'), $var)) . ']';
  480.  
  481. case 'object':
  482. if ($var instanceof Traversable)
  483. {
  484. $vars = array();
  485. foreach ($var as $k=>$v)
  486. $vars[$k] = $v;
  487. }
  488. else
  489. $vars = get_object_vars($var);
  490. return '{' .
  491. join(',', array_map(array('CJSON', 'nameValue'),
  492. array_keys($vars),
  493. array_values($vars)))
  494. . '}';
  495.  
  496. default:
  497. return '';
  498. }
  499. }
  500.  
  501. /**
  502. * array-walking function for use in generating JSON-formatted name-value pairs
  503. *
  504. * @param string $name name of key to use
  505. * @param mixed $value reference to an array element to be encoded
  506. *
  507. * @return string JSON-formatted name-value pair, like '"name":value'
  508. * @access private
  509. */
  510. protected static function nameValue($name, $value)
  511. {
  512. return self::encode(strval($name)) . ':' . self::encode($value);
  513. }
  514.  
  515. /**
  516. * reduce a string by removing leading and trailing comments and whitespace
  517. *
  518. * @param string $str string value to strip of comments and whitespace
  519. *
  520. * @return string string value stripped of comments and whitespace
  521. * @access private
  522. */
  523. protected static function reduceString($str)
  524. {
  525. $str = preg_replace(array(
  526.  
  527. // eliminate single line comments in '// ...' form
  528. '#^\s*//(.+)$#m',
  529.  
  530. // eliminate multi-line comments in '/* ... */' form, at start of string
  531. '#^\s*/\*(.+)\*/#Us',
  532.  
  533. // eliminate multi-line comments in '/* ... */' form, at end of string
  534. '#/\*(.+)\*/\s*$#Us'
  535.  
  536. ), '', $str);
  537.  
  538. // eliminate extraneous space
  539. return trim($str);
  540. }
  541.  
  542. /**
  543. * decodes a JSON string into appropriate variable
  544. *
  545. * @param string $str JSON-formatted string
  546. * @param boolean $useArray whether to use associative array to represent object data
  547. * @return mixed number, boolean, string, array, or object corresponding to given JSON input string.
  548. * Note that decode() always returns strings in ASCII or UTF-8 format!
  549. * @access public
  550. */
  551. public static function decode($str, $useArray=true)
  552. {
  553. if (substr($str,0,3) == pack('CCC',0xEF,0xBB,0xBF))
  554. $str = substr($str,3);
  555. $json = null;
  556. if (function_exists('json_decode'))
  557. {
  558. if (function_exists('iconv'))
  559. $json = json_decode(iconv("UTF-8","UTF-8//IGNORE",$str),$useArray);
  560. else
  561. $json = json_decode($str,$useArray);
  562. }
  563.  
  564. // based on investigation, native fails sometimes returning null.
  565. // see: http://gggeek.altervista.org/sw/article_20070425.html
  566. // As of PHP 5.3.6 it still fails on some valid JSON strings
  567. if(!is_null($json))
  568. return $json;
  569.  
  570. $str = self::reduceString($str);
  571.  
  572. switch (strtolower($str)) {
  573. case 'true':
  574. return true;
  575.  
  576. case 'false':
  577. return false;
  578.  
  579. case 'null':
  580. return null;
  581.  
  582. default:
  583. if (is_numeric($str)) {
  584. // Lookie-loo, it's a number
  585.  
  586. // This would work on its own, but I'm trying to be
  587. // good about returning integers where appropriate:
  588. // return (float)$str;
  589.  
  590. // Return float or int, as appropriate
  591. return ((float)$str == (integer)$str)
  592. ? (integer)$str
  593. : (float)$str;
  594.  
  595. } elseif (preg_match('/^("|\').+(\1)$/s', $str, $m) && $m[1] == $m[2]) {
  596. // STRINGS RETURNED IN UTF-8 FORMAT
  597. $delim = substr($str, 0, 1);
  598. $chrs = substr($str, 1, -1);
  599. $utf8 = '';
  600. $strlen_chrs = strlen($chrs);
  601.  
  602. for ($c = 0; $c < $strlen_chrs; ++$c) {
  603.  
  604. $substr_chrs_c_2 = substr($chrs, $c, 2);
  605. $ord_chrs_c = ord($chrs{$c});
  606.  
  607. switch (true) {
  608. case $substr_chrs_c_2 == '\b':
  609. $utf8 .= chr(0x08);
  610. ++$c;
  611. break;
  612. case $substr_chrs_c_2 == '\t':
  613. $utf8 .= chr(0x09);
  614. ++$c;
  615. break;
  616. case $substr_chrs_c_2 == '\n':
  617. $utf8 .= chr(0x0A);
  618. ++$c;
  619. break;
  620. case $substr_chrs_c_2 == '\f':
  621. $utf8 .= chr(0x0C);
  622. ++$c;
  623. break;
  624. case $substr_chrs_c_2 == '\r':
  625. $utf8 .= chr(0x0D);
  626. ++$c;
  627. break;
  628.  
  629. case $substr_chrs_c_2 == '\\"':
  630. case $substr_chrs_c_2 == '\\\'':
  631. case $substr_chrs_c_2 == '\\\\':
  632. case $substr_chrs_c_2 == '\\/':
  633. if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
  634. ($delim == "'" && $substr_chrs_c_2 != '\\"')) {
  635. $utf8 .= $chrs{++$c};
  636. }
  637. break;
  638.  
  639. case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
  640. // single, escaped unicode character
  641. $utf16 = chr(hexdec(substr($chrs, ($c+2), 2)))
  642. . chr(hexdec(substr($chrs, ($c+4), 2)));
  643. $utf8 .= self::utf16beToUTF8($utf16);
  644. $c+=5;
  645. break;
  646.  
  647. case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
  648. $utf8 .= $chrs{$c};
  649. break;
  650.  
  651. case ($ord_chrs_c & 0xE0) == 0xC0:
  652. // characters U-00000080 - U-000007FF, mask 110XXXXX
  653. //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  654. $utf8 .= substr($chrs, $c, 2);
  655. ++$c;
  656. break;
  657.  
  658. case ($ord_chrs_c & 0xF0) == 0xE0:
  659. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  660. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  661. $utf8 .= substr($chrs, $c, 3);
  662. $c += 2;
  663. break;
  664.  
  665. case ($ord_chrs_c & 0xF8) == 0xF0:
  666. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  667. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  668. $utf8 .= substr($chrs, $c, 4);
  669. $c += 3;
  670. break;
  671.  
  672. case ($ord_chrs_c & 0xFC) == 0xF8:
  673. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  674. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  675. $utf8 .= substr($chrs, $c, 5);
  676. $c += 4;
  677. break;
  678.  
  679. case ($ord_chrs_c & 0xFE) == 0xFC:
  680. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  681. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  682. $utf8 .= substr($chrs, $c, 6);
  683. $c += 5;
  684. break;
  685.  
  686. }
  687.  
  688. }
  689.  
  690. return $utf8;
  691.  
  692. } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
  693. // array, or object notation
  694.  
  695. if ($str{0} == '[') {
  696. $stk = array(self::JSON_IN_ARR);
  697. $arr = array();
  698. } else {
  699. if ($useArray) {
  700. $stk = array(self::JSON_IN_OBJ);
  701. $obj = array();
  702. } else {
  703. $stk = array(self::JSON_IN_OBJ);
  704. $obj = new stdClass();
  705. }
  706. }
  707.  
  708. $stk[] = array('what' => self::JSON_SLICE, 'where' => 0, 'delim' => false);
  709.  
  710. $chrs = substr($str, 1, -1);
  711. $chrs = self::reduceString($chrs);
  712.  
  713. if ($chrs == '') {
  714. if (reset($stk) == self::JSON_IN_ARR) {
  715. return $arr;
  716.  
  717. } else {
  718. return $obj;
  719.  
  720. }
  721. }
  722.  
  723. //print("\nparsing {$chrs}\n");
  724.  
  725. $strlen_chrs = strlen($chrs);
  726.  
  727. for ($c = 0; $c <= $strlen_chrs; ++$c) {
  728.  
  729. $top = end($stk);
  730. $substr_chrs_c_2 = substr($chrs, $c, 2);
  731.  
  732. if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == self::JSON_SLICE))) {
  733. // found a comma that is not inside a string, array, etc.,
  734. // OR we've reached the end of the character list
  735. $slice = substr($chrs, $top['where'], ($c - $top['where']));
  736. $stk[] = array('what' => self::JSON_SLICE, 'where' => ($c + 1), 'delim' => false);
  737. //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  738.  
  739. if (reset($stk) == self::JSON_IN_ARR) {
  740. // we are in an array, so just push an element onto the stack
  741. $arr[] = self::decode($slice,$useArray);
  742.  
  743. } elseif (reset($stk) == self::JSON_IN_OBJ) {
  744. // we are in an object, so figure
  745. // out the property name and set an
  746. // element in an associative array,
  747. // for now
  748. if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
  749. // "name":value pair
  750. $key = self::decode($parts[1],$useArray);
  751. $val = self::decode($parts[2],$useArray);
  752.  
  753. if ($useArray) {
  754. $obj[$key] = $val;
  755. } else {
  756. $obj->$key = $val;
  757. }
  758. } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
  759. // name:value pair, where name is unquoted
  760. $key = $parts[1];
  761. $val = self::decode($parts[2],$useArray);
  762.  
  763. if ($useArray) {
  764. $obj[$key] = $val;
  765. } else {
  766. $obj->$key = $val;
  767. }
  768. }
  769.  
  770. }
  771.  
  772. } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != self::JSON_IN_STR)) {
  773. // found a quote, and we are not inside a string
  774. $stk[] = array('what' => self::JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c});
  775. //print("Found start of string at {$c}\n");
  776.  
  777. } elseif (($chrs{$c} == $top['delim']) &&
  778. ($top['what'] == self::JSON_IN_STR) &&
  779. (($chrs{$c - 1} != "\\") ||
  780. ($chrs{$c - 1} == "\\" && $chrs{$c - 2} == "\\"))) {
  781. // found a quote, we're in a string, and it's not escaped
  782. array_pop($stk);
  783. //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
  784.  
  785. } elseif (($chrs{$c} == '[') &&
  786. in_array($top['what'], array(self::JSON_SLICE, self::JSON_IN_ARR, self::JSON_IN_OBJ))) {
  787. // found a left-bracket, and we are in an array, object, or slice
  788. $stk[] = array('what' => self::JSON_IN_ARR, 'where' => $c, 'delim' => false);
  789. //print("Found start of array at {$c}\n");
  790.  
  791. } elseif (($chrs{$c} == ']') && ($top['what'] == self::JSON_IN_ARR)) {
  792. // found a right-bracket, and we're in an array
  793. array_pop($stk);
  794. //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  795.  
  796. } elseif (($chrs{$c} == '{') &&
  797. in_array($top['what'], array(self::JSON_SLICE, self::JSON_IN_ARR, self::JSON_IN_OBJ))) {
  798. // found a left-brace, and we are in an array, object, or slice
  799. $stk[] = array('what' => self::JSON_IN_OBJ, 'where' => $c, 'delim' => false);
  800. //print("Found start of object at {$c}\n");
  801.  
  802. } elseif (($chrs{$c} == '}') && ($top['what'] == self::JSON_IN_OBJ)) {
  803. // found a right-brace, and we're in an object
  804. array_pop($stk);
  805. //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  806.  
  807. } elseif (($substr_chrs_c_2 == '/*') &&
  808. in_array($top['what'], array(self::JSON_SLICE, self::JSON_IN_ARR, self::JSON_IN_OBJ))) {
  809. // found a comment start, and we are in an array, object, or slice
  810. $stk[] = array('what' => self::JSON_IN_CMT, 'where' => $c, 'delim' => false);
  811. $c++;
  812. //print("Found start of comment at {$c}\n");
  813.  
  814. } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == self::JSON_IN_CMT)) {
  815. // found a comment end, and we're in one now
  816. array_pop($stk);
  817. $c++;
  818.  
  819. for ($i = $top['where']; $i <= $c; ++$i)
  820. $chrs = substr_replace($chrs, ' ', $i, 1);
  821.  
  822. //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  823.  
  824. }
  825.  
  826. }
  827.  
  828. if (reset($stk) == self::JSON_IN_ARR) {
  829. return $arr;
  830.  
  831. } elseif (reset($stk) == self::JSON_IN_OBJ) {
  832. return $obj;
  833.  
  834. }
  835.  
  836. }
  837. }
  838. }
  839.  
  840. /**
  841. * This function returns any UTF-8 encoded text as a list of
  842. * Unicode values:
  843. * @param string $str string to convert
  844. * @return string
  845. * @author Scott Michael Reynen <scott@randomchaos.com>
  846. * @link http://www.randomchaos.com/document.php?source=php_and_unicode
  847. * @see unicodeToUTF8()
  848. */
  849. protected static function utf8ToUnicode( &$str )
  850. {
  851. $unicode = array();
  852. $values = array();
  853. $lookingFor = 1;
  854.  
  855. for ($i = 0; $i < strlen( $str ); $i++ )
  856. {
  857. $thisValue = ord( $str[ $i ] );
  858. if ( $thisValue < 128 )
  859. $unicode[] = $thisValue;
  860. else
  861. {
  862. if ( count( $values ) == 0 )
  863. $lookingFor = ( $thisValue < 224 ) ? 2 : 3;
  864. $values[] = $thisValue;
  865. if ( count( $values ) == $lookingFor )
  866. {
  867. $number = ( $lookingFor == 3 ) ?
  868. ( ( $values[0] % 16 ) * 4096 ) + ( ( $values[1] % 64 ) * 64 ) + ( $values[2] % 64 ):
  869. ( ( $values[0] % 32 ) * 64 ) + ( $values[1] % 64 );
  870. $unicode[] = $number;
  871. $values = array();
  872. $lookingFor = 1;
  873. }
  874. }
  875. }
  876. return $unicode;
  877. }
  878.  
  879. /**
  880. * This function converts a Unicode array back to its UTF-8 representation
  881. * @param string $str string to convert
  882. * @return string
  883. * @author Scott Michael Reynen <scott@randomchaos.com>
  884. * @link http://www.randomchaos.com/document.php?source=php_and_unicode
  885. * @see utf8ToUnicode()
  886. */
  887. protected static function unicodeToUTF8( &$str )
  888. {
  889. $utf8 = '';
  890. foreach( $str as $unicode )
  891. {
  892. if ( $unicode < 128 )
  893. {
  894. $utf8.= chr( $unicode );
  895. }
  896. elseif ( $unicode < 2048 )
  897. {
  898. $utf8.= chr( 192 + ( ( $unicode - ( $unicode % 64 ) ) / 64 ) );
  899. $utf8.= chr( 128 + ( $unicode % 64 ) );
  900. }
  901. else
  902. {
  903. $utf8.= chr( 224 + ( ( $unicode - ( $unicode % 4096 ) ) / 4096 ) );
  904. $utf8.= chr( 128 + ( ( ( $unicode % 4096 ) - ( $unicode % 64 ) ) / 64 ) );
  905. $utf8.= chr( 128 + ( $unicode % 64 ) );
  906. }
  907. }
  908. return $utf8;
  909. }
  910.  
  911. /**
  912. * UTF-8 to UTF-16BE conversion.
  913. *
  914. * Maybe really UCS-2 without mb_string due to utf8ToUnicode limits
  915. * @param string $str string to convert
  916. * @param boolean $bom whether to output BOM header
  917. * @return string
  918. */
  919. protected static function utf8ToUTF16BE(&$str, $bom = false)
  920. {
  921. $out = $bom ? "\xFE\xFF" : '';
  922. if(function_exists('mb_convert_encoding'))
  923. return $out.mb_convert_encoding($str,'UTF-16BE','UTF-8');
  924.  
  925. $uni = self::utf8ToUnicode($str);
  926. foreach($uni as $cp)
  927. $out .= pack('n',$cp);
  928. return $out;
  929. }
  930.  
  931. /**
  932. * UTF-8 to UTF-16BE conversion.
  933. *
  934. * Maybe really UCS-2 without mb_string due to utf8ToUnicode limits
  935. * @param string $str string to convert
  936. * @return string
  937. */
  938. protected static function utf16beToUTF8(&$str)
  939. {
  940. $uni = unpack('n*',$str);
  941. return self::unicodeToUTF8($uni);
  942. }
  943. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement