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_settingsReturn the required Unicode status and errors for admin/settings.
_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_ERROR
UNICODE_MULTIBYTE
UNICODE_SINGLEBYTE

File

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