annotate core/lib/Drupal/Component/Utility/Unicode.php @ 14:1fec387a4317

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