Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 401] [Versions 400 and 402] [Versions 400 and 403]
1 <?php 2 // This file is part of Moodle - http://moodle.org/ 3 // 4 // Moodle is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // Moodle is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>. 16 17 /** 18 * Defines string apis 19 * 20 * @package core 21 * @copyright (C) 2001-3001 Eloy Lafuente (stronk7) {@link http://contiento.com} 22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 23 */ 24 25 defined('MOODLE_INTERNAL') || die(); 26 27 /** 28 * defines string api's for manipulating strings 29 * 30 * This class is used to manipulate strings under Moodle 1.6 an later. As 31 * utf-8 text become mandatory a pool of safe functions under this encoding 32 * become necessary. The name of the methods is exactly the 33 * same than their PHP originals. 34 * 35 * This class was previously based on Typo3 which has now been removed and uses 36 * native functions now. 37 * 38 * @package core 39 * @category string 40 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} 41 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 42 */ 43 class core_text { 44 /** @var string Byte order mark for UTF-8 */ 45 const UTF8_BOM = "\xef\xbb\xbf"; 46 47 /** 48 * @var string[] Array of strings representing Unicode non-characters 49 */ 50 protected static $noncharacters; 51 52 /** 53 * Check whether the charset is supported by mbstring. 54 * @param string $charset Normalised charset 55 * @return bool 56 */ 57 public static function is_charset_supported(string $charset): bool { 58 static $cache = null; 59 if (!$cache) { 60 $cache = array_flip(array_map('strtolower', mb_list_encodings())); 61 } 62 63 if (isset($cache[strtolower($charset)])) { 64 return true; 65 } 66 67 // We haven't found the charset, check if mb has aliases for the charset. 68 try { 69 return mb_encoding_aliases($charset) !== false; 70 } catch (Throwable $e) { 71 // A ValueError will be thrown if unsupported. 72 } 73 74 return false; 75 } 76 77 /** 78 * Reset internal textlib caches. 79 * @static 80 * @deprecated since Moodle 4.0. See MDL-53544. 81 * @todo To be removed in Moodle 4.4 - MDL-71748 82 */ 83 public static function reset_caches() { 84 debugging("reset_caches() is deprecated. Typo3 has been removed and caches aren't used anymore.", DEBUG_DEVELOPER); 85 } 86 87 /** 88 * Standardise charset name 89 * 90 * Please note it does not mean the returned charset is actually supported. 91 * 92 * @static 93 * @param string $charset raw charset name 94 * @return string normalised lowercase charset name 95 */ 96 public static function parse_charset($charset) { 97 $charset = strtolower($charset); 98 99 if ($charset === 'utf8' or $charset === 'utf-8') { 100 return 'utf-8'; 101 } 102 103 if (preg_match('/^(cp|win|windows)-?(12[0-9]{2})$/', $charset, $matches)) { 104 return 'windows-'.$matches[2]; 105 } 106 107 if (preg_match('/^iso-8859-[0-9]+$/', $charset, $matches)) { 108 return $charset; 109 } 110 111 if ($charset === 'euc-jp') { 112 return 'euc-jp'; 113 } 114 if ($charset === 'iso-2022-jp') { 115 return 'iso-2022-jp'; 116 } 117 if ($charset === 'shift-jis' or $charset === 'shift_jis') { 118 return 'shift_jis'; 119 } 120 if ($charset === 'gb2312') { 121 return 'gb2312'; 122 } 123 if ($charset === 'gb18030') { 124 return 'gb18030'; 125 } 126 if ($charset === 'ms-ansi') { 127 return 'windows-1252'; 128 } 129 130 // We have reached this stage and haven't matched with anything. Return the original. 131 return $charset; 132 } 133 134 /** 135 * Converts the text between different encodings. It uses iconv extension with //TRANSLIT parameter. 136 * If both source and target are utf-8 it tries to fix invalid characters only. 137 * 138 * @param string $text 139 * @param string $fromCS source encoding 140 * @param string $toCS result encoding 141 * @return string|bool converted string or false on error 142 */ 143 public static function convert($text, $fromCS, $toCS='utf-8') { 144 $fromCS = self::parse_charset($fromCS); 145 $toCS = self::parse_charset($toCS); 146 147 $text = (string)$text; // we can work only with strings 148 149 if ($text === '') { 150 return ''; 151 } 152 153 if ($fromCS === 'utf-8') { 154 $text = fix_utf8($text); 155 if ($toCS === 'utf-8') { 156 return $text; 157 } 158 } 159 160 if ($toCS === 'ascii') { 161 // Try to normalize the conversion a bit if the target is ascii. 162 return self::specialtoascii($text, $fromCS); 163 } 164 165 // Prevent any error notices, do not use //IGNORE so that we get 166 // consistent result if iconv fails. 167 return @iconv($fromCS, $toCS.'//TRANSLIT', $text); 168 } 169 170 /** 171 * Multibyte safe substr() function, uses mbstring or iconv 172 * 173 * @param string $text string to truncate 174 * @param int $start negative value means from end 175 * @param int $len maximum length of characters beginning from start 176 * @param string $charset encoding of the text 177 * @return string portion of string specified by the $start and $len 178 */ 179 public static function substr($text, $start, $len=null, $charset='utf-8') { 180 $charset = self::parse_charset($charset); 181 182 // Check whether the charset is supported by mbstring. CP1250 is not supported. Fall back to iconv. 183 if (self::is_charset_supported($charset)) { 184 $result = mb_substr($text, $start, $len, $charset); 185 } else { 186 $result = iconv_substr($text, $start, $len, $charset); 187 } 188 189 return $result; 190 } 191 192 /** 193 * Truncates a string to no more than a certain number of bytes in a multi-byte safe manner. 194 * UTF-8 only! 195 * 196 * @param string $string String to truncate 197 * @param int $bytes Maximum length of bytes in the result 198 * @return string Portion of string specified by $bytes 199 * @since Moodle 3.1 200 */ 201 public static function str_max_bytes($string, $bytes) { 202 return mb_strcut($string, 0, $bytes, 'UTF-8'); 203 } 204 205 /** 206 * Finds the last occurrence of a character in a string within another. 207 * UTF-8 ONLY safe mb_strrchr(). 208 * 209 * @param string $haystack The string from which to get the last occurrence of needle. 210 * @param string $needle The string to find in haystack. 211 * @param boolean $part If true, returns the portion before needle, else return the portion after (including needle). 212 * @return string|false False when not found. 213 * @since Moodle 2.4.6, 2.5.2, 2.6 214 */ 215 public static function strrchr($haystack, $needle, $part = false) { 216 return mb_strrchr($haystack, $needle, $part, 'UTF-8'); 217 } 218 219 /** 220 * Multibyte safe strlen() function, uses mbstring or iconv 221 * 222 * @param string $text input string 223 * @param string $charset encoding of the text 224 * @return int number of characters 225 */ 226 public static function strlen($text, $charset='utf-8') { 227 $charset = self::parse_charset($charset); 228 229 if (self::is_charset_supported($charset)) { 230 return mb_strlen($text, $charset); 231 } 232 233 return iconv_strlen($text, $charset); 234 } 235 236 /** 237 * Multibyte safe strtolower() function, uses mbstring. 238 * 239 * @param string $text input string 240 * @param string $charset encoding of the text (may not work for all encodings) 241 * @return string lower case text 242 */ 243 public static function strtolower($text, $charset='utf-8') { 244 $charset = self::parse_charset($charset); 245 246 // Confirm mbstring can handle the charset. 247 if (self::is_charset_supported($charset)) { 248 return mb_strtolower($text, $charset); 249 } 250 251 // The mbstring extension cannot handle the charset. Convert to UTF-8. 252 $convertedtext = self::convert($text, $charset, 'utf-8'); 253 $result = mb_strtolower($convertedtext); 254 $result = self::convert($result, 'utf-8', $charset); 255 return $result; 256 } 257 258 /** 259 * Multibyte safe strtoupper() function, uses mbstring. 260 * 261 * @param string $text input string 262 * @param string $charset encoding of the text (may not work for all encodings) 263 * @return string upper case text 264 */ 265 public static function strtoupper($text, $charset='utf-8') { 266 $charset = self::parse_charset($charset); 267 268 // Confirm mbstring can handle the charset. 269 if (self::is_charset_supported($charset)) { 270 return mb_strtoupper($text, $charset); 271 } 272 273 // The mbstring extension cannot handle the charset. Convert to UTF-8. 274 $convertedtext = self::convert($text, $charset, 'utf-8'); 275 $result = mb_strtoupper($convertedtext); 276 $result = self::convert($result, 'utf-8', $charset); 277 return $result; 278 } 279 280 /** 281 * Find the position of the first occurrence of a substring in a string. 282 * UTF-8 ONLY safe strpos(), uses mbstring 283 * 284 * @param string $haystack the string to search in 285 * @param string $needle one or more charachters to search for 286 * @param int $offset offset from begining of string 287 * @return int the numeric position of the first occurrence of needle in haystack. 288 */ 289 public static function strpos($haystack, $needle, $offset=0) { 290 return mb_strpos($haystack, $needle, $offset, 'UTF-8'); 291 } 292 293 /** 294 * Find the position of the last occurrence of a substring in a string 295 * UTF-8 ONLY safe strrpos(), uses mbstring 296 * 297 * @param string $haystack the string to search in 298 * @param string $needle one or more charachters to search for 299 * @return int the numeric position of the last occurrence of needle in haystack 300 */ 301 public static function strrpos($haystack, $needle) { 302 return mb_strrpos($haystack, $needle, null, 'UTF-8'); 303 } 304 305 /** 306 * Reverse UTF-8 multibytes character sets (used for RTL languages) 307 * (We only do this because there is no mb_strrev or iconv_strrev) 308 * 309 * @param string $str the multibyte string to reverse 310 * @return string the reversed multi byte string 311 */ 312 public static function strrev($str) { 313 preg_match_all('/./us', $str, $ar); 314 return join('', array_reverse($ar[0])); 315 } 316 317 /** 318 * Try to convert upper unicode characters to plain ascii, 319 * the returned string may contain unconverted unicode characters. 320 * 321 * With the removal of typo3, iconv conversions was found to be the best alternative to Typo3's function. 322 * However using the standard iconv call 323 * iconv($charset, 'ASCII//TRANSLIT//IGNORE', (string) $text); 324 * resulted in invalid strings with special character from Russian/Japanese. To solve this, the transliterator was 325 * used but this resulted in empty strings for certain strings in our test. It was decided to use a combo of the 2 326 * to cover all our bases. Refer MDL-53544 for further information. 327 * 328 * @param string $text input string 329 * @param string $charset encoding of the text 330 * @return string converted ascii string 331 */ 332 public static function specialtoascii($text, $charset='utf-8') { 333 $charset = self::parse_charset($charset); 334 $oldlevel = error_reporting(E_PARSE); 335 336 // Always convert to utf-8, so transliteration can do its work always. 337 if ($charset !== 'utf-8') { 338 $text = iconv($charset, 'utf-8'.'//TRANSLIT', $text); 339 } 340 $text = transliterator_transliterate('Any-Latin; Latin-ASCII', (string) $text); 341 342 // Still, apply iconv because some chars are not handled by transliterate. 343 $result = iconv('utf-8', 'ASCII//TRANSLIT//IGNORE', (string) $text); 344 345 error_reporting($oldlevel); 346 return $result; 347 } 348 349 /** 350 * Generate a correct base64 encoded header to be used in MIME mail messages. 351 * This function seems to be 100% compliant with RFC1342. Credits go to: 352 * paravoid (http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283). 353 * 354 * @param string $text input string 355 * @param string $charset encoding of the text 356 * @return string base64 encoded header 357 */ 358 public static function encode_mimeheader($text, $charset='utf-8') { 359 if (empty($text)) { 360 return (string)$text; 361 } 362 // Normalize charset 363 $charset = self::parse_charset($charset); 364 // If the text is pure ASCII, we don't need to encode it 365 if (self::convert($text, $charset, 'ascii') == $text) { 366 return $text; 367 } 368 // Although RFC says that line feed should be \r\n, it seems that 369 // some mailers double convert \r, so we are going to use \n alone 370 $linefeed="\n"; 371 // Define start and end of every chunk 372 $start = "=?$charset?B?"; 373 $end = "?="; 374 // Accumulate results 375 $encoded = ''; 376 // Max line length is 75 (including start and end) 377 $length = 75 - strlen($start) - strlen($end); 378 // Multi-byte ratio 379 $multilength = self::strlen($text, $charset); 380 // Detect if strlen and friends supported 381 if ($multilength === false) { 382 if ($charset == 'GB18030' or $charset == 'gb18030') { 383 while (strlen($text)) { 384 // try to encode first 22 chars - we expect most chars are two bytes long 385 if (preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,22}/m', $text, $matches)) { 386 $chunk = $matches[0]; 387 $encchunk = base64_encode($chunk); 388 if (strlen($encchunk) > $length) { 389 // find first 11 chars - each char in 4 bytes - worst case scenario 390 preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,11}/m', $text, $matches); 391 $chunk = $matches[0]; 392 $encchunk = base64_encode($chunk); 393 } 394 $text = substr($text, strlen($chunk)); 395 $encoded .= ' '.$start.$encchunk.$end.$linefeed; 396 } else { 397 break; 398 } 399 } 400 $encoded = trim($encoded); 401 return $encoded; 402 } else { 403 return false; 404 } 405 } 406 $ratio = $multilength / strlen($text); 407 // Base64 ratio 408 $magic = $avglength = floor(3 * $length * $ratio / 4); 409 // basic infinite loop protection 410 $maxiterations = strlen($text)*2; 411 $iteration = 0; 412 // Iterate over the string in magic chunks 413 for ($i=0; $i <= $multilength; $i+=$magic) { 414 if ($iteration++ > $maxiterations) { 415 return false; // probably infinite loop 416 } 417 $magic = $avglength; 418 $offset = 0; 419 // Ensure the chunk fits in length, reducing magic if necessary 420 do { 421 $magic -= $offset; 422 $chunk = self::substr($text, $i, $magic, $charset); 423 $chunk = base64_encode($chunk); 424 $offset++; 425 } while (strlen($chunk) > $length); 426 // This chunk doesn't break any multi-byte char. Use it. 427 if ($chunk) 428 $encoded .= ' '.$start.$chunk.$end.$linefeed; 429 } 430 // Strip the first space and the last linefeed 431 $encoded = substr($encoded, 1, -strlen($linefeed)); 432 433 return $encoded; 434 } 435 436 /** 437 * Returns HTML entity transliteration table. 438 * @return array with (html entity => utf-8) elements 439 */ 440 protected static function get_entities_table() { 441 static $trans_tbl = null; 442 443 // Generate/create $trans_tbl 444 if (!isset($trans_tbl)) { 445 if (version_compare(phpversion(), '5.3.4') < 0) { 446 $trans_tbl = array(); 447 foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key) { 448 $trans_tbl[$key] = self::convert($val, 'ISO-8859-1', 'utf-8'); 449 } 450 451 } else if (version_compare(phpversion(), '5.4.0') < 0) { 452 $trans_tbl = get_html_translation_table(HTML_ENTITIES, ENT_COMPAT, 'UTF-8'); 453 $trans_tbl = array_flip($trans_tbl); 454 455 } else { 456 $trans_tbl = get_html_translation_table(HTML_ENTITIES, ENT_COMPAT | ENT_HTML401, 'UTF-8'); 457 $trans_tbl = array_flip($trans_tbl); 458 } 459 } 460 461 return $trans_tbl; 462 } 463 464 /** 465 * Converts all the numeric entities &#nnnn; or &#xnnn; to UTF-8 466 * Original from laurynas dot butkus at gmail at: 467 * http://php.net/manual/en/function.html-entity-decode.php#75153 468 * with some custom mods to provide more functionality 469 * 470 * @param string $str input string 471 * @param boolean $htmlent convert also html entities (defaults to true) 472 * @return string encoded UTF-8 string 473 */ 474 public static function entities_to_utf8($str, $htmlent=true) { 475 static $callback1 = null ; 476 static $callback2 = null ; 477 478 if (!$callback1 or !$callback2) { 479 $callback1 = function($matches) { 480 return core_text::code2utf8(hexdec($matches[1])); 481 }; 482 $callback2 = function($matches) { 483 return core_text::code2utf8($matches[1]); 484 }; 485 } 486 487 $result = (string)$str; 488 $result = preg_replace_callback('/&#x([0-9a-f]+);/i', $callback1, $result); 489 $result = preg_replace_callback('/&#([0-9]+);/', $callback2, $result); 490 491 // Replace literal entities (if desired) 492 if ($htmlent) { 493 $trans_tbl = self::get_entities_table(); 494 // It should be safe to search for ascii strings and replace them with utf-8 here. 495 $result = strtr($result, $trans_tbl); 496 } 497 // Return utf8-ised string 498 return $result; 499 } 500 501 /** 502 * Converts all Unicode chars > 127 to numeric entities &#nnnn; or &#xnnn;. 503 * 504 * @param string $str input string 505 * @param boolean $dec output decadic only number entities 506 * @param boolean $nonnum remove all non-numeric entities 507 * @return string converted string 508 */ 509 public static function utf8_to_entities($str, $dec=false, $nonnum=false) { 510 static $callback = null ; 511 512 if ($nonnum) { 513 $str = self::entities_to_utf8($str, true); 514 } 515 516 $result = mb_strtolower(mb_encode_numericentity($str, [0xa0, 0xffff, 0, 0xffff], 'UTF-8', true)); 517 518 // We cannot use the decimal equivalent of the above call due to the unit test and our allowance for 519 // entities to be entered within the provided $str. Refer to the correspond unit test for examples. 520 if ($dec) { 521 if (!$callback) { 522 $callback = function($matches) { 523 return '&#' . hexdec($matches[1]) . ';'; 524 }; 525 } 526 $result = preg_replace_callback('/&#x([0-9a-f]+);/i', $callback, $result); 527 } 528 529 return $result; 530 } 531 532 /** 533 * Removes the BOM from unicode string {@link http://unicode.org/faq/utf_bom.html} 534 * 535 * @param string $str input string 536 * @return string 537 */ 538 public static function trim_utf8_bom($str) { 539 $bom = self::UTF8_BOM; 540 if (strpos($str, $bom) === 0) { 541 return substr($str, strlen($bom)); 542 } 543 return $str; 544 } 545 546 /** 547 * There are a number of Unicode non-characters including the byte-order mark (which may appear 548 * multiple times in a string) and also other ranges. These can cause problems for some 549 * processing. 550 * 551 * This function removes the characters using string replace, so that the rest of the string 552 * remains unchanged. 553 * 554 * @param string $value Input string 555 * @return string Cleaned string value 556 * @since Moodle 3.5 557 */ 558 public static function remove_unicode_non_characters($value) { 559 // Set up list of all Unicode non-characters for fast replacing. 560 if (!self::$noncharacters) { 561 self::$noncharacters = []; 562 // This list of characters is based on the Unicode standard. It includes the last two 563 // characters of each code planes 0-16 inclusive... 564 for ($plane = 0; $plane <= 16; $plane++) { 565 $base = ($plane === 0 ? '' : dechex($plane)); 566 self::$noncharacters[] = html_entity_decode('&#x' . $base . 'fffe;'); 567 self::$noncharacters[] = html_entity_decode('&#x' . $base . 'ffff;'); 568 } 569 // ...And the character range U+FDD0 to U+FDEF. 570 for ($char = 0xfdd0; $char <= 0xfdef; $char++) { 571 self::$noncharacters[] = html_entity_decode('&#x' . dechex($char) . ';'); 572 } 573 } 574 575 // Do character replacement. 576 return str_replace(self::$noncharacters, '', $value); 577 } 578 579 /** 580 * Returns encoding options for select boxes, utf-8 and platform encoding first 581 * 582 * @return array encodings 583 */ 584 public static function get_encodings() { 585 $encodings = array(); 586 $encodings['UTF-8'] = 'UTF-8'; 587 $winenc = strtoupper(get_string('localewincharset', 'langconfig')); 588 if ($winenc != '') { 589 $encodings[$winenc] = $winenc; 590 } 591 $nixenc = strtoupper(get_string('oldcharset', 'langconfig')); 592 $encodings[$nixenc] = $nixenc; 593 594 $listedencodings = mb_list_encodings(); 595 foreach ($listedencodings as $enc) { 596 $enc = strtoupper($enc); 597 $encodings[$enc] = $enc; 598 } 599 return $encodings; 600 } 601 602 /** 603 * Returns the utf8 string corresponding to the unicode value 604 * (from php.net, courtesy - romans@void.lv) 605 * 606 * @param int $num one unicode value 607 * @return string the UTF-8 char corresponding to the unicode value 608 */ 609 public static function code2utf8($num) { 610 if ($num < 128) { 611 return chr($num); 612 } 613 if ($num < 2048) { 614 return chr(($num >> 6) + 192) . chr(($num & 63) + 128); 615 } 616 if ($num < 65536) { 617 return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128); 618 } 619 if ($num < 2097152) { 620 return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128); 621 } 622 return ''; 623 } 624 625 /** 626 * Returns the code of the given UTF-8 character 627 * 628 * @param string $utf8char one UTF-8 character 629 * @return int the code of the given character 630 */ 631 public static function utf8ord($utf8char) { 632 if ($utf8char == '') { 633 return 0; 634 } 635 $ord0 = ord($utf8char[0]); 636 if ($ord0 >= 0 && $ord0 <= 127) { 637 return $ord0; 638 } 639 $ord1 = ord($utf8char[1]); 640 if ($ord0 >= 192 && $ord0 <= 223) { 641 return ($ord0 - 192) * 64 + ($ord1 - 128); 642 } 643 $ord2 = ord($utf8char[2]); 644 if ($ord0 >= 224 && $ord0 <= 239) { 645 return ($ord0 - 224) * 4096 + ($ord1 - 128) * 64 + ($ord2 - 128); 646 } 647 $ord3 = ord($utf8char[3]); 648 if ($ord0 >= 240 && $ord0 <= 247) { 649 return ($ord0 - 240) * 262144 + ($ord1 - 128 )* 4096 + ($ord2 - 128) * 64 + ($ord3 - 128); 650 } 651 return false; 652 } 653 654 /** 655 * Makes first letter of each word capital - words must be separated by spaces. 656 * Use with care, this function does not work properly in many locales!!! 657 * 658 * @param string $text input string 659 * @return string 660 */ 661 public static function strtotitle($text) { 662 if (empty($text)) { 663 return $text; 664 } 665 666 return mb_convert_case($text, MB_CASE_TITLE, 'UTF-8'); 667 } 668 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body