2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
20 * @copyright (C) 2001-3001 Eloy Lafuente (stronk7) {@link http://contiento.com}
21 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 defined('MOODLE_INTERNAL') || die();
27 * Original singleton helper function, please use static methods instead,
28 * ex: textlib::convert()
31 * @return textlib instance
33 function textlib_get_instance() {
39 * This class is used to manipulate strings under Moodle 1.6 an later. As
40 * utf-8 text become mandatory a pool of safe functions under this encoding
41 * become necessary. The name of the methods is exactly the
42 * same than their PHP originals.
44 * A big part of this class acts as a wrapper over the Typo3 charset library,
45 * really a cool group of utilities to handle texts and encoding conversion.
47 * Take a look to its own copyright and license details.
49 * IMPORTANT Note: Typo3 libraries always expect lowercase charsets to use 100%
50 * its capabilities so, don't forget to make the conversion
51 * from every wrapper function!
55 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
56 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
61 * Return t3lib helper class
64 protected static function typo3() {
65 static $typo3cs = null;
67 if (isset($typo3cs)) {
74 require_once($CFG->libdir.'/typo3/class.t3lib_cs.php');
75 require_once($CFG->libdir.'/typo3/class.t3lib_div.php');
77 // If ICONV is available, lets Typo3 library use it for convert
78 if (extension_loaded('iconv')) {
79 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod'] = 'iconv';
80 // Else if mbstring is available, lets Typo3 library use it
81 } else if (extension_loaded('mbstring')) {
82 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod'] = 'mbstring';
83 // Else if recode is available, lets Typo3 library use it
84 } else if (extension_loaded('recode')) {
85 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod'] = 'recode';
87 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod'] = '';
90 // If mbstring is available, lets Typo3 library use it for functions
91 if (extension_loaded('mbstring')) {
92 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] = 'mbstring';
94 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] = '';
97 // Tell Typo3 we are curl enabled always (mandatory since 2.0)
98 $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] = '1';
100 // And this directory must exist to allow Typo to cache conversion
101 // tables when using internal functions
102 make_upload_directory('temp/typo3temp/cs');
104 // Make sure typo is using our dir permissions
105 $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = decoct($CFG->directorypermissions);
107 // Default mask for Typo
108 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = $CFG->directorypermissions;
110 // This full path constants must be defined too, transforming backslashes
111 // to forward slashed because Typo3 requires it.
112 define ('PATH_t3lib', str_replace('\\','/',$CFG->libdir.'/typo3/'));
113 define ('PATH_typo3', str_replace('\\','/',$CFG->libdir.'/typo3/'));
114 define ('PATH_site', str_replace('\\','/',$CFG->dataroot.'/temp/'));
115 define ('TYPO3_OS', stristr(PHP_OS,'win')&&!stristr(PHP_OS,'darwin')?'WIN':'');
117 $typo3cs = new t3lib_cs();
123 * Standardise charset name
125 * Please note it does not mean the returned charset is actually supported.
128 * @param string $charset raw charset name
129 * @return string normalised lowercase charset name
131 public static function parse_charset($charset) {
132 $charset = strtolower($charset);
134 // shortcuts so that we do not have to load typo3 on every page
136 if ($charset === 'utf8' or $charset === 'utf-8') {
140 if (preg_match('/^(cp|win|windows)-?(12[0-9]{2})$/', $charset, $matches)) {
141 return 'windows-'.$matches[2];
144 if (preg_match('/^iso-8859-[0-9]+$/', $charset, $matches)) {
149 return self::typo3()->parse_charset($charset);
153 * Converts the text between different encodings. It uses iconv extension with //TRANSLIT parameter
154 * or mb_string if iconv conversion fails.
155 * Returns false if fails.
157 * @param string $text
158 * @param string $fromCS source encoding
159 * @param string $toCS result encoding
160 * @return string|bool converted string or false on error
162 public static function convert($text, $fromCS, $toCS='utf-8') {
163 $fromCS = self::parse_charset($fromCS);
164 $toCS = self::parse_charset($toCS);
166 $text = (string)$text; // we can work only with strings
172 $result = iconv($fromCS, $toCS.'//TRANSLIT', $text);
174 if ($result === false or $result === '') {
175 // note: iconv is prone to return empty string when invalid char encountered,
176 // mbstring ignores invalid chars completely, mbstring may support more encodings too
177 if (function_exists('mb_convert_encoding')) {
178 $result = mb_convert_encoding($text, $toCS, $fromCS);
186 * Multibyte safe substr() function, uses iconv,
187 * falls back on error to mbstring if available.
189 * @param string $text
190 * @param int $start negative value means from end
192 * @param string $charset encoding of the text
195 public static function substr($text, $start, $len=null, $charset='utf-8') {
196 $charset = self::parse_charset($charset);
198 return iconv_substr($text, $start, $len, $charset);
200 if ($result === false) {
201 if (function_exists('mb_substr')) {
202 $result = mb_substr($text, $start, $len, $charset);
210 * Multibyte safe strlen() function, uses iconv,
211 * falls back on error to mbstring if available.
213 * @param string $text
214 * @param string $charset encoding of the text
215 * @return int number of characters
217 public static function strlen($text, $charset='utf-8') {
218 $charset = self::parse_charset($charset);
220 $result = iconv_strlen($text, $charset);
222 if ($result === false) {
223 if (function_exists('mb_strlen')) {
224 $result = mb_strlen($text, $charset);
232 * Multibyte safe strtolower() function, uses mbstring if available.
234 * @param string $text
235 * @param string $charset encoding of the text (may not work for all encodings)
236 * @return string lower case text
238 public static function strtolower($text, $charset='utf-8') {
239 $charset = self::parse_charset($charset);
241 if (function_exists('mb_strtolower')) {
242 return mb_strtolower($text, $charset);
245 // Avoid some notices from Typo3 code
246 $oldlevel = error_reporting(E_PARSE);
247 // Call Typo3 conv_case() function. It will do all the work
248 $result = self::typo3()->conv_case($charset, $text, 'toLower');
249 // Restore original debug level
250 error_reporting($oldlevel);
255 * Multibyte safe strtoupper() function, uses mbstring if available.
257 * @param string $text
258 * @param string $charset encoding of the text (may not work for all encodings)
259 * @return string upper case text
261 public static function strtoupper($text, $charset='utf-8') {
262 $charset = self::parse_charset($charset);
264 if (function_exists('mb_strtoupper')) {
265 return mb_strtoupper($text, $charset);
268 // Avoid some notices from Typo3 code
269 $oldlevel = error_reporting(E_PARSE);
270 // Call Typo3 conv_case() function. It will do all the work
271 $result = self::typo3()->conv_case($charset, $text, 'toUpper');
272 // Restore original debug level
273 error_reporting($oldlevel);
278 * UTF-8 ONLY safe strpos().
280 * @param string $haystack
281 * @param string $needle
285 public static function strpos($haystack, $needle, $offset=0) {
286 return iconv_strpos($haystack, $needle, $offset, 'utf-8');
290 * UTF-8 ONLY safe strrpos().
292 * @param string $haystack
293 * @param string $needle
296 public static function strrpos($haystack, $needle) {
297 return iconv_strrpos($haystack, $needle, 'utf-8');
301 * Try to convert upper unicode characters to plain ascii,
302 * the returned string may contain unconverted unicode characters.
304 * @param string $text
305 * @param string $charset encoding of the text
308 public static function specialtoascii($text, $charset='utf-8') {
309 $charset = self::parse_charset($charset);
310 // Avoid some notices from Typo3 code
311 $oldlevel = error_reporting(E_PARSE);
312 $result = self::typo3()->specCharsToASCII($charset, $text);
313 // Restore original debug level
314 error_reporting($oldlevel);
319 * Generate a correct base64 encoded header to be used in MIME mail messages.
320 * This function seems to be 100% compliant with RFC1342. Credits go to:
321 * paravoid (http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283).
323 * @param string $text
324 * @param string $charset encoding of the text
327 public static function encode_mimeheader($text, $charset='utf-8') {
329 return (string)$text;
332 $charset = self::parse_charset($charset);
333 // If the text is pure ASCII, we don't need to encode it
334 if (self::convert($text, $charset, 'ascii') == $text) {
337 // Although RFC says that line feed should be \r\n, it seems that
338 // some mailers double convert \r, so we are going to use \n alone
340 // Define start and end of every chunk
341 $start = "=?$charset?B?";
343 // Accumulate results
345 // Max line length is 75 (including start and end)
346 $length = 75 - strlen($start) - strlen($end);
348 $multilength = self::strlen($text, $charset);
349 // Detect if strlen and friends supported
350 if ($multilength === false) {
351 if ($charset == 'GB18030' or $charset == 'gb18030') {
352 while (strlen($text)) {
353 // try to encode first 22 chars - we expect most chars are two bytes long
354 if (preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,22}/m', $text, $matches)) {
355 $chunk = $matches[0];
356 $encchunk = base64_encode($chunk);
357 if (strlen($encchunk) > $length) {
358 // find first 11 chars - each char in 4 bytes - worst case scenario
359 preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,11}/m', $text, $matches);
360 $chunk = $matches[0];
361 $encchunk = base64_encode($chunk);
363 $text = substr($text, strlen($chunk));
364 $encoded .= ' '.$start.$encchunk.$end.$linefeed;
369 $encoded = trim($encoded);
375 $ratio = $multilength / strlen($text);
377 $magic = $avglength = floor(3 * $length * $ratio / 4);
378 // basic infinite loop protection
379 $maxiterations = strlen($text)*2;
381 // Iterate over the string in magic chunks
382 for ($i=0; $i <= $multilength; $i+=$magic) {
383 if ($iteration++ > $maxiterations) {
384 return false; // probably infinite loop
388 // Ensure the chunk fits in length, reducing magic if necessary
391 $chunk = self::substr($text, $i, $magic, $charset);
392 $chunk = base64_encode($chunk);
394 } while (strlen($chunk) > $length);
395 // This chunk doesn't break any multi-byte char. Use it.
397 $encoded .= ' '.$start.$chunk.$end.$linefeed;
399 // Strip the first space and the last linefeed
400 $encoded = substr($encoded, 1, -strlen($linefeed));
406 * Converts all the numeric entities &#nnnn; or &#xnnn; to UTF-8
407 * Original from laurynas dot butkus at gmail at:
408 * http://php.net/manual/en/function.html-entity-decode.php#75153
409 * with some custom mods to provide more functionality
411 * @param string $str input string
412 * @param boolean $htmlent convert also html entities (defaults to true)
415 * NOTE: we could have used typo3 entities_to_utf8() here
416 * but the direct alternative used runs 400% quicker
417 * and uses 0.5Mb less memory, so, let's use it
418 * (tested against 10^6 conversions)
420 public static function entities_to_utf8($str, $htmlent=true) {
421 static $trans_tbl; // Going to use static transliteration table
423 // Replace numeric entities
424 $result = preg_replace('~&#x([0-9a-f]+);~ei', 'textlib::code2utf8(hexdec("\\1"))', $str);
425 $result = preg_replace('~&#([0-9]+);~e', 'textlib::code2utf8(\\1)', $result);
427 // Replace literal entities (if desired)
429 // Generate/create $trans_tbl
430 if (!isset($trans_tbl)) {
431 $trans_tbl = array();
432 foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key) {
433 $trans_tbl[$key] = utf8_encode($val);
436 $result = strtr($result, $trans_tbl);
438 // Return utf8-ised string
443 * Converts all Unicode chars > 127 to numeric entities &#nnnn; or &#xnnn;.
445 * @param string $str input string
446 * @param boolean $dec output decadic only number entities
447 * @param boolean $nonnum remove all non-numeric entities
448 * @return string converted string
450 public static function utf8_to_entities($str, $dec=false, $nonnum=false) {
451 // Avoid some notices from Typo3 code
452 $oldlevel = error_reporting(E_PARSE);
454 $str = self::typo3()->entities_to_utf8($str, true);
456 $result = self::typo3()->utf8_to_entities($str);
458 $result = preg_replace('/&#x([0-9a-f]+);/ie', "'&#'.hexdec('$1').';'", $result);
460 // Restore original debug level
461 error_reporting($oldlevel);
466 * Removes the BOM from unicode string - see http://unicode.org/faq/utf_bom.html
471 public static function trim_utf8_bom($str) {
472 $bom = "\xef\xbb\xbf";
473 if (strpos($str, $bom) === 0) {
474 return substr($str, strlen($bom));
480 * Returns encoding options for select boxes, utf-8 and platform encoding first
481 * @return array encodings
483 public static function get_encodings() {
484 $encodings = array();
485 $encodings['UTF-8'] = 'UTF-8';
486 $winenc = strtoupper(get_string('localewincharset', 'langconfig'));
488 $encodings[$winenc] = $winenc;
490 $nixenc = strtoupper(get_string('oldcharset', 'langconfig'));
491 $encodings[$nixenc] = $nixenc;
493 foreach (self::typo3()->synonyms as $enc) {
494 $enc = strtoupper($enc);
495 $encodings[$enc] = $enc;
501 * Returns the utf8 string corresponding to the unicode value
502 * (from php.net, courtesy - romans@void.lv)
504 * @param int $num one unicode value
505 * @return string the UTF-8 char corresponding to the unicode value
507 public static function code2utf8($num) {
512 return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
515 return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
517 if ($num < 2097152) {
518 return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
524 * Makes first letter of each word capital - words must be separated by spaces.
525 * Use with care, this function does not work properly in many locales!!!
527 * @param string $text
530 public static function strtotitle($text) {
535 if (function_exists('mb_convert_case')) {
536 return mb_convert_case($text, MB_CASE_TITLE, 'UTF-8');
539 $text = self::strtolower($text);
540 $words = explode(' ', $text);
541 foreach ($words as $i=>$word) {
542 $length = self::strlen($word);
546 } else if ($length == 1) {
547 $words[$i] = self::strtoupper($word);
550 $letter = self::substr($word, 0, 1);
551 $letter = self::strtoupper($letter);
552 $rest = self::substr($word, 1);
553 $words[$i] = $letter.$rest;
556 return implode(' ', $words);
560 * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
562 * Note: this function is using current moodle locale.
564 * @param array $arr array to be sorted
565 * @return void, modifies parameter
567 public static function asort(array &$arr) {
568 if (function_exists('collator_asort')) {
569 if ($coll = collator_create(get_string('locale', 'langconfig'))) {
570 collator_asort($coll, $arr);
574 asort($arr, SORT_LOCALE_STRING);