unicode.inc

  1. drupal
    1. 4.7 includes/unicode.inc
    2. 5 includes/unicode.inc
    3. 6 includes/unicode.inc
    4. 7 includes/unicode.inc
    5. 8 core/includes/unicode.inc

Functions & methods

NameDescription
decode_entitiesDecode all HTML entities (including numerical ones) to regular UTF-8 bytes. Double-escaped entities will only be decoded once ("&amp;lt;" becomes "&lt;", not "<").
drupal_convert_to_utf8Convert data to UTF-8
drupal_strlenCount the amount of characters in a UTF-8 string. This is less than or equal to the byte count.
drupal_strtolowerLowercase a UTF-8 string.
drupal_strtoupperUppercase a UTF-8 string.
drupal_substrCut off a piece of a string based on character indices and counts. Follows the same behaviour as PHP's own substr() function.
drupal_ucfirstCapitalize the first letter of a UTF-8 string.
drupal_xml_parser_createPrepare a new XML parser.
mime_header_decodeComplement to mime_header_encode
mime_header_encodeEncodes MIME/HTTP header values that contain non-ASCII, UTF-8 encoded characters.
truncate_utf8Truncate a UTF-8-encoded string safely to a number of bytes.
unicode_checkWrapper around _unicode_check().
unicode_requirementsReturn Unicode library status and errors.
_decode_entitiesHelper function for decode_entities
_mime_header_decodeHelper function to mime_header_decode
_unicode_caseflipHelper function for case conversion of Latin-1. Used for flipping U+C0-U+DE to U+E0-U+FD and back.
_unicode_checkPerform checks about Unicode support in PHP, and set the right settings if needed.

Constants

NameDescription
UNICODE_ERRORIndicates an error during check for PHP unicode support.
UNICODE_MULTIBYTEIndicates that full unicode support with the PHP mbstring extension is being used.
UNICODE_SINGLEBYTEIndicates that standard PHP (emulated) unicode support is being used.

File

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