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