Merge branch 'MDL-33611' of git://github.com/timhunt/moodle
[moodle.git] / lib / textlib.class.php
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/>.
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  */
25 defined('MOODLE_INTERNAL') || die();
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  * 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.
37  *
38  * Take a look to its own copyright and license details.
39  *
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!
43  *
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
48  */
49 class textlib {
51     /**
52      * Return t3lib helper class, which is used for conversion between charsets
53      *
54      * @param bool $reset
55      * @return t3lib_cs
56      */
57     protected static function typo3($reset = false) {
58         static $typo3cs = null;
60         if ($reset) {
61             $typo3cs = null;
62             return null;
63         }
65         if (isset($typo3cs)) {
66             return $typo3cs;
67         }
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':'');
101         }
103         $typo3cs = new t3lib_cs();
105         return $typo3cs;
106     }
108     /**
109      * Reset internal textlib caches.
110      * @static
111      */
112     public static function reset_caches() {
113         self::typo3(true);
114     }
116     /**
117      * Standardise charset name
118      *
119      * Please note it does not mean the returned charset is actually supported.
120      *
121      * @static
122      * @param string $charset raw charset name
123      * @return string normalised lowercase charset name
124      */
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';
132         }
134         if (preg_match('/^(cp|win|windows)-?(12[0-9]{2})$/', $charset, $matches)) {
135             return 'windows-'.$matches[2];
136         }
138         if (preg_match('/^iso-8859-[0-9]+$/', $charset, $matches)) {
139             return $charset;
140         }
142         if ($charset === 'euc-jp') {
143             return 'euc-jp';
144         }
145         if ($charset === 'iso-2022-jp') {
146             return 'iso-2022-jp';
147         }
148         if ($charset === 'shift-jis' or $charset === 'shift_jis') {
149             return 'shift_jis';
150         }
151         if ($charset === 'gb2312') {
152             return 'gb2312';
153         }
154         if ($charset === 'gb18030') {
155             return 'gb18030';
156         }
158         // fallback to typo3
159         return self::typo3()->parse_charset($charset);
160     }
162     /**
163      * Converts the text between different encodings. It uses iconv extension with //TRANSLIT parameter,
164      * falls back to typo3.
165      * Returns false if fails.
166      *
167      * @param string $text
168      * @param string $fromCS source encoding
169      * @param string $toCS result encoding
170      * @return string|bool converted string or false on error
171      */
172     public static function convert($text, $fromCS, $toCS='utf-8') {
173         $fromCS = self::parse_charset($fromCS);
174         $toCS   = self::parse_charset($toCS);
176         $text = (string)$text; // we can work only with strings
178         if ($text === '') {
179             return '';
180         }
182         $result = iconv($fromCS, $toCS.'//TRANSLIT', $text);
184         if ($result === false or $result === '') {
185             // note: iconv is prone to return empty string when invalid char encountered, or false if encoding unsupported
186             $oldlevel = error_reporting(E_PARSE);
187             $result = self::typo3()->conv((string)$text, $fromCS, $toCS);
188             error_reporting($oldlevel);
189         }
191         return $result;
192     }
194     /**
195      * Multibyte safe substr() function, uses mbstring or iconv for UTF-8, falls back to typo3.
196      *
197      * @param string $text string to truncate
198      * @param int $start negative value means from end
199      * @param int $len maximum length of characters beginning from start
200      * @param string $charset encoding of the text
201      * @return string portion of string specified by the $start and $len
202      */
203     public static function substr($text, $start, $len=null, $charset='utf-8') {
204         $charset = self::parse_charset($charset);
206         if ($charset === 'utf-8') {
207             if (function_exists('mb_substr')) {
208                 // this is much faster than iconv - see MDL-31142
209                 if ($len === null) {
210                     $oldcharset = mb_internal_encoding();
211                     mb_internal_encoding('UTF-8');
212                     $result = mb_substr($text, $start);
213                     mb_internal_encoding($oldcharset);
214                     return $result;
215                 } else {
216                     return mb_substr($text, $start, $len, 'UTF-8');
217                 }
219             } else {
220                 if ($len === null) {
221                     $len = iconv_strlen($text, 'UTF-8');
222                 }
223                 return iconv_substr($text, $start, $len, 'UTF-8');
224             }
225         }
227         $oldlevel = error_reporting(E_PARSE);
228         if ($len === null) {
229             $result = self::typo3()->substr($charset, (string)$text, $start);
230         } else {
231             $result = self::typo3()->substr($charset, (string)$text, $start, $len);
232         }
233         error_reporting($oldlevel);
235         return $result;
236     }
238     /**
239      * Multibyte safe strlen() function, uses mbstring or iconv for UTF-8, falls back to typo3.
240      *
241      * @param string $text input string
242      * @param string $charset encoding of the text
243      * @return int number of characters
244      */
245     public static function strlen($text, $charset='utf-8') {
246         $charset = self::parse_charset($charset);
248         if ($charset === 'utf-8') {
249             if (function_exists('mb_strlen')) {
250                 return mb_strlen($text, 'UTF-8');
251             } else {
252                 return iconv_strlen($text, 'UTF-8');
253             }
254         }
256         $oldlevel = error_reporting(E_PARSE);
257         $result = self::typo3()->strlen($charset, (string)$text);
258         error_reporting($oldlevel);
260         return $result;
261     }
263     /**
264      * Multibyte safe strtolower() function, uses mbstring, falls back to typo3.
265      *
266      * @param string $text input string
267      * @param string $charset encoding of the text (may not work for all encodings)
268      * @return string lower case text
269      */
270     public static function strtolower($text, $charset='utf-8') {
271         $charset = self::parse_charset($charset);
273         if ($charset === 'utf-8' and function_exists('mb_strtolower')) {
274             return mb_strtolower($text, 'UTF-8');
275         }
277         $oldlevel = error_reporting(E_PARSE);
278         $result = self::typo3()->conv_case($charset, (string)$text, 'toLower');
279         error_reporting($oldlevel);
281         return $result;
282     }
284     /**
285      * Multibyte safe strtoupper() function, uses mbstring, falls back to typo3.
286      *
287      * @param string $text input string
288      * @param string $charset encoding of the text (may not work for all encodings)
289      * @return string upper case text
290      */
291     public static function strtoupper($text, $charset='utf-8') {
292         $charset = self::parse_charset($charset);
294         if ($charset === 'utf-8' and function_exists('mb_strtoupper')) {
295             return mb_strtoupper($text, 'UTF-8');
296         }
298         $oldlevel = error_reporting(E_PARSE);
299         $result = self::typo3()->conv_case($charset, (string)$text, 'toUpper');
300         error_reporting($oldlevel);
302         return $result;
303     }
305     /**
306      * Find the position of the first occurrence of a substring in a string.
307      * UTF-8 ONLY safe strpos(), uses mbstring, falls back to iconv.
308      *
309      * @param string $haystack the string to search in
310      * @param string $needle one or more charachters to search for
311      * @param int $offset offset from begining of string
312      * @return int the numeric position of the first occurrence of needle in haystack.
313      */
314     public static function strpos($haystack, $needle, $offset=0) {
315         if (function_exists('mb_strpos')) {
316             return mb_strpos($haystack, $needle, $offset, 'UTF-8');
317         } else {
318             return iconv_strpos($haystack, $needle, $offset, 'UTF-8');
319         }
320     }
322     /**
323      * Find the position of the last occurrence of a substring in a string
324      * UTF-8 ONLY safe strrpos(), uses mbstring, falls back to iconv.
325      *
326      * @param string $haystack the string to search in
327      * @param string $needle one or more charachters to search for
328      * @return int the numeric position of the last occurrence of needle in haystack
329      */
330     public static function strrpos($haystack, $needle) {
331         if (function_exists('mb_strpos')) {
332             return mb_strrpos($haystack, $needle, null, 'UTF-8');
333         } else {
334             return iconv_strrpos($haystack, $needle, 'UTF-8');
335         }
336     }
338     /**
339      * Try to convert upper unicode characters to plain ascii,
340      * the returned string may contain unconverted unicode characters.
341      *
342      * @param string $text input string
343      * @param string $charset encoding of the text
344      * @return string converted ascii string
345      */
346     public static function specialtoascii($text, $charset='utf-8') {
347         $charset = self::parse_charset($charset);
348         $oldlevel = error_reporting(E_PARSE);
349         $result = self::typo3()->specCharsToASCII($charset, (string)$text);
350         error_reporting($oldlevel);
351         return $result;
352     }
354     /**
355      * Generate a correct base64 encoded header to be used in MIME mail messages.
356      * This function seems to be 100% compliant with RFC1342. Credits go to:
357      * paravoid (http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283).
358      *
359      * @param string $text input string
360      * @param string $charset encoding of the text
361      * @return string base64 encoded header
362      */
363     public static function encode_mimeheader($text, $charset='utf-8') {
364         if (empty($text)) {
365             return (string)$text;
366         }
367         // Normalize charset
368         $charset = self::parse_charset($charset);
369         // If the text is pure ASCII, we don't need to encode it
370         if (self::convert($text, $charset, 'ascii') == $text) {
371             return $text;
372         }
373         // Although RFC says that line feed should be \r\n, it seems that
374         // some mailers double convert \r, so we are going to use \n alone
375         $linefeed="\n";
376         // Define start and end of every chunk
377         $start = "=?$charset?B?";
378         $end = "?=";
379         // Accumulate results
380         $encoded = '';
381         // Max line length is 75 (including start and end)
382         $length = 75 - strlen($start) - strlen($end);
383         // Multi-byte ratio
384         $multilength = self::strlen($text, $charset);
385         // Detect if strlen and friends supported
386         if ($multilength === false) {
387             if ($charset == 'GB18030' or $charset == 'gb18030') {
388                 while (strlen($text)) {
389                     // try to encode first 22 chars - we expect most chars are two bytes long
390                     if (preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,22}/m', $text, $matches)) {
391                         $chunk = $matches[0];
392                         $encchunk = base64_encode($chunk);
393                         if (strlen($encchunk) > $length) {
394                             // find first 11 chars - each char in 4 bytes - worst case scenario
395                             preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,11}/m', $text, $matches);
396                             $chunk = $matches[0];
397                             $encchunk = base64_encode($chunk);
398                         }
399                         $text = substr($text, strlen($chunk));
400                         $encoded .= ' '.$start.$encchunk.$end.$linefeed;
401                     } else {
402                         break;
403                     }
404                 }
405                 $encoded = trim($encoded);
406                 return $encoded;
407             } else {
408                 return false;
409             }
410         }
411         $ratio = $multilength / strlen($text);
412         // Base64 ratio
413         $magic = $avglength = floor(3 * $length * $ratio / 4);
414         // basic infinite loop protection
415         $maxiterations = strlen($text)*2;
416         $iteration = 0;
417         // Iterate over the string in magic chunks
418         for ($i=0; $i <= $multilength; $i+=$magic) {
419             if ($iteration++ > $maxiterations) {
420                 return false; // probably infinite loop
421             }
422             $magic = $avglength;
423             $offset = 0;
424             // Ensure the chunk fits in length, reducing magic if necessary
425             do {
426                 $magic -= $offset;
427                 $chunk = self::substr($text, $i, $magic, $charset);
428                 $chunk = base64_encode($chunk);
429                 $offset++;
430             } while (strlen($chunk) > $length);
431             // This chunk doesn't break any multi-byte char. Use it.
432             if ($chunk)
433                 $encoded .= ' '.$start.$chunk.$end.$linefeed;
434         }
435         // Strip the first space and the last linefeed
436         $encoded = substr($encoded, 1, -strlen($linefeed));
438         return $encoded;
439     }
441     /**
442      * Converts all the numeric entities &#nnnn; or &#xnnn; to UTF-8
443      * Original from laurynas dot butkus at gmail at:
444      * http://php.net/manual/en/function.html-entity-decode.php#75153
445      * with some custom mods to provide more functionality
446      *
447      * @param string $str input string
448      * @param boolean $htmlent convert also html entities (defaults to true)
449      * @return string encoded UTF-8 string
450      *
451      * NOTE: we could have used typo3 entities_to_utf8() here
452      *       but the direct alternative used runs 400% quicker
453      *       and uses 0.5Mb less memory, so, let's use it
454      *       (tested against 10^6 conversions)
455      */
456     public static function entities_to_utf8($str, $htmlent=true) {
457         static $trans_tbl; // Going to use static transliteration table
459         // Replace numeric entities
460         $result = preg_replace('~&#x([0-9a-f]+);~ei', 'textlib::code2utf8(hexdec("\\1"))', $str);
461         $result = preg_replace('~&#([0-9]+);~e', 'textlib::code2utf8(\\1)', $result);
463         // Replace literal entities (if desired)
464         if ($htmlent) {
465             // Generate/create $trans_tbl
466             if (!isset($trans_tbl)) {
467                 $trans_tbl = array();
468                 foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key) {
469                     $trans_tbl[$key] = utf8_encode($val);
470                 }
471             }
472             $result = strtr($result, $trans_tbl);
473         }
474         // Return utf8-ised string
475         return $result;
476     }
478     /**
479      * Converts all Unicode chars > 127 to numeric entities &#nnnn; or &#xnnn;.
480      *
481      * @param string $str input string
482      * @param boolean $dec output decadic only number entities
483      * @param boolean $nonnum remove all non-numeric entities
484      * @return string converted string
485      */
486     public static function utf8_to_entities($str, $dec=false, $nonnum=false) {
487         // Avoid some notices from Typo3 code
488         $oldlevel = error_reporting(E_PARSE);
489         if ($nonnum) {
490             $str = self::typo3()->entities_to_utf8((string)$str, true);
491         }
492         $result = self::typo3()->utf8_to_entities((string)$str);
493         if ($dec) {
494             $result = preg_replace('/&#x([0-9a-f]+);/ie', "'&#'.hexdec('$1').';'", $result);
495         }
496         // Restore original debug level
497         error_reporting($oldlevel);
498         return $result;
499     }
501     /**
502      * Removes the BOM from unicode string {@link http://unicode.org/faq/utf_bom.html}
503      *
504      * @param string $str input string
505      * @return string
506      */
507     public static function trim_utf8_bom($str) {
508         $bom = "\xef\xbb\xbf";
509         if (strpos($str, $bom) === 0) {
510             return substr($str, strlen($bom));
511         }
512         return $str;
513     }
515     /**
516      * Returns encoding options for select boxes, utf-8 and platform encoding first
517      *
518      * @return array encodings
519      */
520     public static function get_encodings() {
521         $encodings = array();
522         $encodings['UTF-8'] = 'UTF-8';
523         $winenc = strtoupper(get_string('localewincharset', 'langconfig'));
524         if ($winenc != '') {
525             $encodings[$winenc] = $winenc;
526         }
527         $nixenc = strtoupper(get_string('oldcharset', 'langconfig'));
528         $encodings[$nixenc] = $nixenc;
530         foreach (self::typo3()->synonyms as $enc) {
531             $enc = strtoupper($enc);
532             $encodings[$enc] = $enc;
533         }
534         return $encodings;
535     }
537     /**
538      * Returns the utf8 string corresponding to the unicode value
539      * (from php.net, courtesy - romans@void.lv)
540      *
541      * @param  int    $num one unicode value
542      * @return string the UTF-8 char corresponding to the unicode value
543      */
544     public static function code2utf8($num) {
545         if ($num < 128) {
546             return chr($num);
547         }
548         if ($num < 2048) {
549             return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
550         }
551         if ($num < 65536) {
552             return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
553         }
554         if ($num < 2097152) {
555             return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
556         }
557         return '';
558     }
560     /**
561      * Makes first letter of each word capital - words must be separated by spaces.
562      * Use with care, this function does not work properly in many locales!!!
563      *
564      * @param string $text input string
565      * @return string
566      */
567     public static function strtotitle($text) {
568         if (empty($text)) {
569             return $text;
570         }
572         if (function_exists('mb_convert_case')) {
573             return mb_convert_case($text, MB_CASE_TITLE, 'UTF-8');
574         }
576         $text = self::strtolower($text);
577         $words = explode(' ', $text);
578         foreach ($words as $i=>$word) {
579             $length = self::strlen($word);
580             if (!$length) {
581                 continue;
583             } else if ($length == 1) {
584                 $words[$i] = self::strtoupper($word);
586             } else {
587                 $letter = self::substr($word, 0, 1);
588                 $letter = self::strtoupper($letter);
589                 $rest   = self::substr($word, 1);
590                 $words[$i] = $letter.$rest;
591             }
592         }
593         return implode(' ', $words);
594     }
596     /**
597      * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
598      *
599      * @param array $arr array to be sorted (reference)
600      * @param int $sortflag One of Collator::SORT_REGULAR, Collator::SORT_NUMERIC, Collator::SORT_STRING
601      * @return void modifies parameter
602      */
603     public static function asort(array &$arr, $sortflag = null) {
604         debugging('textlib::asort has been superseeded by collatorlib::asort please upgrade your code to use that', DEBUG_DEVELOPER);
605         collatorlib::asort($arr, $sortflag);
606     }
609 /**
610  * A collator class with static methods that can be used for sorting.
611  *
612  * @package   core
613  * @copyright 2011 Sam Hemelryk
614  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
615  */
616 abstract class collatorlib {
618     /** @var Collator|false|null **/
619     protected static $collator = null;
621     /** @var string|null The locale that was used in instantiating the current collator **/
622     protected static $locale = null;
624     /**
625      * Ensures that a collator is available and created
626      *
627      * @return bool Returns true if collation is available and ready
628      */
629     protected static function ensure_collator_available() {
630         global $CFG;
632         $locale = get_string('locale', 'langconfig');
633         if (is_null(self::$collator) || $locale != self::$locale) {
634             self::$collator = false;
635             self::$locale = $locale;
636             if (class_exists('Collator', false)) {
637                 $collator = new Collator($locale);
638                 if (!empty($collator) && $collator instanceof Collator) {
639                     // Check for non fatal error messages. This has to be done immediately
640                     // after instantiation as any further calls to collation will cause
641                     // it to reset to 0 again (or another error code if one occurred)
642                     $errorcode = $collator->getErrorCode();
643                     $errormessage = $collator->getErrorMessage();
644                     // Check for an error code, 0 means no error occurred
645                     if ($errorcode !== 0) {
646                         // Get the actual locale being used, e.g. en, he, zh
647                         $localeinuse = $collator->getLocale(Locale::ACTUAL_LOCALE);
648                         // Check for the common fallback warning error codes. If this occurred
649                         // there is normally little to worry about:
650                         // - U_USING_DEFAULT_WARNING (127)  - default fallback locale used (pt => UCA)
651                         // - U_USING_FALLBACK_WARNING (128) - fallback locale used (de_CH => de)
652                         // (UCA: Unicode Collation Algorithm http://unicode.org/reports/tr10/)
653                         if ($errorcode === -127 || $errorcode === -128) {
654                             // Check if the locale in use is UCA default one ('root') or
655                             // if it is anything like the locale we asked for
656                             if ($localeinuse !== 'root' && strpos($locale, $localeinuse) !== 0) {
657                                 // The locale we asked for is completely different to the locale
658                                 // we have received, let the user know via debugging
659                                 debugging('Invalid locale: "' . $locale . '", with warning (not fatal) "' . $errormessage .
660                                     '", falling back to "' . $collator->getLocale(Locale::VALID_LOCALE) . '"');
661                             } else {
662                                 // Nothing to do here, this is expected!
663                                 // The Moodle locale setting isn't what the collator expected but
664                                 // it is smart enough to match the first characters of our locale
665                                 // to find the correct locale or to use UCA collation
666                             }
667                         } else {
668                             // We've recieved some other sort of non fatal warning - let the
669                             // user know about it via debugging.
670                             debugging('Problem with locale: "' . $locale . '", with message "' . $errormessage .
671                                 '", falling back to "' . $collator->getLocale(Locale::VALID_LOCALE) . '"');
672                         }
673                     }
674                     // Store the collator object now that we can be sure it is in a workable condition
675                     self::$collator = $collator;
676                 } else {
677                     // Fatal error while trying to instantiate the collator... something went wrong
678                     debugging('Error instantiating collator for locale: "' . $locale . '", with error [' .
679                         intl_get_error_code() . '] ' . intl_get_error_message($collator));
680                 }
681             }
682         }
683         return (self::$collator instanceof Collator);
684     }
686     /**
687      * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
688      *
689      * @param array $arr array to be sorted (reference)
690      * @param int $sortflag One of Collator::SORT_REGULAR, Collator::SORT_NUMERIC, Collator::SORT_STRING
691      * @return void modifies parameter
692      */
693     public static function asort(array &$arr, $sortflag = null) {
694         if (self::ensure_collator_available()) {
695             if (!isset($sortflag)) {
696                 $sortflag = Collator::SORT_REGULAR;
697             }
698             self::$collator->asort($arr, $sortflag);
699             return;
700         }
701         asort($arr, SORT_LOCALE_STRING);
702     }
704     /**
705      * Locale aware comparison of two strings.
706      *
707      * Returns:
708      *   1 if str1 is greater than str2
709      *   0 if str1 is equal to str2
710      *  -1 if str1 is less than str2
711      *
712      * @param string $str1 first string to compare
713      * @param string $str2 second string to compare
714      * @return int
715      */
716     public static function compare($str1, $str2) {
717         if (self::ensure_collator_available()) {
718             return self::$collator->compare($str1, $str2);
719         }
720         return strcmp($str1, $str2);
721     }
723     /**
724      * Locale aware sort of objects by a property in common to all objects
725      *
726      * @param array $objects An array of objects to sort (handled by reference)
727      * @param string $property The property to use for comparison
728      * @return bool True on success
729      */
730     public static function asort_objects_by_property(array &$objects, $property) {
731         $comparison = new collatorlib_property_comparison($property);
732         return uasort($objects, array($comparison, 'compare'));
733     }
735     /**
736      * Locale aware sort of objects by a method in common to all objects
737      *
738      * @param array $objects An array of objects to sort (handled by reference)
739      * @param string $method The method to call to generate a value for comparison
740      * @return bool True on success
741      */
742     public static function asort_objects_by_method(array &$objects, $method) {
743         $comparison = new collatorlib_method_comparison($method);
744         return uasort($objects, array($comparison, 'compare'));
745     }
748 /**
749  * Object comparison using collator
750  *
751  * Abstract class to aid the sorting of objects with respect to proper language
752  * comparison using collator
753  *
754  * @package   core
755  * @copyright 2011 Sam Hemelryk
756  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
757  */
758 abstract class collatorlib_comparison {
759     /**
760      * This function will perform the actual comparison of values
761      * It must be overridden by the deriving class.
762      *
763      * Returns:
764      *   1 if str1 is greater than str2
765      *   0 if str1 is equal to str2
766      *  -1 if str1 is less than str2
767      *
768      * @param mixed $a The first something to compare
769      * @param mixed $b The second something to compare
770      * @return int
771      */
772     public abstract function compare($a, $b);
775 /**
776  * Compare properties of two objects
777  *
778  * A comparison helper for comparing properties of two objects
779  *
780  * @package   core
781  * @category  string
782  * @copyright 2011 Sam Hemelryk
783  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
784  */
785 class collatorlib_property_comparison extends collatorlib_comparison {
787     /** @var string The property to sort by **/
788     protected $property;
790     /**
791      * Constructor
792      *
793      * @param string $property
794      */
795     public function __construct($property) {
796         $this->property = $property;
797     }
799     /**
800      * Returns:
801      *   1 if str1 is greater than str2
802      *   0 if str1 is equal to str2
803      *  -1 if str1 is less than str2
804      *
805      * @param mixed $obja The first object to compare
806      * @param mixed $objb The second object to compare
807      * @return int
808      */
809     public function compare($obja, $objb) {
810         $resulta = $obja->{$this->property};
811         $resultb = $objb->{$this->property};
812         return collatorlib::compare($resulta, $resultb);
813     }
816 /**
817  * Compare method of two objects
818  *
819  * A comparison helper for comparing the result of a method on two objects
820  *
821  * @package   core
822  * @copyright 2011 Sam Hemelryk
823  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
824  */
825 class collatorlib_method_comparison extends collatorlib_comparison {
827     /** @var string The method to use for comparison **/
828     protected $method;
830     /**
831      * Constructor
832      *
833      * @param string $method The method to call against each object
834      */
835     public function __construct($method) {
836         $this->method = $method;
837     }
839     /**
840      * Returns:
841      *   1 if str1 is greater than str2
842      *   0 if str1 is equal to str2
843      *  -1 if str1 is less than str2
844      *
845      * @param mixed $obja The first object to compare
846      * @param mixed $objb The second object to compare
847      * @return int
848      */
849     public function compare($obja, $objb) {
850         $resulta = $obja->{$this->method}();
851         $resultb = $objb->{$this->method}();
852         return collatorlib::compare($resulta, $resultb);
853     }