PageRenderTime 24ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/includes/unicode.inc

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