PageRenderTime 29ms CodeModel.GetById 52ms RepoModel.GetById 5ms app.codeStats 0ms

/lib/textlib.class.php

https://bitbucket.org/kudutest1/moodlegit
PHP | 917 lines | 521 code | 95 blank | 301 comment | 105 complexity | 095d09a660df07261904af4a32736f6d MD5 | raw file
  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/>.
  16. /**
  17. * Defines string apis
  18. *
  19. * @package core
  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
  22. */
  23. defined('MOODLE_INTERNAL') || die();
  24. /**
  25. * defines string api's for manipulating strings
  26. *
  27. * This class is used to manipulate strings under Moodle 1.6 an later. As
  28. * utf-8 text become mandatory a pool of safe functions under this encoding
  29. * become necessary. The name of the methods is exactly the
  30. * same than their PHP originals.
  31. *
  32. * A big part of this class acts as a wrapper over the Typo3 charset library,
  33. * really a cool group of utilities to handle texts and encoding conversion.
  34. *
  35. * Take a look to its own copyright and license details.
  36. *
  37. * IMPORTANT Note: Typo3 libraries always expect lowercase charsets to use 100%
  38. * its capabilities so, don't forget to make the conversion
  39. * from every wrapper function!
  40. *
  41. * @package core
  42. * @category string
  43. * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
  44. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  45. */
  46. class textlib {
  47. /**
  48. * Return t3lib helper class, which is used for conversion between charsets
  49. *
  50. * @param bool $reset
  51. * @return t3lib_cs
  52. */
  53. protected static function typo3($reset = false) {
  54. static $typo3cs = null;
  55. if ($reset) {
  56. $typo3cs = null;
  57. return null;
  58. }
  59. if (isset($typo3cs)) {
  60. return $typo3cs;
  61. }
  62. global $CFG;
  63. // Required files
  64. require_once($CFG->libdir.'/typo3/class.t3lib_cs.php');
  65. require_once($CFG->libdir.'/typo3/class.t3lib_div.php');
  66. require_once($CFG->libdir.'/typo3/interface.t3lib_singleton.php');
  67. require_once($CFG->libdir.'/typo3/class.t3lib_l10n_locales.php');
  68. // do not use mbstring or recode because it may return invalid results in some corner cases
  69. $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod'] = 'iconv';
  70. $GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] = 'iconv';
  71. // Tell Typo3 we are curl enabled always (mandatory since 2.0)
  72. $GLOBALS['TYPO3_CONF_VARS']['SYS']['curlUse'] = '1';
  73. // And this directory must exist to allow Typo to cache conversion
  74. // tables when using internal functions
  75. make_temp_directory('typo3temp/cs');
  76. // Make sure typo is using our dir permissions
  77. $GLOBALS['TYPO3_CONF_VARS']['BE']['folderCreateMask'] = decoct($CFG->directorypermissions);
  78. // Default mask for Typo
  79. $GLOBALS['TYPO3_CONF_VARS']['BE']['fileCreateMask'] = $CFG->directorypermissions;
  80. // This full path constants must be defined too, transforming backslashes
  81. // to forward slashed because Typo3 requires it.
  82. if (!defined('PATH_t3lib')) {
  83. define('PATH_t3lib', str_replace('\\','/',$CFG->libdir.'/typo3/'));
  84. define('PATH_typo3', str_replace('\\','/',$CFG->libdir.'/typo3/'));
  85. define('PATH_site', str_replace('\\','/',$CFG->tempdir.'/'));
  86. define('TYPO3_OS', stristr(PHP_OS,'win')&&!stristr(PHP_OS,'darwin')?'WIN':'');
  87. }
  88. $typo3cs = new t3lib_cs();
  89. return $typo3cs;
  90. }
  91. /**
  92. * Reset internal textlib caches.
  93. * @static
  94. */
  95. public static function reset_caches() {
  96. self::typo3(true);
  97. }
  98. /**
  99. * Standardise charset name
  100. *
  101. * Please note it does not mean the returned charset is actually supported.
  102. *
  103. * @static
  104. * @param string $charset raw charset name
  105. * @return string normalised lowercase charset name
  106. */
  107. public static function parse_charset($charset) {
  108. $charset = strtolower($charset);
  109. // shortcuts so that we do not have to load typo3 on every page
  110. if ($charset === 'utf8' or $charset === 'utf-8') {
  111. return 'utf-8';
  112. }
  113. if (preg_match('/^(cp|win|windows)-?(12[0-9]{2})$/', $charset, $matches)) {
  114. return 'windows-'.$matches[2];
  115. }
  116. if (preg_match('/^iso-8859-[0-9]+$/', $charset, $matches)) {
  117. return $charset;
  118. }
  119. if ($charset === 'euc-jp') {
  120. return 'euc-jp';
  121. }
  122. if ($charset === 'iso-2022-jp') {
  123. return 'iso-2022-jp';
  124. }
  125. if ($charset === 'shift-jis' or $charset === 'shift_jis') {
  126. return 'shift_jis';
  127. }
  128. if ($charset === 'gb2312') {
  129. return 'gb2312';
  130. }
  131. if ($charset === 'gb18030') {
  132. return 'gb18030';
  133. }
  134. // fallback to typo3
  135. return self::typo3()->parse_charset($charset);
  136. }
  137. /**
  138. * Converts the text between different encodings. It uses iconv extension with //TRANSLIT parameter,
  139. * falls back to typo3. If both source and target are utf-8 it tries to fix invalid characters only.
  140. *
  141. * @param string $text
  142. * @param string $fromCS source encoding
  143. * @param string $toCS result encoding
  144. * @return string|bool converted string or false on error
  145. */
  146. public static function convert($text, $fromCS, $toCS='utf-8') {
  147. $fromCS = self::parse_charset($fromCS);
  148. $toCS = self::parse_charset($toCS);
  149. $text = (string)$text; // we can work only with strings
  150. if ($text === '') {
  151. return '';
  152. }
  153. if ($toCS === 'utf-8' and $fromCS === 'utf-8') {
  154. return fix_utf8($text);
  155. }
  156. $result = iconv($fromCS, $toCS.'//TRANSLIT', $text);
  157. if ($result === false or $result === '') {
  158. // note: iconv is prone to return empty string when invalid char encountered, or false if encoding unsupported
  159. $oldlevel = error_reporting(E_PARSE);
  160. $result = self::typo3()->conv((string)$text, $fromCS, $toCS);
  161. error_reporting($oldlevel);
  162. }
  163. return $result;
  164. }
  165. /**
  166. * Multibyte safe substr() function, uses mbstring or iconv for UTF-8, falls back to typo3.
  167. *
  168. * @param string $text string to truncate
  169. * @param int $start negative value means from end
  170. * @param int $len maximum length of characters beginning from start
  171. * @param string $charset encoding of the text
  172. * @return string portion of string specified by the $start and $len
  173. */
  174. public static function substr($text, $start, $len=null, $charset='utf-8') {
  175. $charset = self::parse_charset($charset);
  176. if ($charset === 'utf-8') {
  177. if (function_exists('mb_substr')) {
  178. // this is much faster than iconv - see MDL-31142
  179. if ($len === null) {
  180. $oldcharset = mb_internal_encoding();
  181. mb_internal_encoding('UTF-8');
  182. $result = mb_substr($text, $start);
  183. mb_internal_encoding($oldcharset);
  184. return $result;
  185. } else {
  186. return mb_substr($text, $start, $len, 'UTF-8');
  187. }
  188. } else {
  189. if ($len === null) {
  190. $len = iconv_strlen($text, 'UTF-8');
  191. }
  192. return iconv_substr($text, $start, $len, 'UTF-8');
  193. }
  194. }
  195. $oldlevel = error_reporting(E_PARSE);
  196. if ($len === null) {
  197. $result = self::typo3()->substr($charset, (string)$text, $start);
  198. } else {
  199. $result = self::typo3()->substr($charset, (string)$text, $start, $len);
  200. }
  201. error_reporting($oldlevel);
  202. return $result;
  203. }
  204. /**
  205. * Multibyte safe strlen() function, uses mbstring or iconv for UTF-8, falls back to typo3.
  206. *
  207. * @param string $text input string
  208. * @param string $charset encoding of the text
  209. * @return int number of characters
  210. */
  211. public static function strlen($text, $charset='utf-8') {
  212. $charset = self::parse_charset($charset);
  213. if ($charset === 'utf-8') {
  214. if (function_exists('mb_strlen')) {
  215. return mb_strlen($text, 'UTF-8');
  216. } else {
  217. return iconv_strlen($text, 'UTF-8');
  218. }
  219. }
  220. $oldlevel = error_reporting(E_PARSE);
  221. $result = self::typo3()->strlen($charset, (string)$text);
  222. error_reporting($oldlevel);
  223. return $result;
  224. }
  225. /**
  226. * Multibyte safe strtolower() function, uses mbstring, falls back to typo3.
  227. *
  228. * @param string $text input string
  229. * @param string $charset encoding of the text (may not work for all encodings)
  230. * @return string lower case text
  231. */
  232. public static function strtolower($text, $charset='utf-8') {
  233. $charset = self::parse_charset($charset);
  234. if ($charset === 'utf-8' and function_exists('mb_strtolower')) {
  235. return mb_strtolower($text, 'UTF-8');
  236. }
  237. $oldlevel = error_reporting(E_PARSE);
  238. $result = self::typo3()->conv_case($charset, (string)$text, 'toLower');
  239. error_reporting($oldlevel);
  240. return $result;
  241. }
  242. /**
  243. * Multibyte safe strtoupper() function, uses mbstring, falls back to typo3.
  244. *
  245. * @param string $text input string
  246. * @param string $charset encoding of the text (may not work for all encodings)
  247. * @return string upper case text
  248. */
  249. public static function strtoupper($text, $charset='utf-8') {
  250. $charset = self::parse_charset($charset);
  251. if ($charset === 'utf-8' and function_exists('mb_strtoupper')) {
  252. return mb_strtoupper($text, 'UTF-8');
  253. }
  254. $oldlevel = error_reporting(E_PARSE);
  255. $result = self::typo3()->conv_case($charset, (string)$text, 'toUpper');
  256. error_reporting($oldlevel);
  257. return $result;
  258. }
  259. /**
  260. * Find the position of the first occurrence of a substring in a string.
  261. * UTF-8 ONLY safe strpos(), uses mbstring, falls back to iconv.
  262. *
  263. * @param string $haystack the string to search in
  264. * @param string $needle one or more charachters to search for
  265. * @param int $offset offset from begining of string
  266. * @return int the numeric position of the first occurrence of needle in haystack.
  267. */
  268. public static function strpos($haystack, $needle, $offset=0) {
  269. if (function_exists('mb_strpos')) {
  270. return mb_strpos($haystack, $needle, $offset, 'UTF-8');
  271. } else {
  272. return iconv_strpos($haystack, $needle, $offset, 'UTF-8');
  273. }
  274. }
  275. /**
  276. * Find the position of the last occurrence of a substring in a string
  277. * UTF-8 ONLY safe strrpos(), uses mbstring, falls back to iconv.
  278. *
  279. * @param string $haystack the string to search in
  280. * @param string $needle one or more charachters to search for
  281. * @return int the numeric position of the last occurrence of needle in haystack
  282. */
  283. public static function strrpos($haystack, $needle) {
  284. if (function_exists('mb_strpos')) {
  285. return mb_strrpos($haystack, $needle, null, 'UTF-8');
  286. } else {
  287. return iconv_strrpos($haystack, $needle, 'UTF-8');
  288. }
  289. }
  290. /**
  291. * Try to convert upper unicode characters to plain ascii,
  292. * the returned string may contain unconverted unicode characters.
  293. *
  294. * @param string $text input string
  295. * @param string $charset encoding of the text
  296. * @return string converted ascii string
  297. */
  298. public static function specialtoascii($text, $charset='utf-8') {
  299. $charset = self::parse_charset($charset);
  300. $oldlevel = error_reporting(E_PARSE);
  301. $result = self::typo3()->specCharsToASCII($charset, (string)$text);
  302. error_reporting($oldlevel);
  303. return $result;
  304. }
  305. /**
  306. * Generate a correct base64 encoded header to be used in MIME mail messages.
  307. * This function seems to be 100% compliant with RFC1342. Credits go to:
  308. * paravoid (http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283).
  309. *
  310. * @param string $text input string
  311. * @param string $charset encoding of the text
  312. * @return string base64 encoded header
  313. */
  314. public static function encode_mimeheader($text, $charset='utf-8') {
  315. if (empty($text)) {
  316. return (string)$text;
  317. }
  318. // Normalize charset
  319. $charset = self::parse_charset($charset);
  320. // If the text is pure ASCII, we don't need to encode it
  321. if (self::convert($text, $charset, 'ascii') == $text) {
  322. return $text;
  323. }
  324. // Although RFC says that line feed should be \r\n, it seems that
  325. // some mailers double convert \r, so we are going to use \n alone
  326. $linefeed="\n";
  327. // Define start and end of every chunk
  328. $start = "=?$charset?B?";
  329. $end = "?=";
  330. // Accumulate results
  331. $encoded = '';
  332. // Max line length is 75 (including start and end)
  333. $length = 75 - strlen($start) - strlen($end);
  334. // Multi-byte ratio
  335. $multilength = self::strlen($text, $charset);
  336. // Detect if strlen and friends supported
  337. if ($multilength === false) {
  338. if ($charset == 'GB18030' or $charset == 'gb18030') {
  339. while (strlen($text)) {
  340. // try to encode first 22 chars - we expect most chars are two bytes long
  341. if (preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,22}/m', $text, $matches)) {
  342. $chunk = $matches[0];
  343. $encchunk = base64_encode($chunk);
  344. if (strlen($encchunk) > $length) {
  345. // find first 11 chars - each char in 4 bytes - worst case scenario
  346. preg_match('/^(([\x00-\x7f])|([\x81-\xfe][\x40-\x7e])|([\x81-\xfe][\x80-\xfe])|([\x81-\xfe][\x30-\x39]..)){1,11}/m', $text, $matches);
  347. $chunk = $matches[0];
  348. $encchunk = base64_encode($chunk);
  349. }
  350. $text = substr($text, strlen($chunk));
  351. $encoded .= ' '.$start.$encchunk.$end.$linefeed;
  352. } else {
  353. break;
  354. }
  355. }
  356. $encoded = trim($encoded);
  357. return $encoded;
  358. } else {
  359. return false;
  360. }
  361. }
  362. $ratio = $multilength / strlen($text);
  363. // Base64 ratio
  364. $magic = $avglength = floor(3 * $length * $ratio / 4);
  365. // basic infinite loop protection
  366. $maxiterations = strlen($text)*2;
  367. $iteration = 0;
  368. // Iterate over the string in magic chunks
  369. for ($i=0; $i <= $multilength; $i+=$magic) {
  370. if ($iteration++ > $maxiterations) {
  371. return false; // probably infinite loop
  372. }
  373. $magic = $avglength;
  374. $offset = 0;
  375. // Ensure the chunk fits in length, reducing magic if necessary
  376. do {
  377. $magic -= $offset;
  378. $chunk = self::substr($text, $i, $magic, $charset);
  379. $chunk = base64_encode($chunk);
  380. $offset++;
  381. } while (strlen($chunk) > $length);
  382. // This chunk doesn't break any multi-byte char. Use it.
  383. if ($chunk)
  384. $encoded .= ' '.$start.$chunk.$end.$linefeed;
  385. }
  386. // Strip the first space and the last linefeed
  387. $encoded = substr($encoded, 1, -strlen($linefeed));
  388. return $encoded;
  389. }
  390. /**
  391. * Returns HTML entity transliteration table.
  392. * @return array with (html entity => utf-8) elements
  393. */
  394. protected static function get_entities_table() {
  395. static $trans_tbl = null;
  396. // Generate/create $trans_tbl
  397. if (!isset($trans_tbl)) {
  398. if (version_compare(phpversion(), '5.3.4') < 0) {
  399. $trans_tbl = array();
  400. foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key) {
  401. $trans_tbl[$key] = textlib::convert($val, 'ISO-8859-1', 'utf-8');
  402. }
  403. } else if (version_compare(phpversion(), '5.4.0') < 0) {
  404. $trans_tbl = get_html_translation_table(HTML_ENTITIES, ENT_COMPAT, 'UTF-8');
  405. $trans_tbl = array_flip($trans_tbl);
  406. } else {
  407. $trans_tbl = get_html_translation_table(HTML_ENTITIES, ENT_COMPAT | ENT_HTML401, 'UTF-8');
  408. $trans_tbl = array_flip($trans_tbl);
  409. }
  410. }
  411. return $trans_tbl;
  412. }
  413. /**
  414. * Converts all the numeric entities &#nnnn; or &#xnnn; to UTF-8
  415. * Original from laurynas dot butkus at gmail at:
  416. * http://php.net/manual/en/function.html-entity-decode.php#75153
  417. * with some custom mods to provide more functionality
  418. *
  419. * @param string $str input string
  420. * @param boolean $htmlent convert also html entities (defaults to true)
  421. * @return string encoded UTF-8 string
  422. */
  423. public static function entities_to_utf8($str, $htmlent=true) {
  424. static $callback1 = null ;
  425. static $callback2 = null ;
  426. if (!$callback1 or !$callback2) {
  427. $callback1 = create_function('$matches', 'return textlib::code2utf8(hexdec($matches[1]));');
  428. $callback2 = create_function('$matches', 'return textlib::code2utf8($matches[1]);');
  429. }
  430. $result = (string)$str;
  431. $result = preg_replace_callback('/&#x([0-9a-f]+);/i', $callback1, $result);
  432. $result = preg_replace_callback('/&#([0-9]+);/', $callback2, $result);
  433. // Replace literal entities (if desired)
  434. if ($htmlent) {
  435. $trans_tbl = self::get_entities_table();
  436. // It should be safe to search for ascii strings and replace them with utf-8 here.
  437. $result = strtr($result, $trans_tbl);
  438. }
  439. // Return utf8-ised string
  440. return $result;
  441. }
  442. /**
  443. * Converts all Unicode chars > 127 to numeric entities &#nnnn; or &#xnnn;.
  444. *
  445. * @param string $str input string
  446. * @param boolean $dec output decadic only number entities
  447. * @param boolean $nonnum remove all non-numeric entities
  448. * @return string converted string
  449. */
  450. public static function utf8_to_entities($str, $dec=false, $nonnum=false) {
  451. static $callback = null ;
  452. if ($nonnum) {
  453. $str = self::entities_to_utf8($str, true);
  454. }
  455. // Avoid some notices from Typo3 code
  456. $oldlevel = error_reporting(E_PARSE);
  457. $result = self::typo3()->utf8_to_entities((string)$str);
  458. error_reporting($oldlevel);
  459. if ($dec) {
  460. if (!$callback) {
  461. $callback = create_function('$matches', 'return \'&#\'.(hexdec($matches[1])).\';\';');
  462. }
  463. $result = preg_replace_callback('/&#x([0-9a-f]+);/i', $callback, $result);
  464. }
  465. return $result;
  466. }
  467. /**
  468. * Removes the BOM from unicode string {@link http://unicode.org/faq/utf_bom.html}
  469. *
  470. * @param string $str input string
  471. * @return string
  472. */
  473. public static function trim_utf8_bom($str) {
  474. $bom = "\xef\xbb\xbf";
  475. if (strpos($str, $bom) === 0) {
  476. return substr($str, strlen($bom));
  477. }
  478. return $str;
  479. }
  480. /**
  481. * Returns encoding options for select boxes, utf-8 and platform encoding first
  482. *
  483. * @return array encodings
  484. */
  485. public static function get_encodings() {
  486. $encodings = array();
  487. $encodings['UTF-8'] = 'UTF-8';
  488. $winenc = strtoupper(get_string('localewincharset', 'langconfig'));
  489. if ($winenc != '') {
  490. $encodings[$winenc] = $winenc;
  491. }
  492. $nixenc = strtoupper(get_string('oldcharset', 'langconfig'));
  493. $encodings[$nixenc] = $nixenc;
  494. foreach (self::typo3()->synonyms as $enc) {
  495. $enc = strtoupper($enc);
  496. $encodings[$enc] = $enc;
  497. }
  498. return $encodings;
  499. }
  500. /**
  501. * Returns the utf8 string corresponding to the unicode value
  502. * (from php.net, courtesy - romans@void.lv)
  503. *
  504. * @param int $num one unicode value
  505. * @return string the UTF-8 char corresponding to the unicode value
  506. */
  507. public static function code2utf8($num) {
  508. if ($num < 128) {
  509. return chr($num);
  510. }
  511. if ($num < 2048) {
  512. return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
  513. }
  514. if ($num < 65536) {
  515. return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
  516. }
  517. if ($num < 2097152) {
  518. return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
  519. }
  520. return '';
  521. }
  522. /**
  523. * Makes first letter of each word capital - words must be separated by spaces.
  524. * Use with care, this function does not work properly in many locales!!!
  525. *
  526. * @param string $text input string
  527. * @return string
  528. */
  529. public static function strtotitle($text) {
  530. if (empty($text)) {
  531. return $text;
  532. }
  533. if (function_exists('mb_convert_case')) {
  534. return mb_convert_case($text, MB_CASE_TITLE, 'UTF-8');
  535. }
  536. $text = self::strtolower($text);
  537. $words = explode(' ', $text);
  538. foreach ($words as $i=>$word) {
  539. $length = self::strlen($word);
  540. if (!$length) {
  541. continue;
  542. } else if ($length == 1) {
  543. $words[$i] = self::strtoupper($word);
  544. } else {
  545. $letter = self::substr($word, 0, 1);
  546. $letter = self::strtoupper($letter);
  547. $rest = self::substr($word, 1);
  548. $words[$i] = $letter.$rest;
  549. }
  550. }
  551. return implode(' ', $words);
  552. }
  553. /**
  554. * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
  555. *
  556. * @param array $arr array to be sorted (reference)
  557. * @param int $sortflag One of Collator::SORT_REGULAR, Collator::SORT_NUMERIC, Collator::SORT_STRING
  558. * @return void modifies parameter
  559. */
  560. public static function asort(array &$arr, $sortflag = null) {
  561. debugging('textlib::asort has been superseeded by collatorlib::asort please upgrade your code to use that', DEBUG_DEVELOPER);
  562. collatorlib::asort($arr, $sortflag);
  563. }
  564. }
  565. /**
  566. * A collator class with static methods that can be used for sorting.
  567. *
  568. * @package core
  569. * @copyright 2011 Sam Hemelryk
  570. * 2012 Petr Skoda
  571. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  572. */
  573. class collatorlib {
  574. /** @const compare items using general PHP comparison, equivalent to Collator::SORT_REGULAR, this may bot be locale aware! */
  575. const SORT_REGULAR = 0;
  576. /** @const compare items as strings, equivalent to Collator::SORT_STRING */
  577. const SORT_STRING = 1;
  578. /** @const compare items as numbers, equivalent to Collator::SORT_NUMERIC */
  579. const SORT_NUMERIC = 2;
  580. /** @const compare items like natsort(), equivalent to SORT_NATURAL */
  581. const SORT_NATURAL = 6;
  582. /** @const do not ignore case when sorting, use bitwise "|" with SORT_NATURAL or SORT_STRING, equivalent to Collator::UPPER_FIRST */
  583. const CASE_SENSITIVE = 64;
  584. /** @var Collator|false|null **/
  585. protected static $collator = null;
  586. /** @var string|null The locale that was used in instantiating the current collator **/
  587. protected static $locale = null;
  588. /**
  589. * Prevent class instances, all methods are static.
  590. */
  591. private function __construct() {
  592. }
  593. /**
  594. * Ensures that a collator is available and created
  595. *
  596. * @return bool Returns true if collation is available and ready
  597. */
  598. protected static function ensure_collator_available() {
  599. $locale = get_string('locale', 'langconfig');
  600. if (is_null(self::$collator) || $locale != self::$locale) {
  601. self::$collator = false;
  602. self::$locale = $locale;
  603. if (class_exists('Collator', false)) {
  604. $collator = new Collator($locale);
  605. if (!empty($collator) && $collator instanceof Collator) {
  606. // Check for non fatal error messages. This has to be done immediately
  607. // after instantiation as any further calls to collation will cause
  608. // it to reset to 0 again (or another error code if one occurred)
  609. $errorcode = $collator->getErrorCode();
  610. $errormessage = $collator->getErrorMessage();
  611. // Check for an error code, 0 means no error occurred
  612. if ($errorcode !== 0) {
  613. // Get the actual locale being used, e.g. en, he, zh
  614. $localeinuse = $collator->getLocale(Locale::ACTUAL_LOCALE);
  615. // Check for the common fallback warning error codes. If this occurred
  616. // there is normally little to worry about:
  617. // - U_USING_DEFAULT_WARNING (127) - default fallback locale used (pt => UCA)
  618. // - U_USING_FALLBACK_WARNING (128) - fallback locale used (de_CH => de)
  619. // (UCA: Unicode Collation Algorithm http://unicode.org/reports/tr10/)
  620. if ($errorcode === -127 || $errorcode === -128) {
  621. // Check if the locale in use is UCA default one ('root') or
  622. // if it is anything like the locale we asked for
  623. if ($localeinuse !== 'root' && strpos($locale, $localeinuse) !== 0) {
  624. // The locale we asked for is completely different to the locale
  625. // we have received, let the user know via debugging
  626. debugging('Invalid locale: "' . $locale . '", with warning (not fatal) "' . $errormessage .
  627. '", falling back to "' . $collator->getLocale(Locale::VALID_LOCALE) . '"');
  628. } else {
  629. // Nothing to do here, this is expected!
  630. // The Moodle locale setting isn't what the collator expected but
  631. // it is smart enough to match the first characters of our locale
  632. // to find the correct locale or to use UCA collation
  633. }
  634. } else {
  635. // We've received some other sort of non fatal warning - let the
  636. // user know about it via debugging.
  637. debugging('Problem with locale: "' . $locale . '", with message "' . $errormessage .
  638. '", falling back to "' . $collator->getLocale(Locale::VALID_LOCALE) . '"');
  639. }
  640. }
  641. // Store the collator object now that we can be sure it is in a workable condition
  642. self::$collator = $collator;
  643. } else {
  644. // Fatal error while trying to instantiate the collator... something went wrong
  645. debugging('Error instantiating collator for locale: "' . $locale . '", with error [' .
  646. intl_get_error_code() . '] ' . intl_get_error_message($collator));
  647. }
  648. }
  649. }
  650. return (self::$collator instanceof Collator);
  651. }
  652. /**
  653. * Restore array contents keeping new keys.
  654. * @static
  655. * @param array $arr
  656. * @param array $original
  657. * @return void modifies $arr
  658. */
  659. protected static function restore_array(array &$arr, array &$original) {
  660. foreach ($arr as $key => $ignored) {
  661. $arr[$key] = $original[$key];
  662. }
  663. }
  664. /**
  665. * Normalise numbers in strings for natural sorting comparisons.
  666. * @static
  667. * @param string $string
  668. * @return string string with normalised numbers
  669. */
  670. protected static function naturalise($string) {
  671. return preg_replace_callback('/[0-9]+/', array('collatorlib', 'callback_naturalise'), $string);
  672. }
  673. /**
  674. * @internal
  675. * @static
  676. * @param array $matches
  677. * @return string
  678. */
  679. public static function callback_naturalise($matches) {
  680. return str_pad($matches[0], 20, '0', STR_PAD_LEFT);
  681. }
  682. /**
  683. * Locale aware sorting, the key associations are kept, values are sorted alphabetically.
  684. *
  685. * @param array $arr array to be sorted (reference)
  686. * @param int $sortflag One of collatorlib::SORT_NUMERIC, collatorlib::SORT_STRING, collatorlib::SORT_NATURAL, collatorlib::SORT_REGULAR
  687. * optionally "|" collatorlib::CASE_SENSITIVE
  688. * @return bool True on success
  689. */
  690. public static function asort(array &$arr, $sortflag = collatorlib::SORT_STRING) {
  691. if (empty($arr)) {
  692. // nothing to do
  693. return true;
  694. }
  695. $original = null;
  696. $casesensitive = (bool)($sortflag & collatorlib::CASE_SENSITIVE);
  697. $sortflag = ($sortflag & ~collatorlib::CASE_SENSITIVE);
  698. if ($sortflag != collatorlib::SORT_NATURAL and $sortflag != collatorlib::SORT_STRING) {
  699. $casesensitive = false;
  700. }
  701. if (self::ensure_collator_available()) {
  702. if ($sortflag == collatorlib::SORT_NUMERIC) {
  703. $flag = Collator::SORT_NUMERIC;
  704. } else if ($sortflag == collatorlib::SORT_REGULAR) {
  705. $flag = Collator::SORT_REGULAR;
  706. } else {
  707. $flag = Collator::SORT_STRING;
  708. }
  709. if ($sortflag == collatorlib::SORT_NATURAL) {
  710. $original = $arr;
  711. if ($sortflag == collatorlib::SORT_NATURAL) {
  712. foreach ($arr as $key => $value) {
  713. $arr[$key] = self::naturalise((string)$value);
  714. }
  715. }
  716. }
  717. if ($casesensitive) {
  718. self::$collator->setAttribute(Collator::CASE_FIRST, Collator::UPPER_FIRST);
  719. } else {
  720. self::$collator->setAttribute(Collator::CASE_FIRST, Collator::OFF);
  721. }
  722. $result = self::$collator->asort($arr, $flag);
  723. if ($original) {
  724. self::restore_array($arr, $original);
  725. }
  726. return $result;
  727. }
  728. // try some fallback that works at least for English
  729. if ($sortflag == collatorlib::SORT_NUMERIC) {
  730. return asort($arr, SORT_NUMERIC);
  731. } else if ($sortflag == collatorlib::SORT_REGULAR) {
  732. return asort($arr, SORT_REGULAR);
  733. }
  734. if (!$casesensitive) {
  735. $original = $arr;
  736. foreach ($arr as $key => $value) {
  737. $arr[$key] = textlib::strtolower($value);
  738. }
  739. }
  740. if ($sortflag == collatorlib::SORT_NATURAL) {
  741. $result = natsort($arr);
  742. } else {
  743. $result = asort($arr, SORT_LOCALE_STRING);
  744. }
  745. if ($original) {
  746. self::restore_array($arr, $original);
  747. }
  748. return $result;
  749. }
  750. /**
  751. * Locale aware sort of objects by a property in common to all objects
  752. *
  753. * @param array $objects An array of objects to sort (handled by reference)
  754. * @param string $property The property to use for comparison
  755. * @param int $sortflag One of collatorlib::SORT_NUMERIC, collatorlib::SORT_STRING, collatorlib::SORT_NATURAL, collatorlib::SORT_REGULAR
  756. * optionally "|" collatorlib::CASE_SENSITIVE
  757. * @return bool True on success
  758. */
  759. public static function asort_objects_by_property(array &$objects, $property, $sortflag = collatorlib::SORT_STRING) {
  760. $original = $objects;
  761. foreach ($objects as $key => $object) {
  762. $objects[$key] = $object->$property;
  763. }
  764. $result = self::asort($objects, $sortflag);
  765. self::restore_array($objects, $original);
  766. return $result;
  767. }
  768. /**
  769. * Locale aware sort of objects by a method in common to all objects
  770. *
  771. * @param array $objects An array of objects to sort (handled by reference)
  772. * @param string $method The method to call to generate a value for comparison
  773. * @param int $sortflag One of collatorlib::SORT_NUMERIC, collatorlib::SORT_STRING, collatorlib::SORT_NATURAL, collatorlib::SORT_REGULAR
  774. * optionally "|" collatorlib::CASE_SENSITIVE
  775. * @return bool True on success
  776. */
  777. public static function asort_objects_by_method(array &$objects, $method, $sortflag = collatorlib::SORT_STRING) {
  778. $original = $objects;
  779. foreach ($objects as $key => $object) {
  780. $objects[$key] = $object->{$method}();
  781. }
  782. $result = self::asort($objects, $sortflag);
  783. self::restore_array($objects, $original);
  784. return $result;
  785. }
  786. /**
  787. * Locale aware sorting, the key associations are kept, keys are sorted alphabetically.
  788. *
  789. * @param array $arr array to be sorted (reference)
  790. * @param int $sortflag One of collatorlib::SORT_NUMERIC, collatorlib::SORT_STRING, collatorlib::SORT_NATURAL, collatorlib::SORT_REGULAR
  791. * optionally "|" collatorlib::CASE_SENSITIVE
  792. * @return bool True on success
  793. */
  794. public static function ksort(array &$arr, $sortflag = collatorlib::SORT_STRING) {
  795. $keys = array_keys($arr);
  796. if (!self::asort($keys, $sortflag)) {
  797. return false;
  798. }
  799. // This is a bit slow, but we need to keep the references
  800. $original = $arr;
  801. $arr = array(); // Surprisingly this does not break references outside
  802. foreach ($keys as $key) {
  803. $arr[$key] = $original[$key];
  804. }
  805. return true;
  806. }
  807. }