unicode.inc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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. // mbstring.http_input and mbstring.http_output are deprecated and empty by
  111. // default in PHP 5.6.
  112. if (version_compare(PHP_VERSION, '5.6.0') == -1) {
  113. if (ini_get('mbstring.http_input') != 'pass') {
  114. 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')));
  115. }
  116. if (ini_get('mbstring.http_output') != 'pass') {
  117. 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')));
  118. }
  119. }
  120. // Set appropriate configuration
  121. mb_internal_encoding('utf-8');
  122. mb_language('uni');
  123. return array(UNICODE_MULTIBYTE, '');
  124. }
  125. /**
  126. * Returns Unicode library status and errors.
  127. */
  128. function unicode_requirements() {
  129. // Ensure translations don't break during installation.
  130. $t = get_t();
  131. $libraries = array(
  132. UNICODE_SINGLEBYTE => $t('Standard PHP'),
  133. UNICODE_MULTIBYTE => $t('PHP Mbstring Extension'),
  134. UNICODE_ERROR => $t('Error'),
  135. );
  136. $severities = array(
  137. UNICODE_SINGLEBYTE => REQUIREMENT_WARNING,
  138. UNICODE_MULTIBYTE => REQUIREMENT_OK,
  139. UNICODE_ERROR => REQUIREMENT_ERROR,
  140. );
  141. list($library, $description) = _unicode_check();
  142. $requirements['unicode'] = array(
  143. 'title' => $t('Unicode library'),
  144. 'value' => $libraries[$library],
  145. );
  146. if ($description) {
  147. $requirements['unicode']['description'] = $description;
  148. }
  149. $requirements['unicode']['severity'] = $severities[$library];
  150. return $requirements;
  151. }
  152. /**
  153. * Prepares a new XML parser.
  154. *
  155. * This is a wrapper around xml_parser_create() which extracts the encoding
  156. * from the XML data first and sets the output encoding to UTF-8. This function
  157. * should be used instead of xml_parser_create(), because PHP 4's XML parser
  158. * doesn't check the input encoding itself. "Starting from PHP 5, the input
  159. * encoding is automatically detected, so that the encoding parameter specifies
  160. * only the output encoding."
  161. *
  162. * This is also where unsupported encodings will be converted. Callers should
  163. * take this into account: $data might have been changed after the call.
  164. *
  165. * @param $data
  166. * The XML data which will be parsed later.
  167. *
  168. * @return
  169. * An XML parser object or FALSE on error.
  170. *
  171. * @ingroup php_wrappers
  172. */
  173. function drupal_xml_parser_create(&$data) {
  174. // Default XML encoding is UTF-8
  175. $encoding = 'utf-8';
  176. $bom = FALSE;
  177. // Check for UTF-8 byte order mark (PHP5's XML parser doesn't handle it).
  178. if (!strncmp($data, "\xEF\xBB\xBF", 3)) {
  179. $bom = TRUE;
  180. $data = substr($data, 3);
  181. }
  182. // Check for an encoding declaration in the XML prolog if no BOM was found.
  183. if (!$bom && preg_match('/^<\?xml[^>]+encoding="(.+?)"/', $data, $match)) {
  184. $encoding = $match[1];
  185. }
  186. // Unsupported encodings are converted here into UTF-8.
  187. $php_supported = array('utf-8', 'iso-8859-1', 'us-ascii');
  188. if (!in_array(strtolower($encoding), $php_supported)) {
  189. $out = drupal_convert_to_utf8($data, $encoding);
  190. if ($out !== FALSE) {
  191. $encoding = 'utf-8';
  192. $data = preg_replace('/^(<\?xml[^>]+encoding)="(.+?)"/', '\\1="utf-8"', $out);
  193. }
  194. else {
  195. watchdog('php', 'Could not convert XML encoding %s to UTF-8.', array('%s' => $encoding), WATCHDOG_WARNING);
  196. return FALSE;
  197. }
  198. }
  199. $xml_parser = xml_parser_create($encoding);
  200. xml_parser_set_option($xml_parser, XML_OPTION_TARGET_ENCODING, 'utf-8');
  201. return $xml_parser;
  202. }
  203. /**
  204. * Converts data to UTF-8.
  205. *
  206. * Requires the iconv, GNU recode or mbstring PHP extension.
  207. *
  208. * @param $data
  209. * The data to be converted.
  210. * @param $encoding
  211. * The encoding that the data is in.
  212. *
  213. * @return
  214. * Converted data or FALSE.
  215. */
  216. function drupal_convert_to_utf8($data, $encoding) {
  217. if (function_exists('iconv')) {
  218. $out = @iconv($encoding, 'utf-8', $data);
  219. }
  220. elseif (function_exists('mb_convert_encoding')) {
  221. $out = @mb_convert_encoding($data, 'utf-8', $encoding);
  222. }
  223. elseif (function_exists('recode_string')) {
  224. $out = @recode_string($encoding . '..utf-8', $data);
  225. }
  226. else {
  227. watchdog('php', 'Unsupported encoding %s. Please install iconv, GNU recode or mbstring for PHP.', array('%s' => $encoding), WATCHDOG_ERROR);
  228. return FALSE;
  229. }
  230. return $out;
  231. }
  232. /**
  233. * Truncates a UTF-8-encoded string safely to a number of bytes.
  234. *
  235. * If the end position is in the middle of a UTF-8 sequence, it scans backwards
  236. * until the beginning of the byte sequence.
  237. *
  238. * Use this function whenever you want to chop off a string at an unsure
  239. * location. On the other hand, if you're sure that you're splitting on a
  240. * character boundary (e.g. after using strpos() or similar), you can safely
  241. * use substr() instead.
  242. *
  243. * @param $string
  244. * The string to truncate.
  245. * @param $len
  246. * An upper limit on the returned string length.
  247. *
  248. * @return
  249. * The truncated string.
  250. */
  251. function drupal_truncate_bytes($string, $len) {
  252. if (strlen($string) <= $len) {
  253. return $string;
  254. }
  255. if ((ord($string[$len]) < 0x80) || (ord($string[$len]) >= 0xC0)) {
  256. return substr($string, 0, $len);
  257. }
  258. // Scan backwards to beginning of the byte sequence.
  259. while (--$len >= 0 && ord($string[$len]) >= 0x80 && ord($string[$len]) < 0xC0);
  260. return substr($string, 0, $len);
  261. }
  262. /**
  263. * Truncates a UTF-8-encoded string safely to a number of characters.
  264. *
  265. * @param $string
  266. * The string to truncate.
  267. * @param $max_length
  268. * An upper limit on the returned string length, including trailing ellipsis
  269. * if $add_ellipsis is TRUE.
  270. * @param $wordsafe
  271. * If TRUE, attempt to truncate on a word boundary. Word boundaries are
  272. * spaces, punctuation, and Unicode characters used as word boundaries in
  273. * non-Latin languages; see PREG_CLASS_UNICODE_WORD_BOUNDARY for more
  274. * information. If a word boundary cannot be found that would make the length
  275. * of the returned string fall within length guidelines (see parameters
  276. * $max_length and $min_wordsafe_length), word boundaries are ignored.
  277. * @param $add_ellipsis
  278. * If TRUE, add t('...') to the end of the truncated string (defaults to
  279. * FALSE). The string length will still fall within $max_length.
  280. * @param $min_wordsafe_length
  281. * If $wordsafe is TRUE, the minimum acceptable length for truncation (before
  282. * adding an ellipsis, if $add_ellipsis is TRUE). Has no effect if $wordsafe
  283. * is FALSE. This can be used to prevent having a very short resulting string
  284. * that will not be understandable. For instance, if you are truncating the
  285. * string "See myverylongurlexample.com for more information" to a word-safe
  286. * return length of 20, the only available word boundary within 20 characters
  287. * is after the word "See", which wouldn't leave a very informative string. If
  288. * you had set $min_wordsafe_length to 10, though, the function would realise
  289. * that "See" alone is too short, and would then just truncate ignoring word
  290. * boundaries, giving you "See myverylongurl..." (assuming you had set
  291. * $add_ellipses to TRUE).
  292. *
  293. * @return string
  294. * The truncated string.
  295. */
  296. function truncate_utf8($string, $max_length, $wordsafe = FALSE, $add_ellipsis = FALSE, $min_wordsafe_length = 1) {
  297. $ellipsis = '';
  298. $max_length = max($max_length, 0);
  299. $min_wordsafe_length = max($min_wordsafe_length, 0);
  300. if (drupal_strlen($string) <= $max_length) {
  301. // No truncation needed, so don't add ellipsis, just return.
  302. return $string;
  303. }
  304. if ($add_ellipsis) {
  305. // Truncate ellipsis in case $max_length is small.
  306. $ellipsis = drupal_substr(t('...'), 0, $max_length);
  307. $max_length -= drupal_strlen($ellipsis);
  308. $max_length = max($max_length, 0);
  309. }
  310. if ($max_length <= $min_wordsafe_length) {
  311. // Do not attempt word-safe if lengths are bad.
  312. $wordsafe = FALSE;
  313. }
  314. if ($wordsafe) {
  315. $matches = array();
  316. // Find the last word boundary, if there is one within $min_wordsafe_length
  317. // to $max_length characters. preg_match() is always greedy, so it will
  318. // find the longest string possible.
  319. $found = preg_match('/^(.{' . $min_wordsafe_length . ',' . $max_length . '})[' . PREG_CLASS_UNICODE_WORD_BOUNDARY . ']/u', $string, $matches);
  320. if ($found) {
  321. $string = $matches[1];
  322. }
  323. else {
  324. $string = drupal_substr($string, 0, $max_length);
  325. }
  326. }
  327. else {
  328. $string = drupal_substr($string, 0, $max_length);
  329. }
  330. if ($add_ellipsis) {
  331. $string .= $ellipsis;
  332. }
  333. return $string;
  334. }
  335. /**
  336. * Encodes MIME/HTTP header values that contain incorrectly encoded characters.
  337. *
  338. * For example, mime_header_encode('tést.txt') returns "=?UTF-8?B?dMOpc3QudHh0?=".
  339. *
  340. * See http://www.rfc-editor.org/rfc/rfc2047.txt for more information.
  341. *
  342. * Notes:
  343. * - Only encode strings that contain non-ASCII characters.
  344. * - We progressively cut-off a chunk with truncate_utf8(). This is to ensure
  345. * each chunk starts and ends on a character boundary.
  346. * - Using \n as the chunk separator may cause problems on some systems and may
  347. * have to be changed to \r\n or \r.
  348. *
  349. * @param $string
  350. * The header to encode.
  351. *
  352. * @return string
  353. * The mime-encoded header.
  354. *
  355. * @see mime_header_decode()
  356. */
  357. function mime_header_encode($string) {
  358. if (preg_match('/[^\x20-\x7E]/', $string)) {
  359. $chunk_size = 47; // floor((75 - strlen("=?UTF-8?B??=")) * 0.75);
  360. $len = strlen($string);
  361. $output = '';
  362. while ($len > 0) {
  363. $chunk = drupal_truncate_bytes($string, $chunk_size);
  364. $output .= ' =?UTF-8?B?' . base64_encode($chunk) . "?=\n";
  365. $c = strlen($chunk);
  366. $string = substr($string, $c);
  367. $len -= $c;
  368. }
  369. return trim($output);
  370. }
  371. return $string;
  372. }
  373. /**
  374. * Decodes MIME/HTTP encoded header values.
  375. *
  376. * @param $header
  377. * The header to decode.
  378. *
  379. * @return string
  380. * The mime-decoded header.
  381. *
  382. * @see mime_header_encode()
  383. */
  384. function mime_header_decode($header) {
  385. // First step: encoded chunks followed by other encoded chunks (need to collapse whitespace)
  386. $header = preg_replace_callback('/=\?([^?]+)\?(Q|B)\?([^?]+|\?(?!=))\?=\s+(?==\?)/', '_mime_header_decode', $header);
  387. // Second step: remaining chunks (do not collapse whitespace)
  388. return preg_replace_callback('/=\?([^?]+)\?(Q|B)\?([^?]+|\?(?!=))\?=/', '_mime_header_decode', $header);
  389. }
  390. /**
  391. * Decodes encoded header data passed from mime_header_decode().
  392. *
  393. * Callback for preg_replace_callback() within mime_header_decode().
  394. *
  395. * @param $matches
  396. * The array of matches from preg_replace_callback().
  397. *
  398. * @return string
  399. * The mime-decoded string.
  400. *
  401. * @see mime_header_decode()
  402. */
  403. function _mime_header_decode($matches) {
  404. // Regexp groups:
  405. // 1: Character set name
  406. // 2: Escaping method (Q or B)
  407. // 3: Encoded data
  408. $data = ($matches[2] == 'B') ? base64_decode($matches[3]) : str_replace('_', ' ', quoted_printable_decode($matches[3]));
  409. if (strtolower($matches[1]) != 'utf-8') {
  410. $data = drupal_convert_to_utf8($data, $matches[1]);
  411. }
  412. return $data;
  413. }
  414. /**
  415. * Decodes all HTML entities (including numerical ones) to regular UTF-8 bytes.
  416. *
  417. * Double-escaped entities will only be decoded once ("&amp;lt;" becomes "&lt;"
  418. * , not "<"). Be careful when using this function, as decode_entities can
  419. * revert previous sanitization efforts (&lt;script&gt; will become <script>).
  420. *
  421. * @param $text
  422. * The text to decode entities in.
  423. *
  424. * @return
  425. * The input $text, with all HTML entities decoded once.
  426. */
  427. function decode_entities($text) {
  428. return html_entity_decode($text, ENT_QUOTES, 'UTF-8');
  429. }
  430. /**
  431. * Counts the number of characters in a UTF-8 string.
  432. *
  433. * This is less than or equal to the byte count.
  434. *
  435. * @param $text
  436. * The string to run the operation on.
  437. *
  438. * @return integer
  439. * The length of the string.
  440. *
  441. * @ingroup php_wrappers
  442. */
  443. function drupal_strlen($text) {
  444. global $multibyte;
  445. if ($multibyte == UNICODE_MULTIBYTE) {
  446. return mb_strlen($text);
  447. }
  448. else {
  449. // Do not count UTF-8 continuation bytes.
  450. return strlen(preg_replace("/[\x80-\xBF]/", '', $text));
  451. }
  452. }
  453. /**
  454. * Uppercase a UTF-8 string.
  455. *
  456. * @param $text
  457. * The string to run the operation on.
  458. *
  459. * @return string
  460. * The string in uppercase.
  461. *
  462. * @ingroup php_wrappers
  463. */
  464. function drupal_strtoupper($text) {
  465. global $multibyte;
  466. if ($multibyte == UNICODE_MULTIBYTE) {
  467. return mb_strtoupper($text);
  468. }
  469. else {
  470. // Use C-locale for ASCII-only uppercase
  471. $text = strtoupper($text);
  472. // Case flip Latin-1 accented letters
  473. $text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '_unicode_caseflip', $text);
  474. return $text;
  475. }
  476. }
  477. /**
  478. * Lowercase a UTF-8 string.
  479. *
  480. * @param $text
  481. * The string to run the operation on.
  482. *
  483. * @return string
  484. * The string in lowercase.
  485. *
  486. * @ingroup php_wrappers
  487. */
  488. function drupal_strtolower($text) {
  489. global $multibyte;
  490. if ($multibyte == UNICODE_MULTIBYTE) {
  491. return mb_strtolower($text);
  492. }
  493. else {
  494. // Use C-locale for ASCII-only lowercase
  495. $text = strtolower($text);
  496. // Case flip Latin-1 accented letters
  497. $text = preg_replace_callback('/\xC3[\x80-\x96\x98-\x9E]/', '_unicode_caseflip', $text);
  498. return $text;
  499. }
  500. }
  501. /**
  502. * Flips U+C0-U+DE to U+E0-U+FD and back.
  503. *
  504. * @param $matches
  505. * An array of matches.
  506. *
  507. * @return array
  508. * The Latin-1 version of the array of matches.
  509. *
  510. * @see drupal_strtolower()
  511. */
  512. function _unicode_caseflip($matches) {
  513. return $matches[0][0] . chr(ord($matches[0][1]) ^ 32);
  514. }
  515. /**
  516. * Capitalizes the first letter of a UTF-8 string.
  517. *
  518. * @param $text
  519. * The string to convert.
  520. *
  521. * @return
  522. * The string with the first letter as uppercase.
  523. *
  524. * @ingroup php_wrappers
  525. */
  526. function drupal_ucfirst($text) {
  527. // Note: no mbstring equivalent!
  528. return drupal_strtoupper(drupal_substr($text, 0, 1)) . drupal_substr($text, 1);
  529. }
  530. /**
  531. * Cuts off a piece of a string based on character indices and counts.
  532. *
  533. * Follows the same behavior as PHP's own substr() function. Note that for
  534. * cutting off a string at a known character/substring location, the usage of
  535. * PHP's normal strpos/substr is safe and much faster.
  536. *
  537. * @param $text
  538. * The input string.
  539. * @param $start
  540. * The position at which to start reading.
  541. * @param $length
  542. * The number of characters to read.
  543. *
  544. * @return
  545. * The shortened string.
  546. *
  547. * @ingroup php_wrappers
  548. */
  549. function drupal_substr($text, $start, $length = NULL) {
  550. global $multibyte;
  551. if ($multibyte == UNICODE_MULTIBYTE) {
  552. return $length === NULL ? mb_substr($text, $start) : mb_substr($text, $start, $length);
  553. }
  554. else {
  555. $strlen = strlen($text);
  556. // Find the starting byte offset.
  557. $bytes = 0;
  558. if ($start > 0) {
  559. // Count all the continuation bytes from the start until we have found
  560. // $start characters or the end of the string.
  561. $bytes = -1; $chars = -1;
  562. while ($bytes < $strlen - 1 && $chars < $start) {
  563. $bytes++;
  564. $c = ord($text[$bytes]);
  565. if ($c < 0x80 || $c >= 0xC0) {
  566. $chars++;
  567. }
  568. }
  569. }
  570. elseif ($start < 0) {
  571. // Count all the continuation bytes from the end until we have found
  572. // abs($start) characters.
  573. $start = abs($start);
  574. $bytes = $strlen; $chars = 0;
  575. while ($bytes > 0 && $chars < $start) {
  576. $bytes--;
  577. $c = ord($text[$bytes]);
  578. if ($c < 0x80 || $c >= 0xC0) {
  579. $chars++;
  580. }
  581. }
  582. }
  583. $istart = $bytes;
  584. // Find the ending byte offset.
  585. if ($length === NULL) {
  586. $iend = $strlen;
  587. }
  588. elseif ($length > 0) {
  589. // Count all the continuation bytes from the starting index until we have
  590. // found $length characters or reached the end of the string, then
  591. // backtrace one byte.
  592. $iend = $istart - 1;
  593. $chars = -1;
  594. $last_real = FALSE;
  595. while ($iend < $strlen - 1 && $chars < $length) {
  596. $iend++;
  597. $c = ord($text[$iend]);
  598. $last_real = FALSE;
  599. if ($c < 0x80 || $c >= 0xC0) {
  600. $chars++;
  601. $last_real = TRUE;
  602. }
  603. }
  604. // Backtrace one byte if the last character we found was a real character
  605. // and we don't need it.
  606. if ($last_real && $chars >= $length) {
  607. $iend--;
  608. }
  609. }
  610. elseif ($length < 0) {
  611. // Count all the continuation bytes from the end until we have found
  612. // abs($start) characters, then backtrace one byte.
  613. $length = abs($length);
  614. $iend = $strlen; $chars = 0;
  615. while ($iend > 0 && $chars < $length) {
  616. $iend--;
  617. $c = ord($text[$iend]);
  618. if ($c < 0x80 || $c >= 0xC0) {
  619. $chars++;
  620. }
  621. }
  622. // Backtrace one byte if we are not at the beginning of the string.
  623. if ($iend > 0) {
  624. $iend--;
  625. }
  626. }
  627. else {
  628. // $length == 0, return an empty string.
  629. return '';
  630. }
  631. return substr($text, $istart, max(0, $iend - $istart + 1));
  632. }
  633. }