PageRenderTime 73ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/unicode.inc

https://github.com/jacobSingh/drupal
Pascal | 559 lines | 265 code | 38 blank | 256 comment | 44 complexity | 9a09273cd26b396a130a1460a92d1154 MD5 | raw file
  1. <?php
  2. // $Id: unicode.inc,v 1.40 2009-09-28 22:22:54 dries Exp $
  3. /**
  4. * Indicates an error during check for PHP unicode support.
  5. */
  6. define('UNICODE_ERROR', -1);
  7. /**
  8. * Indicates that standard PHP (emulated) unicode support is being used.
  9. */
  10. define('UNICODE_SINGLEBYTE', 0);
  11. /**
  12. * Indicates that full unicode support with the PHP mbstring extension is being
  13. * used.
  14. */
  15. define('UNICODE_MULTIBYTE', 1);
  16. /**
  17. * Wrapper around _unicode_check().
  18. */
  19. function unicode_check() {
  20. list($GLOBALS['multibyte']) = _unicode_check();
  21. }
  22. /**
  23. * Perform checks about Unicode support in PHP, and set the right settings if
  24. * needed.
  25. *
  26. * Because Drupal needs to be able to handle text in various encodings, we do
  27. * not support mbstring function overloading. HTTP input/output conversion must
  28. * be disabled for similar reasons.
  29. *
  30. * @param $errors
  31. * Whether to report any fatal errors with form_set_error().
  32. */
  33. function _unicode_check() {
  34. // Ensure translations don't break at install time
  35. $t = get_t();
  36. // Set the standard C locale to ensure consistent, ASCII-only string handling.
  37. setlocale(LC_CTYPE, 'C');
  38. // Check for mbstring extension
  39. if (!function_exists('mb_strlen')) {
  40. return array(UNICODE_SINGLEBYTE, $t('Operations on Unicode strings are emulated on a best-effort basis. Install the <a href="@url">PHP mbstring extension</a> for improved Unicode support.', array('@url' => 'http://www.php.net/mbstring')));
  41. }
  42. // Check mbstring configuration
  43. if (ini_get('mbstring.func_overload') != 0) {
  44. return array(UNICODE_ERROR, $t('Multibyte string function overloading in PHP is active and must be disabled. Check the php.ini <em>mbstring.func_overload</em> setting. Please refer to the <a href="@url">PHP mbstring documentation</a> for more information.', array('@url' => 'http://www.php.net/mbstring')));
  45. }
  46. if (ini_get('mbstring.encoding_translation') != 0) {
  47. return array(UNICODE_ERROR, $t('Multibyte string input conversion in PHP is active and must be disabled. Check the php.ini <em>mbstring.encoding_translation</em> setting. Please refer to the <a href="@url">PHP mbstring documentation</a> for more information.', array('@url' => 'http://www.php.net/mbstring')));
  48. }
  49. if (ini_get('mbstring.http_input') != 'pass') {
  50. return array(UNICODE_ERROR, $t('Multibyte string input conversion in PHP is active and must be disabled. Check the php.ini <em>mbstring.http_input</em> setting. Please refer to the <a href="@url">PHP mbstring documentation</a> for more information.', array('@url' => 'http://www.php.net/mbstring')));
  51. }
  52. if (ini_get('mbstring.http_output') != 'pass') {
  53. return array(UNICODE_ERROR, $t('Multibyte string output conversion in PHP is active and must be disabled. Check the php.ini <em>mbstring.http_output</em> setting. Please refer to the <a href="@url">PHP mbstring documentation</a> for more information.', array('@url' => 'http://www.php.net/mbstring')));
  54. }
  55. // Set appropriate configuration
  56. mb_internal_encoding('utf-8');
  57. mb_language('uni');
  58. return array(UNICODE_MULTIBYTE, '');
  59. }
  60. /**
  61. * Return Unicode library status and errors.
  62. */
  63. function unicode_requirements() {
  64. // Ensure translations don't break at install time
  65. $t = get_t();
  66. $libraries = array(
  67. UNICODE_SINGLEBYTE => $t('Standard PHP'),
  68. UNICODE_MULTIBYTE => $t('PHP Mbstring Extension'),
  69. UNICODE_ERROR => $t('Error'),
  70. );
  71. $severities = array(
  72. UNICODE_SINGLEBYTE => REQUIREMENT_WARNING,
  73. UNICODE_MULTIBYTE => REQUIREMENT_OK,
  74. UNICODE_ERROR => REQUIREMENT_ERROR,
  75. );
  76. list($library, $description) = _unicode_check();
  77. $requirements['unicode'] = array(
  78. 'title' => $t('Unicode library'),
  79. 'value' => $libraries[$library],
  80. );
  81. if ($description) {
  82. $requirements['unicode']['description'] = $description;
  83. }
  84. $requirements['unicode']['severity'] = $severities[$library];
  85. return $requirements;
  86. }
  87. /**
  88. * Prepare a new XML parser.
  89. *
  90. * This is a wrapper around xml_parser_create() which extracts the encoding from
  91. * the XML data first and sets the output encoding to UTF-8. This function should
  92. * be used instead of xml_parser_create(), because PHP 4's XML parser doesn't
  93. * check the input encoding itself. "Starting from PHP 5, the input encoding is
  94. * automatically detected, so that the encoding parameter specifies only the
  95. * output encoding."
  96. *
  97. * This is also where unsupported encodings will be converted. Callers should
  98. * take this into account: $data might have been changed after the call.
  99. *
  100. * @param &$data
  101. * The XML data which will be parsed later.
  102. * @return
  103. * An XML parser object or FALSE on error.
  104. *
  105. * @ingroup php_wrappers
  106. */
  107. function drupal_xml_parser_create(&$data) {
  108. // Default XML encoding is UTF-8
  109. $encoding = 'utf-8';
  110. $bom = FALSE;
  111. // Check for UTF-8 byte order mark (PHP5's XML parser doesn't handle it).
  112. if (!strncmp($data, "\xEF\xBB\xBF", 3)) {
  113. $bom = TRUE;
  114. $data = substr($data, 3);
  115. }
  116. // Check for an encoding declaration in the XML prolog if no BOM was found.
  117. if (!$bom && preg_match('/^<\?xml[^>]+encoding="(.+?)"/', $data, $match)) {
  118. $encoding = $match[1];
  119. }
  120. // Unsupported encodings are converted here into UTF-8.
  121. $php_supported = array('utf-8', 'iso-8859-1', 'us-ascii');
  122. if (!in_array(strtolower($encoding), $php_supported)) {
  123. $out = drupal_convert_to_utf8($data, $encoding);
  124. if ($out !== FALSE) {
  125. $encoding = 'utf-8';
  126. $data = preg_replace('/^(<\?xml[^>]+encoding)="(.+?)"/', '\\1="utf-8"', $out);
  127. }
  128. else {
  129. watchdog('php', 'Could not convert XML encoding %s to UTF-8.', array('%s' => $encoding), WATCHDOG_WARNING);
  130. return FALSE;
  131. }
  132. }
  133. $xml_parser = xml_parser_create($encoding);
  134. xml_parser_set_option($xml_parser, XML_OPTION_TARGET_ENCODING, 'utf-8');
  135. return $xml_parser;
  136. }
  137. /**
  138. * Convert data to UTF-8
  139. *
  140. * Requires the iconv, GNU recode or mbstring PHP extension.
  141. *
  142. * @param $data
  143. * The data to be converted.
  144. * @param $encoding
  145. * The encoding that the data is in
  146. * @return
  147. * Converted data or FALSE.
  148. */
  149. function drupal_convert_to_utf8($data, $encoding) {
  150. if (function_exists('iconv')) {
  151. $out = @iconv($encoding, 'utf-8', $data);
  152. }
  153. elseif (function_exists('mb_convert_encoding')) {
  154. $out = @mb_convert_encoding($data, 'utf-8', $encoding);
  155. }
  156. elseif (function_exists('recode_string')) {
  157. $out = @recode_string($encoding . '..utf-8', $data);
  158. }
  159. else {
  160. watchdog('php', 'Unsupported encoding %s. Please install iconv, GNU recode or mbstring for PHP.', array('%s' => $encoding), WATCHDOG_ERROR);
  161. return FALSE;
  162. }
  163. return $out;
  164. }
  165. /**
  166. * Truncate a UTF-8-encoded string safely to a number of bytes.
  167. *
  168. * If the end position is in the middle of a UTF-8 sequence, it scans backwards
  169. * until the beginning of the byte sequence.
  170. *
  171. * Use this function whenever you want to chop off a string at an unsure
  172. * location. On the other hand, if you're sure that you're splitting on a
  173. * character boundary (e.g. after using strpos() or similar), you can safely use
  174. * substr() instead.
  175. *
  176. * @param $string
  177. * The string to truncate.
  178. * @param $len
  179. * An upper limit on the returned string length.
  180. * @return
  181. * The truncated string.
  182. */
  183. function drupal_truncate_bytes($string, $len) {
  184. if (strlen($string) <= $len) {
  185. return $string;
  186. }
  187. if ((ord($string[$len]) < 0x80) || (ord($string[$len]) >= 0xC0)) {
  188. return substr($string, 0, $len);
  189. }
  190. // Scan backwards to beginning of the byte sequence.
  191. while (--$len >= 0 && ord($string[$len]) >= 0x80 && ord($string[$len]) < 0xC0);
  192. return substr($string, 0, $len);
  193. }
  194. /**
  195. * Truncate a UTF-8-encoded string safely to a number of characters.
  196. *
  197. * @param $string
  198. * The string to truncate.
  199. * @param $len
  200. * An upper limit on the returned string length.
  201. * @param $wordsafe
  202. * Flag to truncate at last space within the upper limit. Defaults to FALSE.
  203. * @param $dots
  204. * Flag to add trailing dots. Defaults to FALSE.
  205. * @return
  206. * The truncated string.
  207. */
  208. function truncate_utf8($string, $len, $wordsafe = FALSE, $dots = FALSE) {
  209. if (drupal_strlen($string) <= $len) {
  210. return $string;
  211. }
  212. if ($dots) {
  213. $len -= 4;
  214. }
  215. if ($wordsafe) {
  216. $string = drupal_substr($string, 0, $len + 1); // leave one more character
  217. if ($last_space = strrpos($string, ' ')) { // space exists AND is not on position 0
  218. $string = substr($string, 0, $last_space);
  219. }
  220. else {
  221. $string = drupal_substr($string, 0, $len);
  222. }
  223. }
  224. else {
  225. $string = drupal_substr($string, 0, $len);
  226. }
  227. if ($dots) {
  228. $string .= ' ...';
  229. }
  230. return $string;
  231. }
  232. /**
  233. * Encodes MIME/HTTP header values that contain non-ASCII, UTF-8 encoded
  234. * characters.
  235. *
  236. * For example, mime_header_encode('tĂŠst.txt') returns "=?UTF-8?B?dMOpc3QudHh0?=".
  237. *
  238. * See http://www.rfc-editor.org/rfc/rfc2047.txt for more information.
  239. *
  240. * Notes:
  241. * - Only encode strings that contain non-ASCII characters.
  242. * - We progressively cut-off a chunk with truncate_utf8(). This is to ensure
  243. * each chunk starts and ends on a character boundary.
  244. * - Using \n as the chunk separator may cause problems on some systems and may
  245. * have to be changed to \r\n or \r.
  246. */
  247. function mime_header_encode($string) {
  248. if (preg_match('/[^\x20-\x7E]/', $string)) {
  249. $chunk_size = 47; // floor((75 - strlen("=?UTF-8?B??=")) * 0.75);
  250. $len = strlen($string);
  251. $output = '';
  252. while ($len > 0) {
  253. $chunk = drupal_truncate_bytes($string, $chunk_size);
  254. $output .= ' =?UTF-8?B?' . base64_encode($chunk) . "?=\n";
  255. $c = strlen($chunk);
  256. $string = substr($string, $c);
  257. $len -= $c;
  258. }
  259. return trim($output);
  260. }
  261. return $string;
  262. }
  263. /**
  264. * Complement to mime_header_encode
  265. */
  266. function mime_header_decode($header) {
  267. // First step: encoded chunks followed by other encoded chunks (need to collapse whitespace)
  268. $header = preg_replace_callback('/=\?([^?]+)\?(Q|B)\?([^?]+|\?(?!=))\?=\s+(?==\?)/', '_mime_header_decode', $header);
  269. // Second step: remaining chunks (do not collapse whitespace)
  270. return preg_replace_callback('/=\?([^?]+)\?(Q|B)\?([^?]+|\?(?!=))\?=/', '_mime_header_decode', $header);
  271. }
  272. /**
  273. * Helper function to mime_header_decode
  274. */
  275. function _mime_header_decode($matches) {
  276. // Regexp groups:
  277. // 1: Character set name
  278. // 2: Escaping method (Q or B)
  279. // 3: Encoded data
  280. $data = ($matches[2] == 'B') ? base64_decode($matches[3]) : str_replace('_', ' ', quoted_printable_decode($matches[3]));
  281. if (strtolower($matches[1]) != 'utf-8') {
  282. $data = drupal_convert_to_utf8($data, $matches[1]);
  283. }
  284. return $data;
  285. }
  286. /**
  287. * Decode all HTML entities (including numerical ones) to regular UTF-8 bytes.
  288. * Double-escaped entities will only be decoded once ("&amp;lt;" becomes "&lt;", not "<").
  289. *
  290. * @param $text
  291. * The text to decode entities in.
  292. * @param $exclude
  293. * An array of characters which should not be decoded. For example,
  294. * array('<', '&', '"'). This affects both named and numerical entities.
  295. */
  296. function decode_entities($text, $exclude = array()) {
  297. static $html_entities;
  298. if (!isset($html_entities)) {
  299. include DRUPAL_ROOT . '/includes/unicode.entities.inc';
  300. }
  301. // Flip the exclude list so that we can do quick lookups later.
  302. $exclude = array_flip($exclude);
  303. // Use a regexp to select all entities in one pass, to avoid decoding
  304. // double-escaped entities twice. The PREG_REPLACE_EVAL modifier 'e' is
  305. // being used to allow for a callback (see
  306. // http://php.net/manual/en/reference.pcre.pattern.modifiers).
  307. return preg_replace('/&(#x?)?([A-Za-z0-9]+);/e', '_decode_entities("$1", "$2", "$0", $html_entities, $exclude)', $text);
  308. }
  309. /**
  310. * Helper function for decode_entities
  311. */
  312. function _decode_entities($prefix, $codepoint, $original, &$html_entities, &$exclude) {
  313. // Named entity
  314. if (!$prefix) {
  315. // A named entity not in the exclude list.
  316. if (isset($html_entities[$original]) && !isset($exclude[$html_entities[$original]])) {
  317. return $html_entities[$original];
  318. }
  319. else {
  320. return $original;
  321. }
  322. }
  323. // Hexadecimal numerical entity
  324. if ($prefix == '#x') {
  325. $codepoint = base_convert($codepoint, 16, 10);
  326. }
  327. // Decimal numerical entity (strip leading zeros to avoid PHP octal notation)
  328. else {
  329. $codepoint = preg_replace('/^0+/', '', $codepoint);
  330. }
  331. // Encode codepoint as UTF-8 bytes
  332. if ($codepoint < 0x80) {
  333. $str = chr($codepoint);
  334. }
  335. elseif ($codepoint < 0x800) {
  336. $str = chr(0xC0 | ($codepoint >> 6))
  337. . chr(0x80 | ($codepoint & 0x3F));
  338. }
  339. elseif ($codepoint < 0x10000) {
  340. $str = chr(0xE0 | ( $codepoint >> 12))
  341. . chr(0x80 | (($codepoint >> 6) & 0x3F))
  342. . chr(0x80 | ( $codepoint & 0x3F));
  343. }
  344. elseif ($codepoint < 0x200000) {
  345. $str = chr(0xF0 | ( $codepoint >> 18))
  346. . chr(0x80 | (($codepoint >> 12) & 0x3F))
  347. . chr(0x80 | (($codepoint >> 6) & 0x3F))
  348. . chr(0x80 | ( $codepoint & 0x3F));
  349. }
  350. // Check for excluded characters
  351. if (isset($exclude[$str])) {
  352. return $original;
  353. }
  354. else {
  355. return $str;
  356. }
  357. }
  358. /**
  359. * Count the amount of characters in a UTF-8 string. This is less than or
  360. * equal to the byte count.
  361. *
  362. * @ingroup php_wrappers
  363. */
  364. function drupal_strlen($text) {
  365. global $multibyte;
  366. if ($multibyte == UNICODE_MULTIBYTE) {
  367. return mb_strlen($text);
  368. }
  369. else {
  370. // Do not count UTF-8 continuation bytes.
  371. return strlen(preg_replace("/[\x80-\xBF]/", '', $text));
  372. }
  373. }
  374. /**
  375. * Uppercase a UTF-8 string.
  376. *
  377. * @ingroup php_wrappers
  378. */
  379. function drupal_strtoupper($text) {
  380. global $multibyte;
  381. if ($multibyte == UNICODE_MULTIBYTE) {
  382. return mb_strtoupper($text);
  383. }
  384. else {
  385. // Use C-locale for ASCII-only uppercase
  386. $text = strtoupper($text);
  387. // Case flip Latin-1 accented letters
  388. $text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '_unicode_caseflip', $text);
  389. return $text;
  390. }
  391. }
  392. /**
  393. * Lowercase a UTF-8 string.
  394. *
  395. * @ingroup php_wrappers
  396. */
  397. function drupal_strtolower($text) {
  398. global $multibyte;
  399. if ($multibyte == UNICODE_MULTIBYTE) {
  400. return mb_strtolower($text);
  401. }
  402. else {
  403. // Use C-locale for ASCII-only lowercase
  404. $text = strtolower($text);
  405. // Case flip Latin-1 accented letters
  406. $text = preg_replace_callback('/\xC3[\x80-\x96\x98-\x9E]/', '_unicode_caseflip', $text);
  407. return $text;
  408. }
  409. }
  410. /**
  411. * Helper function for case conversion of Latin-1.
  412. * Used for flipping U+C0-U+DE to U+E0-U+FD and back.
  413. */
  414. function _unicode_caseflip($matches) {
  415. return $matches[0][0] . chr(ord($matches[0][1]) ^ 32);
  416. }
  417. /**
  418. * Capitalize the first letter of a UTF-8 string.
  419. *
  420. * @ingroup php_wrappers
  421. */
  422. function drupal_ucfirst($text) {
  423. // Note: no mbstring equivalent!
  424. return drupal_strtoupper(drupal_substr($text, 0, 1)) . drupal_substr($text, 1);
  425. }
  426. /**
  427. * Cut off a piece of a string based on character indices and counts. Follows
  428. * the same behavior as PHP's own substr() function.
  429. *
  430. * Note that for cutting off a string at a known character/substring
  431. * location, the usage of PHP's normal strpos/substr is safe and
  432. * much faster.
  433. *
  434. * @ingroup php_wrappers
  435. */
  436. function drupal_substr($text, $start, $length = NULL) {
  437. global $multibyte;
  438. if ($multibyte == UNICODE_MULTIBYTE) {
  439. return $length === NULL ? mb_substr($text, $start) : mb_substr($text, $start, $length);
  440. }
  441. else {
  442. $strlen = strlen($text);
  443. // Find the starting byte offset.
  444. $bytes = 0;
  445. if ($start > 0) {
  446. // Count all the continuation bytes from the start until we have found
  447. // $start characters or the end of the string.
  448. $bytes = -1; $chars = -1;
  449. while ($bytes < $strlen - 1 && $chars < $start) {
  450. $bytes++;
  451. $c = ord($text[$bytes]);
  452. if ($c < 0x80 || $c >= 0xC0) {
  453. $chars++;
  454. }
  455. }
  456. }
  457. elseif ($start < 0) {
  458. // Count all the continuation bytes from the end until we have found
  459. // abs($start) characters.
  460. $start = abs($start);
  461. $bytes = $strlen; $chars = 0;
  462. while ($bytes > 0 && $chars < $start) {
  463. $bytes--;
  464. $c = ord($text[$bytes]);
  465. if ($c < 0x80 || $c >= 0xC0) {
  466. $chars++;
  467. }
  468. }
  469. }
  470. $istart = $bytes;
  471. // Find the ending byte offset.
  472. if ($length === NULL) {
  473. $iend = $strlen;
  474. }
  475. elseif ($length > 0) {
  476. // Count all the continuation bytes from the starting index until we have
  477. // found $length characters or reached the end of the string, then
  478. // backtrace one byte.
  479. $iend = $istart - 1; $chars = -1;
  480. while ($iend < $strlen - 1 && $chars < $length) {
  481. $iend++;
  482. $c = ord($text[$iend]);
  483. if ($c < 0x80 || $c >= 0xC0) {
  484. $chars++;
  485. }
  486. }
  487. // Backtrace one byte if the end of the string was not reached.
  488. if ($iend < $strlen - 1) {
  489. $iend--;
  490. }
  491. }
  492. elseif ($length < 0) {
  493. // Count all the continuation bytes from the end until we have found
  494. // abs($start) characters, then backtrace one byte.
  495. $length = abs($length);
  496. $iend = $strlen; $chars = 0;
  497. while ($iend > 0 && $chars < $length) {
  498. $iend--;
  499. $c = ord($text[$iend]);
  500. if ($c < 0x80 || $c >= 0xC0) {
  501. $chars++;
  502. }
  503. }
  504. // Backtrace one byte if we are not at the begining of the string.
  505. if ($iend > 0) {
  506. $iend--;
  507. }
  508. }
  509. else {
  510. // $length == 0, return an empty string.
  511. $iend = $istart - 1;
  512. }
  513. return substr($text, $istart, max(0, $iend - $istart + 1));
  514. }
  515. }