unicode.inc 21 KB

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