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/>.
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();
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!
46 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
47 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
52 * Return t3lib helper class, which is used for conversion between charsets
57 protected static function typo3($reset = false) {
58 static $typo3cs = null;
65 if (isset($typo3cs)) {
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();
109 * Reset internal textlib caches.
112 public static function reset_caches() {
117 * Standardise charset name
119 * Please note it does not mean the returned charset is actually supported.
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') {
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)) {
142 if ($charset === 'euc-jp') {
145 if ($charset === 'iso-2022-jp') {
146 return 'iso-2022-jp';
148 if ($charset === 'shift-jis' or $charset === 'shift_jis') {
151 if ($charset === 'gb2312') {
154 if ($charset === 'gb18030') {
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.
165 * Returns false if fails.
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
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
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);
195 * Multibyte safe substr() function, uses mbstring or iconv for UTF-8, falls back to typo3.
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
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
210 $oldcharset = mb_internal_encoding();
211 mb_internal_encoding('UTF-8');
212 $result = mb_substr($text, $start);
213 mb_internal_encoding($oldcharset);
216 return mb_substr($text, $start, $len, 'UTF-8');
221 $len = iconv_strlen($text, 'UTF-8');
223 return iconv_substr($text, $start, $len, 'UTF-8');
227 $oldlevel = error_reporting(E_PARSE
);
229 $result = self
::typo3()->substr($charset, (string)$text, $start);
231 $result = self
::typo3()->substr($charset, (string)$text, $start, $len);
233 error_reporting($oldlevel);
239 * Multibyte safe strlen() function, uses mbstring or iconv for UTF-8, falls back to typo3.
241 * @param string $text input string
242 * @param string $charset encoding of the text
243 * @return int number of characters
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');
252 return iconv_strlen($text, 'UTF-8');
256 $oldlevel = error_reporting(E_PARSE
);
257 $result = self
::typo3()->strlen($charset, (string)$text);
258 error_reporting($oldlevel);
264 * Multibyte safe strtolower() function, uses mbstring, falls back to typo3.
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
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');
277 $oldlevel = error_reporting(E_PARSE
);
278 $result = self
::typo3()->conv_case($charset, (string)$text, 'toLower');
279 error_reporting($oldlevel);
285 * Multibyte safe strtoupper() function, uses mbstring, falls back to typo3.
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
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');
298 $oldlevel = error_reporting(E_PARSE
);
299 $result = self
::typo3()->conv_case($charset, (string)$text, 'toUpper');
300 error_reporting($oldlevel);
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.
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.
314 public static function strpos($haystack, $needle, $offset=0) {
315 if (function_exists('mb_strpos')) {
316 return mb_strpos($haystack, $needle, $offset, 'UTF-8');
318 return iconv_strpos($haystack, $needle, $offset, 'UTF-8');
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.
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
330 public static function strrpos($haystack, $needle) {
331 if (function_exists('mb_strpos')) {
332 return mb_strrpos($haystack, $needle, null, 'UTF-8');
334 return iconv_strrpos($haystack, $needle, 'UTF-8');
339 * Try to convert upper unicode characters to plain ascii,
340 * the returned string may contain unconverted unicode characters.
342 * @param string $text input string
343 * @param string $charset encoding of the text
344 * @return string converted ascii string
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);
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).
359 * @param string $text input string
360 * @param string $charset encoding of the text
361 * @return string base64 encoded header
363 public static function encode_mimeheader($text, $charset='utf-8') {
365 return (string)$text;
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) {
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
376 // Define start and end of every chunk
377 $start = "=?$charset?B?";
379 // Accumulate results
381 // Max line length is 75 (including start and end)
382 $length = 75 - strlen($start) - strlen($end);
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);
399 $text = substr($text, strlen($chunk));
400 $encoded .= ' '.$start.$encchunk.$end.$linefeed;
405 $encoded = trim($encoded);
411 $ratio = $multilength / strlen($text);
413 $magic = $avglength = floor(3 * $length * $ratio / 4);
414 // basic infinite loop protection
415 $maxiterations = strlen($text)*2;
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
424 // Ensure the chunk fits in length, reducing magic if necessary
427 $chunk = self
::substr($text, $i, $magic, $charset);
428 $chunk = base64_encode($chunk);
430 } while (strlen($chunk) > $length);
431 // This chunk doesn't break any multi-byte char. Use it.
433 $encoded .= ' '.$start.$chunk.$end.$linefeed;
435 // Strip the first space and the last linefeed
436 $encoded = substr($encoded, 1, -strlen($linefeed));
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
447 * @param string $str input string
448 * @param boolean $htmlent convert also html entities (defaults to true)
449 * @return string encoded UTF-8 string
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)
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)
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);
472 $result = strtr($result, $trans_tbl);
474 // Return utf8-ised string
479 * Converts all Unicode chars > 127 to numeric entities &#nnnn; or &#xnnn;.
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
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
);
490 $str = self
::typo3()->entities_to_utf8((string)$str, true);
492 $result = self
::typo3()->utf8_to_entities((string)$str);
494 $result = preg_replace('/&#x([0-9a-f]+);/ie', "'&#'.hexdec('$1').';'", $result);
496 // Restore original debug level
497 error_reporting($oldlevel);
502 * Removes the BOM from unicode string {@link http://unicode.org/faq/utf_bom.html}
504 * @param string $str input string
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));
516 * Returns encoding options for select boxes, utf-8 and platform encoding first
518 * @return array encodings
520 public static function get_encodings() {
521 $encodings = array();
522 $encodings['UTF-8'] = 'UTF-8';
523 $winenc = strtoupper(get_string('localewincharset', 'langconfig'));
525 $encodings[$winenc] = $winenc;
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;
538 * Returns the utf8 string corresponding to the unicode value
539 * (from php.net, courtesy - romans@void.lv)
541 * @param int $num one unicode value
542 * @return string the UTF-8 char corresponding to the unicode value
544 public static function code2utf8($num) {
549 return chr(($num >> 6) +
192) . chr(($num & 63) +
128);
552 return chr(($num >> 12) +
224) . chr((($num >> 6) & 63) +
128) . chr(($num & 63) +
128);
554 if ($num < 2097152) {
555 return chr(($num >> 18) +
240) . chr((($num >> 12) & 63) +
128) . chr((($num >> 6) & 63) +
128) . chr(($num & 63) +
128);
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!!!
564 * @param string $text input string
567 public static function strtotitle($text) {
572 if (function_exists('mb_convert_case')) {
573 return mb_convert_case($text, MB_CASE_TITLE
, 'UTF-8');
576 $text = self
::strtolower($text);
577 $words = explode(' ', $text);
578 foreach ($words as $i=>$word) {
579 $length = self
::strlen($word);
583 } else if ($length == 1) {
584 $words[$i] = self
::strtoupper($word);
587 $letter = self
::substr($word, 0, 1);
588 $letter = self
::strtoupper($letter);
589 $rest = self
::substr($word, 1);
590 $words[$i] = $letter.$rest;
593 return implode(' ', $words);
597 * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
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
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);
611 * A collator class with static methods that can be used for sorting.
614 * @copyright 2011 Sam Hemelryk
616 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
619 /** @const compare items as strings, equivalent to Collator::SORT_REGULAR */
620 const SORT_REGULAR
= 0;
622 /** @const compare items as strings, equivalent to Collator::SORT_STRING */
623 const SORT_STRING
= 1;
625 /** @const compare items as numbers, equivalent to Collator::SORT_NUMERIC */
626 const SORT_NUMERIC
= 2;
628 /** @const compare items like natsort(), equivalent to SORT_NATURAL */
629 const SORT_NATURAL
= 6;
631 /** @const do not ignore case when sorting, use bitwise "|" with SORT_NATURAL or SORT_STRING, equivalent to Collator::UPPER_FIRST */
632 const CASE_SENSITIVE
= 64;
634 /** @var Collator|false|null **/
635 protected static $collator = null;
637 /** @var string|null The locale that was used in instantiating the current collator **/
638 protected static $locale = null;
641 * Prevent class instances, all methods are static.
643 private function __construct() {
647 * Ensures that a collator is available and created
649 * @return bool Returns true if collation is available and ready
651 protected static function ensure_collator_available() {
652 $locale = get_string('locale', 'langconfig');
653 if (is_null(self
::$collator) ||
$locale != self
::$locale) {
654 self
::$collator = false;
655 self
::$locale = $locale;
656 if (class_exists('Collator', false)) {
657 $collator = new Collator($locale);
658 if (!empty($collator) && $collator instanceof Collator
) {
659 // Check for non fatal error messages. This has to be done immediately
660 // after instantiation as any further calls to collation will cause
661 // it to reset to 0 again (or another error code if one occurred)
662 $errorcode = $collator->getErrorCode();
663 $errormessage = $collator->getErrorMessage();
664 // Check for an error code, 0 means no error occurred
665 if ($errorcode !== 0) {
666 // Get the actual locale being used, e.g. en, he, zh
667 $localeinuse = $collator->getLocale(Locale
::ACTUAL_LOCALE
);
668 // Check for the common fallback warning error codes. If this occurred
669 // there is normally little to worry about:
670 // - U_USING_DEFAULT_WARNING (127) - default fallback locale used (pt => UCA)
671 // - U_USING_FALLBACK_WARNING (128) - fallback locale used (de_CH => de)
672 // (UCA: Unicode Collation Algorithm http://unicode.org/reports/tr10/)
673 if ($errorcode === -127 ||
$errorcode === -128) {
674 // Check if the locale in use is UCA default one ('root') or
675 // if it is anything like the locale we asked for
676 if ($localeinuse !== 'root' && strpos($locale, $localeinuse) !== 0) {
677 // The locale we asked for is completely different to the locale
678 // we have received, let the user know via debugging
679 debugging('Invalid locale: "' . $locale . '", with warning (not fatal) "' . $errormessage .
680 '", falling back to "' . $collator->getLocale(Locale
::VALID_LOCALE
) . '"');
682 // Nothing to do here, this is expected!
683 // The Moodle locale setting isn't what the collator expected but
684 // it is smart enough to match the first characters of our locale
685 // to find the correct locale or to use UCA collation
688 // We've received some other sort of non fatal warning - let the
689 // user know about it via debugging.
690 debugging('Problem with locale: "' . $locale . '", with message "' . $errormessage .
691 '", falling back to "' . $collator->getLocale(Locale
::VALID_LOCALE
) . '"');
694 // Store the collator object now that we can be sure it is in a workable condition
695 self
::$collator = $collator;
697 // Fatal error while trying to instantiate the collator... something went wrong
698 debugging('Error instantiating collator for locale: "' . $locale . '", with error [' .
699 intl_get_error_code() . '] ' . intl_get_error_message($collator));
703 return (self
::$collator instanceof Collator
);
707 * Restore array contents keeping new keys.
710 * @param array $original
711 * @return void modifies $arr
713 protected static function restore_array(array &$arr, array &$original) {
714 foreach ($arr as $key => $ignored) {
715 $arr[$key] = $original[$key];
720 * Normalise numbers in strings for natural sorting comparisons.
722 * @param string $string
723 * @return string string with normalised numbers
725 protected static function naturalise($string) {
726 return preg_replace_callback('/[0-9]+/', array('collatorlib', 'callback_naturalise'), $string);
732 * @param array $matches
735 public static function callback_naturalise($matches) {
736 return str_pad($matches[0], 20, '0', STR_PAD_LEFT
);
740 * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
742 * @param array $arr array to be sorted (reference)
743 * @param int $sortflag One of collatorlib::SORT_NUMERIC, collatorlib::SORT_STRING, collatorlib::SORT_NATURAL, collatorlib::SORT_REGULAR
744 * optionally "|" collatorlib::CASE_SENSITIVE
745 * @return bool True on success
747 public static function asort(array &$arr, $sortflag = collatorlib
::SORT_STRING
) {
755 $casesensitive = (bool)($sortflag & collatorlib
::CASE_SENSITIVE
);
756 $sortflag = ($sortflag & ~collatorlib
::CASE_SENSITIVE
);
757 if ($sortflag != collatorlib
::SORT_NATURAL
and $sortflag != collatorlib
::SORT_STRING
) {
758 $casesensitive = false;
761 if (self
::ensure_collator_available()) {
762 if ($sortflag == collatorlib
::SORT_NUMERIC
) {
763 $flag = Collator
::SORT_NUMERIC
;
765 } else if ($sortflag == collatorlib
::SORT_REGULAR
) {
766 $flag = Collator
::SORT_REGULAR
;
769 $flag = Collator
::SORT_STRING
;
772 if ($sortflag == collatorlib
::SORT_NATURAL
) {
774 if ($sortflag == collatorlib
::SORT_NATURAL
) {
775 foreach ($arr as $key => $value) {
776 $arr[$key] = self
::naturalise((string)$value);
780 if ($casesensitive) {
781 self
::$collator->setAttribute(Collator
::CASE_FIRST
, Collator
::UPPER_FIRST
);
783 self
::$collator->setAttribute(Collator
::CASE_FIRST
, Collator
::OFF
);
785 $result = self
::$collator->asort($arr, $flag);
787 self
::restore_array($arr, $original);
792 // try some fallback that works at least for English
794 if ($sortflag == collatorlib
::SORT_NUMERIC
) {
795 return asort($arr, SORT_NUMERIC
);
797 } else if ($sortflag == collatorlib
::SORT_REGULAR
) {
798 return asort($arr, SORT_REGULAR
);
801 if (!$casesensitive) {
803 foreach ($arr as $key => $value) {
804 $arr[$key] = textlib
::strtolower($value);
808 if ($sortflag == collatorlib
::SORT_NATURAL
) {
809 $result = natsort($arr);
812 $result = asort($arr, SORT_LOCALE_STRING
);
816 self
::restore_array($arr, $original);
823 * Locale aware sort of objects by a property in common to all objects
825 * @param array $objects An array of objects to sort (handled by reference)
826 * @param string $property The property to use for comparison
827 * @param int $sortflag One of collatorlib::SORT_NUMERIC, collatorlib::SORT_STRING, collatorlib::SORT_NATURAL, collatorlib::SORT_REGULAR
828 * optionally "|" collatorlib::CASE_SENSITIVE
829 * @return bool True on success
831 public static function asort_objects_by_property(array &$objects, $property, $sortflag = collatorlib
::SORT_STRING
) {
832 $original = $objects;
833 foreach ($objects as $key => $object) {
834 $objects[$key] = $object->$property;
836 $result = self
::asort($objects, $sortflag);
837 self
::restore_array($objects, $original);
842 * Locale aware sort of objects by a method in common to all objects
844 * @param array $objects An array of objects to sort (handled by reference)
845 * @param string $method The method to call to generate a value for comparison
846 * @param int $sortflag One of collatorlib::SORT_NUMERIC, collatorlib::SORT_STRING, collatorlib::SORT_NATURAL, collatorlib::SORT_REGULAR
847 * optionally "|" collatorlib::CASE_SENSITIVE
848 * @return bool True on success
850 public static function asort_objects_by_method(array &$objects, $method, $sortflag = collatorlib
::SORT_STRING
) {
851 $original = $objects;
852 foreach ($objects as $key => $object) {
853 $objects[$key] = $object->{$method}();
855 $result = self
::asort($objects, $sortflag);
856 self
::restore_array($objects, $original);
861 * Locale aware sorting, the key associations are kept, keys are sorted alphabetically.
863 * @param array $arr array to be sorted (reference)
864 * @param int $sortflag One of collatorlib::SORT_NUMERIC, collatorlib::SORT_STRING, collatorlib::SORT_NATURAL, collatorlib::SORT_REGULAR
865 * optionally "|" collatorlib::CASE_SENSITIVE
866 * @return bool True on success
868 public static function ksort(array &$arr, $sortflag = collatorlib
::SORT_STRING
) {
869 $keys = array_keys($arr);
870 if (!self
::asort($keys, $sortflag)) {
873 // This is a bit slow, but we need to keep the references
875 $arr = array(); // Surprisingly this does not break references outside
876 foreach ($keys as $key) {
877 $arr[$key] = $original[$key];