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