PageRenderTime 49ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/demo/yii/web/helpers/CJSON.php

https://bitbucket.org/ajx_standart/yii-bootstrap
PHP | 708 lines | 429 code | 87 blank | 192 comment | 92 complexity | 764e8c640642f16f358a0581ce73ab32 MD5 | raw file
Possible License(s): BSD-2-Clause, BSD-3-Clause, GPL-3.0, LGPL-2.1
  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. * @version $Id$
  58. * @package system.web.helpers
  59. * @since 1.0
  60. */
  61. class CJSON
  62. {
  63. /**
  64. * Marker constant for JSON::decode(), used to flag stack state
  65. */
  66. const JSON_SLICE = 1;
  67. /**
  68. * Marker constant for JSON::decode(), used to flag stack state
  69. */
  70. const JSON_IN_STR = 2;
  71. /**
  72. * Marker constant for JSON::decode(), used to flag stack state
  73. */
  74. const JSON_IN_ARR = 4;
  75. /**
  76. * Marker constant for JSON::decode(), used to flag stack state
  77. */
  78. const JSON_IN_OBJ = 8;
  79. /**
  80. * Marker constant for JSON::decode(), used to flag stack state
  81. */
  82. const JSON_IN_CMT = 16;
  83. /**
  84. * Encodes an arbitrary variable into JSON format
  85. *
  86. * @param mixed $var any number, boolean, string, array, or object to be encoded.
  87. * If var is a string, it will be converted to UTF-8 format first before being encoded.
  88. * @return string JSON string representation of input var
  89. */
  90. public static function encode($var)
  91. {
  92. switch (gettype($var)) {
  93. case 'boolean':
  94. return $var ? 'true' : 'false';
  95. case 'NULL':
  96. return 'null';
  97. case 'integer':
  98. return (int) $var;
  99. case 'double':
  100. case 'float':
  101. return str_replace(',','.',(float)$var); // locale-independent representation
  102. case 'string':
  103. if (($enc=strtoupper(Yii::app()->charset))!=='UTF-8')
  104. $var=iconv($enc, 'UTF-8', $var);
  105. if(function_exists('json_encode'))
  106. return json_encode($var);
  107. // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
  108. $ascii = '';
  109. $strlen_var = strlen($var);
  110. /*
  111. * Iterate over every character in the string,
  112. * escaping with a slash or encoding to UTF-8 where necessary
  113. */
  114. for ($c = 0; $c < $strlen_var; ++$c) {
  115. $ord_var_c = ord($var{$c});
  116. switch (true) {
  117. case $ord_var_c == 0x08:
  118. $ascii .= '\b';
  119. break;
  120. case $ord_var_c == 0x09:
  121. $ascii .= '\t';
  122. break;
  123. case $ord_var_c == 0x0A:
  124. $ascii .= '\n';
  125. break;
  126. case $ord_var_c == 0x0C:
  127. $ascii .= '\f';
  128. break;
  129. case $ord_var_c == 0x0D:
  130. $ascii .= '\r';
  131. break;
  132. case $ord_var_c == 0x22:
  133. case $ord_var_c == 0x2F:
  134. case $ord_var_c == 0x5C:
  135. // double quote, slash, slosh
  136. $ascii .= '\\'.$var{$c};
  137. break;
  138. case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
  139. // characters U-00000000 - U-0000007F (same as ASCII)
  140. $ascii .= $var{$c};
  141. break;
  142. case (($ord_var_c & 0xE0) == 0xC0):
  143. // characters U-00000080 - U-000007FF, mask 110XXXXX
  144. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  145. $char = pack('C*', $ord_var_c, ord($var{$c+1}));
  146. $c+=1;
  147. $utf16 = self::utf8ToUTF16BE($char);
  148. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  149. break;
  150. case (($ord_var_c & 0xF0) == 0xE0):
  151. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  152. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  153. $char = pack('C*', $ord_var_c,
  154. ord($var{$c+1}),
  155. ord($var{$c+2}));
  156. $c+=2;
  157. $utf16 = self::utf8ToUTF16BE($char);
  158. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  159. break;
  160. case (($ord_var_c & 0xF8) == 0xF0):
  161. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  162. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  163. $char = pack('C*', $ord_var_c,
  164. ord($var{$c+1}),
  165. ord($var{$c+2}),
  166. ord($var{$c+3}));
  167. $c+=3;
  168. $utf16 = self::utf8ToUTF16BE($char);
  169. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  170. break;
  171. case (($ord_var_c & 0xFC) == 0xF8):
  172. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  173. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  174. $char = pack('C*', $ord_var_c,
  175. ord($var{$c+1}),
  176. ord($var{$c+2}),
  177. ord($var{$c+3}),
  178. ord($var{$c+4}));
  179. $c+=4;
  180. $utf16 = self::utf8ToUTF16BE($char);
  181. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  182. break;
  183. case (($ord_var_c & 0xFE) == 0xFC):
  184. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  185. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  186. $char = pack('C*', $ord_var_c,
  187. ord($var{$c+1}),
  188. ord($var{$c+2}),
  189. ord($var{$c+3}),
  190. ord($var{$c+4}),
  191. ord($var{$c+5}));
  192. $c+=5;
  193. $utf16 = self::utf8ToUTF16BE($char);
  194. $ascii .= sprintf('\u%04s', bin2hex($utf16));
  195. break;
  196. }
  197. }
  198. return '"'.$ascii.'"';
  199. case 'array':
  200. /*
  201. * As per JSON spec if any array key is not an integer
  202. * we must treat the the whole array as an object. We
  203. * also try to catch a sparsely populated associative
  204. * array with numeric keys here because some JS engines
  205. * will create an array with empty indexes up to
  206. * max_index which can cause memory issues and because
  207. * the keys, which may be relevant, will be remapped
  208. * otherwise.
  209. *
  210. * As per the ECMA and JSON specification an object may
  211. * have any string as a property. Unfortunately due to
  212. * a hole in the ECMA specification if the key is a
  213. * ECMA reserved word or starts with a digit the
  214. * parameter is only accessible using ECMAScript's
  215. * bracket notation.
  216. */
  217. // treat as a JSON object
  218. if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
  219. return '{' .
  220. join(',', array_map(array('CJSON', 'nameValue'),
  221. array_keys($var),
  222. array_values($var)))
  223. . '}';
  224. }
  225. // treat it like a regular array
  226. return '[' . join(',', array_map(array('CJSON', 'encode'), $var)) . ']';
  227. case 'object':
  228. if ($var instanceof Traversable)
  229. {
  230. $vars = array();
  231. foreach ($var as $k=>$v)
  232. $vars[$k] = $v;
  233. }
  234. else
  235. $vars = get_object_vars($var);
  236. return '{' .
  237. join(',', array_map(array('CJSON', 'nameValue'),
  238. array_keys($vars),
  239. array_values($vars)))
  240. . '}';
  241. default:
  242. return '';
  243. }
  244. }
  245. /**
  246. * array-walking function for use in generating JSON-formatted name-value pairs
  247. *
  248. * @param string $name name of key to use
  249. * @param mixed $value reference to an array element to be encoded
  250. *
  251. * @return string JSON-formatted name-value pair, like '"name":value'
  252. * @access private
  253. */
  254. protected static function nameValue($name, $value)
  255. {
  256. return self::encode(strval($name)) . ':' . self::encode($value);
  257. }
  258. /**
  259. * reduce a string by removing leading and trailing comments and whitespace
  260. *
  261. * @param string $str string value to strip of comments and whitespace
  262. *
  263. * @return string string value stripped of comments and whitespace
  264. * @access private
  265. */
  266. protected static function reduceString($str)
  267. {
  268. $str = preg_replace(array(
  269. // eliminate single line comments in '// ...' form
  270. '#^\s*//(.+)$#m',
  271. // eliminate multi-line comments in '/* ... */' form, at start of string
  272. '#^\s*/\*(.+)\*/#Us',
  273. // eliminate multi-line comments in '/* ... */' form, at end of string
  274. '#/\*(.+)\*/\s*$#Us'
  275. ), '', $str);
  276. // eliminate extraneous space
  277. return trim($str);
  278. }
  279. /**
  280. * decodes a JSON string into appropriate variable
  281. *
  282. * @param string $str JSON-formatted string
  283. * @param boolean $useArray whether to use associative array to represent object data
  284. * @return mixed number, boolean, string, array, or object corresponding to given JSON input string.
  285. * Note that decode() always returns strings in ASCII or UTF-8 format!
  286. * @access public
  287. */
  288. public static function decode($str, $useArray=true)
  289. {
  290. if(function_exists('json_decode'))
  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. $str = self::reduceString($str);
  298. switch (strtolower($str)) {
  299. case 'true':
  300. return true;
  301. case 'false':
  302. return false;
  303. case 'null':
  304. return null;
  305. default:
  306. if (is_numeric($str)) {
  307. // Lookie-loo, it's a number
  308. // This would work on its own, but I'm trying to be
  309. // good about returning integers where appropriate:
  310. // return (float)$str;
  311. // Return float or int, as appropriate
  312. return ((float)$str == (integer)$str)
  313. ? (integer)$str
  314. : (float)$str;
  315. } elseif (preg_match('/^("|\').+(\1)$/s', $str, $m) && $m[1] == $m[2]) {
  316. // STRINGS RETURNED IN UTF-8 FORMAT
  317. $delim = substr($str, 0, 1);
  318. $chrs = substr($str, 1, -1);
  319. $utf8 = '';
  320. $strlen_chrs = strlen($chrs);
  321. for ($c = 0; $c < $strlen_chrs; ++$c) {
  322. $substr_chrs_c_2 = substr($chrs, $c, 2);
  323. $ord_chrs_c = ord($chrs{$c});
  324. switch (true) {
  325. case $substr_chrs_c_2 == '\b':
  326. $utf8 .= chr(0x08);
  327. ++$c;
  328. break;
  329. case $substr_chrs_c_2 == '\t':
  330. $utf8 .= chr(0x09);
  331. ++$c;
  332. break;
  333. case $substr_chrs_c_2 == '\n':
  334. $utf8 .= chr(0x0A);
  335. ++$c;
  336. break;
  337. case $substr_chrs_c_2 == '\f':
  338. $utf8 .= chr(0x0C);
  339. ++$c;
  340. break;
  341. case $substr_chrs_c_2 == '\r':
  342. $utf8 .= chr(0x0D);
  343. ++$c;
  344. break;
  345. case $substr_chrs_c_2 == '\\"':
  346. case $substr_chrs_c_2 == '\\\'':
  347. case $substr_chrs_c_2 == '\\\\':
  348. case $substr_chrs_c_2 == '\\/':
  349. if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
  350. ($delim == "'" && $substr_chrs_c_2 != '\\"')) {
  351. $utf8 .= $chrs{++$c};
  352. }
  353. break;
  354. case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
  355. // single, escaped unicode character
  356. $utf16 = chr(hexdec(substr($chrs, ($c+2), 2)))
  357. . chr(hexdec(substr($chrs, ($c+4), 2)));
  358. $utf8 .= self::utf16beToUTF8($utf16);
  359. $c+=5;
  360. break;
  361. case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
  362. $utf8 .= $chrs{$c};
  363. break;
  364. case ($ord_chrs_c & 0xE0) == 0xC0:
  365. // characters U-00000080 - U-000007FF, mask 110XXXXX
  366. //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  367. $utf8 .= substr($chrs, $c, 2);
  368. ++$c;
  369. break;
  370. case ($ord_chrs_c & 0xF0) == 0xE0:
  371. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  372. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  373. $utf8 .= substr($chrs, $c, 3);
  374. $c += 2;
  375. break;
  376. case ($ord_chrs_c & 0xF8) == 0xF0:
  377. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  378. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  379. $utf8 .= substr($chrs, $c, 4);
  380. $c += 3;
  381. break;
  382. case ($ord_chrs_c & 0xFC) == 0xF8:
  383. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  384. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  385. $utf8 .= substr($chrs, $c, 5);
  386. $c += 4;
  387. break;
  388. case ($ord_chrs_c & 0xFE) == 0xFC:
  389. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  390. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  391. $utf8 .= substr($chrs, $c, 6);
  392. $c += 5;
  393. break;
  394. }
  395. }
  396. return $utf8;
  397. } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
  398. // array, or object notation
  399. if ($str{0} == '[') {
  400. $stk = array(self::JSON_IN_ARR);
  401. $arr = array();
  402. } else {
  403. if ($useArray) {
  404. $stk = array(self::JSON_IN_OBJ);
  405. $obj = array();
  406. } else {
  407. $stk = array(self::JSON_IN_OBJ);
  408. $obj = new stdClass();
  409. }
  410. }
  411. $stk[] = array('what' => self::JSON_SLICE, 'where' => 0, 'delim' => false);
  412. $chrs = substr($str, 1, -1);
  413. $chrs = self::reduceString($chrs);
  414. if ($chrs == '') {
  415. if (reset($stk) == self::JSON_IN_ARR) {
  416. return $arr;
  417. } else {
  418. return $obj;
  419. }
  420. }
  421. //print("\nparsing {$chrs}\n");
  422. $strlen_chrs = strlen($chrs);
  423. for ($c = 0; $c <= $strlen_chrs; ++$c) {
  424. $top = end($stk);
  425. $substr_chrs_c_2 = substr($chrs, $c, 2);
  426. if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == self::JSON_SLICE))) {
  427. // found a comma that is not inside a string, array, etc.,
  428. // OR we've reached the end of the character list
  429. $slice = substr($chrs, $top['where'], ($c - $top['where']));
  430. $stk[] = array('what' => self::JSON_SLICE, 'where' => ($c + 1), 'delim' => false);
  431. //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  432. if (reset($stk) == self::JSON_IN_ARR) {
  433. // we are in an array, so just push an element onto the stack
  434. $arr[] = self::decode($slice,$useArray);
  435. } elseif (reset($stk) == self::JSON_IN_OBJ) {
  436. // we are in an object, so figure
  437. // out the property name and set an
  438. // element in an associative array,
  439. // for now
  440. if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
  441. // "name":value pair
  442. $key = self::decode($parts[1],$useArray);
  443. $val = self::decode($parts[2],$useArray);
  444. if ($useArray) {
  445. $obj[$key] = $val;
  446. } else {
  447. $obj->$key = $val;
  448. }
  449. } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
  450. // name:value pair, where name is unquoted
  451. $key = $parts[1];
  452. $val = self::decode($parts[2],$useArray);
  453. if ($useArray) {
  454. $obj[$key] = $val;
  455. } else {
  456. $obj->$key = $val;
  457. }
  458. }
  459. }
  460. } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != self::JSON_IN_STR)) {
  461. // found a quote, and we are not inside a string
  462. $stk[] = array('what' => self::JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c});
  463. //print("Found start of string at {$c}\n");
  464. } elseif (($chrs{$c} == $top['delim']) &&
  465. ($top['what'] == self::JSON_IN_STR) &&
  466. (($chrs{$c - 1} != "\\") ||
  467. ($chrs{$c - 1} == "\\" && $chrs{$c - 2} == "\\"))) {
  468. // found a quote, we're in a string, and it's not escaped
  469. array_pop($stk);
  470. //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
  471. } elseif (($chrs{$c} == '[') &&
  472. in_array($top['what'], array(self::JSON_SLICE, self::JSON_IN_ARR, self::JSON_IN_OBJ))) {
  473. // found a left-bracket, and we are in an array, object, or slice
  474. $stk[] = array('what' => self::JSON_IN_ARR, 'where' => $c, 'delim' => false);
  475. //print("Found start of array at {$c}\n");
  476. } elseif (($chrs{$c} == ']') && ($top['what'] == self::JSON_IN_ARR)) {
  477. // found a right-bracket, and we're in an array
  478. array_pop($stk);
  479. //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  480. } elseif (($chrs{$c} == '{') &&
  481. in_array($top['what'], array(self::JSON_SLICE, self::JSON_IN_ARR, self::JSON_IN_OBJ))) {
  482. // found a left-brace, and we are in an array, object, or slice
  483. $stk[] = array('what' => self::JSON_IN_OBJ, 'where' => $c, 'delim' => false);
  484. //print("Found start of object at {$c}\n");
  485. } elseif (($chrs{$c} == '}') && ($top['what'] == self::JSON_IN_OBJ)) {
  486. // found a right-brace, and we're in an object
  487. array_pop($stk);
  488. //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  489. } elseif (($substr_chrs_c_2 == '/*') &&
  490. in_array($top['what'], array(self::JSON_SLICE, self::JSON_IN_ARR, self::JSON_IN_OBJ))) {
  491. // found a comment start, and we are in an array, object, or slice
  492. $stk[] = array('what' => self::JSON_IN_CMT, 'where' => $c, 'delim' => false);
  493. $c++;
  494. //print("Found start of comment at {$c}\n");
  495. } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == self::JSON_IN_CMT)) {
  496. // found a comment end, and we're in one now
  497. array_pop($stk);
  498. $c++;
  499. for ($i = $top['where']; $i <= $c; ++$i)
  500. $chrs = substr_replace($chrs, ' ', $i, 1);
  501. //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  502. }
  503. }
  504. if (reset($stk) == self::JSON_IN_ARR) {
  505. return $arr;
  506. } elseif (reset($stk) == self::JSON_IN_OBJ) {
  507. return $obj;
  508. }
  509. }
  510. }
  511. }
  512. /**
  513. * This function returns any UTF-8 encoded text as a list of
  514. * Unicode values:
  515. * @param string $str string to convert
  516. * @return string
  517. * @author Scott Michael Reynen <scott@randomchaos.com>
  518. * @link http://www.randomchaos.com/document.php?source=php_and_unicode
  519. * @see unicodeToUTF8()
  520. */
  521. protected static function utf8ToUnicode( &$str )
  522. {
  523. $unicode = array();
  524. $values = array();
  525. $lookingFor = 1;
  526. for ($i = 0; $i < strlen( $str ); $i++ )
  527. {
  528. $thisValue = ord( $str[ $i ] );
  529. if ( $thisValue < 128 )
  530. $unicode[] = $thisValue;
  531. else
  532. {
  533. if ( count( $values ) == 0 )
  534. $lookingFor = ( $thisValue < 224 ) ? 2 : 3;
  535. $values[] = $thisValue;
  536. if ( count( $values ) == $lookingFor )
  537. {
  538. $number = ( $lookingFor == 3 ) ?
  539. ( ( $values[0] % 16 ) * 4096 ) + ( ( $values[1] % 64 ) * 64 ) + ( $values[2] % 64 ):
  540. ( ( $values[0] % 32 ) * 64 ) + ( $values[1] % 64 );
  541. $unicode[] = $number;
  542. $values = array();
  543. $lookingFor = 1;
  544. }
  545. }
  546. }
  547. return $unicode;
  548. }
  549. /**
  550. * This function converts a Unicode array back to its UTF-8 representation
  551. * @param string $str string to convert
  552. * @return string
  553. * @author Scott Michael Reynen <scott@randomchaos.com>
  554. * @link http://www.randomchaos.com/document.php?source=php_and_unicode
  555. * @see utf8ToUnicode()
  556. */
  557. protected static function unicodeToUTF8( &$str )
  558. {
  559. $utf8 = '';
  560. foreach( $str as $unicode )
  561. {
  562. if ( $unicode < 128 )
  563. {
  564. $utf8.= chr( $unicode );
  565. }
  566. elseif ( $unicode < 2048 )
  567. {
  568. $utf8.= chr( 192 + ( ( $unicode - ( $unicode % 64 ) ) / 64 ) );
  569. $utf8.= chr( 128 + ( $unicode % 64 ) );
  570. }
  571. else
  572. {
  573. $utf8.= chr( 224 + ( ( $unicode - ( $unicode % 4096 ) ) / 4096 ) );
  574. $utf8.= chr( 128 + ( ( ( $unicode % 4096 ) - ( $unicode % 64 ) ) / 64 ) );
  575. $utf8.= chr( 128 + ( $unicode % 64 ) );
  576. }
  577. }
  578. return $utf8;
  579. }
  580. /**
  581. * UTF-8 to UTF-16BE conversion.
  582. *
  583. * Maybe really UCS-2 without mb_string due to utf8ToUnicode limits
  584. * @param string $str string to convert
  585. * @param boolean $bom whether to output BOM header
  586. * @return string
  587. */
  588. protected static function utf8ToUTF16BE(&$str, $bom = false)
  589. {
  590. $out = $bom ? "\xFE\xFF" : '';
  591. if(function_exists('mb_convert_encoding'))
  592. return $out.mb_convert_encoding($str,'UTF-16BE','UTF-8');
  593. $uni = self::utf8ToUnicode($str);
  594. foreach($uni as $cp)
  595. $out .= pack('n',$cp);
  596. return $out;
  597. }
  598. /**
  599. * UTF-8 to UTF-16BE conversion.
  600. *
  601. * Maybe really UCS-2 without mb_string due to utf8ToUnicode limits
  602. * @param string $str string to convert
  603. * @return string
  604. */
  605. protected static function utf16beToUTF8(&$str)
  606. {
  607. $uni = unpack('n*',$str);
  608. return self::unicodeToUTF8($uni);
  609. }
  610. }