Unicode.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. <?php
  2. namespace Drupal\Component\Utility;
  3. /**
  4. * Provides Unicode-related conversions and operations.
  5. *
  6. * @ingroup utility
  7. */
  8. class Unicode {
  9. /**
  10. * Matches Unicode characters that are word boundaries.
  11. *
  12. * Characters with the following General_category (gc) property values are used
  13. * as word boundaries. While this does not fully conform to the Word Boundaries
  14. * algorithm described in http://unicode.org/reports/tr29, as PCRE does not
  15. * contain the Word_Break property table, this simpler algorithm has to do.
  16. * - Cc, Cf, Cn, Co, Cs: Other.
  17. * - Pc, Pd, Pe, Pf, Pi, Po, Ps: Punctuation.
  18. * - Sc, Sk, Sm, So: Symbols.
  19. * - Zl, Zp, Zs: Separators.
  20. *
  21. * Non-boundary characters include the following General_category (gc) property
  22. * values:
  23. * - Ll, Lm, Lo, Lt, Lu: Letters.
  24. * - Mc, Me, Mn: Combining Marks.
  25. * - Nd, Nl, No: Numbers.
  26. *
  27. * Note that the PCRE property matcher is not used because we wanted to be
  28. * compatible with Unicode 5.2.0 regardless of the PCRE version used (and any
  29. * bugs in PCRE property tables).
  30. *
  31. * @see http://unicode.org/glossary
  32. */
  33. const PREG_CLASS_WORD_BOUNDARY = <<<'EOD'
  34. \x{0}-\x{2F}\x{3A}-\x{40}\x{5B}-\x{60}\x{7B}-\x{A9}\x{AB}-\x{B1}\x{B4}
  35. \x{B6}-\x{B8}\x{BB}\x{BF}\x{D7}\x{F7}\x{2C2}-\x{2C5}\x{2D2}-\x{2DF}
  36. \x{2E5}-\x{2EB}\x{2ED}\x{2EF}-\x{2FF}\x{375}\x{37E}-\x{385}\x{387}\x{3F6}
  37. \x{482}\x{55A}-\x{55F}\x{589}-\x{58A}\x{5BE}\x{5C0}\x{5C3}\x{5C6}
  38. \x{5F3}-\x{60F}\x{61B}-\x{61F}\x{66A}-\x{66D}\x{6D4}\x{6DD}\x{6E9}
  39. \x{6FD}-\x{6FE}\x{700}-\x{70F}\x{7F6}-\x{7F9}\x{830}-\x{83E}
  40. \x{964}-\x{965}\x{970}\x{9F2}-\x{9F3}\x{9FA}-\x{9FB}\x{AF1}\x{B70}
  41. \x{BF3}-\x{BFA}\x{C7F}\x{CF1}-\x{CF2}\x{D79}\x{DF4}\x{E3F}\x{E4F}
  42. \x{E5A}-\x{E5B}\x{F01}-\x{F17}\x{F1A}-\x{F1F}\x{F34}\x{F36}\x{F38}
  43. \x{F3A}-\x{F3D}\x{F85}\x{FBE}-\x{FC5}\x{FC7}-\x{FD8}\x{104A}-\x{104F}
  44. \x{109E}-\x{109F}\x{10FB}\x{1360}-\x{1368}\x{1390}-\x{1399}\x{1400}
  45. \x{166D}-\x{166E}\x{1680}\x{169B}-\x{169C}\x{16EB}-\x{16ED}
  46. \x{1735}-\x{1736}\x{17B4}-\x{17B5}\x{17D4}-\x{17D6}\x{17D8}-\x{17DB}
  47. \x{1800}-\x{180A}\x{180E}\x{1940}-\x{1945}\x{19DE}-\x{19FF}
  48. \x{1A1E}-\x{1A1F}\x{1AA0}-\x{1AA6}\x{1AA8}-\x{1AAD}\x{1B5A}-\x{1B6A}
  49. \x{1B74}-\x{1B7C}\x{1C3B}-\x{1C3F}\x{1C7E}-\x{1C7F}\x{1CD3}\x{1FBD}
  50. \x{1FBF}-\x{1FC1}\x{1FCD}-\x{1FCF}\x{1FDD}-\x{1FDF}\x{1FED}-\x{1FEF}
  51. \x{1FFD}-\x{206F}\x{207A}-\x{207E}\x{208A}-\x{208E}\x{20A0}-\x{20B8}
  52. \x{2100}-\x{2101}\x{2103}-\x{2106}\x{2108}-\x{2109}\x{2114}
  53. \x{2116}-\x{2118}\x{211E}-\x{2123}\x{2125}\x{2127}\x{2129}\x{212E}
  54. \x{213A}-\x{213B}\x{2140}-\x{2144}\x{214A}-\x{214D}\x{214F}
  55. \x{2190}-\x{244A}\x{249C}-\x{24E9}\x{2500}-\x{2775}\x{2794}-\x{2B59}
  56. \x{2CE5}-\x{2CEA}\x{2CF9}-\x{2CFC}\x{2CFE}-\x{2CFF}\x{2E00}-\x{2E2E}
  57. \x{2E30}-\x{3004}\x{3008}-\x{3020}\x{3030}\x{3036}-\x{3037}
  58. \x{303D}-\x{303F}\x{309B}-\x{309C}\x{30A0}\x{30FB}\x{3190}-\x{3191}
  59. \x{3196}-\x{319F}\x{31C0}-\x{31E3}\x{3200}-\x{321E}\x{322A}-\x{3250}
  60. \x{3260}-\x{327F}\x{328A}-\x{32B0}\x{32C0}-\x{33FF}\x{4DC0}-\x{4DFF}
  61. \x{A490}-\x{A4C6}\x{A4FE}-\x{A4FF}\x{A60D}-\x{A60F}\x{A673}\x{A67E}
  62. \x{A6F2}-\x{A716}\x{A720}-\x{A721}\x{A789}-\x{A78A}\x{A828}-\x{A82B}
  63. \x{A836}-\x{A839}\x{A874}-\x{A877}\x{A8CE}-\x{A8CF}\x{A8F8}-\x{A8FA}
  64. \x{A92E}-\x{A92F}\x{A95F}\x{A9C1}-\x{A9CD}\x{A9DE}-\x{A9DF}
  65. \x{AA5C}-\x{AA5F}\x{AA77}-\x{AA79}\x{AADE}-\x{AADF}\x{ABEB}
  66. \x{E000}-\x{F8FF}\x{FB29}\x{FD3E}-\x{FD3F}\x{FDFC}-\x{FDFD}
  67. \x{FE10}-\x{FE19}\x{FE30}-\x{FE6B}\x{FEFF}-\x{FF0F}\x{FF1A}-\x{FF20}
  68. \x{FF3B}-\x{FF40}\x{FF5B}-\x{FF65}\x{FFE0}-\x{FFFD}
  69. EOD;
  70. /**
  71. * Indicates that standard PHP (emulated) unicode support is being used.
  72. */
  73. const STATUS_SINGLEBYTE = 0;
  74. /**
  75. * Indicates that full unicode support with the PHP mbstring extension is
  76. * being used.
  77. */
  78. const STATUS_MULTIBYTE = 1;
  79. /**
  80. * Indicates an error during check for PHP unicode support.
  81. */
  82. const STATUS_ERROR = -1;
  83. /**
  84. * Holds the multibyte capabilities of the current environment.
  85. *
  86. * @var int
  87. */
  88. protected static $status = 0;
  89. /**
  90. * Gets the current status of unicode/multibyte support on this environment.
  91. *
  92. * @return int
  93. * The status of multibyte support. It can be one of:
  94. * - \Drupal\Component\Utility\Unicode::STATUS_MULTIBYTE
  95. * Full unicode support using an extension.
  96. * - \Drupal\Component\Utility\Unicode::STATUS_SINGLEBYTE
  97. * Standard PHP (emulated) unicode support.
  98. * - \Drupal\Component\Utility\Unicode::STATUS_ERROR
  99. * An error occurred. No unicode support.
  100. */
  101. public static function getStatus() {
  102. return static::$status;
  103. }
  104. /**
  105. * Sets the value for multibyte support status for the current environment.
  106. *
  107. * The following status keys are supported:
  108. * - \Drupal\Component\Utility\Unicode::STATUS_MULTIBYTE
  109. * Full unicode support using an extension.
  110. * - \Drupal\Component\Utility\Unicode::STATUS_SINGLEBYTE
  111. * Standard PHP (emulated) unicode support.
  112. * - \Drupal\Component\Utility\Unicode::STATUS_ERROR
  113. * An error occurred. No unicode support.
  114. *
  115. * @param int $status
  116. * The new status of multibyte support.
  117. */
  118. public static function setStatus($status) {
  119. if (!in_array($status, [static::STATUS_SINGLEBYTE, static::STATUS_MULTIBYTE, static::STATUS_ERROR])) {
  120. throw new \InvalidArgumentException('Invalid status value for unicode support.');
  121. }
  122. static::$status = $status;
  123. }
  124. /**
  125. * Checks for Unicode support in PHP and sets the proper settings if possible.
  126. *
  127. * Because of the need to be able to handle text in various encodings, we do
  128. * not support mbstring function overloading. HTTP input/output conversion
  129. * must be disabled for similar reasons.
  130. *
  131. * @return string
  132. * A string identifier of a failed multibyte extension check, if any.
  133. * Otherwise, an empty string.
  134. */
  135. public static function check() {
  136. // Check for mbstring extension.
  137. if (!function_exists('mb_strlen')) {
  138. static::$status = static::STATUS_SINGLEBYTE;
  139. return 'mb_strlen';
  140. }
  141. // Check mbstring configuration.
  142. if (ini_get('mbstring.func_overload') != 0) {
  143. static::$status = static::STATUS_ERROR;
  144. return 'mbstring.func_overload';
  145. }
  146. if (ini_get('mbstring.encoding_translation') != 0) {
  147. static::$status = static::STATUS_ERROR;
  148. return 'mbstring.encoding_translation';
  149. }
  150. // mbstring.http_input and mbstring.http_output are deprecated and empty by
  151. // default in PHP 5.6.
  152. if (version_compare(PHP_VERSION, '5.6.0') == -1) {
  153. if (ini_get('mbstring.http_input') != 'pass') {
  154. static::$status = static::STATUS_ERROR;
  155. return 'mbstring.http_input';
  156. }
  157. if (ini_get('mbstring.http_output') != 'pass') {
  158. static::$status = static::STATUS_ERROR;
  159. return 'mbstring.http_output';
  160. }
  161. }
  162. // Set appropriate configuration.
  163. mb_internal_encoding('utf-8');
  164. mb_language('uni');
  165. static::$status = static::STATUS_MULTIBYTE;
  166. return '';
  167. }
  168. /**
  169. * Decodes UTF byte-order mark (BOM) into the encoding's name.
  170. *
  171. * @param string $data
  172. * The data possibly containing a BOM. This can be the entire contents of
  173. * a file, or just a fragment containing at least the first five bytes.
  174. *
  175. * @return string|bool
  176. * The name of the encoding, or FALSE if no byte order mark was present.
  177. */
  178. public static function encodingFromBOM($data) {
  179. static $bomMap = [
  180. "\xEF\xBB\xBF" => 'UTF-8',
  181. "\xFE\xFF" => 'UTF-16BE',
  182. "\xFF\xFE" => 'UTF-16LE',
  183. "\x00\x00\xFE\xFF" => 'UTF-32BE',
  184. "\xFF\xFE\x00\x00" => 'UTF-32LE',
  185. "\x2B\x2F\x76\x38" => 'UTF-7',
  186. "\x2B\x2F\x76\x39" => 'UTF-7',
  187. "\x2B\x2F\x76\x2B" => 'UTF-7',
  188. "\x2B\x2F\x76\x2F" => 'UTF-7',
  189. "\x2B\x2F\x76\x38\x2D" => 'UTF-7',
  190. ];
  191. foreach ($bomMap as $bom => $encoding) {
  192. if (strpos($data, $bom) === 0) {
  193. return $encoding;
  194. }
  195. }
  196. return FALSE;
  197. }
  198. /**
  199. * Converts data to UTF-8.
  200. *
  201. * Requires the iconv, GNU recode or mbstring PHP extension.
  202. *
  203. * @param string $data
  204. * The data to be converted.
  205. * @param string $encoding
  206. * The encoding that the data is in.
  207. *
  208. * @return string|bool
  209. * Converted data or FALSE.
  210. */
  211. public static function convertToUtf8($data, $encoding) {
  212. if (function_exists('iconv')) {
  213. return @iconv($encoding, 'utf-8', $data);
  214. }
  215. elseif (function_exists('mb_convert_encoding')) {
  216. return @mb_convert_encoding($data, 'utf-8', $encoding);
  217. }
  218. elseif (function_exists('recode_string')) {
  219. return @recode_string($encoding . '..utf-8', $data);
  220. }
  221. // Cannot convert.
  222. return FALSE;
  223. }
  224. /**
  225. * Truncates 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
  233. * use substr() instead.
  234. *
  235. * @param string $string
  236. * The string to truncate.
  237. * @param int $len
  238. * An upper limit on the returned string length.
  239. *
  240. * @return string
  241. * The truncated string.
  242. */
  243. public static function truncateBytes($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. // @todo Make the code more readable in https://www.drupal.org/node/2911497.
  252. while (--$len >= 0 && ord($string[$len]) >= 0x80 && ord($string[$len]) < 0xC0) {
  253. }
  254. return substr($string, 0, $len);
  255. }
  256. /**
  257. * Counts the number of characters in a UTF-8 string.
  258. *
  259. * This is less than or equal to the byte count.
  260. *
  261. * @param string $text
  262. * The string to run the operation on.
  263. *
  264. * @return int
  265. * The length of the string.
  266. */
  267. public static function strlen($text) {
  268. if (static::getStatus() == static::STATUS_MULTIBYTE) {
  269. return mb_strlen($text);
  270. }
  271. else {
  272. // Do not count UTF-8 continuation bytes.
  273. return strlen(preg_replace("/[\x80-\xBF]/", '', $text));
  274. }
  275. }
  276. /**
  277. * Converts a UTF-8 string to uppercase.
  278. *
  279. * @param string $text
  280. * The string to run the operation on.
  281. *
  282. * @return string
  283. * The string in uppercase.
  284. */
  285. public static function strtoupper($text) {
  286. if (static::getStatus() == static::STATUS_MULTIBYTE) {
  287. return mb_strtoupper($text);
  288. }
  289. else {
  290. // Use C-locale for ASCII-only uppercase.
  291. $text = strtoupper($text);
  292. // Case flip Latin-1 accented letters.
  293. $text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text);
  294. return $text;
  295. }
  296. }
  297. /**
  298. * Converts a UTF-8 string to lowercase.
  299. *
  300. * @param string $text
  301. * The string to run the operation on.
  302. *
  303. * @return string
  304. * The string in lowercase.
  305. */
  306. public static function strtolower($text) {
  307. if (static::getStatus() == static::STATUS_MULTIBYTE) {
  308. return mb_strtolower($text);
  309. }
  310. else {
  311. // Use C-locale for ASCII-only lowercase.
  312. $text = strtolower($text);
  313. // Case flip Latin-1 accented letters.
  314. $text = preg_replace_callback('/\xC3[\x80-\x96\x98-\x9E]/', '\Drupal\Component\Utility\Unicode::caseFlip', $text);
  315. return $text;
  316. }
  317. }
  318. /**
  319. * Capitalizes the first character of a UTF-8 string.
  320. *
  321. * @param string $text
  322. * The string to convert.
  323. *
  324. * @return string
  325. * The string with the first character as uppercase.
  326. */
  327. public static function ucfirst($text) {
  328. return static::strtoupper(static::substr($text, 0, 1)) . static::substr($text, 1);
  329. }
  330. /**
  331. * Converts the first character of a UTF-8 string to lowercase.
  332. *
  333. * @param string $text
  334. * The string that will be converted.
  335. *
  336. * @return string
  337. * The string with the first character as lowercase.
  338. *
  339. * @ingroup php_wrappers
  340. */
  341. public static function lcfirst($text) {
  342. // Note: no mbstring equivalent!
  343. return static::strtolower(static::substr($text, 0, 1)) . static::substr($text, 1);
  344. }
  345. /**
  346. * Capitalizes the first character of each word in a UTF-8 string.
  347. *
  348. * @param string $text
  349. * The text that will be converted.
  350. *
  351. * @return string
  352. * The input $text with each word capitalized.
  353. *
  354. * @ingroup php_wrappers
  355. */
  356. public static function ucwords($text) {
  357. $regex = '/(^|[' . static::PREG_CLASS_WORD_BOUNDARY . '])([^' . static::PREG_CLASS_WORD_BOUNDARY . '])/u';
  358. return preg_replace_callback($regex, function (array $matches) {
  359. return $matches[1] . Unicode::strtoupper($matches[2]);
  360. }, $text);
  361. }
  362. /**
  363. * Cuts off a piece of a string based on character indices and counts.
  364. *
  365. * Follows the same behavior as PHP's own substr() function. Note that for
  366. * cutting off a string at a known character/substring location, the usage of
  367. * PHP's normal strpos/substr is safe and much faster.
  368. *
  369. * @param string $text
  370. * The input string.
  371. * @param int $start
  372. * The position at which to start reading.
  373. * @param int $length
  374. * The number of characters to read.
  375. *
  376. * @return string
  377. * The shortened string.
  378. */
  379. public static function substr($text, $start, $length = NULL) {
  380. if (static::getStatus() == static::STATUS_MULTIBYTE) {
  381. return $length === NULL ? mb_substr($text, $start) : mb_substr($text, $start, $length);
  382. }
  383. else {
  384. $strlen = strlen($text);
  385. // Find the starting byte offset.
  386. $bytes = 0;
  387. if ($start > 0) {
  388. // Count all the characters except continuation bytes from the start
  389. // until we have found $start characters or the end of the string.
  390. $bytes = -1; $chars = -1;
  391. while ($bytes < $strlen - 1 && $chars < $start) {
  392. $bytes++;
  393. $c = ord($text[$bytes]);
  394. if ($c < 0x80 || $c >= 0xC0) {
  395. $chars++;
  396. }
  397. }
  398. }
  399. elseif ($start < 0) {
  400. // Count all the characters except continuation bytes from the end
  401. // until we have found abs($start) characters.
  402. $start = abs($start);
  403. $bytes = $strlen; $chars = 0;
  404. while ($bytes > 0 && $chars < $start) {
  405. $bytes--;
  406. $c = ord($text[$bytes]);
  407. if ($c < 0x80 || $c >= 0xC0) {
  408. $chars++;
  409. }
  410. }
  411. }
  412. $istart = $bytes;
  413. // Find the ending byte offset.
  414. if ($length === NULL) {
  415. $iend = $strlen;
  416. }
  417. elseif ($length > 0) {
  418. // Count all the characters except continuation bytes from the starting
  419. // index until we have found $length characters or reached the end of
  420. // the string, then backtrace one byte.
  421. $iend = $istart - 1;
  422. $chars = -1;
  423. $last_real = FALSE;
  424. while ($iend < $strlen - 1 && $chars < $length) {
  425. $iend++;
  426. $c = ord($text[$iend]);
  427. $last_real = FALSE;
  428. if ($c < 0x80 || $c >= 0xC0) {
  429. $chars++;
  430. $last_real = TRUE;
  431. }
  432. }
  433. // Backtrace one byte if the last character we found was a real
  434. // character and we don't need it.
  435. if ($last_real && $chars >= $length) {
  436. $iend--;
  437. }
  438. }
  439. elseif ($length < 0) {
  440. // Count all the characters except continuation bytes from the end
  441. // until we have found abs($start) characters, then backtrace one byte.
  442. $length = abs($length);
  443. $iend = $strlen; $chars = 0;
  444. while ($iend > 0 && $chars < $length) {
  445. $iend--;
  446. $c = ord($text[$iend]);
  447. if ($c < 0x80 || $c >= 0xC0) {
  448. $chars++;
  449. }
  450. }
  451. // Backtrace one byte if we are not at the beginning of the string.
  452. if ($iend > 0) {
  453. $iend--;
  454. }
  455. }
  456. else {
  457. // $length == 0, return an empty string.
  458. return '';
  459. }
  460. return substr($text, $istart, max(0, $iend - $istart + 1));
  461. }
  462. }
  463. /**
  464. * Truncates a UTF-8-encoded string safely to a number of characters.
  465. *
  466. * @param string $string
  467. * The string to truncate.
  468. * @param int $max_length
  469. * An upper limit on the returned string length, including trailing ellipsis
  470. * if $add_ellipsis is TRUE.
  471. * @param bool $wordsafe
  472. * If TRUE, attempt to truncate on a word boundary. Word boundaries are
  473. * spaces, punctuation, and Unicode characters used as word boundaries in
  474. * non-Latin languages; see Unicode::PREG_CLASS_WORD_BOUNDARY for more
  475. * information. If a word boundary cannot be found that would make the length
  476. * of the returned string fall within length guidelines (see parameters
  477. * $max_length and $min_wordsafe_length), word boundaries are ignored.
  478. * @param bool $add_ellipsis
  479. * If TRUE, add '...' to the end of the truncated string (defaults to
  480. * FALSE). The string length will still fall within $max_length.
  481. * @param int $min_wordsafe_length
  482. * If $wordsafe is TRUE, the minimum acceptable length for truncation (before
  483. * adding an ellipsis, if $add_ellipsis is TRUE). Has no effect if $wordsafe
  484. * is FALSE. This can be used to prevent having a very short resulting string
  485. * that will not be understandable. For instance, if you are truncating the
  486. * string "See myverylongurlexample.com for more information" to a word-safe
  487. * return length of 20, the only available word boundary within 20 characters
  488. * is after the word "See", which wouldn't leave a very informative string. If
  489. * you had set $min_wordsafe_length to 10, though, the function would realise
  490. * that "See" alone is too short, and would then just truncate ignoring word
  491. * boundaries, giving you "See myverylongurl..." (assuming you had set
  492. * $add_ellipses to TRUE).
  493. *
  494. * @return string
  495. * The truncated string.
  496. */
  497. public static function truncate($string, $max_length, $wordsafe = FALSE, $add_ellipsis = FALSE, $min_wordsafe_length = 1) {
  498. $ellipsis = '';
  499. $max_length = max($max_length, 0);
  500. $min_wordsafe_length = max($min_wordsafe_length, 0);
  501. if (static::strlen($string) <= $max_length) {
  502. // No truncation needed, so don't add ellipsis, just return.
  503. return $string;
  504. }
  505. if ($add_ellipsis) {
  506. // Truncate ellipsis in case $max_length is small.
  507. $ellipsis = static::substr('…', 0, $max_length);
  508. $max_length -= static::strlen($ellipsis);
  509. $max_length = max($max_length, 0);
  510. }
  511. if ($max_length <= $min_wordsafe_length) {
  512. // Do not attempt word-safe if lengths are bad.
  513. $wordsafe = FALSE;
  514. }
  515. if ($wordsafe) {
  516. $matches = [];
  517. // Find the last word boundary, if there is one within $min_wordsafe_length
  518. // to $max_length characters. preg_match() is always greedy, so it will
  519. // find the longest string possible.
  520. $found = preg_match('/^(.{' . $min_wordsafe_length . ',' . $max_length . '})[' . Unicode::PREG_CLASS_WORD_BOUNDARY . ']/u', $string, $matches);
  521. if ($found) {
  522. $string = $matches[1];
  523. }
  524. else {
  525. $string = static::substr($string, 0, $max_length);
  526. }
  527. }
  528. else {
  529. $string = static::substr($string, 0, $max_length);
  530. }
  531. if ($add_ellipsis) {
  532. // If we're adding an ellipsis, remove any trailing periods.
  533. $string = rtrim($string, '.');
  534. $string .= $ellipsis;
  535. }
  536. return $string;
  537. }
  538. /**
  539. * Compares UTF-8-encoded strings in a binary safe case-insensitive manner.
  540. *
  541. * @param string $str1
  542. * The first string.
  543. * @param string $str2
  544. * The second string.
  545. *
  546. * @return int
  547. * Returns < 0 if $str1 is less than $str2; > 0 if $str1 is greater than
  548. * $str2, and 0 if they are equal.
  549. */
  550. public static function strcasecmp($str1, $str2) {
  551. return strcmp(static::strtoupper($str1), static::strtoupper($str2));
  552. }
  553. /**
  554. * Encodes MIME/HTTP headers that contain incorrectly encoded characters.
  555. *
  556. * For example, Unicode::mimeHeaderEncode('tést.txt') returns
  557. * "=?UTF-8?B?dMOpc3QudHh0?=".
  558. *
  559. * See http://www.rfc-editor.org/rfc/rfc2047.txt for more information.
  560. *
  561. * Notes:
  562. * - Only encode strings that contain non-ASCII characters.
  563. * - We progressively cut-off a chunk with self::truncateBytes(). This ensures
  564. * each chunk starts and ends on a character boundary.
  565. * - Using \n as the chunk separator may cause problems on some systems and
  566. * may have to be changed to \r\n or \r.
  567. *
  568. * @param string $string
  569. * The header to encode.
  570. * @param bool $shorten
  571. * If TRUE, only return the first chunk of a multi-chunk encoded string.
  572. *
  573. * @return string
  574. * The mime-encoded header.
  575. */
  576. public static function mimeHeaderEncode($string, $shorten = FALSE) {
  577. if (preg_match('/[^\x20-\x7E]/', $string)) {
  578. // floor((75 - strlen("=?UTF-8?B??=")) * 0.75);
  579. $chunk_size = 47;
  580. $len = strlen($string);
  581. $output = '';
  582. while ($len > 0) {
  583. $chunk = static::truncateBytes($string, $chunk_size);
  584. $output .= ' =?UTF-8?B?' . base64_encode($chunk) . "?=\n";
  585. if ($shorten) {
  586. break;
  587. }
  588. $c = strlen($chunk);
  589. $string = substr($string, $c);
  590. $len -= $c;
  591. }
  592. return trim($output);
  593. }
  594. return $string;
  595. }
  596. /**
  597. * Decodes MIME/HTTP encoded header values.
  598. *
  599. * @param string $header
  600. * The header to decode.
  601. *
  602. * @return string
  603. * The mime-decoded header.
  604. */
  605. public static function mimeHeaderDecode($header) {
  606. $callback = function ($matches) {
  607. $data = ($matches[2] == 'B') ? base64_decode($matches[3]) : str_replace('_', ' ', quoted_printable_decode($matches[3]));
  608. if (strtolower($matches[1]) != 'utf-8') {
  609. $data = static::convertToUtf8($data, $matches[1]);
  610. }
  611. return $data;
  612. };
  613. // First step: encoded chunks followed by other encoded chunks (need to collapse whitespace)
  614. $header = preg_replace_callback('/=\?([^?]+)\?(Q|B)\?([^?]+|\?(?!=))\?=\s+(?==\?)/', $callback, $header);
  615. // Second step: remaining chunks (do not collapse whitespace)
  616. return preg_replace_callback('/=\?([^?]+)\?(Q|B)\?([^?]+|\?(?!=))\?=/', $callback, $header);
  617. }
  618. /**
  619. * Flip U+C0-U+DE to U+E0-U+FD and back. Can be used as preg_replace callback.
  620. *
  621. * @param array $matches
  622. * An array of matches by preg_replace_callback().
  623. *
  624. * @return string
  625. * The flipped text.
  626. */
  627. public static function caseFlip($matches) {
  628. return $matches[0][0] . chr(ord($matches[0][1]) ^ 32);
  629. }
  630. /**
  631. * Checks whether a string is valid UTF-8.
  632. *
  633. * All functions designed to filter input should use drupal_validate_utf8
  634. * to ensure they operate on valid UTF-8 strings to prevent bypass of the
  635. * filter.
  636. *
  637. * When text containing an invalid UTF-8 lead byte (0xC0 - 0xFF) is presented
  638. * as UTF-8 to Internet Explorer 6, the program may misinterpret subsequent
  639. * bytes. When these subsequent bytes are HTML control characters such as
  640. * quotes or angle brackets, parts of the text that were deemed safe by filters
  641. * end up in locations that are potentially unsafe; An onerror attribute that
  642. * is outside of a tag, and thus deemed safe by a filter, can be interpreted
  643. * by the browser as if it were inside the tag.
  644. *
  645. * The function does not return FALSE for strings containing character codes
  646. * above U+10FFFF, even though these are prohibited by RFC 3629.
  647. *
  648. * @param string $text
  649. * The text to check.
  650. *
  651. * @return bool
  652. * TRUE if the text is valid UTF-8, FALSE if not.
  653. */
  654. public static function validateUtf8($text) {
  655. if (strlen($text) == 0) {
  656. return TRUE;
  657. }
  658. // With the PCRE_UTF8 modifier 'u', preg_match() fails silently on strings
  659. // containing invalid UTF-8 byte sequences. It does not reject character
  660. // codes above U+10FFFF (represented by 4 or more octets), though.
  661. return (preg_match('/^./us', $text) == 1);
  662. }
  663. /**
  664. * Finds the position of the first occurrence of a string in another string.
  665. *
  666. * @param string $haystack
  667. * The string to search in.
  668. * @param string $needle
  669. * The string to find in $haystack.
  670. * @param int $offset
  671. * If specified, start the search at this number of characters from the
  672. * beginning (default 0).
  673. *
  674. * @return int|false
  675. * The position where $needle occurs in $haystack, always relative to the
  676. * beginning (independent of $offset), or FALSE if not found. Note that
  677. * a return value of 0 is not the same as FALSE.
  678. */
  679. public static function strpos($haystack, $needle, $offset = 0) {
  680. if (static::getStatus() == static::STATUS_MULTIBYTE) {
  681. return mb_strpos($haystack, $needle, $offset);
  682. }
  683. else {
  684. // Remove Unicode continuation characters, to be compatible with
  685. // Unicode::strlen() and Unicode::substr().
  686. $haystack = preg_replace("/[\x80-\xBF]/", '', $haystack);
  687. $needle = preg_replace("/[\x80-\xBF]/", '', $needle);
  688. return strpos($haystack, $needle, $offset);
  689. }
  690. }
  691. }