PageRenderTime 56ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/unicode.inc

https://github.com/ayappan/drupal
Pascal | 664 lines | 531 code | 24 blank | 109 comment | 36 complexity | 2b07290e5716c0a35d5f07c891ecd5ad MD5 | raw file
  1. <?php
  2. // $Id: unicode.inc,v 1.44 2010/06/14 12:37:15 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. * Matches Unicode characters that are word boundaries.
  18. *
  19. * @see http://unicode.org/glossary
  20. *
  21. * Characters with the following General_category (gc) property values are used
  22. * as word boundaries. While this does not fully conform to the Word Boundaries
  23. * algorithm described in http://unicode.org/reports/tr29, as PCRE does not
  24. * contain the Word_Break property table, this simpler algorithm has to do.
  25. * - Cc, Cf, Cn, Co, Cs: Other.
  26. * - Pc, Pd, Pe, Pf, Pi, Po, Ps: Punctuation.
  27. * - Sc, Sk, Sm, So: Symbols.
  28. * - Zl, Zp, Zs: Separators.
  29. *
  30. * Non-boundary characters include the following General_category (gc) property
  31. * values:
  32. * - Ll, Lm, Lo, Lt, Lu: Letters.
  33. * - Mc, Me, Mn: Combining Marks.
  34. * - Nd, Nl, No: Numbers.
  35. *
  36. * Note that the PCRE property matcher is not used because we wanted to be
  37. * compatible with Unicode 5.2.0 regardless of the PCRE version used (and any
  38. * bugs in PCRE property tables).
  39. */
  40. define('PREG_CLASS_UNICODE_WORD_BOUNDARY',
  41. '\x{0}-\x{2F}\x{3A}-\x{40}\x{5B}-\x{60}\x{7B}-\x{A9}\x{AB}-\x{B1}\x{B4}' .
  42. '\x{B6}-\x{B8}\x{BB}\x{BF}\x{D7}\x{F7}\x{2C2}-\x{2C5}\x{2D2}-\x{2DF}' .
  43. '\x{2E5}-\x{2EB}\x{2ED}\x{2EF}-\x{2FF}\x{375}\x{37E}-\x{385}\x{387}\x{3F6}' .
  44. '\x{482}\x{55A}-\x{55F}\x{589}-\x{58A}\x{5BE}\x{5C0}\x{5C3}\x{5C6}' .
  45. '\x{5F3}-\x{60F}\x{61B}-\x{61F}\x{66A}-\x{66D}\x{6D4}\x{6DD}\x{6E9}' .
  46. '\x{6FD}-\x{6FE}\x{700}-\x{70F}\x{7F6}-\x{7F9}\x{830}-\x{83E}' .
  47. '\x{964}-\x{965}\x{970}\x{9F2}-\x{9F3}\x{9FA}-\x{9FB}\x{AF1}\x{B70}' .
  48. '\x{BF3}-\x{BFA}\x{C7F}\x{CF1}-\x{CF2}\x{D79}\x{DF4}\x{E3F}\x{E4F}' .
  49. '\x{E5A}-\x{E5B}\x{F01}-\x{F17}\x{F1A}-\x{F1F}\x{F34}\x{F36}\x{F38}' .
  50. '\x{F3A}-\x{F3D}\x{F85}\x{FBE}-\x{FC5}\x{FC7}-\x{FD8}\x{104A}-\x{104F}' .
  51. '\x{109E}-\x{109F}\x{10FB}\x{1360}-\x{1368}\x{1390}-\x{1399}\x{1400}' .
  52. '\x{166D}-\x{166E}\x{1680}\x{169B}-\x{169C}\x{16EB}-\x{16ED}' .
  53. '\x{1735}-\x{1736}\x{17B4}-\x{17B5}\x{17D4}-\x{17D6}\x{17D8}-\x{17DB}' .
  54. '\x{1800}-\x{180A}\x{180E}\x{1940}-\x{1945}\x{19DE}-\x{19FF}' .
  55. '\x{1A1E}-\x{1A1F}\x{1AA0}-\x{1AA6}\x{1AA8}-\x{1AAD}\x{1B5A}-\x{1B6A}' .
  56. '\x{1B74}-\x{1B7C}\x{1C3B}-\x{1C3F}\x{1C7E}-\x{1C7F}\x{1CD3}\x{1FBD}' .
  57. '\x{1FBF}-\x{1FC1}\x{1FCD}-\x{1FCF}\x{1FDD}-\x{1FDF}\x{1FED}-\x{1FEF}' .
  58. '\x{1FFD}-\x{206F}\x{207A}-\x{207E}\x{208A}-\x{208E}\x{20A0}-\x{20B8}' .
  59. '\x{2100}-\x{2101}\x{2103}-\x{2106}\x{2108}-\x{2109}\x{2114}' .
  60. '\x{2116}-\x{2118}\x{211E}-\x{2123}\x{2125}\x{2127}\x{2129}\x{212E}' .
  61. '\x{213A}-\x{213B}\x{2140}-\x{2144}\x{214A}-\x{214D}\x{214F}' .
  62. '\x{2190}-\x{244A}\x{249C}-\x{24E9}\x{2500}-\x{2775}\x{2794}-\x{2B59}' .
  63. '\x{2CE5}-\x{2CEA}\x{2CF9}-\x{2CFC}\x{2CFE}-\x{2CFF}\x{2E00}-\x{2E2E}' .
  64. '\x{2E30}-\x{3004}\x{3008}-\x{3020}\x{3030}\x{3036}-\x{3037}' .
  65. '\x{303D}-\x{303F}\x{309B}-\x{309C}\x{30A0}\x{30FB}\x{3190}-\x{3191}' .
  66. '\x{3196}-\x{319F}\x{31C0}-\x{31E3}\x{3200}-\x{321E}\x{322A}-\x{3250}' .
  67. '\x{3260}-\x{327F}\x{328A}-\x{32B0}\x{32C0}-\x{33FF}\x{4DC0}-\x{4DFF}' .
  68. '\x{A490}-\x{A4C6}\x{A4FE}-\x{A4FF}\x{A60D}-\x{A60F}\x{A673}\x{A67E}' .
  69. '\x{A6F2}-\x{A716}\x{A720}-\x{A721}\x{A789}-\x{A78A}\x{A828}-\x{A82B}' .
  70. '\x{A836}-\x{A839}\x{A874}-\x{A877}\x{A8CE}-\x{A8CF}\x{A8F8}-\x{A8FA}' .
  71. '\x{A92E}-\x{A92F}\x{A95F}\x{A9C1}-\x{A9CD}\x{A9DE}-\x{A9DF}' .
  72. '\x{AA5C}-\x{AA5F}\x{AA77}-\x{AA79}\x{AADE}-\x{AADF}\x{ABEB}' .
  73. '\x{D800}-\x{F8FF}\x{FB29}\x{FD3E}-\x{FD3F}\x{FDFC}-\x{FDFD}' .
  74. '\x{FE10}-\x{FE19}\x{FE30}-\x{FE6B}\x{FEFF}-\x{FF0F}\x{FF1A}-\x{FF20}' .
  75. '\x{FF3B}-\x{FF40}\x{FF5B}-\x{FF65}\x{FFE0}-\x{FFFD}');
  76. /**
  77. * Wrapper around _unicode_check().
  78. */
  79. function unicode_check() {
  80. list($GLOBALS['multibyte']) = _unicode_check();
  81. }
  82. /**
  83. * Perform checks about Unicode support in PHP, and set the right settings if
  84. * needed.
  85. *
  86. * Because Drupal needs to be able to handle text in various encodings, we do
  87. * not support mbstring function overloading. HTTP input/output conversion must
  88. * be disabled for similar reasons.
  89. *
  90. * @param $errors
  91. * Whether to report any fatal errors with form_set_error().
  92. */
  93. function _unicode_check() {
  94. // Ensure translations don't break at install time
  95. $t = get_t();
  96. // Check for mbstring extension
  97. if (!function_exists('mb_strlen')) {
  98. 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')));
  99. }
  100. // Check mbstring configuration
  101. if (ini_get('mbstring.func_overload') != 0) {
  102. 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')));
  103. }
  104. if (ini_get('mbstring.encoding_translation') != 0) {
  105. 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')));
  106. }
  107. if (ini_get('mbstring.http_input') != 'pass') {
  108. 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')));
  109. }
  110. if (ini_get('mbstring.http_output') != 'pass') {
  111. 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')));
  112. }
  113. // Set appropriate configuration
  114. mb_internal_encoding('utf-8');
  115. mb_language('uni');
  116. return array(UNICODE_MULTIBYTE, '');
  117. }
  118. /**
  119. * Return Unicode library status and errors.
  120. */
  121. function unicode_requirements() {
  122. // Ensure translations don't break at install time
  123. $t = get_t();
  124. $libraries = array(
  125. UNICODE_SINGLEBYTE => $t('Standard PHP'),
  126. UNICODE_MULTIBYTE => $t('PHP Mbstring Extension'),
  127. UNICODE_ERROR => $t('Error'),
  128. );
  129. $severities = array(
  130. UNICODE_SINGLEBYTE => REQUIREMENT_WARNING,
  131. UNICODE_MULTIBYTE => REQUIREMENT_OK,
  132. UNICODE_ERROR => REQUIREMENT_ERROR,
  133. );
  134. list($library, $description) = _unicode_check();
  135. $requirements['unicode'] = array(
  136. 'title' => $t('Unicode library'),
  137. 'value' => $libraries[$library],
  138. );
  139. if ($description) {
  140. $requirements['unicode']['description'] = $description;
  141. }
  142. $requirements['unicode']['severity'] = $severities[$library];
  143. return $requirements;
  144. }
  145. /**
  146. * Prepare a new XML parser.
  147. *
  148. * This is a wrapper around xml_parser_create() which extracts the encoding from
  149. * the XML data first and sets the output encoding to UTF-8. This function should
  150. * be used instead of xml_parser_create(), because PHP 4's XML parser doesn't
  151. * check the input encoding itself. "Starting from PHP 5, the input encoding is
  152. * automatically detected, so that the encoding parameter specifies only the
  153. * output encoding."
  154. *
  155. * This is also where unsupported encodings will be converted. Callers should
  156. * take this into account: $data might have been changed after the call.
  157. *
  158. * @param &$data
  159. * The XML data which will be parsed later.
  160. * @return
  161. * An XML parser object or FALSE on error.
  162. *
  163. * @ingroup php_wrappers
  164. */
  165. function drupal_xml_parser_create(&$data) {
  166. // Default XML encoding is UTF-8
  167. $encoding = 'utf-8';
  168. $bom = FALSE;
  169. // Check for UTF-8 byte order mark (PHP5's XML parser doesn't handle it).
  170. if (!strncmp($data, "\xEF\xBB\xBF", 3)) {
  171. $bom = TRUE;
  172. $data = substr($data, 3);
  173. }
  174. // Check for an encoding declaration in the XML prolog if no BOM was found.
  175. if (!$bom && preg_match('/^<\?xml[^>]+encoding="(.+?)"/', $data, $match)) {
  176. $encoding = $match[1];
  177. }
  178. // Unsupported encodings are converted here into UTF-8.
  179. $php_supported = array('utf-8', 'iso-8859-1', 'us-ascii');
  180. if (!in_array(strtolower($encoding), $php_supported)) {
  181. $out = drupal_convert_to_utf8($data, $encoding);
  182. if ($out !== FALSE) {
  183. $encoding = 'utf-8';
  184. $data = preg_replace('/^(<\?xml[^>]+encoding)="(.+?)"/', '\\1="utf-8"', $out);
  185. }
  186. else {
  187. watchdog('php', 'Could not convert XML encoding %s to UTF-8.', array('%s' => $encoding), WATCHDOG_WARNING);
  188. return FALSE;
  189. }
  190. }
  191. $xml_parser = xml_parser_create($encoding);
  192. xml_parser_set_option($xml_parser, XML_OPTION_TARGET_ENCODING, 'utf-8');
  193. return $xml_parser;
  194. }
  195. /**
  196. * Convert data to UTF-8
  197. *
  198. * Requires the iconv, GNU recode or mbstring PHP extension.
  199. *
  200. * @param $data
  201. * The data to be converted.
  202. * @param $encoding
  203. * The encoding that the data is in
  204. * @return
  205. * Converted data or FALSE.
  206. */
  207. function drupal_convert_to_utf8($data, $encoding) {
  208. if (function_exists('iconv')) {
  209. $out = @iconv($encoding, 'utf-8', $data);
  210. }
  211. elseif (function_exists('mb_convert_encoding')) {
  212. $out = @mb_convert_encoding($data, 'utf-8', $encoding);
  213. }
  214. elseif (function_exists('recode_string')) {
  215. $out = @recode_string($encoding . '..utf-8', $data);
  216. }
  217. else {
  218. watchdog('php', 'Unsupported encoding %s. Please install iconv, GNU recode or mbstring for PHP.', array('%s' => $encoding), WATCHDOG_ERROR);
  219. return FALSE;
  220. }
  221. return $out;
  222. }
  223. /**
  224. * Truncate a UTF-8-encoded string safely to a number of bytes.
  225. *
  226. * If the end position is in the middle of a UTF-8 sequence, it scans backwards
  227. * until the beginning of the byte sequence.
  228. *
  229. * Use this function whenever you want to chop off a string at an unsure
  230. * location. On the other hand, if you're sure that you're splitting on a
  231. * character boundary (e.g. after using strpos() or similar), you can safely use
  232. * substr() instead.
  233. *
  234. * @param $string
  235. * The string to truncate.
  236. * @param $len
  237. * An upper limit on the returned string length.
  238. * @return
  239. * The truncated string.
  240. */
  241. function drupal_truncate_bytes($string, $len) {
  242. if (strlen($string) <= $len) {
  243. return $string;
  244. }
  245. if ((ord($string[$len]) < 0x80) || (ord($string[$len]) >= 0xC0)) {
  246. return substr($string, 0, $len);
  247. }
  248. // Scan backwards to beginning of the byte sequence.
  249. while (--$len >= 0 && ord($string[$len]) >= 0x80 && ord($string[$len]) < 0xC0);
  250. return substr($string, 0, $len);
  251. }
  252. /**
  253. * Truncates a UTF-8-encoded string safely to a number of characters.
  254. *
  255. * @param $string
  256. * The string to truncate.
  257. * @param $max_length
  258. * An upper limit on the returned string length, including trailing ellipsis
  259. * if $add_ellipsis is TRUE.
  260. * @param $wordsafe
  261. * If TRUE, attempt to truncate on a word boundary. Word boundaries are
  262. * spaces, punctuation, and Unicode characters used as word boundaries in
  263. * non-Latin languages; see PREG_CLASS_UNICODE_WORD_BOUNDARY for more
  264. * information. If a word boundary cannot be found that would make the length
  265. * of the returned string fall within length guidelines (see parameters
  266. * $max_return_length and $min_wordsafe_length), word boundaries are ignored.
  267. * @param $add_ellipsis
  268. * If TRUE, add t('...') to the end of the truncated string (defaults to
  269. * FALSE). The string length will still fall within $max_return_length.
  270. * @param $min_wordsafe_length
  271. * If $wordsafe is TRUE, the minimum acceptable length for truncation (before
  272. * adding an ellipsis, if $add_ellipsis is TRUE). Has no effect if $wordsafe
  273. * is FALSE. This can be used to prevent having a very short resulting string
  274. * that will not be understandable. For instance, if you are truncating the
  275. * string "See myverylongurlexample.com for more information" to a word-safe
  276. * return length of 20, the only available word boundary within 20 characters
  277. * is after the word "See", which wouldn't leave a very informative string. If
  278. * you had set $min_wordsafe_length to 10, though, the function would realise
  279. * that "See" alone is too short, and would then just truncate ignoring word
  280. * boundaries, giving you "See myverylongurl..." (assuming you had set
  281. * $add_ellipses to TRUE).
  282. *
  283. * @return
  284. * The truncated string.
  285. */
  286. function truncate_utf8($string, $max_length, $wordsafe = FALSE, $add_ellipsis = FALSE, $min_wordsafe_length = 1) {
  287. $ellipsis = '';
  288. $max_length = max($max_length, 0);
  289. $min_wordsafe_length = max($min_wordsafe_length, 0);
  290. if (drupal_strlen($string) <= $max_length) {
  291. // No truncation needed, so don't add ellipsis, just return.
  292. return $string;
  293. }
  294. if ($add_ellipsis) {
  295. // Truncate ellipsis in case $max_length is small.
  296. $ellipsis = drupal_substr(t('...'), 0, $max_length);
  297. $max_length -= drupal_strlen($ellipsis);
  298. $max_length = max($max_length, 0);
  299. }
  300. if ($max_length <= $min_wordsafe_length) {
  301. // Do not attempt word-safe if lengths are bad.
  302. $wordsafe = FALSE;
  303. }
  304. if ($wordsafe) {
  305. $matches = array();
  306. // Find the last word boundary, if there is one within $min_wordsafe_length
  307. // to $max_length characters. preg_match() is always greedy, so it will
  308. // find the longest string possible.
  309. $found = preg_match('/^(.{' . $min_wordsafe_length . ',' . $max_length . '})[' . PREG_CLASS_UNICODE_WORD_BOUNDARY . ']/u', $string, $matches);
  310. if ($found) {
  311. $string = $matches[1];
  312. }
  313. else {
  314. $string = drupal_substr($string, 0, $max_length);
  315. }
  316. }
  317. else {
  318. $string = drupal_substr($string, 0, $max_length);
  319. }
  320. if ($add_ellipsis) {
  321. $string .= $ellipsis;
  322. }
  323. return $string;
  324. }
  325. /**
  326. * Encodes MIME/HTTP header values that contain non-ASCII, UTF-8 encoded
  327. * characters.
  328. *
  329. * For example, mime_header_encode('tĂŠst.txt') returns "=?UTF-8?B?dMOpc3QudHh0?=".
  330. *
  331. * See http://www.rfc-editor.org/rfc/rfc2047.txt for more information.
  332. *
  333. * Notes:
  334. * - Only encode strings that contain non-ASCII characters.
  335. * - We progressively cut-off a chunk with truncate_utf8(). This is to ensure
  336. * each chunk starts and ends on a character boundary.
  337. * - Using \n as the chunk separator may cause problems on some systems and may
  338. * have to be changed to \r\n or \r.
  339. */
  340. function mime_header_encode($string) {
  341. if (preg_match('/[^\x20-\x7E]/', $string)) {
  342. $chunk_size = 47; // floor((75 - strlen("=?UTF-8?B??=")) * 0.75);
  343. $len = strlen($string);
  344. $output = '';
  345. while ($len > 0) {
  346. $chunk = drupal_truncate_bytes($string, $chunk_size);
  347. $output .= ' =?UTF-8?B?' . base64_encode($chunk) . "?=\n";
  348. $c = strlen($chunk);
  349. $string = substr($string, $c);
  350. $len -= $c;
  351. }
  352. return trim($output);
  353. }
  354. return $string;
  355. }
  356. /**
  357. * Complement to mime_header_encode
  358. */
  359. function mime_header_decode($header) {
  360. // First step: encoded chunks followed by other encoded chunks (need to collapse whitespace)
  361. $header = preg_replace_callback('/=\?([^?]+)\?(Q|B)\?([^?]+|\?(?!=))\?=\s+(?==\?)/', '_mime_header_decode', $header);
  362. // Second step: remaining chunks (do not collapse whitespace)
  363. return preg_replace_callback('/=\?([^?]+)\?(Q|B)\?([^?]+|\?(?!=))\?=/', '_mime_header_decode', $header);
  364. }
  365. /**
  366. * Helper function to mime_header_decode
  367. */
  368. function _mime_header_decode($matches) {
  369. // Regexp groups:
  370. // 1: Character set name
  371. // 2: Escaping method (Q or B)
  372. // 3: Encoded data
  373. $data = ($matches[2] == 'B') ? base64_decode($matches[3]) : str_replace('_', ' ', quoted_printable_decode($matches[3]));
  374. if (strtolower($matches[1]) != 'utf-8') {
  375. $data = drupal_convert_to_utf8($data, $matches[1]);
  376. }
  377. return $data;
  378. }
  379. /**
  380. * Decodes all HTML entities (including numerical ones) to regular UTF-8 bytes.
  381. *
  382. * Double-escaped entities will only be decoded once ("&amp;lt;" becomes "&lt;",
  383. * not "<"). Be careful when using this function, as decode_entities can revert
  384. * previous sanitization efforts (&lt;script&gt; will become <script>).
  385. *
  386. * @param $text
  387. * The text to decode entities in.
  388. * @param $exclude
  389. * An array of characters which should not be decoded. For example,
  390. * array('<', '&', '"'). This affects both named and numerical entities.
  391. *
  392. * @return
  393. * The input $text, with all HTML entities decoded once.
  394. */
  395. function decode_entities($text, $exclude = array()) {
  396. static $html_entities;
  397. if (!isset($html_entities)) {
  398. include DRUPAL_ROOT . '/includes/unicode.entities.inc';
  399. }
  400. // Flip the exclude list so that we can do quick lookups later.
  401. $exclude = array_flip($exclude);
  402. // Use a regexp to select all entities in one pass, to avoid decoding
  403. // double-escaped entities twice. The PREG_REPLACE_EVAL modifier 'e' is
  404. // being used to allow for a callback (see
  405. // http://php.net/manual/en/reference.pcre.pattern.modifiers).
  406. return preg_replace('/&(#x?)?([A-Za-z0-9]+);/e', '_decode_entities("$1", "$2", "$0", $html_entities, $exclude)', $text);
  407. }
  408. /**
  409. * Helper function for decode_entities
  410. */
  411. function _decode_entities($prefix, $codepoint, $original, &$html_entities, &$exclude) {
  412. // Named entity
  413. if (!$prefix) {
  414. // A named entity not in the exclude list.
  415. if (isset($html_entities[$original]) && !isset($exclude[$html_entities[$original]])) {
  416. return $html_entities[$original];
  417. }
  418. else {
  419. return $original;
  420. }
  421. }
  422. // Hexadecimal numerical entity
  423. if ($prefix == '#x') {
  424. $codepoint = base_convert($codepoint, 16, 10);
  425. }
  426. // Decimal numerical entity (strip leading zeros to avoid PHP octal notation)
  427. else {
  428. $codepoint = preg_replace('/^0+/', '', $codepoint);
  429. }
  430. // Encode codepoint as UTF-8 bytes
  431. if ($codepoint < 0x80) {
  432. $str = chr($codepoint);
  433. }
  434. elseif ($codepoint < 0x800) {
  435. $str = chr(0xC0 | ($codepoint >> 6))
  436. . chr(0x80 | ($codepoint & 0x3F));
  437. }
  438. elseif ($codepoint < 0x10000) {
  439. $str = chr(0xE0 | ( $codepoint >> 12))
  440. . chr(0x80 | (($codepoint >> 6) & 0x3F))
  441. . chr(0x80 | ( $codepoint & 0x3F));
  442. }
  443. elseif ($codepoint < 0x200000) {
  444. $str = chr(0xF0 | ( $codepoint >> 18))
  445. . chr(0x80 | (($codepoint >> 12) & 0x3F))
  446. . chr(0x80 | (($codepoint >> 6) & 0x3F))
  447. . chr(0x80 | ( $codepoint & 0x3F));
  448. }
  449. // Check for excluded characters
  450. if (isset($exclude[$str])) {
  451. return $original;
  452. }
  453. else {
  454. return $str;
  455. }
  456. }
  457. /**
  458. * Count the amount of characters in a UTF-8 string. This is less than or
  459. * equal to the byte count.
  460. *
  461. * @ingroup php_wrappers
  462. */
  463. function drupal_strlen($text) {
  464. global $multibyte;
  465. if ($multibyte == UNICODE_MULTIBYTE) {
  466. return mb_strlen($text);
  467. }
  468. else {
  469. // Do not count UTF-8 continuation bytes.
  470. return strlen(preg_replace("/[\x80-\xBF]/", '', $text));
  471. }
  472. }
  473. /**
  474. * Uppercase a UTF-8 string.
  475. *
  476. * @ingroup php_wrappers
  477. */
  478. function drupal_strtoupper($text) {
  479. global $multibyte;
  480. if ($multibyte == UNICODE_MULTIBYTE) {
  481. return mb_strtoupper($text);
  482. }
  483. else {
  484. // Use C-locale for ASCII-only uppercase
  485. $text = strtoupper($text);
  486. // Case flip Latin-1 accented letters
  487. $text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '_unicode_caseflip', $text);
  488. return $text;
  489. }
  490. }
  491. /**
  492. * Lowercase a UTF-8 string.
  493. *
  494. * @ingroup php_wrappers
  495. */
  496. function drupal_strtolower($text) {
  497. global $multibyte;
  498. if ($multibyte == UNICODE_MULTIBYTE) {
  499. return mb_strtolower($text);
  500. }
  501. else {
  502. // Use C-locale for ASCII-only lowercase
  503. $text = strtolower($text);
  504. // Case flip Latin-1 accented letters
  505. $text = preg_replace_callback('/\xC3[\x80-\x96\x98-\x9E]/', '_unicode_caseflip', $text);
  506. return $text;
  507. }
  508. }
  509. /**
  510. * Helper function for case conversion of Latin-1.
  511. * Used for flipping U+C0-U+DE to U+E0-U+FD and back.
  512. */
  513. function _unicode_caseflip($matches) {
  514. return $matches[0][0] . chr(ord($matches[0][1]) ^ 32);
  515. }
  516. /**
  517. * Capitalize the first letter of a UTF-8 string.
  518. *
  519. * @ingroup php_wrappers
  520. */
  521. function drupal_ucfirst($text) {
  522. // Note: no mbstring equivalent!
  523. return drupal_strtoupper(drupal_substr($text, 0, 1)) . drupal_substr($text, 1);
  524. }
  525. /**
  526. * Cut off a piece of a string based on character indices and counts. Follows
  527. * the same behavior as PHP's own substr() function.
  528. *
  529. * Note that for cutting off a string at a known character/substring
  530. * location, the usage of PHP's normal strpos/substr is safe and
  531. * much faster.
  532. *
  533. * @ingroup php_wrappers
  534. */
  535. function drupal_substr($text, $start, $length = NULL) {
  536. global $multibyte;
  537. if ($multibyte == UNICODE_MULTIBYTE) {
  538. return $length === NULL ? mb_substr($text, $start) : mb_substr($text, $start, $length);
  539. }
  540. else {
  541. $strlen = strlen($text);
  542. // Find the starting byte offset.
  543. $bytes = 0;
  544. if ($start > 0) {
  545. // Count all the continuation bytes from the start until we have found
  546. // $start characters or the end of the string.
  547. $bytes = -1; $chars = -1;
  548. while ($bytes < $strlen - 1 && $chars < $start) {
  549. $bytes++;
  550. $c = ord($text[$bytes]);
  551. if ($c < 0x80 || $c >= 0xC0) {
  552. $chars++;
  553. }
  554. }
  555. }
  556. elseif ($start < 0) {
  557. // Count all the continuation bytes from the end until we have found
  558. // abs($start) characters.
  559. $start = abs($start);
  560. $bytes = $strlen; $chars = 0;
  561. while ($bytes > 0 && $chars < $start) {
  562. $bytes--;
  563. $c = ord($text[$bytes]);
  564. if ($c < 0x80 || $c >= 0xC0) {
  565. $chars++;
  566. }
  567. }
  568. }
  569. $istart = $bytes;
  570. // Find the ending byte offset.
  571. if ($length === NULL) {
  572. $iend = $strlen;
  573. }
  574. elseif ($length > 0) {
  575. // Count all the continuation bytes from the starting index until we have
  576. // found $length characters or reached the end of the string, then
  577. // backtrace one byte.
  578. $iend = $istart - 1;
  579. $chars = -1;
  580. $last_real = FALSE;
  581. while ($iend < $strlen - 1 && $chars < $length) {
  582. $iend++;
  583. $c = ord($text[$iend]);
  584. $last_real = FALSE;
  585. if ($c < 0x80 || $c >= 0xC0) {
  586. $chars++;
  587. $last_real = TRUE;
  588. }
  589. }
  590. // Backtrace one byte if the last character we found was a real character
  591. // and we don't need it.
  592. if ($last_real && $chars >= $length) {
  593. $iend--;
  594. }
  595. }
  596. elseif ($length < 0) {
  597. // Count all the continuation bytes from the end until we have found
  598. // abs($start) characters, then backtrace one byte.
  599. $length = abs($length);
  600. $iend = $strlen; $chars = 0;
  601. while ($iend > 0 && $chars < $length) {
  602. $iend--;
  603. $c = ord($text[$iend]);
  604. if ($c < 0x80 || $c >= 0xC0) {
  605. $chars++;
  606. }
  607. }
  608. // Backtrace one byte if we are not at the beginning of the string.
  609. if ($iend > 0) {
  610. $iend--;
  611. }
  612. }
  613. else {
  614. // $length == 0, return an empty string.
  615. return '';
  616. }
  617. return substr($text, $istart, max(0, $iend - $istart + 1));
  618. }
  619. }