PageRenderTime 58ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/yii/framework/web/helpers/CJSON.php

https://bitbucket.org/syed_webt/yii_syed
PHP | 709 lines | 431 code | 87 blank | 191 comment | 92 complexity | 0b89ec1ff6f0d1c61bdaa2a98f91021c MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, BSD-3-Clause, BSD-2-Clause
  1. <?php
  2. /**
  3. * JSON (JavaScript Object Notation) is a lightweight data-interchange
  4. * format. It is easy for humans to read and write. It is easy for machines
  5. * to parse and generate. It is based on a subset of the JavaScript
  6. * Programming Language, Standard ECMA-262 3rd Edition - December 1999.
  7. * This feature can also be found in Python. JSON is a text format that is
  8. * completely language independent but uses conventions that are familiar
  9. * to programmers of the C-family of languages, including C, C++, C#, Java,
  10. * JavaScript, Perl, TCL, and many others. These properties make JSON an
  11. * ideal data-interchange language.
  12. *
  13. * This package provides a simple encoder and decoder for JSON notation. It
  14. * is intended for use with client-side Javascript applications that make
  15. * use of HTTPRequest to perform server communication functions - data can
  16. * be encoded into JSON notation for use in a client-side javascript, or
  17. * decoded from incoming Javascript requests. JSON format is native to
  18. * Javascript, and can be directly eval()'ed with no further parsing
  19. * overhead
  20. *
  21. * All strings should be in ASCII or UTF-8 format!
  22. *
  23. * LICENSE: Redistribution and use in source and binary forms, with or
  24. * without modification, are permitted provided that the following
  25. * conditions are met: Redistributions of source code must retain the
  26. * above copyright notice, this list of conditions and the following
  27. * disclaimer. Redistributions in binary form must reproduce the above
  28. * copyright notice, this list of conditions and the following disclaimer
  29. * in the documentation and/or other materials provided with the
  30. * distribution.
  31. *
  32. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
  33. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  34. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
  35. * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  36. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  37. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  38. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  39. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  40. * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  41. * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  42. * DAMAGE.
  43. *
  44. * @author Michal Migurski <mike-json@teczno.com>
  45. * @author Matt Knapp <mdknapp[at]gmail[dot]com>
  46. * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
  47. * @copyright 2005 Michal Migurski
  48. * @license http://www.opensource.org/licenses/bsd-license.php
  49. * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
  50. */
  51. /**
  52. * CJSON converts PHP data to and from JSON format.
  53. *
  54. * @author Michal Migurski <mike-json@teczno.com>
  55. * @author Matt Knapp <mdknapp[at]gmail[dot]com>
  56. * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
  57. * @package system.web.helpers
  58. * @since 1.0
  59. */
  60. class CJSON
  61. {
  62. /**
  63. * Marker constant for JSON::decode(), used to flag stack state
  64. */
  65. const JSON_SLICE = 1;
  66. /**
  67. * Marker constant for JSON::decode(), used to flag stack state
  68. */
  69. const JSON_IN_STR = 2;
  70. /**
  71. * Marker constant for JSON::decode(), used to flag stack state
  72. */
  73. const JSON_IN_ARR = 4;
  74. /**
  75. * Marker constant for JSON::decode(), used to flag stack state
  76. */
  77. const JSON_IN_OBJ = 8;
  78. /**
  79. * Marker constant for JSON::decode(), used to flag stack state
  80. */
  81. const JSON_IN_CMT = 16;
  82. /**
  83. * Encodes an arbitrary variable into JSON format
  84. *
  85. * @param mixed $var any number, boolean, string, array, or object to be encoded.
  86. * If var is a string, it will be converted to UTF-8 format first before being encoded.
  87. * @return string JSON string representation of input var
  88. */
  89. public static function encode($var)
  90. {
  91. switch (gettype($var)) {
  92. case 'boolean':
  93. return $var ? 'true' : 'false';
  94. case 'NULL':
  95. return 'null';
  96. case 'integer':
  97. return (int) $var;
  98. case 'double':
  99. case 'float':
  100. return str_replace(',','.',(float)$var); // locale-independent representation
  101. case 'string':
  102. if (($enc=strtoupper(Yii::app()->charset))!=='UTF-8')
  103. $var=iconv($enc, 'UTF-8', $var);
  104. if(function_exists('json_encode'))
  105. return json_encode($var);
  106. // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
  107. $ascii = '';
  108. $strlen_var = strlen($var);
  109. /*
  110. * Iterate over every character in the string,
  111. * escaping with a slash or encoding to UTF-8 where necessary
  112. */
  113. for ($c = 0; $c < $strlen_var; ++$c) {
  114. $ord_var_c = ord($var{$c});
  115. switch (true) {
  116. case $ord_var_c == 0x08:
  117. $ascii .= '\b';
  118. break;
  119. case $ord_var_c == 0x09:
  120. $ascii .= '\t';
  121. break;
  122. case $ord_var_c == 0x0A:
  123. $ascii .= '\n';
  124. break;
  125. case $ord_var_c == 0x0C:
  126. $ascii .= '\f';
  127. break;
  128. case $ord_var_c == 0x0D:
  129. $ascii .= '\r';
  130. break;
  131. case $ord_var_c == 0x22:
  132. case $ord_var_c == 0x2F:
  133. case $ord_var_c == 0x5C:
  134. // double quote, slash, slosh
  135. $ascii .= '\\'.$var{$c};
  136. break;
  137. case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
  138. // characters U-00000000 - U-0000007F (same as ASCII)
  139. $ascii .= $var{$c};
  140. break;
  141. case (($ord_var_c & 0xE0) == 0xC0):
  142. // characters U-00000080 - U-000007FF, mask 110XXXXX
  143. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  144. $char = pack('C*', $ord_var_c, ord($var{$c+1}));
  145. $c+=1;
  146. $utf16 = self::utf8ToUTF16BE($char);
  147. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  148. break;
  149. case (($ord_var_c & 0xF0) == 0xE0):
  150. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  151. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  152. $char = pack('C*', $ord_var_c,
  153. ord($var{$c+1}),
  154. ord($var{$c+2}));
  155. $c+=2;
  156. $utf16 = self::utf8ToUTF16BE($char);
  157. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  158. break;
  159. case (($ord_var_c & 0xF8) == 0xF0):
  160. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  161. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  162. $char = pack('C*', $ord_var_c,
  163. ord($var{$c+1}),
  164. ord($var{$c+2}),
  165. ord($var{$c+3}));
  166. $c+=3;
  167. $utf16 = self::utf8ToUTF16BE($char);
  168. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  169. break;
  170. case (($ord_var_c & 0xFC) == 0xF8):
  171. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  172. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  173. $char = pack('C*', $ord_var_c,
  174. ord($var{$c+1}),
  175. ord($var{$c+2}),
  176. ord($var{$c+3}),
  177. ord($var{$c+4}));
  178. $c+=4;
  179. $utf16 = self::utf8ToUTF16BE($char);
  180. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  181. break;
  182. case (($ord_var_c & 0xFE) == 0xFC):
  183. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  184. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  185. $char = pack('C*', $ord_var_c,
  186. ord($var{$c+1}),
  187. ord($var{$c+2}),
  188. ord($var{$c+3}),
  189. ord($var{$c+4}),
  190. ord($var{$c+5}));
  191. $c+=5;
  192. $utf16 = self::utf8ToUTF16BE($char);
  193. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  194. break;
  195. }
  196. }
  197. return '"'.$ascii.'"';
  198. case 'array':
  199. /*
  200. * As per JSON spec if any array key is not an integer
  201. * we must treat the the whole array as an object. We
  202. * also try to catch a sparsely populated associative
  203. * array with numeric keys here because some JS engines
  204. * will create an array with empty indexes up to
  205. * max_index which can cause memory issues and because
  206. * the keys, which may be relevant, will be remapped
  207. * otherwise.
  208. *
  209. * As per the ECMA and JSON specification an object may
  210. * have any string as a property. Unfortunately due to
  211. * a hole in the ECMA specification if the key is a
  212. * ECMA reserved word or starts with a digit the
  213. * parameter is only accessible using ECMAScript's
  214. * bracket notation.
  215. */
  216. // treat as a JSON object
  217. if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
  218. return '{' .
  219. join(',', array_map(array('CJSON', 'nameValue'),
  220. array_keys($var),
  221. array_values($var)))
  222. . '}';
  223. }
  224. // treat it like a regular array
  225. return '[' . join(',', array_map(array('CJSON', 'encode'), $var)) . ']';
  226. case 'object':
  227. if ($var instanceof Traversable)
  228. {
  229. $vars = array();
  230. foreach ($var as $k=>$v)
  231. $vars[$k] = $v;
  232. }
  233. else
  234. $vars = get_object_vars($var);
  235. return '{' .
  236. join(',', array_map(array('CJSON', 'nameValue'),
  237. array_keys($vars),
  238. array_values($vars)))
  239. . '}';
  240. default:
  241. return '';
  242. }
  243. }
  244. /**
  245. * array-walking function for use in generating JSON-formatted name-value pairs
  246. *
  247. * @param string $name name of key to use
  248. * @param mixed $value reference to an array element to be encoded
  249. *
  250. * @return string JSON-formatted name-value pair, like '"name":value'
  251. * @access private
  252. */
  253. protected static function nameValue($name, $value)
  254. {
  255. return self::encode(strval($name)) . ':' . self::encode($value);
  256. }
  257. /**
  258. * reduce a string by removing leading and trailing comments and whitespace
  259. *
  260. * @param string $str string value to strip of comments and whitespace
  261. *
  262. * @return string string value stripped of comments and whitespace
  263. * @access private
  264. */
  265. protected static function reduceString($str)
  266. {
  267. $str = preg_replace(array(
  268. // eliminate single line comments in '// ...' form
  269. '#^\s*//(.+)$#m',
  270. // eliminate multi-line comments in '/* ... */' form, at start of string
  271. '#^\s*/\*(.+)\*/#Us',
  272. // eliminate multi-line comments in '/* ... */' form, at end of string
  273. '#/\*(.+)\*/\s*$#Us'
  274. ), '', $str);
  275. // eliminate extraneous space
  276. return trim($str);
  277. }
  278. /**
  279. * decodes a JSON string into appropriate variable
  280. *
  281. * @param string $str JSON-formatted string
  282. * @param boolean $useArray whether to use associative array to represent object data
  283. * @return mixed number, boolean, string, array, or object corresponding to given JSON input string.
  284. * Note that decode() always returns strings in ASCII or UTF-8 format!
  285. * @access public
  286. */
  287. public static function decode($str, $useArray=true)
  288. {
  289. if(function_exists('json_decode'))
  290. {
  291. $json = json_decode($str,$useArray);
  292. // based on investigation, native fails sometimes returning null.
  293. // see: http://gggeek.altervista.org/sw/article_20070425.html
  294. // As of PHP 5.3.6 it still fails on some valid JSON strings
  295. if(!is_null($json))
  296. return $json;
  297. }
  298. $str = self::reduceString($str);
  299. switch (strtolower($str)) {
  300. case 'true':
  301. return true;
  302. case 'false':
  303. return false;
  304. case 'null':
  305. return null;
  306. default:
  307. if (is_numeric($str)) {
  308. // Lookie-loo, it's a number
  309. // This would work on its own, but I'm trying to be
  310. // good about returning integers where appropriate:
  311. // return (float)$str;
  312. // Return float or int, as appropriate
  313. return ((float)$str == (integer)$str)
  314. ? (integer)$str
  315. : (float)$str;
  316. } elseif (preg_match('/^("|\').+(\1)$/s', $str, $m) && $m[1] == $m[2]) {
  317. // STRINGS RETURNED IN UTF-8 FORMAT
  318. $delim = substr($str, 0, 1);
  319. $chrs = substr($str, 1, -1);
  320. $utf8 = '';
  321. $strlen_chrs = strlen($chrs);
  322. for ($c = 0; $c < $strlen_chrs; ++$c) {
  323. $substr_chrs_c_2 = substr($chrs, $c, 2);
  324. $ord_chrs_c = ord($chrs{$c});
  325. switch (true) {
  326. case $substr_chrs_c_2 == '\b':
  327. $utf8 .= chr(0x08);
  328. ++$c;
  329. break;
  330. case $substr_chrs_c_2 == '\t':
  331. $utf8 .= chr(0x09);
  332. ++$c;
  333. break;
  334. case $substr_chrs_c_2 == '\n':
  335. $utf8 .= chr(0x0A);
  336. ++$c;
  337. break;
  338. case $substr_chrs_c_2 == '\f':
  339. $utf8 .= chr(0x0C);
  340. ++$c;
  341. break;
  342. case $substr_chrs_c_2 == '\r':
  343. $utf8 .= chr(0x0D);
  344. ++$c;
  345. break;
  346. case $substr_chrs_c_2 == '\\"':
  347. case $substr_chrs_c_2 == '\\\'':
  348. case $substr_chrs_c_2 == '\\\\':
  349. case $substr_chrs_c_2 == '\\/':
  350. if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
  351. ($delim == "'" && $substr_chrs_c_2 != '\\"')) {
  352. $utf8 .= $chrs{++$c};
  353. }
  354. break;
  355. case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
  356. // single, escaped unicode character
  357. $utf16 = chr(hexdec(substr($chrs, ($c+2), 2)))
  358. . chr(hexdec(substr($chrs, ($c+4), 2)));
  359. $utf8 .= self::utf16beToUTF8($utf16);
  360. $c+=5;
  361. break;
  362. case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
  363. $utf8 .= $chrs{$c};
  364. break;
  365. case ($ord_chrs_c & 0xE0) == 0xC0:
  366. // characters U-00000080 - U-000007FF, mask 110XXXXX
  367. //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  368. $utf8 .= substr($chrs, $c, 2);
  369. ++$c;
  370. break;
  371. case ($ord_chrs_c & 0xF0) == 0xE0:
  372. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  373. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  374. $utf8 .= substr($chrs, $c, 3);
  375. $c += 2;
  376. break;
  377. case ($ord_chrs_c & 0xF8) == 0xF0:
  378. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  379. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  380. $utf8 .= substr($chrs, $c, 4);
  381. $c += 3;
  382. break;
  383. case ($ord_chrs_c & 0xFC) == 0xF8:
  384. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  385. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  386. $utf8 .= substr($chrs, $c, 5);
  387. $c += 4;
  388. break;
  389. case ($ord_chrs_c & 0xFE) == 0xFC:
  390. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  391. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  392. $utf8 .= substr($chrs, $c, 6);
  393. $c += 5;
  394. break;
  395. }
  396. }
  397. return $utf8;
  398. } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
  399. // array, or object notation
  400. if ($str{0} == '[') {
  401. $stk = array(self::JSON_IN_ARR);
  402. $arr = array();
  403. } else {
  404. if ($useArray) {
  405. $stk = array(self::JSON_IN_OBJ);
  406. $obj = array();
  407. } else {
  408. $stk = array(self::JSON_IN_OBJ);
  409. $obj = new stdClass();
  410. }
  411. }
  412. $stk[] = array('what' => self::JSON_SLICE, 'where' => 0, 'delim' => false);
  413. $chrs = substr($str, 1, -1);
  414. $chrs = self::reduceString($chrs);
  415. if ($chrs == '') {
  416. if (reset($stk) == self::JSON_IN_ARR) {
  417. return $arr;
  418. } else {
  419. return $obj;
  420. }
  421. }
  422. //print("\nparsing {$chrs}\n");
  423. $strlen_chrs = strlen($chrs);
  424. for ($c = 0; $c <= $strlen_chrs; ++$c) {
  425. $top = end($stk);
  426. $substr_chrs_c_2 = substr($chrs, $c, 2);
  427. if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == self::JSON_SLICE))) {
  428. // found a comma that is not inside a string, array, etc.,
  429. // OR we've reached the end of the character list
  430. $slice = substr($chrs, $top['where'], ($c - $top['where']));
  431. $stk[] = array('what' => self::JSON_SLICE, 'where' => ($c + 1), 'delim' => false);
  432. //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  433. if (reset($stk) == self::JSON_IN_ARR) {
  434. // we are in an array, so just push an element onto the stack
  435. $arr[] = self::decode($slice,$useArray);
  436. } elseif (reset($stk) == self::JSON_IN_OBJ) {
  437. // we are in an object, so figure
  438. // out the property name and set an
  439. // element in an associative array,
  440. // for now
  441. if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
  442. // "name":value pair
  443. $key = self::decode($parts[1],$useArray);
  444. $val = self::decode($parts[2],$useArray);
  445. if ($useArray) {
  446. $obj[$key] = $val;
  447. } else {
  448. $obj->$key = $val;
  449. }
  450. } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
  451. // name:value pair, where name is unquoted
  452. $key = $parts[1];
  453. $val = self::decode($parts[2],$useArray);
  454. if ($useArray) {
  455. $obj[$key] = $val;
  456. } else {
  457. $obj->$key = $val;
  458. }
  459. }
  460. }
  461. } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != self::JSON_IN_STR)) {
  462. // found a quote, and we are not inside a string
  463. $stk[] = array('what' => self::JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c});
  464. //print("Found start of string at {$c}\n");
  465. } elseif (($chrs{$c} == $top['delim']) &&
  466. ($top['what'] == self::JSON_IN_STR) &&
  467. (($chrs{$c - 1} != "\\") ||
  468. ($chrs{$c - 1} == "\\" && $chrs{$c - 2} == "\\"))) {
  469. // found a quote, we're in a string, and it's not escaped
  470. array_pop($stk);
  471. //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
  472. } elseif (($chrs{$c} == '[') &&
  473. in_array($top['what'], array(self::JSON_SLICE, self::JSON_IN_ARR, self::JSON_IN_OBJ))) {
  474. // found a left-bracket, and we are in an array, object, or slice
  475. $stk[] = array('what' => self::JSON_IN_ARR, 'where' => $c, 'delim' => false);
  476. //print("Found start of array at {$c}\n");
  477. } elseif (($chrs{$c} == ']') && ($top['what'] == self::JSON_IN_ARR)) {
  478. // found a right-bracket, and we're in an array
  479. array_pop($stk);
  480. //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  481. } elseif (($chrs{$c} == '{') &&
  482. in_array($top['what'], array(self::JSON_SLICE, self::JSON_IN_ARR, self::JSON_IN_OBJ))) {
  483. // found a left-brace, and we are in an array, object, or slice
  484. $stk[] = array('what' => self::JSON_IN_OBJ, 'where' => $c, 'delim' => false);
  485. //print("Found start of object at {$c}\n");
  486. } elseif (($chrs{$c} == '}') && ($top['what'] == self::JSON_IN_OBJ)) {
  487. // found a right-brace, and we're in an object
  488. array_pop($stk);
  489. //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  490. } elseif (($substr_chrs_c_2 == '/*') &&
  491. in_array($top['what'], array(self::JSON_SLICE, self::JSON_IN_ARR, self::JSON_IN_OBJ))) {
  492. // found a comment start, and we are in an array, object, or slice
  493. $stk[] = array('what' => self::JSON_IN_CMT, 'where' => $c, 'delim' => false);
  494. $c++;
  495. //print("Found start of comment at {$c}\n");
  496. } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == self::JSON_IN_CMT)) {
  497. // found a comment end, and we're in one now
  498. array_pop($stk);
  499. $c++;
  500. for ($i = $top['where']; $i <= $c; ++$i)
  501. $chrs = substr_replace($chrs, ' ', $i, 1);
  502. //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  503. }
  504. }
  505. if (reset($stk) == self::JSON_IN_ARR) {
  506. return $arr;
  507. } elseif (reset($stk) == self::JSON_IN_OBJ) {
  508. return $obj;
  509. }
  510. }
  511. }
  512. }
  513. /**
  514. * This function returns any UTF-8 encoded text as a list of
  515. * Unicode values:
  516. * @param string $str string to convert
  517. * @return string
  518. * @author Scott Michael Reynen <scott@randomchaos.com>
  519. * @link http://www.randomchaos.com/document.php?source=php_and_unicode
  520. * @see unicodeToUTF8()
  521. */
  522. protected static function utf8ToUnicode( &$str )
  523. {
  524. $unicode = array();
  525. $values = array();
  526. $lookingFor = 1;
  527. for ($i = 0; $i < strlen( $str ); $i++ )
  528. {
  529. $thisValue = ord( $str[ $i ] );
  530. if ( $thisValue < 128 )
  531. $unicode[] = $thisValue;
  532. else
  533. {
  534. if ( count( $values ) == 0 )
  535. $lookingFor = ( $thisValue < 224 ) ? 2 : 3;
  536. $values[] = $thisValue;
  537. if ( count( $values ) == $lookingFor )
  538. {
  539. $number = ( $lookingFor == 3 ) ?
  540. ( ( $values[0] % 16 ) * 4096 ) + ( ( $values[1] % 64 ) * 64 ) + ( $values[2] % 64 ):
  541. ( ( $values[0] % 32 ) * 64 ) + ( $values[1] % 64 );
  542. $unicode[] = $number;
  543. $values = array();
  544. $lookingFor = 1;
  545. }
  546. }
  547. }
  548. return $unicode;
  549. }
  550. /**
  551. * This function converts a Unicode array back to its UTF-8 representation
  552. * @param string $str string to convert
  553. * @return string
  554. * @author Scott Michael Reynen <scott@randomchaos.com>
  555. * @link http://www.randomchaos.com/document.php?source=php_and_unicode
  556. * @see utf8ToUnicode()
  557. */
  558. protected static function unicodeToUTF8( &$str )
  559. {
  560. $utf8 = '';
  561. foreach( $str as $unicode )
  562. {
  563. if ( $unicode < 128 )
  564. {
  565. $utf8.= chr( $unicode );
  566. }
  567. elseif ( $unicode < 2048 )
  568. {
  569. $utf8.= chr( 192 + ( ( $unicode - ( $unicode % 64 ) ) / 64 ) );
  570. $utf8.= chr( 128 + ( $unicode % 64 ) );
  571. }
  572. else
  573. {
  574. $utf8.= chr( 224 + ( ( $unicode - ( $unicode % 4096 ) ) / 4096 ) );
  575. $utf8.= chr( 128 + ( ( ( $unicode % 4096 ) - ( $unicode % 64 ) ) / 64 ) );
  576. $utf8.= chr( 128 + ( $unicode % 64 ) );
  577. }
  578. }
  579. return $utf8;
  580. }
  581. /**
  582. * UTF-8 to UTF-16BE conversion.
  583. *
  584. * Maybe really UCS-2 without mb_string due to utf8ToUnicode limits
  585. * @param string $str string to convert
  586. * @param boolean $bom whether to output BOM header
  587. * @return string
  588. */
  589. protected static function utf8ToUTF16BE(&$str, $bom = false)
  590. {
  591. $out = $bom ? "\xFE\xFF" : '';
  592. if(function_exists('mb_convert_encoding'))
  593. return $out.mb_convert_encoding($str,'UTF-16BE','UTF-8');
  594. $uni = self::utf8ToUnicode($str);
  595. foreach($uni as $cp)
  596. $out .= pack('n',$cp);
  597. return $out;
  598. }
  599. /**
  600. * UTF-8 to UTF-16BE conversion.
  601. *
  602. * Maybe really UCS-2 without mb_string due to utf8ToUnicode limits
  603. * @param string $str string to convert
  604. * @return string
  605. */
  606. protected static function utf16beToUTF8(&$str)
  607. {
  608. $uni = unpack('n*',$str);
  609. return self::unicodeToUTF8($uni);
  610. }
  611. }