unicode.inc 22 KB

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