PageRenderTime 48ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/web/helpers/CJSON.php

https://bitbucket.org/diegoaraujo/alexikeda
PHP | 704 lines | 429 code | 86 blank | 189 comment | 91 complexity | 175b8f727160688a873544f4872d0e0e MD5 | raw file
Possible License(s): 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. * @version $Id: CJSON.php 3204 2011-05-05 21:36:32Z alexander.makarow $
  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. return json_decode($str,$useArray);
  292. $str = self::reduceString($str);
  293. switch (strtolower($str)) {
  294. case 'true':
  295. return true;
  296. case 'false':
  297. return false;
  298. case 'null':
  299. return null;
  300. default:
  301. if (is_numeric($str)) {
  302. // Lookie-loo, it's a number
  303. // This would work on its own, but I'm trying to be
  304. // good about returning integers where appropriate:
  305. // return (float)$str;
  306. // Return float or int, as appropriate
  307. return ((float)$str == (integer)$str)
  308. ? (integer)$str
  309. : (float)$str;
  310. } elseif (preg_match('/^("|\').+(\1)$/s', $str, $m) && $m[1] == $m[2]) {
  311. // STRINGS RETURNED IN UTF-8 FORMAT
  312. $delim = substr($str, 0, 1);
  313. $chrs = substr($str, 1, -1);
  314. $utf8 = '';
  315. $strlen_chrs = strlen($chrs);
  316. for ($c = 0; $c < $strlen_chrs; ++$c) {
  317. $substr_chrs_c_2 = substr($chrs, $c, 2);
  318. $ord_chrs_c = ord($chrs{$c});
  319. switch (true) {
  320. case $substr_chrs_c_2 == '\b':
  321. $utf8 .= chr(0x08);
  322. ++$c;
  323. break;
  324. case $substr_chrs_c_2 == '\t':
  325. $utf8 .= chr(0x09);
  326. ++$c;
  327. break;
  328. case $substr_chrs_c_2 == '\n':
  329. $utf8 .= chr(0x0A);
  330. ++$c;
  331. break;
  332. case $substr_chrs_c_2 == '\f':
  333. $utf8 .= chr(0x0C);
  334. ++$c;
  335. break;
  336. case $substr_chrs_c_2 == '\r':
  337. $utf8 .= chr(0x0D);
  338. ++$c;
  339. break;
  340. case $substr_chrs_c_2 == '\\"':
  341. case $substr_chrs_c_2 == '\\\'':
  342. case $substr_chrs_c_2 == '\\\\':
  343. case $substr_chrs_c_2 == '\\/':
  344. if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
  345. ($delim == "'" && $substr_chrs_c_2 != '\\"')) {
  346. $utf8 .= $chrs{++$c};
  347. }
  348. break;
  349. case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
  350. // single, escaped unicode character
  351. $utf16 = chr(hexdec(substr($chrs, ($c+2), 2)))
  352. . chr(hexdec(substr($chrs, ($c+4), 2)));
  353. $utf8 .= self::utf16beToUTF8($utf16);
  354. $c+=5;
  355. break;
  356. case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
  357. $utf8 .= $chrs{$c};
  358. break;
  359. case ($ord_chrs_c & 0xE0) == 0xC0:
  360. // characters U-00000080 - U-000007FF, mask 110XXXXX
  361. //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  362. $utf8 .= substr($chrs, $c, 2);
  363. ++$c;
  364. break;
  365. case ($ord_chrs_c & 0xF0) == 0xE0:
  366. // characters U-00000800 - U-0000FFFF, mask 1110XXXX
  367. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  368. $utf8 .= substr($chrs, $c, 3);
  369. $c += 2;
  370. break;
  371. case ($ord_chrs_c & 0xF8) == 0xF0:
  372. // characters U-00010000 - U-001FFFFF, mask 11110XXX
  373. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  374. $utf8 .= substr($chrs, $c, 4);
  375. $c += 3;
  376. break;
  377. case ($ord_chrs_c & 0xFC) == 0xF8:
  378. // characters U-00200000 - U-03FFFFFF, mask 111110XX
  379. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  380. $utf8 .= substr($chrs, $c, 5);
  381. $c += 4;
  382. break;
  383. case ($ord_chrs_c & 0xFE) == 0xFC:
  384. // characters U-04000000 - U-7FFFFFFF, mask 1111110X
  385. // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  386. $utf8 .= substr($chrs, $c, 6);
  387. $c += 5;
  388. break;
  389. }
  390. }
  391. return $utf8;
  392. } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
  393. // array, or object notation
  394. if ($str{0} == '[') {
  395. $stk = array(self::JSON_IN_ARR);
  396. $arr = array();
  397. } else {
  398. if ($useArray) {
  399. $stk = array(self::JSON_IN_OBJ);
  400. $obj = array();
  401. } else {
  402. $stk = array(self::JSON_IN_OBJ);
  403. $obj = new stdClass();
  404. }
  405. }
  406. array_push($stk, array('what' => self::JSON_SLICE,
  407. 'where' => 0,
  408. 'delim' => false));
  409. $chrs = substr($str, 1, -1);
  410. $chrs = self::reduceString($chrs);
  411. if ($chrs == '') {
  412. if (reset($stk) == self::JSON_IN_ARR) {
  413. return $arr;
  414. } else {
  415. return $obj;
  416. }
  417. }
  418. //print("\nparsing {$chrs}\n");
  419. $strlen_chrs = strlen($chrs);
  420. for ($c = 0; $c <= $strlen_chrs; ++$c) {
  421. $top = end($stk);
  422. $substr_chrs_c_2 = substr($chrs, $c, 2);
  423. if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == self::JSON_SLICE))) {
  424. // found a comma that is not inside a string, array, etc.,
  425. // OR we've reached the end of the character list
  426. $slice = substr($chrs, $top['where'], ($c - $top['where']));
  427. array_push($stk, array('what' => self::JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
  428. //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  429. if (reset($stk) == self::JSON_IN_ARR) {
  430. // we are in an array, so just push an element onto the stack
  431. array_push($arr, self::decode($slice,$useArray));
  432. } elseif (reset($stk) == self::JSON_IN_OBJ) {
  433. // we are in an object, so figure
  434. // out the property name and set an
  435. // element in an associative array,
  436. // for now
  437. if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
  438. // "name":value pair
  439. $key = self::decode($parts[1],$useArray);
  440. $val = self::decode($parts[2],$useArray);
  441. if ($useArray) {
  442. $obj[$key] = $val;
  443. } else {
  444. $obj->$key = $val;
  445. }
  446. } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
  447. // name:value pair, where name is unquoted
  448. $key = $parts[1];
  449. $val = self::decode($parts[2],$useArray);
  450. if ($useArray) {
  451. $obj[$key] = $val;
  452. } else {
  453. $obj->$key = $val;
  454. }
  455. }
  456. }
  457. } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != self::JSON_IN_STR)) {
  458. // found a quote, and we are not inside a string
  459. array_push($stk, array('what' => self::JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
  460. //print("Found start of string at {$c}\n");
  461. } elseif (($chrs{$c} == $top['delim']) &&
  462. ($top['what'] == self::JSON_IN_STR) &&
  463. (($chrs{$c - 1} != "\\") ||
  464. ($chrs{$c - 1} == "\\" && $chrs{$c - 2} == "\\"))) {
  465. // found a quote, we're in a string, and it's not escaped
  466. array_pop($stk);
  467. //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
  468. } elseif (($chrs{$c} == '[') &&
  469. in_array($top['what'], array(self::JSON_SLICE, self::JSON_IN_ARR, self::JSON_IN_OBJ))) {
  470. // found a left-bracket, and we are in an array, object, or slice
  471. array_push($stk, array('what' => self::JSON_IN_ARR, 'where' => $c, 'delim' => false));
  472. //print("Found start of array at {$c}\n");
  473. } elseif (($chrs{$c} == ']') && ($top['what'] == self::JSON_IN_ARR)) {
  474. // found a right-bracket, and we're in an array
  475. array_pop($stk);
  476. //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  477. } elseif (($chrs{$c} == '{') &&
  478. in_array($top['what'], array(self::JSON_SLICE, self::JSON_IN_ARR, self::JSON_IN_OBJ))) {
  479. // found a left-brace, and we are in an array, object, or slice
  480. array_push($stk, array('what' => self::JSON_IN_OBJ, 'where' => $c, 'delim' => false));
  481. //print("Found start of object at {$c}\n");
  482. } elseif (($chrs{$c} == '}') && ($top['what'] == self::JSON_IN_OBJ)) {
  483. // found a right-brace, and we're in an object
  484. array_pop($stk);
  485. //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  486. } elseif (($substr_chrs_c_2 == '/*') &&
  487. in_array($top['what'], array(self::JSON_SLICE, self::JSON_IN_ARR, self::JSON_IN_OBJ))) {
  488. // found a comment start, and we are in an array, object, or slice
  489. array_push($stk, array('what' => self::JSON_IN_CMT, 'where' => $c, 'delim' => false));
  490. $c++;
  491. //print("Found start of comment at {$c}\n");
  492. } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == self::JSON_IN_CMT)) {
  493. // found a comment end, and we're in one now
  494. array_pop($stk);
  495. $c++;
  496. for ($i = $top['where']; $i <= $c; ++$i)
  497. $chrs = substr_replace($chrs, ' ', $i, 1);
  498. //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
  499. }
  500. }
  501. if (reset($stk) == self::JSON_IN_ARR) {
  502. return $arr;
  503. } elseif (reset($stk) == self::JSON_IN_OBJ) {
  504. return $obj;
  505. }
  506. }
  507. }
  508. }
  509. /**
  510. * This function returns any UTF-8 encoded text as a list of
  511. * Unicode values:
  512. * @param string $str string to convert
  513. * @return string
  514. * @author Scott Michael Reynen <scott@randomchaos.com>
  515. * @link http://www.randomchaos.com/document.php?source=php_and_unicode
  516. * @see unicodeToUTF8()
  517. */
  518. protected static function utf8ToUnicode( &$str )
  519. {
  520. $unicode = array();
  521. $values = array();
  522. $lookingFor = 1;
  523. for ($i = 0; $i < strlen( $str ); $i++ )
  524. {
  525. $thisValue = ord( $str[ $i ] );
  526. if ( $thisValue < 128 )
  527. $unicode[] = $thisValue;
  528. else
  529. {
  530. if ( count( $values ) == 0 )
  531. $lookingFor = ( $thisValue < 224 ) ? 2 : 3;
  532. $values[] = $thisValue;
  533. if ( count( $values ) == $lookingFor )
  534. {
  535. $number = ( $lookingFor == 3 ) ?
  536. ( ( $values[0] % 16 ) * 4096 ) + ( ( $values[1] % 64 ) * 64 ) + ( $values[2] % 64 ):
  537. ( ( $values[0] % 32 ) * 64 ) + ( $values[1] % 64 );
  538. $unicode[] = $number;
  539. $values = array();
  540. $lookingFor = 1;
  541. }
  542. }
  543. }
  544. return $unicode;
  545. }
  546. /**
  547. * This function converts a Unicode array back to its UTF-8 representation
  548. * @param string $str string to convert
  549. * @return string
  550. * @author Scott Michael Reynen <scott@randomchaos.com>
  551. * @link http://www.randomchaos.com/document.php?source=php_and_unicode
  552. * @see utf8ToUnicode()
  553. */
  554. protected static function unicodeToUTF8( &$str )
  555. {
  556. $utf8 = '';
  557. foreach( $str as $unicode )
  558. {
  559. if ( $unicode < 128 )
  560. {
  561. $utf8.= chr( $unicode );
  562. }
  563. elseif ( $unicode < 2048 )
  564. {
  565. $utf8.= chr( 192 + ( ( $unicode - ( $unicode % 64 ) ) / 64 ) );
  566. $utf8.= chr( 128 + ( $unicode % 64 ) );
  567. }
  568. else
  569. {
  570. $utf8.= chr( 224 + ( ( $unicode - ( $unicode % 4096 ) ) / 4096 ) );
  571. $utf8.= chr( 128 + ( ( ( $unicode % 4096 ) - ( $unicode % 64 ) ) / 64 ) );
  572. $utf8.= chr( 128 + ( $unicode % 64 ) );
  573. }
  574. }
  575. return $utf8;
  576. }
  577. /**
  578. * UTF-8 to UTF-16BE conversion.
  579. *
  580. * Maybe really UCS-2 without mb_string due to utf8ToUnicode limits
  581. * @param string $str string to convert
  582. * @param boolean $bom whether to output BOM header
  583. * @return string
  584. */
  585. protected static function utf8ToUTF16BE(&$str, $bom = false)
  586. {
  587. $out = $bom ? "\xFE\xFF" : '';
  588. if(function_exists('mb_convert_encoding'))
  589. return $out.mb_convert_encoding($str,'UTF-16BE','UTF-8');
  590. $uni = self::utf8ToUnicode($str);
  591. foreach($uni as $cp)
  592. $out .= pack('n',$cp);
  593. return $out;
  594. }
  595. /**
  596. * UTF-8 to UTF-16BE conversion.
  597. *
  598. * Maybe really UCS-2 without mb_string due to utf8ToUnicode limits
  599. * @param string $str string to convert
  600. * @return string
  601. */
  602. protected static function utf16beToUTF8(&$str)
  603. {
  604. $uni = unpack('n*',$str);
  605. return self::unicodeToUTF8($uni);
  606. }
  607. }