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 // shortcuts so that we do not have to load typo on every page
133 $charset = strtolower($charset);
141 case 'windowns-1250':
142 return 'windows-1250';
146 case 'windowns-1252':
147 return 'windows-1252';
161 //TODO: add more common charsets here - all win and unix encodings from our lang packs
166 return self::typo3()->parse_charset($charset);
170 * Converts the text between different encodings. It uses iconv extension with //TRANSLIT parameter.
171 * Returns false if fails.
173 * @param string $text
174 * @param string $fromCS source encoding
175 * @param string $toCS result encoding
176 * @return string|bool
178 public static function convert($text, $fromCS, $toCS='utf-8') {
179 $fromCS = self::parse_charset($fromCS);
180 $toCS = self::parse_charset($toCS);
182 return iconv($fromCS, $toCS.'//TRANSLIT', $text);
186 * Multibyte safe substr() function, uses mbstring if available.
188 * @param string $text
189 * @param int $start negative value means from end
191 * @param string $charset encoding of the text
194 public static function substr($text, $start, $len=null, $charset='utf-8') {
195 $charset = self::parse_charset($charset);
197 return iconv_substr($text, $start, $len, $charset);
201 * Multibyte safe strlen() function, uses mbstring if available.
203 * @param string $text
204 * @param string $charset encoding of the text
205 * @return int number of characters
207 public static function strlen($text, $charset='utf-8') {
208 $charset = self::parse_charset($charset);
210 return iconv_strlen($text, $charset);
214 * Multibyte safe strtolower() function, uses mbstring if available.
216 * @param string $text
217 * @param string $charset encoding of the text (may not work for all encodings)
218 * @return string lower case text
220 public static function strtolower($text, $charset='utf-8') {
221 $charset = self::parse_charset($charset);
223 if (function_exists('mb_strtolower')) {
224 return mb_strtolower($text, $charset);
227 // Avoid some notices from Typo3 code
228 $oldlevel = error_reporting(E_PARSE);
229 // Call Typo3 conv_case() function. It will do all the work
230 $result = self::typo3()->conv_case($charset, $text, 'toLower');
231 // Restore original debug level
232 error_reporting($oldlevel);
237 * Multibyte safe strtoupper() function, uses mbstring if available.
239 * @param string $text
240 * @param string $charset encoding of the text (may not work for all encodings)
241 * @return string upper case text
243 public static function strtoupper($text, $charset='utf-8') {
244 $charset = self::parse_charset($charset);
246 if (function_exists('mb_strtoupper')) {
247 return mb_strtoupper($text, $charset);
250 // Avoid some notices from Typo3 code
251 $oldlevel = error_reporting(E_PARSE);
252 // Call Typo3 conv_case() function. It will do all the work
253 $result = self::typo3()->conv_case($charset, $text, 'toUpper');
254 // Restore original debug level
255 error_reporting($oldlevel);
260 * UTF-8 ONLY safe strpos().
262 * @param string $haystack
263 * @param string $needle
267 public static function strpos($haystack, $needle, $offset=0) {
268 return iconv_strpos($haystack, $needle, $offset, 'utf-8');
272 * UTF-8 ONLY safe strrpos().
274 * @param string $haystack
275 * @param string $needle
278 public static function strrpos($haystack, $needle) {
279 return iconv_strrpos($haystack, $needle, 'utf-8');
283 * Try to convert upper unicode characters to plain ascii,
284 * the returned string may contain unconverted unicode characters.
286 * @param string $text
287 * @param string $charset encoding of the text
290 public static function specialtoascii($text, $charset='utf-8') {
291 $charset = self::parse_charset($charset);
292 // Avoid some notices from Typo3 code
293 $oldlevel = error_reporting(E_PARSE);
294 $result = self::typo3()->specCharsToASCII($charset, $text);
295 // Restore original debug level
296 error_reporting($oldlevel);
301 * Generate a correct base64 encoded header to be used in MIME mail messages.
302 * This function seems to be 100% compliant with RFC1342. Credits go to:
303 * paravoid (http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283).
305 * @param string $text
306 * @param string $charset encoding of the text
309 public static function encode_mimeheader($text, $charset='utf-8') {
311 return (string)$text;
314 $charset = self::parse_charset($charset);
315 // If the text is pure ASCII, we don't need to encode it
316 if (self::convert($text, $charset, 'ascii') == $text) {
319 // Although RFC says that line feed should be \r\n, it seems that
320 // some mailers double convert \r, so we are going to use \n alone
322 // Define start and end of every chunk
323 $start = "=?$charset?B?";
325 // Accumulate results
327 // Max line length is 75 (including start and end)
328 $length = 75 - strlen($start) - strlen($end);
330 $multilength = self::strlen($text, $charset);
331 // Detect if strlen and friends supported
332 if ($multilength === false) {
333 if ($charset == 'GB18030' or $charset == 'gb18030') {
334 while (strlen($text)) {
335 // try to encode first 22 chars - we expect most chars are two bytes long
336 if (preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,22}/m', $text, $matches)) {
337 $chunk = $matches[0];
338 $encchunk = base64_encode($chunk);
339 if (strlen($encchunk) > $length) {
340 // find first 11 chars - each char in 4 bytes - worst case scenario
341 preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,11}/m', $text, $matches);
342 $chunk = $matches[0];
343 $encchunk = base64_encode($chunk);
345 $text = substr($text, strlen($chunk));
346 $encoded .= ' '.$start.$encchunk.$end.$linefeed;
351 $encoded = trim($encoded);
357 $ratio = $multilength / strlen($text);
359 $magic = $avglength = floor(3 * $length * $ratio / 4);
360 // basic infinite loop protection
361 $maxiterations = strlen($text)*2;
363 // Iterate over the string in magic chunks
364 for ($i=0; $i <= $multilength; $i+=$magic) {
365 if ($iteration++ > $maxiterations) {
366 return false; // probably infinite loop
370 // Ensure the chunk fits in length, reducing magic if necessary
373 $chunk = self::substr($text, $i, $magic, $charset);
374 $chunk = base64_encode($chunk);
376 } while (strlen($chunk) > $length);
377 // This chunk doesn't break any multi-byte char. Use it.
379 $encoded .= ' '.$start.$chunk.$end.$linefeed;
381 // Strip the first space and the last linefeed
382 $encoded = substr($encoded, 1, -strlen($linefeed));
388 * Converts all the numeric entities &#nnnn; or &#xnnn; to UTF-8
389 * Original from laurynas dot butkus at gmail at:
390 * http://php.net/manual/en/function.html-entity-decode.php#75153
391 * with some custom mods to provide more functionality
393 * @param string $str input string
394 * @param boolean $htmlent convert also html entities (defaults to true)
397 * NOTE: we could have used typo3 entities_to_utf8() here
398 * but the direct alternative used runs 400% quicker
399 * and uses 0.5Mb less memory, so, let's use it
400 * (tested against 10^6 conversions)
402 public static function entities_to_utf8($str, $htmlent=true) {
403 static $trans_tbl; // Going to use static transliteration table
405 // Replace numeric entities
406 $result = preg_replace('~&#x([0-9a-f]+);~ei', 'textlib::code2utf8(hexdec("\\1"))', $str);
407 $result = preg_replace('~&#([0-9]+);~e', 'textlib::code2utf8(\\1)', $result);
409 // Replace literal entities (if desired)
411 // Generate/create $trans_tbl
412 if (!isset($trans_tbl)) {
413 $trans_tbl = array();
414 foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key) {
415 $trans_tbl[$key] = utf8_encode($val);
418 $result = strtr($result, $trans_tbl);
420 // Return utf8-ised string
425 * Converts all Unicode chars > 127 to numeric entities &#nnnn; or &#xnnn;.
427 * @param string $str input string
428 * @param boolean $dec output decadic only number entities
429 * @param boolean $nonnum remove all non-numeric entities
430 * @return string converted string
432 public static function utf8_to_entities($str, $dec=false, $nonnum=false) {
433 // Avoid some notices from Typo3 code
434 $oldlevel = error_reporting(E_PARSE);
436 $str = self::typo3()->entities_to_utf8($str, true);
438 $result = self::typo3()->utf8_to_entities($str);
440 $result = preg_replace('/&#x([0-9a-f]+);/ie', "'&#'.hexdec('$1').';'", $result);
442 // Restore original debug level
443 error_reporting($oldlevel);
448 * Removes the BOM from unicode string - see http://unicode.org/faq/utf_bom.html
453 public static function trim_utf8_bom($str) {
454 $bom = "\xef\xbb\xbf";
455 if (strpos($str, $bom) === 0) {
456 return substr($str, strlen($bom));
462 * Returns encoding options for select boxes, utf-8 and platform encoding first
463 * @return array encodings
465 public static function get_encodings() {
466 $encodings = array();
467 $encodings['UTF-8'] = 'UTF-8';
468 $winenc = strtoupper(get_string('localewincharset', 'langconfig'));
470 $encodings[$winenc] = $winenc;
472 $nixenc = strtoupper(get_string('oldcharset', 'langconfig'));
473 $encodings[$nixenc] = $nixenc;
475 foreach (self::typo3()->synonyms as $enc) {
476 $enc = strtoupper($enc);
477 $encodings[$enc] = $enc;
483 * Returns the utf8 string corresponding to the unicode value
484 * (from php.net, courtesy - romans@void.lv)
486 * @param int $num one unicode value
487 * @return string the UTF-8 char corresponding to the unicode value
489 public static function code2utf8($num) {
494 return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
497 return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
499 if ($num < 2097152) {
500 return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
506 * Makes first letter of each word capital - words must be separated by spaces.
507 * Use with care, this function does not work properly in many locales!!!
509 * @param string $text
512 public static function strtotitle($text) {
517 if (function_exists('mb_convert_case')) {
518 return mb_convert_case($text, MB_CASE_TITLE, 'UTF-8');
521 $text = self::strtolower($text);
522 $words = explode(' ', $text);
523 foreach ($words as $i=>$word) {
524 $length = self::strlen($word);
528 } else if ($length == 1) {
529 $words[$i] = self::strtoupper($word);
532 $letter = self::substr($word, 0, 1);
533 $letter = self::strtoupper($letter);
534 $rest = self::substr($word, 1);
535 $words[$i] = $letter.$rest;
538 return implode(' ', $words);
542 * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
544 * Note: this function is using current moodle locale.
546 * @param array $arr array to be sorted
547 * @return void, modifies parameter
549 public static function asort(array &$arr) {
550 if (function_exists('collator_asort')) {
551 if ($coll = collator_create(get_string('locale', 'langconfig'))) {
552 collator_asort($coll, $arr);
556 asort($arr, SORT_LOCALE_STRING);