PageRenderTime 52ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/unicode.inc

https://github.com/jianingy/guild-web
Pascal | 684 lines | 551 code | 24 blank | 109 comment | 36 complexity | 8e3854a29807bb8a9253c8ddccd720c2 MD5 | raw file
  1. <?php
  2. // $Id: unicode.inc,v 1.46 2010/07/29 00:38:24 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. *
  161. * @return
  162. * An XML parser object or FALSE on error.
  163. *
  164. * @ingroup php_wrappers
  165. */
  166. function drupal_xml_parser_create(&$data) {
  167. // Default XML encoding is UTF-8
  168. $encoding = 'utf-8';
  169. $bom = FALSE;
  170. // Check for UTF-8 byte order mark (PHP5's XML parser doesn't handle it).
  171. if (!strncmp($data, "\xEF\xBB\xBF", 3)) {
  172. $bom = TRUE;
  173. $data = substr($data, 3);
  174. }
  175. // Check for an encoding declaration in the XML prolog if no BOM was found.
  176. if (!$bom && preg_match('/^<\?xml[^>]+encoding="(.+?)"/', $data, $match)) {
  177. $encoding = $match[1];
  178. }
  179. // Unsupported encodings are converted here into UTF-8.
  180. $php_supported = array('utf-8', 'iso-8859-1', 'us-ascii');
  181. if (!in_array(strtolower($encoding), $php_supported)) {
  182. $out = drupal_convert_to_utf8($data, $encoding);
  183. if ($out !== FALSE) {
  184. $encoding = 'utf-8';
  185. $data = preg_replace('/^(<\?xml[^>]+encoding)="(.+?)"/', '\\1="utf-8"', $out);
  186. }
  187. else {
  188. watchdog('php', 'Could not convert XML encoding %s to UTF-8.', array('%s' => $encoding), WATCHDOG_WARNING);
  189. return FALSE;
  190. }
  191. }
  192. $xml_parser = xml_parser_create($encoding);
  193. xml_parser_set_option($xml_parser, XML_OPTION_TARGET_ENCODING, 'utf-8');
  194. return $xml_parser;
  195. }
  196. /**
  197. * Convert data to UTF-8
  198. *
  199. * Requires the iconv, GNU recode or mbstring PHP extension.
  200. *
  201. * @param $data
  202. * The data to be converted.
  203. * @param $encoding
  204. * The encoding that the data is in
  205. *
  206. * @return
  207. * Converted data or FALSE.
  208. */
  209. function drupal_convert_to_utf8($data, $encoding) {
  210. if (function_exists('iconv')) {
  211. $out = @iconv($encoding, 'utf-8', $data);
  212. }
  213. elseif (function_exists('mb_convert_encoding')) {
  214. $out = @mb_convert_encoding($data, 'utf-8', $encoding);
  215. }
  216. elseif (function_exists('recode_string')) {
  217. $out = @recode_string($encoding . '..utf-8', $data);
  218. }
  219. else {
  220. watchdog('php', 'Unsupported encoding %s. Please install iconv, GNU recode or mbstring for PHP.', array('%s' => $encoding), WATCHDOG_ERROR);
  221. return FALSE;
  222. }
  223. return $out;
  224. }
  225. /**
  226. * Truncate a UTF-8-encoded string safely to a number of bytes.
  227. *
  228. * If the end position is in the middle of a UTF-8 sequence, it scans backwards
  229. * until the beginning of the byte sequence.
  230. *
  231. * Use this function whenever you want to chop off a string at an unsure
  232. * location. On the other hand, if you're sure that you're splitting on a
  233. * character boundary (e.g. after using strpos() or similar), you can safely use
  234. * substr() instead.
  235. *
  236. * @param $string
  237. * The string to truncate.
  238. * @param $len
  239. * An upper limit on the returned string length.
  240. *
  241. * @return
  242. * The truncated string.
  243. */
  244. function drupal_truncate_bytes($string, $len) {
  245. if (strlen($string) <= $len) {
  246. return $string;
  247. }
  248. if ((ord($string[$len]) < 0x80) || (ord($string[$len]) >= 0xC0)) {
  249. return substr($string, 0, $len);
  250. }
  251. // Scan backwards to beginning of the byte sequence.
  252. while (--$len >= 0 && ord($string[$len]) >= 0x80 && ord($string[$len]) < 0xC0);
  253. return substr($string, 0, $len);
  254. }
  255. /**
  256. * Truncates a UTF-8-encoded string safely to a number of characters.
  257. *
  258. * @param $string
  259. * The string to truncate.
  260. * @param $max_length
  261. * An upper limit on the returned string length, including trailing ellipsis
  262. * if $add_ellipsis is TRUE.
  263. * @param $wordsafe
  264. * If TRUE, attempt to truncate on a word boundary. Word boundaries are
  265. * spaces, punctuation, and Unicode characters used as word boundaries in
  266. * non-Latin languages; see PREG_CLASS_UNICODE_WORD_BOUNDARY for more
  267. * information. If a word boundary cannot be found that would make the length
  268. * of the returned string fall within length guidelines (see parameters
  269. * $max_return_length and $min_wordsafe_length), word boundaries are ignored.
  270. * @param $add_ellipsis
  271. * If TRUE, add t('...') to the end of the truncated string (defaults to
  272. * FALSE). The string length will still fall within $max_return_length.
  273. * @param $min_wordsafe_length
  274. * If $wordsafe is TRUE, the minimum acceptable length for truncation (before
  275. * adding an ellipsis, if $add_ellipsis is TRUE). Has no effect if $wordsafe
  276. * is FALSE. This can be used to prevent having a very short resulting string
  277. * that will not be understandable. For instance, if you are truncating the
  278. * string "See myverylongurlexample.com for more information" to a word-safe
  279. * return length of 20, the only available word boundary within 20 characters
  280. * is after the word "See", which wouldn't leave a very informative string. If
  281. * you had set $min_wordsafe_length to 10, though, the function would realise
  282. * that "See" alone is too short, and would then just truncate ignoring word
  283. * boundaries, giving you "See myverylongurl..." (assuming you had set
  284. * $add_ellipses to TRUE).
  285. *
  286. * @return
  287. * The truncated string.
  288. */
  289. function truncate_utf8($string, $max_length, $wordsafe = FALSE, $add_ellipsis = FALSE, $min_wordsafe_length = 1) {
  290. $ellipsis = '';
  291. $max_length = max($max_length, 0);
  292. $min_wordsafe_length = max($min_wordsafe_length, 0);
  293. if (drupal_strlen($string) <= $max_length) {
  294. // No truncation needed, so don't add ellipsis, just return.
  295. return $string;
  296. }
  297. if ($add_ellipsis) {
  298. // Truncate ellipsis in case $max_length is small.
  299. $ellipsis = drupal_substr(t('...'), 0, $max_length);
  300. $max_length -= drupal_strlen($ellipsis);
  301. $max_length = max($max_length, 0);
  302. }
  303. if ($max_length <= $min_wordsafe_length) {
  304. // Do not attempt word-safe if lengths are bad.
  305. $wordsafe = FALSE;
  306. }
  307. if ($wordsafe) {
  308. $matches = array();
  309. // Find the last word boundary, if there is one within $min_wordsafe_length
  310. // to $max_length characters. preg_match() is always greedy, so it will
  311. // find the longest string possible.
  312. $found = preg_match('/^(.{' . $min_wordsafe_length . ',' . $max_length . '})[' . PREG_CLASS_UNICODE_WORD_BOUNDARY . ']/u', $string, $matches);
  313. if ($found) {
  314. $string = $matches[1];
  315. }
  316. else {
  317. $string = drupal_substr($string, 0, $max_length);
  318. }
  319. }
  320. else {
  321. $string = drupal_substr($string, 0, $max_length);
  322. }
  323. if ($add_ellipsis) {
  324. $string .= $ellipsis;
  325. }
  326. return $string;
  327. }
  328. /**
  329. * Encodes MIME/HTTP header values that contain non-ASCII, UTF-8 encoded
  330. * characters.
  331. *
  332. * For example, mime_header_encode('tĂŠst.txt') returns "=?UTF-8?B?dMOpc3QudHh0?=".
  333. *
  334. * See http://www.rfc-editor.org/rfc/rfc2047.txt for more information.
  335. *
  336. * Notes:
  337. * - Only encode strings that contain non-ASCII characters.
  338. * - We progressively cut-off a chunk with truncate_utf8(). This is to ensure
  339. * each chunk starts and ends on a character boundary.
  340. * - Using \n as the chunk separator may cause problems on some systems and may
  341. * have to be changed to \r\n or \r.
  342. */
  343. function mime_header_encode($string) {
  344. if (preg_match('/[^\x20-\x7E]/', $string)) {
  345. $chunk_size = 47; // floor((75 - strlen("=?UTF-8?B??=")) * 0.75);
  346. $len = strlen($string);
  347. $output = '';
  348. while ($len > 0) {
  349. $chunk = drupal_truncate_bytes($string, $chunk_size);
  350. $output .= ' =?UTF-8?B?' . base64_encode($chunk) . "?=\n";
  351. $c = strlen($chunk);
  352. $string = substr($string, $c);
  353. $len -= $c;
  354. }
  355. return trim($output);
  356. }
  357. return $string;
  358. }
  359. /**
  360. * Complement to mime_header_encode
  361. */
  362. function mime_header_decode($header) {
  363. // First step: encoded chunks followed by other encoded chunks (need to collapse whitespace)
  364. $header = preg_replace_callback('/=\?([^?]+)\?(Q|B)\?([^?]+|\?(?!=))\?=\s+(?==\?)/', '_mime_header_decode', $header);
  365. // Second step: remaining chunks (do not collapse whitespace)
  366. return preg_replace_callback('/=\?([^?]+)\?(Q|B)\?([^?]+|\?(?!=))\?=/', '_mime_header_decode', $header);
  367. }
  368. /**
  369. * Helper function to mime_header_decode
  370. */
  371. function _mime_header_decode($matches) {
  372. // Regexp groups:
  373. // 1: Character set name
  374. // 2: Escaping method (Q or B)
  375. // 3: Encoded data
  376. $data = ($matches[2] == 'B') ? base64_decode($matches[3]) : str_replace('_', ' ', quoted_printable_decode($matches[3]));
  377. if (strtolower($matches[1]) != 'utf-8') {
  378. $data = drupal_convert_to_utf8($data, $matches[1]);
  379. }
  380. return $data;
  381. }
  382. /**
  383. * Decodes all HTML entities (including numerical ones) to regular UTF-8 bytes.
  384. *
  385. * Double-escaped entities will only be decoded once ("&amp;lt;" becomes "&lt;",
  386. * not "<"). Be careful when using this function, as decode_entities can revert
  387. * previous sanitization efforts (&lt;script&gt; will become <script>).
  388. *
  389. * @param $text
  390. * The text to decode entities in.
  391. * @param $exclude
  392. * An array of characters which should not be decoded. For example,
  393. * array('<', '&', '"'). This affects both named and numerical entities.
  394. *
  395. * @return
  396. * The input $text, with all HTML entities decoded once.
  397. */
  398. function decode_entities($text, $exclude = array()) {
  399. // Flip the exclude list so that we can do quick lookups later.
  400. $exclude = array_flip($exclude);
  401. // Prepare the callback function.
  402. _decode_entities(NULL, $exclude);
  403. // Use a regexp to select all entities in one pass, to avoid decoding
  404. // double-escaped entities twice.
  405. return preg_replace_callback('/&(#x?)?([A-Za-z0-9]+);/', '_decode_entities', $text);
  406. }
  407. /**
  408. * Helper function for decode_entities
  409. *
  410. * @param $matches
  411. * An array of matches found by preg_replace_callback(). Elements 0, 1, and 2
  412. * of $matches must be the original entity, its prefix, and its codepoint.
  413. * @param $set_exclude
  414. * An array of entities that should be excluded from decoding. This should
  415. * only be set during a preparatory call before preg_replace_callback().
  416. *
  417. * @return
  418. * The decoded entity for a given match, or the original encoded entity if
  419. * the entity is in the list of excluded entities.
  420. */
  421. function _decode_entities($matches = NULL, $set_exclude = NULL) {
  422. static $html_entities, $exclude;
  423. if (!isset($html_entities)) {
  424. include DRUPAL_ROOT . '/includes/unicode.entities.inc';
  425. }
  426. if (isset($set_exclude)) {
  427. // This is a preparatory call.
  428. $exclude = $set_exclude;
  429. return;
  430. }
  431. list($original, $prefix, $codepoint) = $matches;
  432. // Named entity
  433. if (!$prefix) {
  434. // A named entity not in the exclude list.
  435. if (isset($html_entities[$original]) && !isset($exclude[$html_entities[$original]])) {
  436. return $html_entities[$original];
  437. }
  438. else {
  439. return $original;
  440. }
  441. }
  442. // Hexadecimal numerical entity
  443. if ($prefix == '#x') {
  444. $codepoint = base_convert($codepoint, 16, 10);
  445. }
  446. // Decimal numerical entity (strip leading zeros to avoid PHP octal notation)
  447. else {
  448. $codepoint = preg_replace('/^0+/', '', $codepoint);
  449. }
  450. // Encode codepoint as UTF-8 bytes
  451. if ($codepoint < 0x80) {
  452. $str = chr($codepoint);
  453. }
  454. elseif ($codepoint < 0x800) {
  455. $str = chr(0xC0 | ($codepoint >> 6))
  456. . chr(0x80 | ($codepoint & 0x3F));
  457. }
  458. elseif ($codepoint < 0x10000) {
  459. $str = chr(0xE0 | ( $codepoint >> 12))
  460. . chr(0x80 | (($codepoint >> 6) & 0x3F))
  461. . chr(0x80 | ( $codepoint & 0x3F));
  462. }
  463. elseif ($codepoint < 0x200000) {
  464. $str = chr(0xF0 | ( $codepoint >> 18))
  465. . chr(0x80 | (($codepoint >> 12) & 0x3F))
  466. . chr(0x80 | (($codepoint >> 6) & 0x3F))
  467. . chr(0x80 | ( $codepoint & 0x3F));
  468. }
  469. // Check for excluded characters
  470. if (isset($exclude[$str])) {
  471. return $original;
  472. }
  473. else {
  474. return $str;
  475. }
  476. }
  477. /**
  478. * Count the amount of characters in a UTF-8 string. This is less than or
  479. * equal to the byte count.
  480. *
  481. * @ingroup php_wrappers
  482. */
  483. function drupal_strlen($text) {
  484. global $multibyte;
  485. if ($multibyte == UNICODE_MULTIBYTE) {
  486. return mb_strlen($text);
  487. }
  488. else {
  489. // Do not count UTF-8 continuation bytes.
  490. return strlen(preg_replace("/[\x80-\xBF]/", '', $text));
  491. }
  492. }
  493. /**
  494. * Uppercase a UTF-8 string.
  495. *
  496. * @ingroup php_wrappers
  497. */
  498. function drupal_strtoupper($text) {
  499. global $multibyte;
  500. if ($multibyte == UNICODE_MULTIBYTE) {
  501. return mb_strtoupper($text);
  502. }
  503. else {
  504. // Use C-locale for ASCII-only uppercase
  505. $text = strtoupper($text);
  506. // Case flip Latin-1 accented letters
  507. $text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '_unicode_caseflip', $text);
  508. return $text;
  509. }
  510. }
  511. /**
  512. * Lowercase a UTF-8 string.
  513. *
  514. * @ingroup php_wrappers
  515. */
  516. function drupal_strtolower($text) {
  517. global $multibyte;
  518. if ($multibyte == UNICODE_MULTIBYTE) {
  519. return mb_strtolower($text);
  520. }
  521. else {
  522. // Use C-locale for ASCII-only lowercase
  523. $text = strtolower($text);
  524. // Case flip Latin-1 accented letters
  525. $text = preg_replace_callback('/\xC3[\x80-\x96\x98-\x9E]/', '_unicode_caseflip', $text);
  526. return $text;
  527. }
  528. }
  529. /**
  530. * Helper function for case conversion of Latin-1.
  531. * Used for flipping U+C0-U+DE to U+E0-U+FD and back.
  532. */
  533. function _unicode_caseflip($matches) {
  534. return $matches[0][0] . chr(ord($matches[0][1]) ^ 32);
  535. }
  536. /**
  537. * Capitalize the first letter of a UTF-8 string.
  538. *
  539. * @ingroup php_wrappers
  540. */
  541. function drupal_ucfirst($text) {
  542. // Note: no mbstring equivalent!
  543. return drupal_strtoupper(drupal_substr($text, 0, 1)) . drupal_substr($text, 1);
  544. }
  545. /**
  546. * Cut off a piece of a string based on character indices and counts. Follows
  547. * the same behavior as PHP's own substr() function.
  548. *
  549. * Note that for cutting off a string at a known character/substring
  550. * location, the usage of PHP's normal strpos/substr is safe and
  551. * much faster.
  552. *
  553. * @ingroup php_wrappers
  554. */
  555. function drupal_substr($text, $start, $length = NULL) {
  556. global $multibyte;
  557. if ($multibyte == UNICODE_MULTIBYTE) {
  558. return $length === NULL ? mb_substr($text, $start) : mb_substr($text, $start, $length);
  559. }
  560. else {
  561. $strlen = strlen($text);
  562. // Find the starting byte offset.
  563. $bytes = 0;
  564. if ($start > 0) {
  565. // Count all the continuation bytes from the start until we have found
  566. // $start characters or the end of the string.
  567. $bytes = -1; $chars = -1;
  568. while ($bytes < $strlen - 1 && $chars < $start) {
  569. $bytes++;
  570. $c = ord($text[$bytes]);
  571. if ($c < 0x80 || $c >= 0xC0) {
  572. $chars++;
  573. }
  574. }
  575. }
  576. elseif ($start < 0) {
  577. // Count all the continuation bytes from the end until we have found
  578. // abs($start) characters.
  579. $start = abs($start);
  580. $bytes = $strlen; $chars = 0;
  581. while ($bytes > 0 && $chars < $start) {
  582. $bytes--;
  583. $c = ord($text[$bytes]);
  584. if ($c < 0x80 || $c >= 0xC0) {
  585. $chars++;
  586. }
  587. }
  588. }
  589. $istart = $bytes;
  590. // Find the ending byte offset.
  591. if ($length === NULL) {
  592. $iend = $strlen;
  593. }
  594. elseif ($length > 0) {
  595. // Count all the continuation bytes from the starting index until we have
  596. // found $length characters or reached the end of the string, then
  597. // backtrace one byte.
  598. $iend = $istart - 1;
  599. $chars = -1;
  600. $last_real = FALSE;
  601. while ($iend < $strlen - 1 && $chars < $length) {
  602. $iend++;
  603. $c = ord($text[$iend]);
  604. $last_real = FALSE;
  605. if ($c < 0x80 || $c >= 0xC0) {
  606. $chars++;
  607. $last_real = TRUE;
  608. }
  609. }
  610. // Backtrace one byte if the last character we found was a real character
  611. // and we don't need it.
  612. if ($last_real && $chars >= $length) {
  613. $iend--;
  614. }
  615. }
  616. elseif ($length < 0) {
  617. // Count all the continuation bytes from the end until we have found
  618. // abs($start) characters, then backtrace one byte.
  619. $length = abs($length);
  620. $iend = $strlen; $chars = 0;
  621. while ($iend > 0 && $chars < $length) {
  622. $iend--;
  623. $c = ord($text[$iend]);
  624. if ($c < 0x80 || $c >= 0xC0) {
  625. $chars++;
  626. }
  627. }
  628. // Backtrace one byte if we are not at the beginning of the string.
  629. if ($iend > 0) {
  630. $iend--;
  631. }
  632. }
  633. else {
  634. // $length == 0, return an empty string.
  635. return '';
  636. }
  637. return substr($text, $istart, max(0, $iend - $istart + 1));
  638. }
  639. }