internationalization_internal.lib.php 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * File: internationalization_internal.lib.php
  5. * Main API extension library for Chamilo 1.8.7 LMS,
  6. * contains functions for internal use only.
  7. * License: GNU/GPL version 2 or later (Free Software Foundation)
  8. * @author Ivan Tcholakov, <ivantcholakov@gmail.com>, 2009, 2010
  9. * @author More authors, mentioned in the correpsonding fragments of this source.
  10. * @package chamilo.library
  11. *
  12. * Note: All functions and data structures here are not to be used directly.
  13. * See the file internationalization.lib.php which contains the "public" API.
  14. */
  15. /**
  16. * Internal constants
  17. */
  18. // A regular expression for accessing declared encoding within xml-formatted text.
  19. // Published by Steve Minutillo,
  20. // http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss/
  21. define('_PCRE_XML_ENCODING', '/<?xml.*encoding=[\'"](.*?)[\'"].*?>/m');
  22. /**
  23. * Global variables used by some callback functions
  24. */
  25. $_api_encoding = null;
  26. $_api_collator = null;
  27. /**
  28. * Appendix to "Language support"
  29. */
  30. /**
  31. * Upgrades the function get_lang() with the following logic:
  32. * 1. Checks whether the retrieved human language string is UTF-8 valid or not.
  33. * 2. If the system encoding is UTF-8 and the string is not UTF-8, the function
  34. * performs conversion from supposed non UTF-8 encodeng.
  35. * 3. If the system encoding is non UTF-8 but the string is valid UTF-8, then
  36. * conversion from UTF-8 is performed.
  37. * 4. At the end the string is purified from HTML entities.
  38. * @param string $string This is the retrieved human language string.
  39. * @param string $language A language identiticator.
  40. * @return string Returns the human language string, checked for proper encoding and purified.
  41. */
  42. function & _get_lang_purifier(& $string, & $language) {
  43. $system_encoding = api_get_system_encoding();
  44. if (api_is_utf8($system_encoding)) {
  45. if (!api_is_valid_utf8($string)) {
  46. $string = api_utf8_encode($string, api_get_non_utf8_encoding($language));
  47. }
  48. } else {
  49. if (api_is_valid_utf8($string)) {
  50. $string = api_utf8_decode($string, $system_encoding);
  51. }
  52. }
  53. return api_html_entity_decode($string, ENT_QUOTES, $system_encoding);
  54. }
  55. /**
  56. * This function returns an array of those languages that can use Latin 1 encoding.
  57. * @return array The array of languages that can use Latin 1 encoding (ISO-8859-15, ISO-8859-1, WINDOWS-1252, ...).
  58. * Note: The returned language identificators are purified, without suffixes.
  59. */
  60. function _api_get_latin1_compatible_languages() {
  61. static $latin1_languages;
  62. if (!isset($latin1_languages)) {
  63. $latin1_languages = array();
  64. $encodings = & _api_non_utf8_encodings();
  65. foreach ($encodings as $key => $value) {
  66. if (api_is_latin1($value[0])) {
  67. $latin1_languages[] = $key;
  68. }
  69. }
  70. }
  71. return $latin1_languages;
  72. }
  73. /**
  74. * Appendix to "Language recognition"
  75. * Based on the publication:
  76. * W. B. Cavnar and J. M. Trenkle. N-gram-based text categorization.
  77. * Proceedings of SDAIR-94, 3rd Annual Symposium on Document Analysis
  78. * and Information Retrieval, 1994.
  79. * @link http://citeseer.ist.psu.edu/cache/papers/cs/810/http:zSzzSzwww.info.unicaen.frzSz~giguetzSzclassifzSzcavnar_trenkle_ngram.pdf/n-gram-based-text.pdf
  80. */
  81. /**
  82. * Generates statistical, based on n-grams language profile from the given text.
  83. * @param string $string The input text. It should be UTF-8 encoded. Practically it should be at least 3000 characters long, 40000 characters size is for increased accuracy.
  84. * @param int $n_grams_max (optional) The size of the array of the generated n-grams.
  85. * @param int $n_max (optional) The limit if the number of characters that a n-gram may contain.
  86. * @return array An array that contains cunstructed n-grams, sorted in reverse order by their frequences. Frequences are not stored in the array.
  87. */
  88. function &_api_generate_n_grams(&$string, $encoding, $n_grams_max = 350, $n_max = 4) {
  89. if (empty($string)) {
  90. return array();
  91. }
  92. // We construct only lowercase n-grams if it is applicable for the given language.
  93. // Removing all puntuation and some other non-letter characters. Apostrophe characters stay.
  94. // Splitting the sample text into separate words.
  95. $words = preg_split('/_/u', preg_replace('/[\x00-\x1F\x20-\x26\x28-\x3E\?@\x5B-\x60{|}~\x7F]/u', '_', ' '.api_strtolower(api_utf8_encode($string, $encoding), 'UTF-8').' '), -1, PREG_SPLIT_NO_EMPTY);
  96. $prefix = '_'; // Beginning of a word.
  97. $suffix = str_repeat('_', $n_nax); // End of a word. Only the last '_' stays.
  98. $n_grams = array(); // The array that will contain the constructed n-grams.
  99. foreach ($words as $word) {
  100. $k = api_strlen($word, 'UTF-8') + 1;
  101. $word = $prefix.$word.$suffix;
  102. for ($n = 1; $n <= $n_max; $n++) {
  103. for ($i = 0; $i < $k; $i++) {
  104. $n_gram = api_utf8_decode(api_substr($word, $i, $n, 'UTF-8'), $encoding);
  105. if (isset($n_grams[$n_gram])) {
  106. $n_grams[$n_gram]++;
  107. } else {
  108. $n_grams[$n_gram] = 1;
  109. }
  110. }
  111. }
  112. }
  113. // Sorting the n-grams in reverse order by their frequences.
  114. arsort($n_grams);
  115. // Reduction the number of n-grams.
  116. return array_keys(array_slice($n_grams, 0, $n_grams_max));
  117. }
  118. /**
  119. *
  120. * The value $max_delta = 80000 is good enough for speed and detection accuracy.
  121. * If you set the value of $max_delta too low, no language will be recognized.
  122. * $max_delta = 400 * 350 = 140000 is the best detection with lowest speed.
  123. */
  124. function & _api_compare_n_grams(&$n_grams, $encoding, $max_delta = LANGUAGE_DETECT_MAX_DELTA) {
  125. static $language_profiles;
  126. if (!isset($language_profiles)) {
  127. // Reading the language profile files from the internationalization database.
  128. $exceptions = array('.', '..', 'CVS', '.htaccess', '.svn', '_svn', 'index.html');
  129. $path = str_replace("\\", '/', dirname(__FILE__).'/internationalization_database/language_detection/language_profiles/');
  130. $non_utf8_encodings = & _api_non_utf8_encodings();
  131. if (is_dir($path)) {
  132. if ($handle = @opendir($path)) {
  133. while (($dir_entry = @readdir($handle)) !== false) {
  134. if (api_in_array_nocase($dir_entry, $exceptions)) continue;
  135. if (strpos($dir_entry, '.txt') === false) continue;
  136. $dir_entry_full_path = $path .'/'. $dir_entry;
  137. if (@filetype($dir_entry_full_path) != 'dir') {
  138. if (false !== $data = @file_get_contents($dir_entry_full_path)) {
  139. $language = basename($dir_entry_full_path, '.txt');
  140. $encodings = array('UTF-8');
  141. if (!empty($non_utf8_encodings[$language])) {
  142. $encodings = array_merge($encodings, $non_utf8_encodings[$language]);
  143. }
  144. foreach ($encodings as $enc) {
  145. $data_enc = api_utf8_decode($data, $enc);
  146. if (empty($data_enc)) {
  147. continue;
  148. }
  149. $key = $language.':'.$enc;
  150. $language_profiles[$key]['data'] = array_flip(explode("\n", $data_enc));
  151. $language_profiles[$key]['language'] = $language;
  152. $language_profiles[$key]['encoding'] = $enc;
  153. }
  154. }
  155. }
  156. }
  157. }
  158. }
  159. @closedir($handle);
  160. ksort($language_profiles);
  161. }
  162. if (!is_array($n_grams) || empty($n_grams)) {
  163. return array();
  164. }
  165. // Comparison between the input n-grams and the lanuage profiles.
  166. foreach ($language_profiles as $key => &$language_profile) {
  167. if (!api_is_language_supported($language_profile['language']) || !api_equal_encodings($encoding, $language_profile['encoding'])) {
  168. continue;
  169. }
  170. $delta = 0; // This is a summary measurment for matching between the input text and the current language profile.
  171. // Searching each n-gram from the input text into the language profile.
  172. foreach ($n_grams as $rank => &$n_gram) {
  173. if (isset($language_profile['data'][$n_gram])) {
  174. // The n-gram has been found, the difference between places in both
  175. // arrays is calculated (so called delta-points are adopted for
  176. // measuring distances between n-gram ranks.
  177. $delta += abs($rank - $language_profile['data'][$n_gram]);
  178. } else {
  179. // The n-gram has not been found in the profile. We add then
  180. // a large enough "distance" in delta-points.
  181. $delta += 400;
  182. }
  183. // Abort: This language already differs too much.
  184. if ($delta > $max_delta) {
  185. break;
  186. }
  187. }
  188. // Include only non-aborted languages in result array.
  189. if ($delta < ($max_delta - 400)) {
  190. $result[$key] = $delta;
  191. }
  192. }
  193. if (!isset($result)) {
  194. return array();
  195. }
  196. asort($result);
  197. return $result;
  198. }
  199. /**
  200. * Appendix to "Date and time formats"
  201. */
  202. /**
  203. * Returns an array of translated week days and months, short and normal names.
  204. * @param string $language (optional) Language indentificator. If it is omited, the current interface language is assumed.
  205. * @return array Returns a multidimensional array with translated week days and months.
  206. */
  207. function &_api_get_day_month_names($language = null) {
  208. static $date_parts = array();
  209. if (empty($language)) {
  210. $language = api_get_interface_language();
  211. }
  212. if (!isset($date_parts[$language])) {
  213. $week_day = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
  214. $month = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
  215. for ($i = 0; $i < 7; $i++) {
  216. $date_parts[$language]['days_short'][] = get_lang($week_day[$i].'Short', '', $language);
  217. $date_parts[$language]['days_long'][] = get_lang($week_day[$i].'Long', '', $language);
  218. }
  219. for ($i = 0; $i < 12; $i++) {
  220. $date_parts[$language]['months_short'][] = get_lang($month[$i].'Short', '', $language);
  221. $date_parts[$language]['months_long'][] = get_lang($month[$i].'Long', '', $language);
  222. }
  223. }
  224. return $date_parts[$language];
  225. }
  226. /**
  227. * Appendix to "Name order conventions"
  228. */
  229. /**
  230. * Returns returns person name convention for a given language.
  231. * @param string $language The input language.
  232. * @param string $type The type of the requested convention. It may be 'format' for name order convention or 'sort_by' for name sorting convention.
  233. * @return mixed Depending of the requested type, the returned result may be string or boolean; null is returned on error;
  234. */
  235. function _api_get_person_name_convention($language, $type) {
  236. static $conventions;
  237. $language = api_purify_language_id($language);
  238. if (!isset($conventions)) {
  239. $file = dirname(__FILE__).'/internationalization_database/name_order_conventions.php';
  240. if (file_exists($file)) {
  241. $conventions = include ($file);
  242. } else {
  243. $conventions = array('english' => array('format' => 'title first_name last_name', 'sort_by' => 'first_name'));
  244. }
  245. $search1 = array('FIRST_NAME', 'LAST_NAME', 'TITLE');
  246. $replacement1 = array('%F', '%L', '%T');
  247. $search2 = array('first_name', 'last_name', 'title');
  248. $replacement2 = array('%f', '%l', '%t');
  249. foreach (array_keys($conventions) as $key) {
  250. $conventions[$key]['format'] = str_replace($search1, $replacement1, $conventions[$key]['format']);
  251. $conventions[$key]['format'] = _api_validate_person_name_format(_api_clean_person_name(str_replace('%', ' %', str_ireplace($search2, $replacement2, $conventions[$key]['format']))));
  252. $conventions[$key]['sort_by'] = strtolower($conventions[$key]['sort_by']) != 'last_name' ? true : false;
  253. }
  254. }
  255. switch ($type) {
  256. case 'format':
  257. return is_string($conventions[$language]['format']) ? $conventions[$language]['format'] : '%t %f %l';
  258. case 'sort_by':
  259. return is_bool($conventions[$language]['sort_by']) ? $conventions[$language]['sort_by'] : true;
  260. }
  261. return null;
  262. }
  263. /**
  264. * Replaces non-valid formats for person names with the default (English) format.
  265. * @param string $format The input format to be verified.
  266. * @return bool Returns the same format if is is valid, otherwise returns a valid English format.
  267. */
  268. function _api_validate_person_name_format($format) {
  269. if (empty($format) || stripos($format, '%f') === false || stripos($format, '%l') === false) {
  270. return '%t %f %l';
  271. }
  272. return $format;
  273. }
  274. /**
  275. * Removes leading, trailing and duplicate whitespace and/or commas in a full person name.
  276. * Cleaning is needed for the cases when not all parts of the name are available or when the name is constructed using a "dirty" pattern.
  277. * @param string $person_name The input person name.
  278. * @return string Returns cleaned person name.
  279. */
  280. function _api_clean_person_name($person_name) {
  281. return preg_replace(array('/\s+/', '/, ,/', '/,+/', '/^[ ,]/', '/[ ,]$/'), array(' ', ', ', ',', '', ''), $person_name);
  282. }
  283. /**
  284. * Appendix to "Multibyte string conversion functions"
  285. */
  286. /**
  287. * This is a php-implementation of a function that is similar to mb_convert_encoding() from mbstring extension.
  288. * The function converts a given string from one to another character encoding.
  289. * @param string $string The string being converted.
  290. * @param string $to_encoding The encoding that $string is being converted to.
  291. * @param string $from_encoding The encoding that $string is being converted from.
  292. * @return string Returns the converted string.
  293. */
  294. function _api_convert_encoding(&$string, $to_encoding, $from_encoding) {
  295. $str = (string)$string;
  296. static $character_map = array();
  297. static $utf8_compatible = array('UTF-8', 'US-ASCII');
  298. if (empty($str)) {
  299. return $str;
  300. }
  301. $to_encoding = api_refine_encoding_id($to_encoding);
  302. $from_encoding = api_refine_encoding_id($from_encoding);
  303. if (api_equal_encodings($to_encoding, $from_encoding)) {
  304. return $str;
  305. }
  306. if ($to_encoding == 'HTML-ENTITIES') {
  307. return api_htmlentities($str, ENT_QUOTES, $from_encoding);
  308. }
  309. if ($from_encoding == 'HTML-ENTITIES') {
  310. return api_html_entity_decode($str, ENT_QUOTES, $to_encoding);
  311. }
  312. $to = _api_get_character_map_name($to_encoding);
  313. $from = _api_get_character_map_name($from_encoding);
  314. if (empty($to) || empty($from) || $to == $from || (in_array($to, $utf8_compatible) && in_array($from, $utf8_compatible))) {
  315. return $str;
  316. }
  317. if (!isset($character_map[$to])) {
  318. $character_map[$to] = &_api_parse_character_map($to);
  319. }
  320. if ($character_map[$to] === false) {
  321. return $str;
  322. }
  323. if (!isset($character_map[$from])) {
  324. $character_map[$from] = &_api_parse_character_map($from);
  325. }
  326. if ($character_map[$from] === false) {
  327. return $str;
  328. }
  329. if ($from != 'UTF-8') {
  330. $len = api_byte_count($str);
  331. $codepoints = array();
  332. for ($i = 0; $i < $len; $i++) {
  333. $ord = ord($str[$i]);
  334. if ($ord > 127) {
  335. if (isset($character_map[$from]['local'][$ord])) {
  336. $codepoints[] = $character_map[$from]['local'][$ord];
  337. } else {
  338. $codepoints[] = 0xFFFD; // U+FFFD REPLACEMENT CHARACTER is the general substitute character in the Unicode Standard.
  339. }
  340. } else {
  341. $codepoints[] = $ord;
  342. }
  343. }
  344. } else {
  345. $codepoints = _api_utf8_to_unicode($str);
  346. }
  347. if ($to != 'UTF-8') {
  348. foreach ($codepoints as $i => &$codepoint) {
  349. if ($codepoint > 127) {
  350. if (isset($character_map[$to]['unicode'][$codepoint])) {
  351. $codepoint = chr($character_map[$to]['unicode'][$codepoint]);
  352. } else {
  353. $codepoint = '?'; // Unknown character.
  354. }
  355. } else {
  356. $codepoint = chr($codepoint);
  357. }
  358. }
  359. $str = implode($codepoints);
  360. } else {
  361. $str = _api_utf8_from_unicode($codepoints);
  362. }
  363. return $str;
  364. }
  365. /**
  366. * This function determines the name of corresponding to a given encoding conversion table.
  367. * It is able to deal with some aliases of the encoding.
  368. * @param string $encoding The given encoding identificator, for example 'WINDOWS-1252'.
  369. * @return string Returns the name of the corresponding conversion table, for the same example - 'CP1252'.
  370. */
  371. function _api_get_character_map_name($encoding) {
  372. static $character_map_selector;
  373. if (!isset($character_map_selector)) {
  374. $file = dirname(__FILE__).'/internationalization_database/conversion/character_map_selector.php';
  375. if (file_exists($file)) {
  376. $character_map_selector = include ($file);
  377. } else {
  378. $character_map_selector = array();
  379. }
  380. }
  381. return isset($character_map_selector[$encoding]) ? $character_map_selector[$encoding] : '';
  382. }
  383. /**
  384. * This function parses a given conversion table (a text file) and creates in the memory
  385. * two tables for conversion - character set from/to Unicode codepoints.
  386. * @param string $name The name of the thext file that contains the conversion table, for example 'CP1252' (file CP1252.TXT will be parsed).
  387. * @return array Returns an array that contains forward and reverse tables (from/to Unicode).
  388. */
  389. function &_api_parse_character_map($name) {
  390. $result = array();
  391. $file = dirname(__FILE__).'/internationalization_database/conversion/' . $name . '.TXT';
  392. if (file_exists($file)) {
  393. $text = @file_get_contents($file);
  394. if ($text !== false) {
  395. $text = explode(chr(10), $text);
  396. foreach ($text as $line) {
  397. if (empty($line)) {
  398. continue;
  399. }
  400. if (!empty($line) && trim($line) && $line[0] != '#') {
  401. $matches = array();
  402. preg_match('/[[:space:]]*0x([[:alnum:]]*)[[:space:]]+0x([[:alnum:]]*)[[:space:]]+/', $line, $matches);
  403. $ord = hexdec(trim($matches[1]));
  404. if ($ord > 127) {
  405. $codepoint = hexdec(trim($matches[2]));
  406. $result['local'][$ord] = $codepoint;
  407. $result['unicode'][$codepoint] = $ord;
  408. }
  409. }
  410. }
  411. } else {
  412. return false ;
  413. }
  414. } else {
  415. return false;
  416. }
  417. return $result;
  418. }
  419. /**
  420. * Takes an UTF-8 string and returns an array of integer values representing the Unicode characters.
  421. * Astral planes are supported ie. the ints in the output can be > 0xFFFF. Occurrances of the BOM are ignored.
  422. * Surrogates are not allowed.
  423. * @param string $string The UTF-8 encoded string.
  424. * @return array Returns an array of unicode code points.
  425. * @author Henri Sivonen, mailto:hsivonen@iki.fi
  426. * @link http://hsivonen.iki.fi/php-utf8/
  427. * @author Ivan Tcholakov, August 2009, adaptation for the Dokeos LMS.
  428. */
  429. function _api_utf8_to_unicode(&$string) {
  430. $str = (string)$string;
  431. $state = 0; // cached expected number of octets after the current octet
  432. // until the beginning of the next UTF8 character sequence
  433. $codepoint = 0; // cached Unicode character
  434. $bytes = 1; // cached expected number of octets in the current sequence
  435. $result = array();
  436. $len = api_byte_count($str);
  437. for ($i = 0; $i < $len; $i++) {
  438. $byte = ord($str[$i]);
  439. if ($state == 0) {
  440. // When state is zero we expect either a US-ASCII character or a multi-octet sequence.
  441. if (0 == (0x80 & ($byte))) {
  442. // US-ASCII, pass straight through.
  443. $result[] = $byte;
  444. $bytes = 1;
  445. } else if (0xC0 == (0xE0 & ($byte))) {
  446. // First octet of 2 octet sequence
  447. $codepoint = ($byte);
  448. $codepoint = ($codepoint & 0x1F) << 6;
  449. $state = 1;
  450. $bytes = 2;
  451. } else if (0xE0 == (0xF0 & ($byte))) {
  452. // First octet of 3 octet sequence
  453. $codepoint = ($byte);
  454. $codepoint = ($codepoint & 0x0F) << 12;
  455. $state = 2;
  456. $bytes = 3;
  457. } else if (0xF0 == (0xF8 & ($byte))) {
  458. // First octet of 4 octet sequence
  459. $codepoint = ($byte);
  460. $codepoint = ($codepoint & 0x07) << 18;
  461. $state = 3;
  462. $bytes = 4;
  463. } else if (0xF8 == (0xFC & ($byte))) {
  464. // First octet of 5 octet sequence.
  465. // This is illegal because the encoded codepoint must be either
  466. // (a) not the shortest form or
  467. // (b) outside the Unicode range of 0-0x10FFFF.
  468. // Rather than trying to resynchronize, we will carry on until the end
  469. // of the sequence and let the later error handling code catch it.
  470. $codepoint = ($byte);
  471. $codepoint = ($codepoint & 0x03) << 24;
  472. $state = 4;
  473. $bytes = 5;
  474. } else if (0xFC == (0xFE & ($byte))) {
  475. // First octet of 6 octet sequence, see comments for 5 octet sequence.
  476. $codepoint = ($byte);
  477. $codepoint = ($codepoint & 1) << 30;
  478. $state = 5;
  479. $bytes = 6;
  480. } else {
  481. // Current octet is neither in the US-ASCII range nor a legal first octet of a multi-octet sequence.
  482. $state = 0;
  483. $codepoint = 0;
  484. $bytes = 1;
  485. $result[] = 0xFFFD; // U+FFFD REPLACEMENT CHARACTER is the general substitute character in the Unicode Standard.
  486. continue ;
  487. }
  488. } else {
  489. // When state is non-zero, we expect a continuation of the multi-octet sequence
  490. if (0x80 == (0xC0 & ($byte))) {
  491. // Legal continuation.
  492. $shift = ($state - 1) * 6;
  493. $tmp = $byte;
  494. $tmp = ($tmp & 0x0000003F) << $shift;
  495. $codepoint |= $tmp;
  496. // End of the multi-octet sequence. $codepoint now contains the final Unicode codepoint to be output
  497. if (0 == --$state) {
  498. // Check for illegal sequences and codepoints.
  499. // From Unicode 3.1, non-shortest form is illegal
  500. if (((2 == $bytes) && ($codepoint < 0x0080)) ||
  501. ((3 == $bytes) && ($codepoint < 0x0800)) ||
  502. ((4 == $bytes) && ($codepoint < 0x10000)) ||
  503. (4 < $bytes) ||
  504. // From Unicode 3.2, surrogate characters are illegal
  505. (($codepoint & 0xFFFFF800) == 0xD800) ||
  506. // Codepoints outside the Unicode range are illegal
  507. ($codepoint > 0x10FFFF)) {
  508. $state = 0;
  509. $codepoint = 0;
  510. $bytes = 1;
  511. $result[] = 0xFFFD;
  512. continue ;
  513. }
  514. if (0xFEFF != $codepoint) {
  515. // BOM is legal but we don't want to output it
  516. $result[] = $codepoint;
  517. }
  518. // Initialize UTF8 cache
  519. $state = 0;
  520. $codepoint = 0;
  521. $bytes = 1;
  522. }
  523. } else {
  524. // ((0xC0 & (*in) != 0x80) && (state != 0))
  525. // Incomplete multi-octet sequence.
  526. $state = 0;
  527. $codepoint = 0;
  528. $bytes = 1;
  529. $result[] = 0xFFFD;
  530. }
  531. }
  532. }
  533. return $result;
  534. }
  535. /**
  536. * Takes an array of Unicode codepoints and returns a UTF-8 string.
  537. * @param array $codepoints An array of Unicode codepoints representing a string.
  538. * @return string Returns a UTF-8 string constructed using the given codepoints.
  539. */
  540. function _api_utf8_from_unicode($codepoints) {
  541. return implode(array_map('_api_utf8_chr', $codepoints));
  542. }
  543. /**
  544. * Takes a codepoint and returns its correspondent UTF-8 encoded character.
  545. * Astral planes are supported, ie the intger input can be > 0xFFFF. Occurrances of the BOM are ignored.
  546. * Surrogates are not allowed.
  547. * @param int $codepoint The Unicode codepoint.
  548. * @return string Returns the corresponding UTF-8 character.
  549. * @author Henri Sivonen, mailto:hsivonen@iki.fi
  550. * @link http://hsivonen.iki.fi/php-utf8/
  551. * @author Ivan Tcholakov, 2009, modifications for the Dokeos LMS.
  552. * @see _api_utf8_from_unicode()
  553. * This is a UTF-8 aware version of the function chr().
  554. * @link http://php.net/manual/en/function.chr.php
  555. */
  556. function _api_utf8_chr($codepoint) {
  557. // ASCII range (including control chars)
  558. if ( ($codepoint >= 0) && ($codepoint <= 0x007f) ) {
  559. $result = chr($codepoint);
  560. // 2 byte sequence
  561. } else if ($codepoint <= 0x07ff) {
  562. $result = chr(0xc0 | ($codepoint >> 6)) . chr(0x80 | ($codepoint & 0x003f));
  563. // Byte order mark (skip)
  564. } else if($codepoint == 0xFEFF) {
  565. // nop -- zap the BOM
  566. $result = '';
  567. // Test for illegal surrogates
  568. } else if ($codepoint >= 0xD800 && $codepoint <= 0xDFFF) {
  569. // found a surrogate
  570. $result = _api_utf8_chr(0xFFFD); // U+FFFD REPLACEMENT CHARACTER is the general substitute character in the Unicode Standard.
  571. // 3 byte sequence
  572. } else if ($codepoint <= 0xffff) {
  573. $result = chr(0xe0 | ($codepoint >> 12)) . chr(0x80 | (($codepoint >> 6) & 0x003f)) . chr(0x80 | ($codepoint & 0x003f));
  574. // 4 byte sequence
  575. } else if ($codepoint <= 0x10ffff) {
  576. $result = chr(0xf0 | ($codepoint >> 18)) . chr(0x80 | (($codepoint >> 12) & 0x3f)) . chr(0x80 | (($codepoint >> 6) & 0x3f)) . chr(0x80 | ($codepoint & 0x3f));
  577. } else {
  578. // out of range
  579. $result = _api_utf8_chr(0xFFFD);
  580. }
  581. return $result;
  582. }
  583. /**
  584. * Takes the first UTF-8 character in a string and returns its Unicode codepoint.
  585. * @param string $utf8_character The UTF-8 encoded character.
  586. * @return int Returns: the codepoint; or 0xFFFD (unknown character) when the input string is empty.
  587. * This is a UTF-8 aware version of the function ord().
  588. * @link http://php.net/manual/en/function.ord.php
  589. * Note about a difference with the original funtion ord(): ord('') returns 0.
  590. */
  591. function _api_utf8_ord($utf8_character) {
  592. if (empty($utf8_character)) {
  593. return 0xFFFD;
  594. }
  595. $codepoints = _api_utf8_to_unicode($utf8_character);
  596. return $codepoints[0];
  597. }
  598. /**
  599. * Makes a html-entity from Unicode codepoint.
  600. * @param int $codepoint The Unicode codepoint.
  601. * @return string Returns the corresponding html-entity; or ASCII character if $codepoint < 128.
  602. */
  603. function _api_html_entity_from_unicode($codepoint) {
  604. if ($codepoint < 128) {
  605. return chr($codepoint);
  606. }
  607. return '&#'.$codepoint.';';
  608. }
  609. /**
  610. * Converts character encoding of a xml-formatted text. If inside the text the encoding is declared, it is modified accordingly.
  611. * @param string $string The text being converted.
  612. * @param string $to_encoding The encoding that text is being converted to.
  613. * @param string $from_encoding (optional) The encoding that text is being converted from. If the value is empty, it is tried to be detected then.
  614. * @return string Returns the converted xml-text.
  615. */
  616. function _api_convert_encoding_xml(&$string, $to_encoding, $from_encoding) {
  617. if (empty($from_encoding)) {
  618. $from_encoding = api_detect_encoding_xml($string);
  619. }
  620. global $_api_encoding;
  621. $_api_encoding = api_refine_encoding_id($to_encoding);
  622. return api_convert_encoding(preg_replace_callback(_PCRE_XML_ENCODING, '_api_convert_encoding_xml_callback', $string), $to_encoding, $from_encoding);
  623. }
  624. /**
  625. * A callback for serving the function _api_convert_encoding_xml().
  626. * @param array $matches Input array of matches corresponding to the xml-declaration.
  627. * @return string Returns the xml-declaration with modified encoding.
  628. */
  629. function _api_convert_encoding_xml_callback($matches) {
  630. global $_api_encoding;
  631. return str_replace($matches[1], $_api_encoding, $matches[0]);
  632. }
  633. /**
  634. * Appendix to "Common multibyte string functions"
  635. */
  636. /**
  637. * The following function reads case folding properties about a given character from a file-based "database".
  638. * @param int $codepoint The Unicode codepoint that represents a caharacter.
  639. * @param string $type (optional) The type of initial case to be altered: 'lower' (default) or 'upper'.
  640. * @return array Returns an array with properties used to change case of the character.
  641. */
  642. function &_api_utf8_get_letter_case_properties($codepoint, $type = 'lower') {
  643. static $config = array();
  644. static $range = array();
  645. if (!isset($range[$codepoint])) {
  646. if ($codepoint > 128 && $codepoint < 256) {
  647. $range[$codepoint] = '0080_00ff'; // Latin-1 Supplement
  648. } elseif ($codepoint < 384) {
  649. $range[$codepoint] = '0100_017f'; // Latin Extended-A
  650. } elseif ($codepoint < 592) {
  651. $range[$codepoint] = '0180_024F'; // Latin Extended-B
  652. } elseif ($codepoint < 688) {
  653. $range[$codepoint] = '0250_02af'; // IPA Extensions
  654. } elseif ($codepoint >= 880 && $codepoint < 1024) {
  655. $range[$codepoint] = '0370_03ff'; // Greek and Coptic
  656. } elseif ($codepoint < 1280) {
  657. $range[$codepoint] = '0400_04ff'; // Cyrillic
  658. } elseif ($codepoint < 1328) {
  659. $range[$codepoint] = '0500_052f'; // Cyrillic Supplement
  660. } elseif ($codepoint < 1424) {
  661. $range[$codepoint] = '0530_058f'; // Armenian
  662. } elseif ($codepoint >= 7680 && $codepoint < 7936) {
  663. $range[$codepoint] = '1e00_1eff'; // Latin Extended Additional
  664. } elseif ($codepoint < 8192) {
  665. $range[$codepoint] = '1f00_1fff'; // Greek Extended
  666. } elseif ($codepoint >= 8448 && $codepoint < 8528) {
  667. $range[$codepoint] = '2100_214f'; // Letterlike Symbols
  668. } elseif ($codepoint < 8592) {
  669. $range[$codepoint] = '2150_218f'; // Number Forms
  670. } elseif ($codepoint >= 9312 && $codepoint < 9472) {
  671. $range[$codepoint] = '2460_24ff'; // Enclosed Alphanumerics
  672. } elseif ($codepoint >= 11264 && $codepoint < 11360) {
  673. $range[$codepoint] = '2c00_2c5f'; // Glagolitic
  674. } elseif ($codepoint < 11392) {
  675. $range[$codepoint] = '2c60_2c7f'; // Latin Extended-C
  676. } elseif ($codepoint < 11520) {
  677. $range[$codepoint] = '2c80_2cff'; // Coptic
  678. } elseif ($codepoint >= 65280 && $codepoint < 65520) {
  679. $range[$codepoint] = 'ff00_ffef'; // Halfwidth and Fullwidth Forms
  680. } else {
  681. $range[$codepoint] = false;
  682. }
  683. if ($range[$codepoint] === false) {
  684. return null;
  685. }
  686. if (!isset($config[$range[$codepoint]])) {
  687. $file = dirname(__FILE__).'/internationalization_database/casefolding/' . $range[$codepoint] . '.php';
  688. if (file_exists($file)) {
  689. include $file;
  690. }
  691. }
  692. }
  693. if ($range[$codepoint] === false || !isset($config[$range[$codepoint]])) {
  694. return null;
  695. }
  696. $result = array();
  697. $count = count($config[$range[$codepoint]]);
  698. for ($i = 0; $i < $count; $i++) {
  699. if ($type === 'lower' && $config[$range[$codepoint]][$i][$type][0] === $codepoint) {
  700. $result[] = $config[$range[$codepoint]][$i];
  701. } elseif ($type === 'upper' && $config[$range[$codepoint]][$i][$type] === $codepoint) {
  702. $result[] = $config[$range[$codepoint]][$i];
  703. }
  704. }
  705. return $result;
  706. }
  707. /**
  708. * A callback for serving the function api_ucwords().
  709. * @param array $matches Input array of matches corresponding to a single word
  710. * @return string Returns a with first char of the word in uppercase
  711. */
  712. function _api_utf8_ucwords_callback($matches) {
  713. return $matches[2] . api_ucfirst(ltrim($matches[0]), 'UTF-8');
  714. }
  715. /**
  716. * Appendix to "Common sting operations with arrays"
  717. */
  718. /**
  719. * This callback function converts from UTF-8 to other encoding. It works with strings or arrays of strings.
  720. * @param mixed $variable The variable to be converted, a string or an array.
  721. * @return mixed Returns the converted form UTF-8 $variable with the same type, string or array.
  722. */
  723. function _api_array_utf8_decode($variable) {
  724. global $_api_encoding;
  725. if (is_array($variable)) {
  726. return array_map('_api_array_utf8_decode', $variable);
  727. }
  728. if (is_string($var)) {
  729. return api_utf8_decode($variable, $_api_encoding);
  730. }
  731. return $variable;
  732. }
  733. /**
  734. * Appendix to "String comparison"
  735. */
  736. /**
  737. * Returns an instance of Collator class (ICU) created for a specified language.
  738. * @param string $language (optional) Language indentificator: 'english', 'french' ... If it is omited, the current interface language is assumed.
  739. * @return object Returns a instance of Collator class that is suitable for common string comparisons.
  740. */
  741. function _api_get_collator($language = null) {
  742. static $collator = array();
  743. if (empty($language)) {
  744. $language = api_get_interface_language();
  745. }
  746. if (!isset($collator[$language])) {
  747. $locale = _api_get_locale_from_language($language);
  748. $collator[$language] = collator_create($locale);
  749. if (is_object($collator[$language])) {
  750. collator_set_attribute($collator[$language], Collator::CASE_FIRST, Collator::UPPER_FIRST);
  751. }
  752. }
  753. return $collator[$language];
  754. }
  755. /**
  756. * Returns an instance of Collator class (ICU) created for a specified language. This collator treats substrings of digits as numbers.
  757. * @param string $language (optional) Language indentificator. If it is omited, the current interface language is assumed.
  758. * @return object Returns a instance of Collator class that is suitable for alpha-numerical comparisons.
  759. */
  760. function _api_get_alpha_numerical_collator($language = null) {
  761. static $collator = array();
  762. if (empty($language)) {
  763. $language = api_get_interface_language();
  764. }
  765. if (!isset($collator[$language])) {
  766. $locale = _api_get_locale_from_language($language);
  767. $collator[$language] = collator_create($locale);
  768. if (is_object($collator[$language])) {
  769. collator_set_attribute($collator[$language], Collator::CASE_FIRST, Collator::UPPER_FIRST);
  770. collator_set_attribute($collator[$language], Collator::NUMERIC_COLLATION, Collator::ON);
  771. }
  772. }
  773. return $collator[$language];
  774. }
  775. /**
  776. * A string comparison callback function for sorting.
  777. * @param string $string1 The first string.
  778. * @param string $string2 The second string.
  779. * @return int Returns 0 if $string1 = $string2 or if there is an error; 1 if $string1 > $string2; -1 if $string1 < $string2.
  780. */
  781. function _api_cmp($string1, $string2) {
  782. global $_api_collator, $_api_encoding;
  783. $result = collator_compare($_api_collator, api_utf8_encode($string1, $_api_encoding), api_utf8_encode($string2, $_api_encoding));
  784. return $result === false ? 0 : $result;
  785. }
  786. /**
  787. * A reverse string comparison callback function for sorting.
  788. * @param string $string1 The first string.
  789. * @param string $string2 The second string.
  790. * @return int Returns 0 if $string1 = $string2 or if there is an error; 1 if $string1 < $string2; -1 if $string1 > $string2.
  791. */
  792. function _api_rcmp($string1, $string2) {
  793. global $_api_collator, $_api_encoding;
  794. $result = collator_compare($_api_collator, api_utf8_encode($string2, $_api_encoding), api_utf8_encode($string1, $_api_encoding));
  795. return $result === false ? 0 : $result;
  796. }
  797. /**
  798. * A case-insensitive string comparison callback function for sorting.
  799. * @param string $string1 The first string.
  800. * @param string $string2 The second string.
  801. * @return int Returns 0 if $string1 = $string2 or if there is an error; 1 if $string1 > $string2; -1 if $string1 < $string2.
  802. */
  803. function _api_casecmp($string1, $string2) {
  804. global $_api_collator, $_api_encoding;
  805. $result = collator_compare($_api_collator, api_strtolower(api_utf8_encode($string1, $_api_encoding), 'UTF-8'), api_strtolower(api_utf8_encode($string2, $_api_encoding), 'UTF-8'));
  806. return $result === false ? 0 : $result;
  807. }
  808. /**
  809. * A reverse case-insensitive string comparison callback function for sorting.
  810. * @param string $string1 The first string.
  811. * @param string $string2 The second string.
  812. * @return int Returns 0 if $string1 = $string2 or if there is an error; 1 if $string1 < $string2; -1 if $string1 > $string2.
  813. */
  814. function _api_casercmp($string1, $string2) {
  815. global $_api_collator, $_api_encoding;
  816. $result = collator_compare($_api_collator, api_strtolower(api_utf8_encode($string2, $_api_encoding), 'UTF-8'), api_strtolower(api_utf8_encode($string1, $_api_encoding), 'UTF-8'));
  817. return $result === false ? 0 : $result;
  818. }
  819. /**
  820. * A reverse function from php-core function strnatcmp(), performs string comparison in reverse natural (alpha-numerical) order.
  821. * @param string $string1 The first string.
  822. * @param string $string2 The second string.
  823. * @return int Returns 0 if $string1 = $string2; >0 if $string1 < $string2; <0 if $string1 > $string2.
  824. */
  825. function _api_strnatrcmp($string1, $string2) {
  826. return strnatcmp($string2, $string1);
  827. }
  828. /**
  829. * A reverse function from php-core function strnatcasecmp(), performs string comparison in reverse case-insensitive natural (alpha-numerical) order.
  830. * @param string $string1 The first string.
  831. * @param string $string2 The second string.
  832. * @return int Returns 0 if $string1 = $string2; >0 if $string1 < $string2; <0 if $string1 > $string2.
  833. */
  834. function _api_strnatcasercmp($string1, $string2) {
  835. return strnatcasecmp($string2, $string1);
  836. }
  837. /**
  838. * A fuction that translates sorting flag constants from php core to correspondent constants from intl extension.
  839. * @param int $sort_flag (optional) Sorting modifier flag as it is defined for php core. The default value is SORT_REGULAR.
  840. * @return int Retturns the corresponding sorting modifier flag as it is defined in intl php-extension.
  841. */
  842. function _api_get_collator_sort_flag($sort_flag = SORT_REGULAR) {
  843. switch ($sort_flag) {
  844. case SORT_STRING:
  845. case SORT_SORT_LOCALE_STRING:
  846. return Collator::SORT_STRING;
  847. case SORT_NUMERIC:
  848. return Collator::SORT_NUMERIC;
  849. }
  850. return Collator::SORT_REGULAR;
  851. }
  852. /**
  853. * ICU locales (accessible through intl extension).
  854. */
  855. /**
  856. * Returns isocode (see api_get_language_isocode()) which is purified accordingly to
  857. * be used by the php intl extension (ICU library).
  858. * @param string $language (optional) This is the name of the folder containing translations for the corresponding language.
  859. * If $language is omitted, interface language is assumed then.
  860. * @return string The found language locale id or null on error. Examples: bg, en, pt_BR, ...
  861. */
  862. function _api_get_locale_from_language($language = null) {
  863. static $locale = array();
  864. if (empty($language)) {
  865. $language = api_get_interface_language();
  866. }
  867. if (!isset($locale[$language])) {
  868. $locale[$language] = str_replace('-', '_', api_get_language_isocode($language));
  869. }
  870. return $locale[$language];
  871. }
  872. /**
  873. * Sets/gets the default internal value of the locale id (for the intl extension, ICU).
  874. * @param string $locale (optional) The locale id to be set. When it is omitted, the function returns (gets, reads) the default internal value.
  875. * @return mixed When the function sets the default value, it returns TRUE on success or FALSE on error. Otherwise the function returns as string the current default value.
  876. */
  877. function _api_set_default_locale($locale = null) {
  878. static $default_locale = 'en';
  879. if (!empty($locale)) {
  880. $default_locale = $locale;
  881. if (INTL_INSTALLED) {
  882. return @locale_set_default($locale);
  883. }
  884. return true;
  885. } else {
  886. if (INTL_INSTALLED) {
  887. $default_locale = @locale_get_default();
  888. }
  889. }
  890. return $default_locale;
  891. }
  892. /**
  893. * Gets the default internal value of the locale id (for the intl extension, ICU).
  894. * @return string Returns as string the current default value.
  895. */
  896. function api_get_default_locale() {
  897. return _api_set_default_locale();
  898. }
  899. /**
  900. * Appendix to "Encoding management functions"
  901. */
  902. /**
  903. * Returns a table with non-UTF-8 encodings for all system languages.
  904. * @return array Returns an array in the form array('language1' => array('encoding1', encoding2', ...), ...)
  905. * Note: The function api_get_non_utf8_encoding() returns the first encoding from this array that is correspondent to the given language.
  906. */
  907. function & _api_non_utf8_encodings() {
  908. static $encodings;
  909. if (!isset($encodings)) {
  910. $file = dirname(__FILE__).'/internationalization_database/non_utf8_encodings.php';
  911. if (file_exists($file)) {
  912. $encodings = include ($file);
  913. } else {
  914. $encodings = array('english' => array('ISO-8859-15'));
  915. }
  916. }
  917. return $encodings;
  918. }
  919. /**
  920. * Sets/Gets internal character encoding of the common string functions within the PHP mbstring extension.
  921. * @param string $encoding (optional) When this parameter is given, the function sets the internal encoding.
  922. * @return string When $encoding parameter is not given, the function returns the internal encoding.
  923. * Note: This function is used in the global initialization script for setting the internal encoding to the platform's character set.
  924. * @link http://php.net/manual/en/function.mb-internal-encoding
  925. */
  926. function _api_mb_internal_encoding($encoding = null) {
  927. static $mb_internal_encoding = null;
  928. if (empty($encoding)) {
  929. if (is_null($mb_internal_encoding)) {
  930. if (MBSTRING_INSTALLED) {
  931. $mb_internal_encoding = @mb_internal_encoding();
  932. } else {
  933. $mb_internal_encoding = 'ISO-8859-15';
  934. }
  935. }
  936. return $mb_internal_encoding;
  937. }
  938. $mb_internal_encoding = $encoding;
  939. if (_api_mb_supports($encoding)) {
  940. return @mb_internal_encoding($encoding);
  941. }
  942. return false;
  943. }
  944. /**
  945. * Sets/Gets internal character encoding of the regular expression functions (ereg-like) within the PHP mbstring extension.
  946. * @param string $encoding (optional) When this parameter is given, the function sets the internal encoding.
  947. * @return string When $encoding parameter is not given, the function returns the internal encoding.
  948. * Note: This function is used in the global initialization script for setting the internal encoding to the platform's character set.
  949. * @link http://php.net/manual/en/function.mb-regex-encoding
  950. */
  951. function _api_mb_regex_encoding($encoding = null) {
  952. static $mb_regex_encoding = null;
  953. if (empty($encoding)) {
  954. if (is_null($mb_regex_encoding)) {
  955. if (MBSTRING_INSTALLED) {
  956. $mb_regex_encoding = @mb_regex_encoding();
  957. } else {
  958. $mb_regex_encoding = 'ISO-8859-15';
  959. }
  960. }
  961. return $mb_regex_encoding;
  962. }
  963. $mb_regex_encoding = $encoding;
  964. if (_api_mb_supports($encoding)) {
  965. return @mb_regex_encoding($encoding);
  966. }
  967. return false;
  968. }
  969. /**
  970. * Retrieves specified internal encoding configuration variable within the PHP iconv extension.
  971. * @param string $type The parameter $type could be: 'iconv_internal_encoding', 'iconv_input_encoding', or 'iconv_output_encoding'.
  972. * @return mixed The function returns the requested encoding or FALSE on error.
  973. * @link http://php.net/manual/en/function.iconv-get-encoding
  974. */
  975. function _api_iconv_get_encoding($type) {
  976. return _api_iconv_set_encoding($type);
  977. }
  978. /**
  979. * Sets specified internal encoding configuration variables within the PHP iconv extension.
  980. * @param string $type The parameter $type could be: 'iconv_internal_encoding', 'iconv_input_encoding', or 'iconv_output_encoding'.
  981. * @param string $encoding (optional) The desired encoding to be set.
  982. * @return bool Returns TRUE on success, FALSE on error.
  983. * Note: This function is used in the global initialization script for setting these three internal encodings to the platform's character set.
  984. * @link http://php.net/manual/en/function.iconv-set-encoding
  985. */
  986. function _api_iconv_set_encoding($type, $encoding = null) {
  987. static $iconv_internal_encoding = null;
  988. static $iconv_input_encoding = null;
  989. static $iconv_output_encoding = null;
  990. if (!ICONV_INSTALLED) {
  991. return false;
  992. }
  993. switch ($type) {
  994. case 'iconv_internal_encoding':
  995. if (empty($encoding)) {
  996. if (is_null($iconv_internal_encoding)) {
  997. $iconv_internal_encoding = @iconv_get_encoding($type);
  998. }
  999. return $iconv_internal_encoding;
  1000. }
  1001. if (_api_iconv_supports($encoding)) {
  1002. if(@iconv_set_encoding($type, $encoding)) {
  1003. $iconv_internal_encoding = $encoding;
  1004. return true;
  1005. }
  1006. return false;
  1007. }
  1008. return false;
  1009. case 'iconv_input_encoding':
  1010. if (empty($encoding)) {
  1011. if (is_null($iconv_input_encoding)) {
  1012. $iconv_input_encoding = @iconv_get_encoding($type);
  1013. }
  1014. return $iconv_input_encoding;
  1015. }
  1016. if (_api_iconv_supports($encoding)) {
  1017. if(@iconv_set_encoding($type, $encoding)) {
  1018. $iconv_input_encoding = $encoding;
  1019. return true;
  1020. }
  1021. return false;
  1022. }
  1023. return false;
  1024. case 'iconv_output_encoding':
  1025. if (empty($encoding)) {
  1026. if (is_null($iconv_output_encoding)) {
  1027. $iconv_output_encoding = @iconv_get_encoding($type);
  1028. }
  1029. return $iconv_output_encoding;
  1030. }
  1031. if (_api_iconv_supports($encoding)) {
  1032. if(@iconv_set_encoding($type, $encoding)) {
  1033. $iconv_output_encoding = $encoding;
  1034. return true;
  1035. }
  1036. return false;
  1037. }
  1038. return false;
  1039. }
  1040. return false;
  1041. }
  1042. /**
  1043. * Ckecks whether a given encoding is known to define single-byte characters only.
  1044. * The result might be not accurate for unknown by this library encodings. This is not fatal,
  1045. * then the library picks up conversions plus Unicode related internal algorithms.
  1046. * @param string $encoding A given encoding identificator.
  1047. * @return bool TRUE if the encoding is known as single-byte (for ISO-8859-15, WINDOWS-1251, etc.), FALSE otherwise.
  1048. */
  1049. function _api_is_single_byte_encoding($encoding) {
  1050. static $checked = array();
  1051. if (!isset($checked[$encoding])) {
  1052. $character_map = _api_get_character_map_name(api_refine_encoding_id($encoding));
  1053. $checked[$encoding] = (!empty($character_map)
  1054. && !in_array($character_map, array('UTF-8', 'HTML-ENTITIES')));
  1055. }
  1056. return $checked[$encoding];
  1057. }
  1058. /**
  1059. * Checks whether the specified encoding is supported by the PHP mbstring extension.
  1060. * @param string $encoding The specified encoding.
  1061. * @return bool Returns TRUE when the specified encoding is supported, FALSE othewise.
  1062. */
  1063. function _api_mb_supports($encoding) {
  1064. static $supported = array();
  1065. if (!isset($supported[$encoding])) {
  1066. if (MBSTRING_INSTALLED) {
  1067. $supported[$encoding] = api_equal_encodings($encoding, mb_list_encodings(), true);
  1068. } else {
  1069. $supported[$encoding] = false;
  1070. }
  1071. }
  1072. return $supported[$encoding];
  1073. }
  1074. /**
  1075. * Checks whether the specified encoding is supported by the PHP iconv extension.
  1076. * @param string $encoding The specified encoding.
  1077. * @return bool Returns TRUE when the specified encoding is supported, FALSE othewise.
  1078. */
  1079. function _api_iconv_supports($encoding) {
  1080. static $supported = array();
  1081. if (!isset($supported[$encoding])) {
  1082. if (ICONV_INSTALLED) {
  1083. $enc = api_refine_encoding_id($encoding);
  1084. if ($enc != 'HTML-ENTITIES') {
  1085. $test_string = '';
  1086. for ($i = 32; $i < 128; $i++) {
  1087. $test_string .= chr($i);
  1088. }
  1089. $supported[$encoding] = (@iconv_strlen($test_string, $enc)) ? true : false;
  1090. } else {
  1091. $supported[$encoding] = false;
  1092. }
  1093. } else {
  1094. $supported[$encoding] = false;
  1095. }
  1096. }
  1097. return $supported[$encoding];
  1098. }
  1099. // This function checks whether the function _api_convert_encoding() (the php-
  1100. // implementation) is able to convert from/to a given encoding.
  1101. function _api_convert_encoding_supports($encoding) {
  1102. static $supports = array();
  1103. if (!isset($supports[$encoding])) {
  1104. $supports[$encoding] = _api_get_character_map_name(api_refine_encoding_id($encoding)) != '';
  1105. }
  1106. return $supports[$encoding];
  1107. }
  1108. /**
  1109. * Checks whether the specified encoding is supported by the html-entitiy related functions.
  1110. * @param string $encoding The specified encoding.
  1111. * @return bool Returns TRUE when the specified encoding is supported, FALSE othewise.
  1112. */
  1113. function _api_html_entity_supports($encoding) {
  1114. static $supports = array();
  1115. if (!isset($supports[$encoding])) {
  1116. // See http://php.net/manual/en/function.htmlentities.php
  1117. $html_entity_encodings = array(
  1118. 'ISO-8859-1',
  1119. 'ISO-8859-15',
  1120. 'UTF-8',
  1121. 'CP866',
  1122. 'CP1251',
  1123. 'CP1252',
  1124. 'KOI8-R',
  1125. 'BIG5', '950',
  1126. 'GB2312', '936',
  1127. 'BIG5-HKSCS',
  1128. 'Shift_JIS', 'SJIS', '932',
  1129. 'EUC-JP', 'EUCJP'
  1130. );
  1131. $supports[$encoding] = api_equal_encodings($encoding, $html_entity_encodings);
  1132. }
  1133. return $supports[$encoding];
  1134. }
  1135. /**
  1136. * Upgrading the PHP5 mbstring extension
  1137. */
  1138. // A multibyte replacement of strchr(). This function exists in PHP 5 >= 5.2.0
  1139. // See http://php.net/manual/en/function.mb-strrchr
  1140. if (MBSTRING_INSTALLED && !function_exists('mb_strchr')) {
  1141. function mb_strchr($haystack, $needle, $part = false, $encoding = null) {
  1142. if (empty($encoding)) {
  1143. $encoding = mb_internal_encoding();
  1144. }
  1145. return mb_strstr($haystack, $needle, $part, $encoding);
  1146. }
  1147. }
  1148. // A multibyte replacement of stripos(). This function exists in PHP 5 >= 5.2.0
  1149. // See http://php.net/manual/en/function.mb-stripos
  1150. if (MBSTRING_INSTALLED && !function_exists('mb_stripos')) {
  1151. function mb_stripos($haystack, $needle, $offset = 0, $encoding = null) {
  1152. if (empty($encoding)) {
  1153. $encoding = mb_internal_encoding();
  1154. }
  1155. return mb_strpos(mb_strtolower($haystack, $encoding), mb_strtolower($needle, $encoding), $offset, $encoding);
  1156. }
  1157. }
  1158. // A multibyte replacement of stristr(). This function exists in PHP 5 >= 5.2.0
  1159. // See http://php.net/manual/en/function.mb-stristr
  1160. if (MBSTRING_INSTALLED && !function_exists('mb_stristr')) {
  1161. function mb_stristr($haystack, $needle, $part = false, $encoding = null) {
  1162. if (empty($encoding)) {
  1163. $encoding = mb_internal_encoding();
  1164. }
  1165. $pos = mb_strpos(mb_strtolower($haystack, $encoding), mb_strtolower($needle, $encoding), 0, $encoding);
  1166. if ($pos === false) {
  1167. return false;
  1168. }
  1169. if ($part) {
  1170. return mb_substr($haystack, 0, $pos + 1, $encoding);
  1171. }
  1172. return mb_substr($haystack, $pos, mb_strlen($haystack, $encoding), $encoding);
  1173. }
  1174. }
  1175. // A multibyte replacement of strrchr(). This function exists in PHP 5 >= 5.2.0
  1176. // See http://php.net/manual/en/function.mb-strrchr
  1177. if (MBSTRING_INSTALLED && !function_exists('mb_strrchr')) {
  1178. function mb_strrchr($haystack, $needle, $part = false, $encoding = null) {
  1179. if (empty($encoding)) {
  1180. $encoding = mb_internal_encoding();
  1181. }
  1182. $needle = mb_substr($needle, 0, 1, $encoding);
  1183. $pos = mb_strrpos($haystack, $needle, mb_strlen($haystack, $encoding) - 1, $encoding);
  1184. if ($pos === false) {
  1185. return false;
  1186. }
  1187. if ($part) {
  1188. return mb_substr($haystack, 0, $pos + 1, $encoding);
  1189. }
  1190. return mb_substr($haystack, $pos, mb_strlen($haystack, $encoding), $encoding);
  1191. }
  1192. }
  1193. // A multibyte replacement of strstr(). This function exists in PHP 5 >= 5.2.0
  1194. // See http://php.net/manual/en/function.mb-strstr
  1195. if (MBSTRING_INSTALLED && !function_exists('mb_strstr')) {
  1196. function mb_strstr($haystack, $needle, $part = false, $encoding = null) {
  1197. if (empty($encoding)) {
  1198. $encoding = mb_internal_encoding();
  1199. }
  1200. $pos = mb_strpos($haystack, $needle, 0, $encoding);
  1201. if ($pos === false) {
  1202. return false;
  1203. }
  1204. if ($part) {
  1205. return mb_substr($haystack, 0, $pos + 1, $encoding);
  1206. }
  1207. return mb_substr($haystack, $pos, mb_strlen($haystack, $encoding), $encoding);
  1208. }
  1209. }