Merge branch 'MDL-42957-26' of https://github.com/jamiepratt/moodle into MOODLE_26_STABLE
[moodle.git] / lib / classes / text.php
blob7b13d7550ceadb432710b98f228336d929ebd747
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.
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/>.
17 /**
18 * Defines string apis
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
25 defined('MOODLE_INTERNAL') || die();
27 /**
28 * defines string api's for manipulating strings
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.
35 * A big part of this class acts as a wrapper over the Typo3 charset library,
36 * really a cool group of utilities to handle texts and encoding conversion.
38 * Take a look to its own copyright and license details.
40 * IMPORTANT Note: Typo3 libraries always expect lowercase charsets to use 100%
41 * its capabilities so, don't forget to make the conversion
42 * from every wrapper function!
44 * @package core
45 * @category string
46 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
47 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 class core_text {
51 /**
52 * Return t3lib helper class, which is used for conversion between charsets
54 * @param bool $reset
55 * @return t3lib_cs
57 protected static function typo3($reset = false) {
58 static $typo3cs = null;
60 if ($reset) {
61 $typo3cs = null;
62 return null;
65 if (isset($typo3cs)) {
66 return $typo3cs;
69 global $CFG;
71 // Required files
72 require_once($CFG->libdir.'/typo3/class.t3lib_cs.php');
73 require_once($CFG->libdir.'/typo3/class.t3lib_div.php');
74 require_once($CFG->libdir.'/typo3/interface.t3lib_singleton.php');
75 require_once($CFG->libdir.'/typo3/class.t3lib_l10n_locales.php');
77 // do not use mbstring or recode because it may return invalid results in some corner cases
78 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod'] = 'iconv';
79 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] = 'iconv';
81 // Tell Typo3 we are curl enabled always (mandatory since 2.0)
82 $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] = '1';
84 // And this directory must exist to allow Typo to cache conversion
85 // tables when using internal functions
86 make_temp_directory('typo3temp/cs');
88 // Make sure typo is using our dir permissions
89 $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = decoct($CFG->directorypermissions);
91 // Default mask for Typo
92 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = $CFG->directorypermissions;
94 // This full path constants must be defined too, transforming backslashes
95 // to forward slashed because Typo3 requires it.
96 if (!defined('PATH_t3lib')) {
97 define('PATH_t3lib', str_replace('\\','/',$CFG->libdir.'/typo3/'));
98 define('PATH_typo3', str_replace('\\','/',$CFG->libdir.'/typo3/'));
99 define('PATH_site', str_replace('\\','/',$CFG->tempdir.'/'));
100 define('TYPO3_OS', stristr(PHP_OS,'win')&&!stristr(PHP_OS,'darwin')?'WIN':'');
103 $typo3cs = new t3lib_cs();
105 return $typo3cs;
109 * Reset internal textlib caches.
110 * @static
112 public static function reset_caches() {
113 self::typo3(true);
117 * Standardise charset name
119 * Please note it does not mean the returned charset is actually supported.
121 * @static
122 * @param string $charset raw charset name
123 * @return string normalised lowercase charset name
125 public static function parse_charset($charset) {
126 $charset = strtolower($charset);
128 // shortcuts so that we do not have to load typo3 on every page
130 if ($charset === 'utf8' or $charset === 'utf-8') {
131 return 'utf-8';
134 if (preg_match('/^(cp|win|windows)-?(12[0-9]{2})$/', $charset, $matches)) {
135 return 'windows-'.$matches[2];
138 if (preg_match('/^iso-8859-[0-9]+$/', $charset, $matches)) {
139 return $charset;
142 if ($charset === 'euc-jp') {
143 return 'euc-jp';
145 if ($charset === 'iso-2022-jp') {
146 return 'iso-2022-jp';
148 if ($charset === 'shift-jis' or $charset === 'shift_jis') {
149 return 'shift_jis';
151 if ($charset === 'gb2312') {
152 return 'gb2312';
154 if ($charset === 'gb18030') {
155 return 'gb18030';
158 // fallback to typo3
159 return self::typo3()->parse_charset($charset);
163 * Converts the text between different encodings. It uses iconv extension with //TRANSLIT parameter,
164 * falls back to typo3. If both source and target are utf-8 it tries to fix invalid characters only.
166 * @param string $text
167 * @param string $fromCS source encoding
168 * @param string $toCS result encoding
169 * @return string|bool converted string or false on error
171 public static function convert($text, $fromCS, $toCS='utf-8') {
172 $fromCS = self::parse_charset($fromCS);
173 $toCS = self::parse_charset($toCS);
175 $text = (string)$text; // we can work only with strings
177 if ($text === '') {
178 return '';
181 if ($fromCS === 'utf-8') {
182 $text = fix_utf8($text);
183 if ($toCS === 'utf-8') {
184 return $text;
188 if ($toCS === 'ascii') {
189 // Try to normalize the conversion a bit.
190 $text = self::specialtoascii($text, $fromCS);
193 // Prevent any error notices, do not use //IGNORE so that we get
194 // consistent result from Typo3 if iconv fails.
195 $result = @iconv($fromCS, $toCS.'//TRANSLIT', $text);
197 if ($result === false or $result === '') {
198 // note: iconv is prone to return empty string when invalid char encountered, or false if encoding unsupported
199 $oldlevel = error_reporting(E_PARSE);
200 $result = self::typo3()->conv((string)$text, $fromCS, $toCS);
201 error_reporting($oldlevel);
204 return $result;
208 * Multibyte safe substr() function, uses mbstring or iconv for UTF-8, falls back to typo3.
210 * @param string $text string to truncate
211 * @param int $start negative value means from end
212 * @param int $len maximum length of characters beginning from start
213 * @param string $charset encoding of the text
214 * @return string portion of string specified by the $start and $len
216 public static function substr($text, $start, $len=null, $charset='utf-8') {
217 $charset = self::parse_charset($charset);
219 if ($charset === 'utf-8') {
220 if (function_exists('mb_substr')) {
221 // this is much faster than iconv - see MDL-31142
222 if ($len === null) {
223 $oldcharset = mb_internal_encoding();
224 mb_internal_encoding('UTF-8');
225 $result = mb_substr($text, $start);
226 mb_internal_encoding($oldcharset);
227 return $result;
228 } else {
229 return mb_substr($text, $start, $len, 'UTF-8');
232 } else {
233 if ($len === null) {
234 $len = iconv_strlen($text, 'UTF-8');
236 return iconv_substr($text, $start, $len, 'UTF-8');
240 $oldlevel = error_reporting(E_PARSE);
241 if ($len === null) {
242 $result = self::typo3()->substr($charset, (string)$text, $start);
243 } else {
244 $result = self::typo3()->substr($charset, (string)$text, $start, $len);
246 error_reporting($oldlevel);
248 return $result;
252 * Finds the last occurrence of a character in a string within another.
253 * UTF-8 ONLY safe mb_strrchr().
255 * @param string $haystack The string from which to get the last occurrence of needle.
256 * @param string $needle The string to find in haystack.
257 * @param boolean $part If true, returns the portion before needle, else return the portion after (including needle).
258 * @return string|false False when not found.
259 * @since 2.4.6, 2.5.2, 2.6
261 public static function strrchr($haystack, $needle, $part = false) {
263 if (function_exists('mb_strrchr')) {
264 return mb_strrchr($haystack, $needle, $part, 'UTF-8');
267 $pos = self::strrpos($haystack, $needle);
268 if ($pos === false) {
269 return false;
272 $length = null;
273 if ($part) {
274 $length = $pos;
275 $pos = 0;
278 return self::substr($haystack, $pos, $length, 'utf-8');
282 * Multibyte safe strlen() function, uses mbstring or iconv for UTF-8, falls back to typo3.
284 * @param string $text input string
285 * @param string $charset encoding of the text
286 * @return int number of characters
288 public static function strlen($text, $charset='utf-8') {
289 $charset = self::parse_charset($charset);
291 if ($charset === 'utf-8') {
292 if (function_exists('mb_strlen')) {
293 return mb_strlen($text, 'UTF-8');
294 } else {
295 return iconv_strlen($text, 'UTF-8');
299 $oldlevel = error_reporting(E_PARSE);
300 $result = self::typo3()->strlen($charset, (string)$text);
301 error_reporting($oldlevel);
303 return $result;
307 * Multibyte safe strtolower() function, uses mbstring, falls back to typo3.
309 * @param string $text input string
310 * @param string $charset encoding of the text (may not work for all encodings)
311 * @return string lower case text
313 public static function strtolower($text, $charset='utf-8') {
314 $charset = self::parse_charset($charset);
316 if ($charset === 'utf-8' and function_exists('mb_strtolower')) {
317 return mb_strtolower($text, 'UTF-8');
320 $oldlevel = error_reporting(E_PARSE);
321 $result = self::typo3()->conv_case($charset, (string)$text, 'toLower');
322 error_reporting($oldlevel);
324 return $result;
328 * Multibyte safe strtoupper() function, uses mbstring, falls back to typo3.
330 * @param string $text input string
331 * @param string $charset encoding of the text (may not work for all encodings)
332 * @return string upper case text
334 public static function strtoupper($text, $charset='utf-8') {
335 $charset = self::parse_charset($charset);
337 if ($charset === 'utf-8' and function_exists('mb_strtoupper')) {
338 return mb_strtoupper($text, 'UTF-8');
341 $oldlevel = error_reporting(E_PARSE);
342 $result = self::typo3()->conv_case($charset, (string)$text, 'toUpper');
343 error_reporting($oldlevel);
345 return $result;
349 * Find the position of the first occurrence of a substring in a string.
350 * UTF-8 ONLY safe strpos(), uses mbstring, falls back to iconv.
352 * @param string $haystack the string to search in
353 * @param string $needle one or more charachters to search for
354 * @param int $offset offset from begining of string
355 * @return int the numeric position of the first occurrence of needle in haystack.
357 public static function strpos($haystack, $needle, $offset=0) {
358 if (function_exists('mb_strpos')) {
359 return mb_strpos($haystack, $needle, $offset, 'UTF-8');
360 } else {
361 return iconv_strpos($haystack, $needle, $offset, 'UTF-8');
366 * Find the position of the last occurrence of a substring in a string
367 * UTF-8 ONLY safe strrpos(), uses mbstring, falls back to iconv.
369 * @param string $haystack the string to search in
370 * @param string $needle one or more charachters to search for
371 * @return int the numeric position of the last occurrence of needle in haystack
373 public static function strrpos($haystack, $needle) {
374 if (function_exists('mb_strrpos')) {
375 return mb_strrpos($haystack, $needle, null, 'UTF-8');
376 } else {
377 return iconv_strrpos($haystack, $needle, 'UTF-8');
382 * Try to convert upper unicode characters to plain ascii,
383 * the returned string may contain unconverted unicode characters.
385 * @param string $text input string
386 * @param string $charset encoding of the text
387 * @return string converted ascii string
389 public static function specialtoascii($text, $charset='utf-8') {
390 $charset = self::parse_charset($charset);
391 $oldlevel = error_reporting(E_PARSE);
392 $result = self::typo3()->specCharsToASCII($charset, (string)$text);
393 error_reporting($oldlevel);
394 return $result;
398 * Generate a correct base64 encoded header to be used in MIME mail messages.
399 * This function seems to be 100% compliant with RFC1342. Credits go to:
400 * paravoid (http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283).
402 * @param string $text input string
403 * @param string $charset encoding of the text
404 * @return string base64 encoded header
406 public static function encode_mimeheader($text, $charset='utf-8') {
407 if (empty($text)) {
408 return (string)$text;
410 // Normalize charset
411 $charset = self::parse_charset($charset);
412 // If the text is pure ASCII, we don't need to encode it
413 if (self::convert($text, $charset, 'ascii') == $text) {
414 return $text;
416 // Although RFC says that line feed should be \r\n, it seems that
417 // some mailers double convert \r, so we are going to use \n alone
418 $linefeed="\n";
419 // Define start and end of every chunk
420 $start = "=?$charset?B?";
421 $end = "?=";
422 // Accumulate results
423 $encoded = '';
424 // Max line length is 75 (including start and end)
425 $length = 75 - strlen($start) - strlen($end);
426 // Multi-byte ratio
427 $multilength = self::strlen($text, $charset);
428 // Detect if strlen and friends supported
429 if ($multilength === false) {
430 if ($charset == 'GB18030' or $charset == 'gb18030') {
431 while (strlen($text)) {
432 // try to encode first 22 chars - we expect most chars are two bytes long
433 if (preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,22}/m', $text, $matches)) {
434 $chunk = $matches[0];
435 $encchunk = base64_encode($chunk);
436 if (strlen($encchunk) > $length) {
437 // find first 11 chars - each char in 4 bytes - worst case scenario
438 preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,11}/m', $text, $matches);
439 $chunk = $matches[0];
440 $encchunk = base64_encode($chunk);
442 $text = substr($text, strlen($chunk));
443 $encoded .= ' '.$start.$encchunk.$end.$linefeed;
444 } else {
445 break;
448 $encoded = trim($encoded);
449 return $encoded;
450 } else {
451 return false;
454 $ratio = $multilength / strlen($text);
455 // Base64 ratio
456 $magic = $avglength = floor(3 * $length * $ratio / 4);
457 // basic infinite loop protection
458 $maxiterations = strlen($text)*2;
459 $iteration = 0;
460 // Iterate over the string in magic chunks
461 for ($i=0; $i <= $multilength; $i+=$magic) {
462 if ($iteration++ > $maxiterations) {
463 return false; // probably infinite loop
465 $magic = $avglength;
466 $offset = 0;
467 // Ensure the chunk fits in length, reducing magic if necessary
468 do {
469 $magic -= $offset;
470 $chunk = self::substr($text, $i, $magic, $charset);
471 $chunk = base64_encode($chunk);
472 $offset++;
473 } while (strlen($chunk) > $length);
474 // This chunk doesn't break any multi-byte char. Use it.
475 if ($chunk)
476 $encoded .= ' '.$start.$chunk.$end.$linefeed;
478 // Strip the first space and the last linefeed
479 $encoded = substr($encoded, 1, -strlen($linefeed));
481 return $encoded;
485 * Returns HTML entity transliteration table.
486 * @return array with (html entity => utf-8) elements
488 protected static function get_entities_table() {
489 static $trans_tbl = null;
491 // Generate/create $trans_tbl
492 if (!isset($trans_tbl)) {
493 if (version_compare(phpversion(), '5.3.4') < 0) {
494 $trans_tbl = array();
495 foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key) {
496 $trans_tbl[$key] = self::convert($val, 'ISO-8859-1', 'utf-8');
499 } else if (version_compare(phpversion(), '5.4.0') < 0) {
500 $trans_tbl = get_html_translation_table(HTML_ENTITIES, ENT_COMPAT, 'UTF-8');
501 $trans_tbl = array_flip($trans_tbl);
503 } else {
504 $trans_tbl = get_html_translation_table(HTML_ENTITIES, ENT_COMPAT | ENT_HTML401, 'UTF-8');
505 $trans_tbl = array_flip($trans_tbl);
509 return $trans_tbl;
513 * Converts all the numeric entities &#nnnn; or &#xnnn; to UTF-8
514 * Original from laurynas dot butkus at gmail at:
515 * http://php.net/manual/en/function.html-entity-decode.php#75153
516 * with some custom mods to provide more functionality
518 * @param string $str input string
519 * @param boolean $htmlent convert also html entities (defaults to true)
520 * @return string encoded UTF-8 string
522 public static function entities_to_utf8($str, $htmlent=true) {
523 static $callback1 = null ;
524 static $callback2 = null ;
526 if (!$callback1 or !$callback2) {
527 $callback1 = create_function('$matches', 'return core_text::code2utf8(hexdec($matches[1]));');
528 $callback2 = create_function('$matches', 'return core_text::code2utf8($matches[1]);');
531 $result = (string)$str;
532 $result = preg_replace_callback('/&#x([0-9a-f]+);/i', $callback1, $result);
533 $result = preg_replace_callback('/&#([0-9]+);/', $callback2, $result);
535 // Replace literal entities (if desired)
536 if ($htmlent) {
537 $trans_tbl = self::get_entities_table();
538 // It should be safe to search for ascii strings and replace them with utf-8 here.
539 $result = strtr($result, $trans_tbl);
541 // Return utf8-ised string
542 return $result;
546 * Converts all Unicode chars > 127 to numeric entities &#nnnn; or &#xnnn;.
548 * @param string $str input string
549 * @param boolean $dec output decadic only number entities
550 * @param boolean $nonnum remove all non-numeric entities
551 * @return string converted string
553 public static function utf8_to_entities($str, $dec=false, $nonnum=false) {
554 static $callback = null ;
556 if ($nonnum) {
557 $str = self::entities_to_utf8($str, true);
560 // Avoid some notices from Typo3 code
561 $oldlevel = error_reporting(E_PARSE);
562 $result = self::typo3()->utf8_to_entities((string)$str);
563 error_reporting($oldlevel);
565 if ($dec) {
566 if (!$callback) {
567 $callback = create_function('$matches', 'return \'&#\'.(hexdec($matches[1])).\';\';');
569 $result = preg_replace_callback('/&#x([0-9a-f]+);/i', $callback, $result);
572 return $result;
576 * Removes the BOM from unicode string {@link http://unicode.org/faq/utf_bom.html}
578 * @param string $str input string
579 * @return string
581 public static function trim_utf8_bom($str) {
582 $bom = "\xef\xbb\xbf";
583 if (strpos($str, $bom) === 0) {
584 return substr($str, strlen($bom));
586 return $str;
590 * Returns encoding options for select boxes, utf-8 and platform encoding first
592 * @return array encodings
594 public static function get_encodings() {
595 $encodings = array();
596 $encodings['UTF-8'] = 'UTF-8';
597 $winenc = strtoupper(get_string('localewincharset', 'langconfig'));
598 if ($winenc != '') {
599 $encodings[$winenc] = $winenc;
601 $nixenc = strtoupper(get_string('oldcharset', 'langconfig'));
602 $encodings[$nixenc] = $nixenc;
604 foreach (self::typo3()->synonyms as $enc) {
605 $enc = strtoupper($enc);
606 $encodings[$enc] = $enc;
608 return $encodings;
612 * Returns the utf8 string corresponding to the unicode value
613 * (from php.net, courtesy - romans@void.lv)
615 * @param int $num one unicode value
616 * @return string the UTF-8 char corresponding to the unicode value
618 public static function code2utf8($num) {
619 if ($num < 128) {
620 return chr($num);
622 if ($num < 2048) {
623 return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
625 if ($num < 65536) {
626 return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
628 if ($num < 2097152) {
629 return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
631 return '';
635 * Returns the code of the given UTF-8 character
637 * @param string $utf8char one UTF-8 character
638 * @return int the code of the given character
640 public static function utf8ord($utf8char) {
641 if ($utf8char == '') {
642 return 0;
644 $ord0 = ord($utf8char{0});
645 if ($ord0 >= 0 && $ord0 <= 127) {
646 return $ord0;
648 $ord1 = ord($utf8char{1});
649 if ($ord0 >= 192 && $ord0 <= 223) {
650 return ($ord0 - 192) * 64 + ($ord1 - 128);
652 $ord2 = ord($utf8char{2});
653 if ($ord0 >= 224 && $ord0 <= 239) {
654 return ($ord0 - 224) * 4096 + ($ord1 - 128) * 64 + ($ord2 - 128);
656 $ord3 = ord($utf8char{3});
657 if ($ord0 >= 240 && $ord0 <= 247) {
658 return ($ord0 - 240) * 262144 + ($ord1 - 128 )* 4096 + ($ord2 - 128) * 64 + ($ord3 - 128);
660 return false;
664 * Makes first letter of each word capital - words must be separated by spaces.
665 * Use with care, this function does not work properly in many locales!!!
667 * @param string $text input string
668 * @return string
670 public static function strtotitle($text) {
671 if (empty($text)) {
672 return $text;
675 if (function_exists('mb_convert_case')) {
676 return mb_convert_case($text, MB_CASE_TITLE, 'UTF-8');
679 $text = self::strtolower($text);
680 $words = explode(' ', $text);
681 foreach ($words as $i=>$word) {
682 $length = self::strlen($word);
683 if (!$length) {
684 continue;
686 } else if ($length == 1) {
687 $words[$i] = self::strtoupper($word);
689 } else {
690 $letter = self::substr($word, 0, 1);
691 $letter = self::strtoupper($letter);
692 $rest = self::substr($word, 1);
693 $words[$i] = $letter.$rest;
696 return implode(' ', $words);
701 * Legacy tectlib.
702 * @deprecated since 2.6, use core_text:: instead.
704 class textlib extends core_text {
706 * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
708 * @param array $arr array to be sorted (reference)
709 * @param int $sortflag One of Collator::SORT_REGULAR, Collator::SORT_NUMERIC, Collator::SORT_STRING
710 * @return void modifies parameter
712 public static function asort(array &$arr, $sortflag = null) {
713 debugging('textlib::asort has been superseeded by collatorlib::asort please upgrade your code to use that', DEBUG_DEVELOPER);
714 collatorlib::asort($arr, $sortflag);