MDL-27588 Fixed up several bugs with the formal_white theme
[moodle.git] / lib / textlib.class.php
blob1adceea660b3deb6dd0e36eaf2f5ef5106100ba4
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * @package core
20 * @subpackage lib
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 * As we implement the singleton pattern to use this class (only one instance
29 * is shared globally), we need this helper function
31 * IMPORTANT Note: Typo3 libraries always expect lowercase charsets to use 100%
32 * its capabilities so, don't forget to make the conversion
33 * from every wrapper function!
35 * @return textlib singleton instance of textlib
37 function textlib_get_instance() {
38 global $CFG;
40 static $instance = null;
42 if (!$instance) {
43 /// initialisation is delayed because we do not want this on each page ;-)
45 /// Required files
46 require_once($CFG->libdir.'/typo3/class.t3lib_cs.php');
47 require_once($CFG->libdir.'/typo3/class.t3lib_div.php');
49 /// If ICONV is available, lets Typo3 library use it for convert
50 if (extension_loaded('iconv')) {
51 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod'] = 'iconv';
52 /// Else if mbstring is available, lets Typo3 library use it
53 } else if (extension_loaded('mbstring')) {
54 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod'] = 'mbstring';
55 /// Else if recode is available, lets Typo3 library use it
56 } else if (extension_loaded('recode')) {
57 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod'] = 'recode';
58 } else {
59 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod'] = '';
62 /// If mbstring is available, lets Typo3 library use it for functions
63 if (extension_loaded('mbstring')) {
64 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] = 'mbstring';
65 } else {
66 $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] = '';
69 /// Tell Typo3 we are curl enabled always (mandatory since 2.0)
70 $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] = '1';
72 /// And this directory must exist to allow Typo to cache conversion
73 /// tables when using internal functions
74 make_upload_directory('temp/typo3temp/cs');
76 /// Make sure typo is using our dir permissions
77 $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = decoct($CFG->directorypermissions);
79 /// Default mask for Typo
80 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = $CFG->directorypermissions;
82 /// This full path constants must be defined too, transforming backslashes
83 /// to forward slashed beacuse Typo3 requires it.
84 define ('PATH_t3lib', str_replace('\\','/',$CFG->libdir.'/typo3/'));
85 define ('PATH_typo3', str_replace('\\','/',$CFG->libdir.'/typo3/'));
86 define ('PATH_site', str_replace('\\','/',$CFG->dataroot.'/temp/'));
87 define ('TYPO3_OS', stristr(PHP_OS,'win')&&!stristr(PHP_OS,'darwin')?'WIN':'');
89 $instance = new textlib();
91 return $instance;
94 /**
95 * This class is used to manipulate strings under Moodle 1.6 an later. As
96 * utf-8 text become mandatory a pool of safe functions under this encoding
97 * become necessary. The name of the methods is exactly the
98 * same than their PHP originals.
100 * A big part of this class acts as a wrapper over the Typo3 charset library,
101 * really a cool group of utilities to handle texts and encoding conversion.
103 * Take a look to its own copyright and license details.
105 * @package moodlecore
106 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
107 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
109 class textlib {
111 var $typo3cs;
114 * Standard constructor of the class. All it does is to instantiate
115 * a new t3lib_cs object to have all their functions ready.
117 * Instead of istantiating a lot of objects of this class everytime
118 * some of their functions is going to be used, you can invoke the:
119 * textlib_get_instance() function, avoiding the creation of them
120 * (following the singleton pattern)
122 function textlib() {
123 /// Instantiate a conversor object some of the methods in typo3
124 /// reference to $this and cannot be executed in a static context
125 $this->typo3cs = new t3lib_cs();
129 * Converts the text between different encodings. It will use iconv, mbstring
130 * or internal (typo3) methods to try such conversion. Returns false if fails.
132 function convert($text, $fromCS, $toCS='utf-8') {
133 /// Normalize charsets
134 $fromCS = $this->typo3cs->parse_charset($fromCS);
135 $toCS = $this->typo3cs->parse_charset($toCS);
136 /// Avoid some notices from Typo3 code
137 $oldlevel = error_reporting(E_PARSE);
138 /// Call Typo3 conv() function. It will do all the work
139 $result = $this->typo3cs->conv($text, $fromCS, $toCS);
140 /// Restore original debug level
141 error_reporting($oldlevel);
142 return $result;
146 * Multibyte safe substr() function, uses mbstring if available.
148 function substr($text, $start, $len=null, $charset='utf-8') {
149 /// Normalize charset
150 $charset = $this->typo3cs->parse_charset($charset);
151 /// Avoid some notices from Typo3 code
152 $oldlevel = error_reporting(E_PARSE);
153 /// Call Typo3 substr() function. It will do all the work
154 $result = $this->typo3cs->substr($charset,$text,$start,$len);
155 /// Restore original debug level
156 error_reporting($oldlevel);
157 return $result;
161 * Multibyte safe strlen() function, uses mbstring if available.
163 function strlen($text, $charset='utf-8') {
164 /// Normalize charset
165 $charset = $this->typo3cs->parse_charset($charset);
166 /// Avoid some notices from Typo3 code
167 $oldlevel = error_reporting(E_PARSE);
168 /// Call Typo3 strlen() function. It will do all the work
169 $result = $this->typo3cs->strlen($charset,$text);
170 /// Restore original debug level
171 error_reporting($oldlevel);
172 return $result;
176 * Multibyte safe strtolower() function, uses mbstring if available.
178 function strtolower($text, $charset='utf-8') {
179 /// Normalize charset
180 $charset = $this->typo3cs->parse_charset($charset);
181 /// Avoid some notices from Typo3 code
182 $oldlevel = error_reporting(E_PARSE);
183 /// Call Typo3 conv_case() function. It will do all the work
184 $result = $this->typo3cs->conv_case($charset,$text,'toLower');
185 /// Restore original debug level
186 error_reporting($oldlevel);
187 return $result;
191 * Multibyte safe strtoupper() function, uses mbstring if available.
193 function strtoupper($text, $charset='utf-8') {
194 /// Normalize charset
195 $charset = $this->typo3cs->parse_charset($charset);
196 /// Avoid some notices from Typo3 code
197 $oldlevel = error_reporting(E_PARSE);
198 /// Call Typo3 conv_case() function. It will do all the work
199 $result = $this->typo3cs->conv_case($charset,$text,'toUpper');
200 /// Restore original debug level
201 error_reporting($oldlevel);
202 return $result;
206 * UTF-8 ONLY safe strpos() function, uses mbstring if available.
208 function strpos($haystack,$needle,$offset=0) {
209 /// Call Typo3 utf8_strpos() function. It will do all the work
210 return $this->typo3cs->utf8_strpos($haystack,$needle,$offset);
214 * UTF-8 ONLY safe strrpos() function, uses mbstring if available.
216 function strrpos($haystack,$needle) {
217 /// Call Typo3 utf8_strrpos() function. It will do all the work
218 return $this->typo3cs->utf8_strrpos($haystack,$needle);
222 * Try to convert upper unicode characters to plain ascii,
223 * the returned string may cantain unconverted unicode characters.
225 function specialtoascii($text,$charset='utf-8') {
226 /// Normalize charset
227 $charset = $this->typo3cs->parse_charset($charset);
228 /// Avoid some notices from Typo3 code
229 $oldlevel = error_reporting(E_PARSE);
230 $result = $this->typo3cs->specCharsToASCII($charset,$text);
231 /// Restore original debug level
232 error_reporting($oldlevel);
233 return $result;
237 * Generate a correct base64 encoded header to be used in MIME mail messages.
238 * This function seems to be 100% compliant with RFC1342. Credits go to:
239 * paravoid (http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283).
241 function encode_mimeheader($text, $charset='utf-8') {
242 if (empty($text)) {
243 return (string)$text;
245 /// Normalize charset
246 $charset = $this->typo3cs->parse_charset($charset);
247 /// If the text is pure ASCII, we don't need to encode it
248 if ($this->convert($text, $charset, 'ascii') == $text) {
249 return $text;
251 /// Although RFC says that line feed should be \r\n, it seems that
252 /// some mailers double convert \r, so we are going to use \n alone
253 $linefeed="\n";
254 /// Define start and end of every chunk
255 $start = "=?$charset?B?";
256 $end = "?=";
257 /// Acumulate results
258 $encoded = '';
259 /// Max line length is 75 (including start and end)
260 $length = 75 - strlen($start) - strlen($end);
261 /// Multi-byte ratio
262 $multilength = $this->strlen($text, $charset);
263 /// Detect if strlen and friends supported
264 if ($multilength === false) {
265 if ($charset == 'GB18030' or $charset == 'gb18030') {
266 while (strlen($text)) {
267 // try to encode first 22 chars - we expect most chars are two bytes long
268 if (preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,22}/m', $text, $matches)) {
269 $chunk = $matches[0];
270 $encchunk = base64_encode($chunk);
271 if (strlen($encchunk) > $length) {
272 // find first 11 chars - each char in 4 bytes - worst case scenario
273 preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,11}/m', $text, $matches);
274 $chunk = $matches[0];
275 $encchunk = base64_encode($chunk);
277 $text = substr($text, strlen($chunk));
278 $encoded .= ' '.$start.$encchunk.$end.$linefeed;
279 } else {
280 break;
283 $encoded = trim($encoded);
284 return $encoded;
285 } else {
286 return false;
289 $ratio = $multilength / strlen($text);
290 /// Base64 ratio
291 $magic = $avglength = floor(3 * $length * $ratio / 4);
292 /// basic infinite loop protection
293 $maxiterations = strlen($text)*2;
294 $iteration = 0;
295 /// Iterate over the string in magic chunks
296 for ($i=0; $i <= $multilength; $i+=$magic) {
297 if ($iteration++ > $maxiterations) {
298 return false; // probably infinite loop
300 $magic = $avglength;
301 $offset = 0;
302 /// Ensure the chunk fits in length, reduding magic if necessary
303 do {
304 $magic -= $offset;
305 $chunk = $this->substr($text, $i, $magic, $charset);
306 $chunk = base64_encode($chunk);
307 $offset++;
308 } while (strlen($chunk) > $length);
309 /// This chunk doen't break any multi-byte char. Use it.
310 if ($chunk)
311 $encoded .= ' '.$start.$chunk.$end.$linefeed;
313 /// Strip the first space and the last linefeed
314 $encoded = substr($encoded, 1, -strlen($linefeed));
316 return $encoded;
320 * Converts all the numeric entities &#nnnn; or &#xnnn; to UTF-8
321 * Original from laurynas dot butkus at gmail at:
322 * http://php.net/manual/en/function.html-entity-decode.php#75153
323 * with some custom mods to provide more functionality
325 * @param string $str input string
326 * @param boolean $htmlent convert also html entities (defaults to true)
328 * NOTE: we could have used typo3 entities_to_utf8() here
329 * but the direct alternative used runs 400% quicker
330 * and uses 0.5Mb less memory, so, let's use it
331 * (tested agains 10^6 conversions)
333 function entities_to_utf8($str, $htmlent=true) {
335 static $trans_tbl; /// Going to use static translit table
337 /// Replace numeric entities
338 $result = preg_replace('~&#x([0-9a-f]+);~ei', 'textlib::code2utf8(hexdec("\\1"))', $str);
339 $result = preg_replace('~&#([0-9]+);~e', 'textlib::code2utf8(\\1)', $result);
341 /// Replace literal entities (if desired)
342 if ($htmlent) {
343 /// Generate/create $trans_tbl
344 if (!isset($trans_tbl)) {
345 $trans_tbl = array();
346 foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key) {
347 $trans_tbl[$key] = utf8_encode($val);
350 $result = strtr($result, $trans_tbl);
352 /// Return utf8-ised string
353 return $result;
357 * Converts all Unicode chars > 127 to numeric entities &#nnnn; or &#xnnn;.
359 * @param string input string
360 * @param boolean output decadic only number entities
361 * @param boolean remove all nonumeric entities
362 * @return string converted string
364 function utf8_to_entities($str, $dec=false, $nonnum=false) {
365 /// Avoid some notices from Typo3 code
366 $oldlevel = error_reporting(E_PARSE);
367 if ($nonnum) {
368 $str = $this->typo3cs->entities_to_utf8($str, true);
370 $result = $this->typo3cs->utf8_to_entities($str);
371 if ($dec) {
372 $result = preg_replace('/&#x([0-9a-f]+);/ie', "'&#'.hexdec('$1').';'", $result);
374 /// Restore original debug level
375 error_reporting($oldlevel);
376 return $result;
380 * Removes the BOM from unicode string - see http://unicode.org/faq/utf_bom.html
382 function trim_utf8_bom($str) {
383 $bom = "\xef\xbb\xbf";
384 if (strpos($str, $bom) === 0) {
385 return substr($str, strlen($bom));
387 return $str;
391 * Returns encoding options for select boxes, utf-8 and platform encoding first
392 * @return array encodings
394 function get_encodings() {
395 $encodings = array();
396 $encodings['UTF-8'] = 'UTF-8';
397 $winenc = strtoupper(get_string('localewincharset', 'langconfig'));
398 if ($winenc != '') {
399 $encodings[$winenc] = $winenc;
401 $nixenc = strtoupper(get_string('oldcharset', 'langconfig'));
402 $encodings[$nixenc] = $nixenc;
404 foreach ($this->typo3cs->synonyms as $enc) {
405 $enc = strtoupper($enc);
406 $encodings[$enc] = $enc;
408 return $encodings;
412 * Returns the utf8 string corresponding to the unicode value
413 * (from php.net, courtesy - romans@void.lv)
415 * @param int $num one unicode value
416 * @return string the UTF-8 char corresponding to the unicode value
418 function code2utf8($num) {
419 if ($num < 128) {
420 return chr($num);
422 if ($num < 2048) {
423 return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
425 if ($num < 65536) {
426 return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
428 if ($num < 2097152) {
429 return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
431 return '';
435 * Makes first letter of each word capital - words must be separated by spaces.
436 * Use with care, this function does not work properly in many locales!!!
437 * @param string $text
438 * @return string
440 function strtotitle($text) {
441 if (empty($text)) {
442 return $text;
445 if (function_exists('mb_convert_case')) {
446 return mb_convert_case($text, MB_CASE_TITLE,"UTF-8");
449 $text = $this->strtolower($text);
450 $words = explode(' ', $text);
451 foreach ($words as $i=>$word) {
452 $length = $this->strlen($word);
453 if (!$length) {
454 continue;
456 } else if ($length == 1) {
457 $words[$i] = $this->strtoupper($word);
459 } else {
460 $letter = $this->substr($word, 0, 1);
461 $letter = $this->strtoupper($letter);
462 $rest = $this->substr($word, 1);
463 $words[$i] = $letter.$rest;
466 return implode(' ', $words);
470 * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
471 * @param array $arr array to be sorted
472 * @param string $lang moodle language
473 * @return void, modifies parameter
475 function asort(array &$arr) {
476 if (function_exists('collator_asort')) {
477 if ($coll = collator_create(get_string('locale', 'langconfig'))) {
478 collator_asort($coll, $arr);
479 return;
482 asort($arr, SORT_LOCALE_STRING);