internationalization.lib.php 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * File: internationalization.lib.php
  5. * Internationalization library for Chamilo 1.8.7 LMS
  6. * A library implementing internationalization related functions.
  7. * License: GNU General Public License Version 3 (Free Software Foundation)ww
  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. use Patchwork\Utf8;
  13. /**
  14. * Constants
  15. */
  16. // Special tags for marking untranslated variables.
  17. define('SPECIAL_OPENING_TAG', '[=');
  18. define('SPECIAL_CLOSING_TAG', '=]');
  19. // Predefined date formats in Chamilo provided by the language sub-system.
  20. // To be used as a parameter for the function api_format_date()
  21. define('TIME_NO_SEC_FORMAT', 0); // 15:23
  22. define('DATE_FORMAT_SHORT', 1); // Aug 25, 09
  23. define('DATE_FORMAT_LONG', 2); // Monday August 25, 09
  24. define('DATE_FORMAT_LONG_NO_DAY', 10); // August 25, 2009
  25. define('DATE_TIME_FORMAT_LONG', 3); // Monday August 25, 2009 at 03:28 PM
  26. define('DATE_FORMAT_NUMBER', 4); // 25.08.09
  27. define('DATE_TIME_FORMAT_LONG_24H', 5); // August 25, 2009 at 15:28
  28. define('DATE_TIME_FORMAT_SHORT', 6); // Aug 25, 2009 at 03:28 PM
  29. define('DATE_TIME_FORMAT_SHORT_TIME_FIRST', 7); // 03:28 PM, Aug 25 2009
  30. define('DATE_FORMAT_NUMBER_NO_YEAR', 8); // 25.08 dd-mm
  31. define('DATE_FORMAT_ONLY_DAYNAME', 9); // Monday, Sunday, etc
  32. // Formatting person's name.
  33. // Formatting a person's name using the pattern as it has been
  34. // configured in the internationalization database for every language.
  35. // This (default) option would be the most used.
  36. define('PERSON_NAME_COMMON_CONVENTION', 0);
  37. // The following options may be used in limited number of places for overriding the common convention:
  38. // Formatting a person's name in Western order: first_name last_name
  39. define('PERSON_NAME_WESTERN_ORDER', 1);
  40. // Formatting a person's name in Eastern order: last_name first_name
  41. define('PERSON_NAME_EASTERN_ORDER', 2);
  42. // Contextual: formatting person's name in library order: last_name, first_name
  43. define('PERSON_NAME_LIBRARY_ORDER', 3);
  44. // Contextual: formatting a person's name assotiated with an email-address.
  45. // Ivan: I am not sure how seems email servers an clients would interpret name order, so I assign the Western order.
  46. define('PERSON_NAME_EMAIL_ADDRESS', PERSON_NAME_WESTERN_ORDER);
  47. // Contextual: formatting a person's name for data-exporting operations.
  48. // For backward compatibility this format has been set to Eastern order.
  49. define('PERSON_NAME_DATA_EXPORT', PERSON_NAME_EASTERN_ORDER);
  50. // The following constants are used for tuning language detection functionality.
  51. // We reduce the text for language detection to the given number of characters
  52. // for increasing speed and to decrease memory consumption.
  53. define('LANGUAGE_DETECT_MAX_LENGTH', 2000);
  54. // Maximum allowed difference in so called delta-points for aborting certain language detection.
  55. // The value 80000 is good enough for speed and detection accuracy.
  56. // If you set the value of $max_delta too low, no language will be recognized.
  57. // $max_delta = 400 * 350 = 140000 is the best detection with lowest speed.
  58. define('LANGUAGE_DETECT_MAX_DELTA', 140000);
  59. /**
  60. * Returns a translated (localized) string, called by its identificator.
  61. * @param string $variable This is the identificator (name) of the translated string to be retrieved.
  62. * @param string $reserved This parameter has been reserved for future use.
  63. * @param string $language (optional) Language indentificator. If it is omited, the current interface language is assumed.
  64. * @return string Returns the requested string in the correspondent language.
  65. *
  66. * @author Roan Embrechts
  67. * @author Patrick Cool
  68. * @author Ivan Tcholakov, 2009-2010 (caching functionality, additional parameter $language, other adaptations).
  69. *
  70. * Notes:
  71. * 1. If the name of a given language variable has the prefix "lang" it may be omited, i.e. get_lang('Yes') == get_lang('Yes').
  72. * 2. Untranslated variables might be indicated by special opening and closing tags - [= =]
  73. * The special tags do not show up in these two cases:
  74. * - when the system has been switched to "production server mode";
  75. * - when a special platform setting 'hide_dltt_markup' is set to "true" (the name of this setting comes from history);
  76. * 3. Translations are created many contributors through using a special tool: Chamilo Translation Application.
  77. * @link http://translate.chamilo.org/
  78. */
  79. function get_lang($variable, $reserved = null, $language = null) {
  80. global
  81. // For serving some old hacks:
  82. // By manipulating this global variable the translation may be done in different languages too (not the elegant way).
  83. $language_interface,
  84. // Because of possibility for manipulations of the global variable $language_interface, we need its initial value.
  85. $language_interface_initial_value;
  86. global $used_lang_vars, $_configuration;
  87. // add language_measure_frequency to your main/inc/conf/configuration.php in order to generate language
  88. // variables frequency measurements (you can then see them trhough main/cron/lang/langstats.php)
  89. // The $langstats object is instanciated at the end of main/inc/global.inc.php
  90. if (isset($_configuration['language_measure_frequency']) &&
  91. $_configuration['language_measure_frequency'] == 1
  92. ) {
  93. require_once api_get_path(SYS_CODE_PATH).'/cron/lang/langstats.class.php';
  94. global $langstats;
  95. $langstats->add_use($variable,'');
  96. }
  97. if (!isset($used_lang_vars)) {
  98. $used_lang_vars = array();
  99. }
  100. // Caching results from some API functions, for speed.
  101. static $initialized, $encoding, $langpath, $test_server_mode, $show_special_markup;
  102. if (!isset($initialized)) {
  103. $langpath = api_get_path(SYS_LANG_PATH);
  104. $test_server_mode = api_get_setting('server_type') == 'test';
  105. $show_special_markup = api_get_setting('hide_dltt_markup') != 'true' || $test_server_mode;
  106. $initialized = true;
  107. }
  108. // Combining both ways for requesting specific language.
  109. if (empty($language)) {
  110. $language = $language_interface;
  111. }
  112. $lang_postfix = isset($is_interface_language) && $is_interface_language ? '' : '('.$language.')';
  113. $is_interface_language = $language == $language_interface_initial_value;
  114. // This is a cache for already translated language variables. By using it, we avoid repetitive translations, gaining speed.
  115. static $cache;
  116. // Looking up into the cache for existing translation.
  117. if (isset($cache[$language][$variable])) {
  118. // There is a previously saved translation, returning it.
  119. //return $cache[$language][$variable];
  120. $ret = $cache[$language][$variable];
  121. $used_lang_vars[$variable.$lang_postfix] = $ret;
  122. return $ret;
  123. }
  124. // There is no cached translation, we have to retrieve it:
  125. // - from a global variable (the faster way) - on production server mode;
  126. // - from a local variable after reloading the language files - on test server mode or when requested language
  127. // is different than the genuine interface language.
  128. $read_global_variables = $is_interface_language;
  129. if ($read_global_variables) {
  130. if (isset($GLOBALS[$variable])) {
  131. $langvar = $GLOBALS[$variable];
  132. } elseif (isset($GLOBALS["lang$variable"])) {
  133. $langvar = $GLOBALS["lang$variable"];
  134. } else {
  135. $langvar = $show_special_markup ? SPECIAL_OPENING_TAG.$variable.SPECIAL_CLOSING_TAG : $variable;
  136. }
  137. } else {
  138. /*if (isset($$variable)) {
  139. $langvar = $$variable;
  140. } elseif (isset(${"lang$variable"})) {
  141. $langvar = ${"lang$variable"};
  142. } else {
  143. $langvar = $show_special_markup ? SPECIAL_OPENING_TAG.$variable.SPECIAL_CLOSING_TAG : $variable;
  144. }*/
  145. }
  146. if (empty($langvar) || !is_string($langvar)) {
  147. $langvar = $show_special_markup ? SPECIAL_OPENING_TAG.$variable.SPECIAL_CLOSING_TAG : $variable;
  148. }
  149. $ret = $cache[$language][$variable] = $langvar;
  150. $used_lang_vars[$variable.$lang_postfix] = $ret;
  151. return $ret;
  152. }
  153. /**
  154. * Gets the current interface language.
  155. * @param bool $purified (optional) When it is true, a purified (refined)
  156. * language value will be returned, for example 'french' instead of 'french_unicode'.
  157. * @return string The current language of the interface.
  158. */
  159. function api_get_interface_language($purified = false, $check_sub_language = false)
  160. {
  161. global $language_interface;
  162. if (empty($language_interface)) {
  163. return 'english';
  164. }
  165. if ($check_sub_language) {
  166. static $parent_language_name = null;
  167. if (!isset($parent_language_name)) {
  168. // 2. The current language is a sub language so we grab the father's
  169. // setting according to the internalization_database/name_order_convetions.php file
  170. $language_id = api_get_language_id($language_interface);
  171. $language_info = api_get_language_info($language_id);
  172. if (
  173. !empty($language_id) &&
  174. !empty($language_info)
  175. ) {
  176. if (!empty($language_info['parent_id'])) {
  177. $language_info = api_get_language_info($language_info['parent_id']);
  178. $parent_language_name = $language_info['english_name'];
  179. if (!empty($parent_language_name)) {
  180. return $parent_language_name;
  181. }
  182. }
  183. return $language_info['english_name'];
  184. }
  185. return 'english';
  186. } else {
  187. return $parent_language_name;
  188. }
  189. } else {
  190. // 2. Normal way
  191. $interface_language = $purified ? api_purify_language_id($language_interface) : $language_interface;
  192. }
  193. return $interface_language;
  194. }
  195. /**
  196. * Returns a purified language id, without possible suffixes that will disturb language identification in certain cases.
  197. * @param string $language The input language identificator, for example 'french_unicode'.
  198. * @param string The same purified or filtered language identificator, for example 'french'.
  199. */
  200. function api_purify_language_id($language) {
  201. static $purified = array();
  202. if (!isset($purified[$language])) {
  203. $purified[$language] = trim(str_replace(array('_unicode', '_latin', '_corporate', '_org', '_km'), '', strtolower($language)));
  204. }
  205. return $purified[$language];
  206. }
  207. /**
  208. * Gets language isocode column from the language table, taking the given language as a query parameter.
  209. * @param string $language This is the name of the folder containing translations for the corresponding language (e.g arabic, english).
  210. * @param string $default_code This is the value to be returned if there was no code found corresponding to the given language.
  211. * If $language is omitted, interface language is assumed then.
  212. * @return string The found isocode or null on error.
  213. * Returned codes are according to the following standards (in order of preference):
  214. * - ISO 639-1 : Alpha-2 code (two-letters code - en, fr, es, ...)
  215. * - RFC 4646 : five-letter code based on the ISO 639 two-letter language codes
  216. * and the ISO 3166 two-letter territory codes (pt-BR, ...)
  217. * - ISO 639-2 : Alpha-3 code (three-letters code - ast, fur, ...)
  218. */
  219. function api_get_language_isocode($language = null, $default_code = 'en')
  220. {
  221. static $iso_code = array();
  222. if (empty($language)) {
  223. $language = api_get_interface_language(false, true);
  224. }
  225. if (!isset($iso_code[$language])) {
  226. if (!class_exists('Database')) {
  227. return $default_code; // This might happen, in case of calling this function early during the global initialization.
  228. }
  229. $sql_result = Database::query("SELECT isocode FROM ".Database::get_main_table(TABLE_MAIN_LANGUAGE)." WHERE dokeos_folder = '$language'");
  230. if (Database::num_rows($sql_result)) {
  231. $result = Database::fetch_array($sql_result);
  232. $iso_code[$language] = trim($result['isocode']);
  233. } else {
  234. $language_purified_id = api_purify_language_id($language);
  235. $iso_code[$language] = isset($iso_code[$language_purified_id]) ? $iso_code[$language_purified_id] : null;
  236. }
  237. if (empty($iso_code[$language])) {
  238. $iso_code[$language] = $default_code;
  239. }
  240. }
  241. return $iso_code[$language];
  242. }
  243. /**
  244. * Gets language isocode column from the language table
  245. *
  246. * @return array An array with the current isocodes
  247. *
  248. * */
  249. function api_get_platform_isocodes()
  250. {
  251. $iso_code = array();
  252. $sql_result = Database::query("SELECT isocode FROM ".Database::get_main_table(TABLE_MAIN_LANGUAGE)." ORDER BY isocode ");
  253. if (Database::num_rows($sql_result)) {
  254. while ($row = Database::fetch_array($sql_result)) {;
  255. $iso_code[] = trim($row['isocode']);
  256. }
  257. }
  258. return $iso_code;
  259. }
  260. /**
  261. * Gets text direction according to the given language.
  262. * @param string $language This is the name of the
  263. * folder containing translations for the corresponding language (e.g 'arabic', 'english', ...).
  264. * ISO-codes are acceptable too ('ar', 'en', ...).
  265. * If $language is omitted, interface language is assumed then.
  266. * @return string The correspondent to the language text direction ('ltr' or 'rtl').
  267. */
  268. function api_get_text_direction($language = null)
  269. {
  270. static $text_direction = array();
  271. if (empty($language)) {
  272. $language = api_get_interface_language();
  273. }
  274. if (!isset($text_direction[$language])) {
  275. $text_direction[$language] = in_array(api_purify_language_id($language),
  276. array(
  277. 'arabic',
  278. 'ar',
  279. 'dari',
  280. 'prs',
  281. 'hebrew',
  282. 'he',
  283. 'iw',
  284. 'pashto',
  285. 'ps',
  286. 'persian',
  287. 'fa',
  288. 'ur',
  289. 'yiddish',
  290. 'yid'
  291. )
  292. ) ? 'rtl' : 'ltr';
  293. }
  294. return $text_direction[$language];
  295. }
  296. /**
  297. * Returns an alphabetized list of timezones in an associative array that can be used to populate a select
  298. *
  299. * @return array List of timezone identifiers
  300. *
  301. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  302. */
  303. function api_get_timezones()
  304. {
  305. $timezone_identifiers = DateTimeZone::listIdentifiers();
  306. sort($timezone_identifiers);
  307. $out = array();
  308. foreach ($timezone_identifiers as $tz) {
  309. $out[$tz] = $tz;
  310. }
  311. $null_option = array('' => '');
  312. $result = array_merge($null_option, $out);
  313. return $result;
  314. }
  315. /**
  316. * Returns the timezone to be converted to/from, based on user or admin preferences
  317. *
  318. * @return string The timezone chosen
  319. */
  320. function _api_get_timezone()
  321. {
  322. // First, get the default timezone of the server
  323. $to_timezone = date_default_timezone_get();
  324. // Second, see if a timezone has been chosen for the platform
  325. $timezone_value = api_get_setting('timezone_value', 'timezones');
  326. if ($timezone_value != null) {
  327. $to_timezone = $timezone_value;
  328. }
  329. // If allowed by the administrator
  330. $use_users_timezone = api_get_setting('use_users_timezone', 'timezones');
  331. if ($use_users_timezone == 'true') {
  332. $userId = api_get_user_id();
  333. // Get the timezone based on user preference, if it exists
  334. $timezone_user = UserManager::get_extra_user_data_by_field($userId,'timezone');
  335. if (isset($timezone_user['timezone']) && $timezone_user['timezone'] != null) {
  336. $to_timezone = $timezone_user['timezone'];
  337. }
  338. }
  339. return $to_timezone;
  340. }
  341. /**
  342. * Returns the given date as a DATETIME in UTC timezone.
  343. * This function should be used before entering any date in the DB.
  344. *
  345. * @param mixed The date to be converted (can be a string supported by date() or a timestamp)
  346. * @param bool if the date is not correct return null instead of the current date
  347. * @return string The DATETIME in UTC to be inserted in the DB,
  348. * or null if the format of the argument is not supported
  349. *
  350. * @author Julio Montoya - Adding the 2nd parameter
  351. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  352. */
  353. function api_get_utc_datetime($time = null, $return_null_if_invalid_date = false)
  354. {
  355. $from_timezone = _api_get_timezone();
  356. $to_timezone = 'UTC';
  357. if (is_null($time) || empty($time) || $time == '0000-00-00 00:00:00') {
  358. if ($return_null_if_invalid_date) {
  359. return null;
  360. }
  361. return gmdate('Y-m-d H:i:s');
  362. }
  363. // If time is a timestamp, return directly in utc
  364. if (is_numeric($time)) {
  365. $time = intval($time);
  366. return gmdate('Y-m-d H:i:s', $time);
  367. }
  368. try {
  369. $date = new DateTime($time, new DateTimezone($from_timezone));
  370. $date->setTimezone(new DateTimeZone($to_timezone));
  371. return $date->format('Y-m-d H:i:s');
  372. } catch (Exception $e) {
  373. return null;
  374. }
  375. }
  376. /**
  377. * Returns a DATETIME string converted to the right timezone
  378. * @param mixed The time to be converted
  379. * @param string The timezone to be converted to.
  380. * If null, the timezone will be determined based on user preference,
  381. * or timezone chosen by the admin for the platform.
  382. * @param string The timezone to be converted from. If null, UTC will be assumed.
  383. * @return string The converted time formatted as Y-m-d H:i:s
  384. *
  385. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  386. */
  387. function api_get_local_time($time = null, $to_timezone = null, $from_timezone = null, $return_null_if_invalid_date = false)
  388. {
  389. // Determining the timezone to be converted from
  390. if (is_null($from_timezone)) {
  391. $from_timezone = 'UTC';
  392. }
  393. // Determining the timezone to be converted to
  394. if (is_null($to_timezone)) {
  395. $to_timezone = _api_get_timezone();
  396. }
  397. // If time is a timestamp, convert it to a string
  398. if (is_null($time) || empty($time) || $time == '0000-00-00 00:00:00') {
  399. if ($return_null_if_invalid_date) {
  400. return null;
  401. }
  402. $from_timezone = 'UTC';
  403. $time = gmdate('Y-m-d H:i:s');
  404. }
  405. if (is_numeric($time)) {
  406. $time = intval($time);
  407. $from_timezone = 'UTC';
  408. $time = gmdate('Y-m-d H:i:s', $time);
  409. }
  410. if ($time instanceof DateTime) {
  411. $time = $time->format('Y-m-d H:i:s');
  412. $from_timezone = 'UTC';
  413. }
  414. try {
  415. $date = new DateTime($time, new DateTimezone($from_timezone));
  416. $date->setTimezone(new DateTimeZone($to_timezone));
  417. return $date->format('Y-m-d H:i:s');
  418. } catch (Exception $e) {
  419. return null;
  420. }
  421. }
  422. /**
  423. * Converts a string into a timestamp safely (handling timezones), using strtotime
  424. *
  425. * @param string String to be converted
  426. * @param string Timezone (if null, the timezone will be determined based
  427. * on user preference, or timezone chosen by the admin for the platform)
  428. * @return int Timestamp
  429. *
  430. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  431. */
  432. function api_strtotime($time, $timezone = null) {
  433. $system_timezone = date_default_timezone_get();
  434. if (!empty($timezone)) {
  435. date_default_timezone_set($timezone);
  436. }
  437. $timestamp = strtotime($time);
  438. date_default_timezone_set($system_timezone);
  439. return $timestamp;
  440. }
  441. /**
  442. * Returns formatted date/time, correspondent to a given language.
  443. * The given date should be in the timezone chosen by the administrator
  444. * and/or user. Use api_get_local_time to get it.
  445. *
  446. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  447. * @author Christophe Gesche<gesche@ipm.ucl.ac.be>
  448. * originally inspired from from PhpMyAdmin
  449. * @author Ivan Tcholakov, 2009, code refactoring, adding support for predefined date/time formats.
  450. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  451. *
  452. * @param mixed Timestamp or datetime string
  453. * @param mixed Date format (string or int; see date formats in the Chamilo system: TIME_NO_SEC_FORMAT, DATE_FORMAT_SHORT, DATE_FORMAT_LONG, DATE_TIME_FORMAT_LONG)
  454. * @param string $language (optional) Language identificator. If it is omited, the current interface language is assumed.
  455. * @return string Returns the formatted date.
  456. *
  457. * @link http://php.net/manual/en/function.strftime.php
  458. */
  459. function api_format_date($time, $format = null, $language = null)
  460. {
  461. $system_timezone = date_default_timezone_get();
  462. date_default_timezone_set(_api_get_timezone());
  463. if (is_string($time)) {
  464. $time = strtotime($time);
  465. }
  466. if (is_null($format)) {
  467. $format = DATE_TIME_FORMAT_LONG;
  468. }
  469. $datetype = null;
  470. $timetype = null;
  471. if (is_int($format)) {
  472. switch ($format) {
  473. case DATE_FORMAT_ONLY_DAYNAME:
  474. $date_format = get_lang('dateFormatOnlyDayName', '', $language);
  475. if (INTL_INSTALLED) {
  476. $datetype = IntlDateFormatter::SHORT;
  477. $timetype = IntlDateFormatter::NONE;
  478. }
  479. break;
  480. case DATE_FORMAT_NUMBER_NO_YEAR:
  481. $date_format = get_lang('dateFormatShortNumberNoYear', '', $language);
  482. if (INTL_INSTALLED) {
  483. $datetype = IntlDateFormatter::SHORT;
  484. $timetype = IntlDateFormatter::NONE;
  485. }
  486. break;
  487. case DATE_FORMAT_NUMBER:
  488. $date_format = get_lang('dateFormatShortNumber', '', $language);
  489. if (INTL_INSTALLED) {
  490. $datetype = IntlDateFormatter::SHORT;
  491. $timetype = IntlDateFormatter::NONE;
  492. }
  493. break;
  494. case TIME_NO_SEC_FORMAT:
  495. $date_format = get_lang('timeNoSecFormat', '', $language);
  496. if (INTL_INSTALLED) {
  497. $datetype = IntlDateFormatter::NONE;
  498. $timetype = IntlDateFormatter::SHORT;
  499. }
  500. break;
  501. case DATE_FORMAT_SHORT:
  502. $date_format = get_lang('dateFormatShort', '', $language);
  503. if (INTL_INSTALLED) {
  504. $datetype = IntlDateFormatter::LONG;
  505. $timetype = IntlDateFormatter::NONE;
  506. }
  507. break;
  508. case DATE_FORMAT_LONG:
  509. $date_format = get_lang('dateFormatLong', '', $language);
  510. if (INTL_INSTALLED) {
  511. $datetype = IntlDateFormatter::FULL;
  512. $timetype = IntlDateFormatter::NONE;
  513. }
  514. break;
  515. case DATE_TIME_FORMAT_LONG:
  516. $date_format = get_lang('dateTimeFormatLong', '', $language);
  517. if (INTL_INSTALLED) {
  518. $datetype = IntlDateFormatter::FULL;
  519. $timetype = IntlDateFormatter::SHORT;
  520. }
  521. break;
  522. case DATE_FORMAT_LONG_NO_DAY:
  523. $date_format = get_lang('dateFormatLongNoDay', '', $language);
  524. if (INTL_INSTALLED) {
  525. $datetype = IntlDateFormatter::FULL;
  526. $timetype = IntlDateFormatter::SHORT;
  527. }
  528. break;
  529. case DATE_TIME_FORMAT_SHORT:
  530. $date_format = get_lang('dateTimeFormatShort', '', $language);
  531. if (INTL_INSTALLED) {
  532. $datetype = IntlDateFormatter::FULL;
  533. $timetype = IntlDateFormatter::SHORT;
  534. }
  535. break;
  536. case DATE_TIME_FORMAT_SHORT_TIME_FIRST:
  537. $date_format = get_lang('dateTimeFormatShortTimeFirst', '', $language);
  538. if (INTL_INSTALLED) {
  539. $datetype = IntlDateFormatter::FULL;
  540. $timetype = IntlDateFormatter::SHORT;
  541. }
  542. break;
  543. case DATE_TIME_FORMAT_LONG_24H:
  544. $date_format = get_lang('dateTimeFormatLong24H', '', $language);
  545. if (INTL_INSTALLED) {
  546. $datetype = IntlDateFormatter::FULL;
  547. $timetype = IntlDateFormatter::SHORT;
  548. }
  549. break;
  550. default:
  551. $date_format = get_lang('dateTimeFormatLong', '', $language);
  552. if (INTL_INSTALLED) {
  553. $datetype = IntlDateFormatter::FULL;
  554. $timetype = IntlDateFormatter::SHORT;
  555. }
  556. }
  557. } else {
  558. $date_format = $format;
  559. }
  560. if (0) {
  561. //if using PHP 5.3 format dates like: $dateFormatShortNumber, can't be used
  562. //
  563. // Use ICU
  564. if (is_null($language)) {
  565. $language = api_get_language_isocode();
  566. }
  567. $date_formatter = new IntlDateFormatter($language, $datetype, $timetype, date_default_timezone_get());
  568. //$date_formatter->setPattern($date_format);
  569. $formatted_date = api_to_system_encoding($date_formatter->format($time), 'UTF-8');
  570. } else {
  571. // We replace %a %A %b %B masks of date format with translated strings
  572. $translated = &_api_get_day_month_names($language);
  573. $date_format = str_replace(array('%A', '%a', '%B', '%b'),
  574. array($translated['days_long'][(int)strftime('%w', $time )],
  575. $translated['days_short'][(int)strftime('%w', $time)],
  576. $translated['months_long'][(int)strftime('%m', $time) - 1],
  577. $translated['months_short'][(int)strftime('%m', $time) - 1]),
  578. $date_format);
  579. $formatted_date = api_to_system_encoding(strftime($date_format, $time), 'UTF-8');
  580. }
  581. date_default_timezone_set($system_timezone);
  582. return $formatted_date;
  583. }
  584. /**
  585. * Returns the difference between the current date (date(now)) with the parameter $date in a string format like "2 days, 1 hour"
  586. * Example: $date = '2008-03-07 15:44:08';
  587. * date_to_str($date) it will return 3 days, 20 hours
  588. * The given date should be in the timezone chosen by the user or administrator. Use api_get_local_time() to get it...
  589. *
  590. * @param string The string has to be the result of a date function in this format -> date('Y-m-d H:i:s', time());
  591. * @return string The difference between the current date and the parameter in a literal way "3 days, 2 hour" *
  592. * @author Julio Montoya
  593. */
  594. function date_to_str_ago($date)
  595. {
  596. static $initialized = false;
  597. static $today, $yesterday;
  598. static $min_decade, $min_year, $min_month, $min_week, $min_day, $min_hour, $min_minute;
  599. static $min_decades, $min_years, $min_months, $min_weeks, $min_days, $min_hours, $min_minutes;
  600. static $sec_time_time, $sec_time_sing, $sec_time_plu;
  601. $system_timezone = date_default_timezone_get();
  602. date_default_timezone_set(_api_get_timezone());
  603. if (!$initialized) {
  604. $today = get_lang('Today');
  605. $yesterday = get_lang('Yesterday');
  606. $min_decade = get_lang('MinDecade');
  607. $min_year = get_lang('MinYear');
  608. $min_month = get_lang('MinMonth');
  609. $min_week = get_lang('MinWeek');
  610. $min_day = get_lang('MinDay');
  611. $min_hour = get_lang('MinHour');
  612. $min_minute = get_lang('MinMinute');
  613. $min_decades = get_lang('MinDecades');
  614. $min_years = get_lang('MinYears');
  615. $min_months = get_lang('MinMonths');
  616. $min_weeks = get_lang('MinWeeks');
  617. $min_days = get_lang('MinDays');
  618. $min_hours = get_lang('MinHours');
  619. $min_minutes = get_lang('MinMinutes');
  620. // original 1
  621. //$sec_time=array('century'=>3.1556926*pow(10,9),'decade'=>315569260,'year'=>31556926,'month'=>2629743.83,'week'=>604800,'day'=>86400,'hour'=>3600,'minute'=>60,'second'=>1);
  622. //$sec_time=array(get_lang('MinDecade')=>315569260,get_lang('MinYear')=>31556926,get_lang('MinMonth')=>2629743.83,get_lang('MinWeek')=>604800,get_lang('MinDay')=>86400,get_lang('MinHour')=>3600,get_lang('MinMinute')=>60);
  623. $sec_time_time = array(315569260, 31556926, 2629743.83, 604800, 86400, 3600, 60);
  624. $sec_time_sing = array($min_decade, $min_year, $min_month, $min_week, $min_day, $min_hour, $min_minute);
  625. $sec_time_plu = array($min_decades, $min_years, $min_months, $min_weeks, $min_days, $min_hours, $min_minutes);
  626. $initialized = true;
  627. }
  628. $dst_date = is_string($date) ? strtotime($date) : $date;
  629. // For avoiding calling date() several times
  630. $date_array = date('s/i/G/j/n/Y', $dst_date);
  631. $date_split = explode('/', $date_array);
  632. $dst_s = $date_split[0];
  633. $dst_m = $date_split[1];
  634. $dst_h = $date_split[2];
  635. $dst_day = $date_split[3];
  636. $dst_mth = $date_split[4];
  637. $dst_yr = $date_split[5];
  638. $dst_date = mktime($dst_h, $dst_m, $dst_s, $dst_mth, $dst_day, $dst_yr);
  639. $time = $offset = time() - $dst_date; // Seconds between current days and today.
  640. // Here start the functions sec_to_str()
  641. $act_day = date('d');
  642. $act_mth = date('n');
  643. $act_yr = date('Y');
  644. if ($dst_day == $act_day && $dst_mth == $act_mth && $dst_yr == $act_yr) {
  645. return $today;
  646. }
  647. if ($dst_day == $act_day - 1 && $dst_mth == $act_mth && $dst_yr == $act_yr) {
  648. return $yesterday;
  649. }
  650. $str_result = array();
  651. $time_result = array();
  652. $key_result = array();
  653. $str = '';
  654. $i = 0;
  655. for ($i = 0; $i < count($sec_time_time); $i++) {
  656. $seconds = $sec_time_time[$i];
  657. if ($seconds > $time) {
  658. continue;
  659. }
  660. $current_value = intval($time/$seconds);
  661. if ($current_value != 1) {
  662. $date_str = $sec_time_plu[$i];
  663. } else {
  664. $date_str = $sec_time_sing[$i];
  665. }
  666. $key_result[] = $sec_time_sing[$i];
  667. $str_result[] = $current_value.' '.$date_str;
  668. $time_result[] = $current_value;
  669. $str .= $current_value.$date_str;
  670. $time %= $seconds;
  671. }
  672. if ($key_result[0] == $min_day && $key_result[1]== $min_minute) {
  673. $key_result[1] = ' 0 '.$min_hours;
  674. $str_result[0] = $time_result[0].' '.$key_result[0];
  675. $str_result[1] = $key_result[1];
  676. }
  677. if ($key_result[0] == $min_year && ($key_result[1] == $min_day || $key_result[1] == $min_week)) {
  678. $key_result[1] = ' 0 '.$min_months;
  679. $str_result[0] = $time_result[0].' '.$key_result[0];
  680. $str_result[1] = $key_result[1];
  681. }
  682. if (!empty($str_result[1])) {
  683. $str = $str_result[0].', '.$str_result[1];
  684. } else {
  685. $str = $str_result[0];
  686. }
  687. date_default_timezone_set($system_timezone);
  688. return $str;
  689. }
  690. /**
  691. * Converts a date to the right timezone and localizes it in the format given as an argument
  692. * @param mixed The time to be converted
  693. * @param mixed Format to be used (TIME_NO_SEC_FORMAT, DATE_FORMAT_SHORT, DATE_FORMAT_LONG, DATE_TIME_FORMAT_LONG)
  694. * @param string Timezone to be converted from. If null, UTC will be assumed.
  695. * @return string Converted and localized date
  696. *
  697. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  698. */
  699. function api_convert_and_format_date($time = null, $format = null, $from_timezone = null) {
  700. // First, convert the datetime to the right timezone
  701. $time = api_get_local_time($time, null, $from_timezone);
  702. // Second, localize the date
  703. return api_format_date($time, $format);
  704. }
  705. /**
  706. * Returns an array of translated week days in short names.
  707. * @param string $language (optional) Language id. If it is omitted, the current interface language is assumed.
  708. * @return string Returns an array of week days (short names).
  709. * Example: api_get_week_days_short('english') means array('Sun', 'Mon', ... 'Sat').
  710. * Note: For all languges returned days are in the English order.
  711. */
  712. function api_get_week_days_short($language = null) {
  713. $days = &_api_get_day_month_names($language);
  714. return $days['days_short'];
  715. }
  716. /**
  717. * Returns an array of translated week days.
  718. * @param string $language (optional) Language id. If it is omitted, the current interface language is assumed.
  719. * @return string Returns an array of week days.
  720. * Example: api_get_week_days_long('english') means array('Sunday, 'Monday', ... 'Saturday').
  721. * Note: For all languges returned days are in the English order.
  722. */
  723. function api_get_week_days_long($language = null) {
  724. $days = &_api_get_day_month_names($language);
  725. return $days['days_long'];
  726. }
  727. /**
  728. * Returns an array of translated months in short names.
  729. * @param string $language (optional) Language id. If it is omitted, the current interface language is assumed.
  730. * @return string Returns an array of months (short names).
  731. * Example: api_get_months_short('english') means array('Jan', 'Feb', ... 'Dec').
  732. */
  733. function api_get_months_short($language = null) {
  734. $months = &_api_get_day_month_names($language);
  735. return $months['months_short'];
  736. }
  737. /**
  738. * Returns an array of translated months.
  739. * @param string $language (optional) Language id. If it is omitted, the current interface language is assumed.
  740. * @return string Returns an array of months.
  741. * Example: api_get_months_long('english') means array('January, 'February' ... 'December').
  742. */
  743. function api_get_months_long($language = null) {
  744. $months = &_api_get_day_month_names($language);
  745. return $months['months_long'];
  746. }
  747. /**
  748. * Name order conventions
  749. */
  750. /**
  751. * Builds a person (full) name depending on the convention for a given language.
  752. * @param string $first_name The first name of the person.
  753. * @param string $last_name The last name of the person.
  754. * @param string $title The title of the person.
  755. * @param int/string $format (optional) The person name format. It may be a pattern-string (for example '%t %l, %f' or '%T %F %L', ...) or some of the constants PERSON_NAME_COMMON_CONVENTION (default), PERSON_NAME_WESTERN_ORDER, PERSON_NAME_EASTERN_ORDER, PERSON_NAME_LIBRARY_ORDER.
  756. * @param string $language (optional) The language id. If it is omitted, the current interface language is assumed. This parameter has meaning with the format PERSON_NAME_COMMON_CONVENTION only.
  757. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  758. * @return bool The result is sort of full name of the person.
  759. * Sample results:
  760. * Peter Ustinoff or Dr. Peter Ustinoff - the Western order
  761. * Ustinoff Peter or Dr. Ustinoff Peter - the Eastern order
  762. * Ustinoff, Peter or - Dr. Ustinoff, Peter - the library order
  763. * Note: See the file chamilo/main/inc/lib/internationalization_database/name_order_conventions.php where you can revise the convention for your language.
  764. * @author Carlos Vargas <carlos.vargas@dokeos.com> - initial implementation.
  765. * @author Ivan Tcholakov
  766. */
  767. function api_get_person_name(
  768. $first_name,
  769. $last_name,
  770. $title = null,
  771. $format = null,
  772. $language = null,
  773. $encoding = null,
  774. $username = null
  775. ) {
  776. static $valid = array();
  777. if (empty($format)) {
  778. $format = PERSON_NAME_COMMON_CONVENTION;
  779. }
  780. //We check if the language is supported, otherwise we check the interface language of the parent language of sublanguage
  781. if (empty($language)) {
  782. $language = api_get_interface_language(false, true);
  783. }
  784. if (!isset($valid[$format][$language])) {
  785. if (is_int($format)) {
  786. switch ($format) {
  787. case PERSON_NAME_COMMON_CONVENTION:
  788. $valid[$format][$language] = _api_get_person_name_convention($language, 'format');
  789. $usernameOrderFromDatabase = api_get_setting('user_name_order');
  790. if (isset($usernameOrderFromDatabase) && !empty($usernameOrderFromDatabase)) {
  791. $valid[$format][$language] = $usernameOrderFromDatabase;
  792. }
  793. break;
  794. case PERSON_NAME_WESTERN_ORDER:
  795. $valid[$format][$language] = '%t %f %l';
  796. break;
  797. case PERSON_NAME_EASTERN_ORDER:
  798. $valid[$format][$language] = '%t %l %f';
  799. break;
  800. case PERSON_NAME_LIBRARY_ORDER:
  801. $valid[$format][$language] = '%t %l, %f';
  802. break;
  803. default:
  804. $valid[$format][$language] = '%t %f %l';
  805. break;
  806. }
  807. } else {
  808. $valid[$format][$language] = _api_validate_person_name_format($format);
  809. }
  810. }
  811. $format = $valid[$format][$language];
  812. $keywords = array(
  813. '%firstname',
  814. '%f',
  815. '%F',
  816. '%lastname',
  817. '%l',
  818. '%L',
  819. '%title',
  820. '%t',
  821. '%T',
  822. '%username',
  823. '%u',
  824. '%U',
  825. );
  826. $values = array(
  827. $first_name,
  828. $first_name,
  829. api_strtoupper($first_name),
  830. $last_name,
  831. $last_name,
  832. api_strtoupper($last_name),
  833. $title,
  834. $title,
  835. api_strtoupper($title),
  836. $username,
  837. $username,
  838. api_strtoupper($username),
  839. );
  840. $person_name = str_replace($keywords, $values, $format);
  841. return _api_clean_person_name($person_name);
  842. }
  843. /**
  844. * Checks whether a given format represents person name in Western order (for which first name is first).
  845. * @param int/string $format (optional) The person name format. It may be a pattern-string (for example '%t. %l, %f') or some of the constants PERSON_NAME_COMMON_CONVENTION (default), PERSON_NAME_WESTERN_ORDER, PERSON_NAME_EASTERN_ORDER, PERSON_NAME_LIBRARY_ORDER.
  846. * @param string $language (optional) The language id. If it is omitted, the current interface language is assumed. This parameter has meaning with the format PERSON_NAME_COMMON_CONVENTION only.
  847. * @return bool The result TRUE means that the order is first_name last_name, FALSE means last_name first_name.
  848. * Note: You may use this function for determing the order of the fields or columns "First name" and "Last name" in forms, tables and reports.
  849. * @author Ivan Tcholakov
  850. */
  851. function api_is_western_name_order($format = null, $language = null)
  852. {
  853. static $order = array();
  854. if (empty($format)) {
  855. $format = PERSON_NAME_COMMON_CONVENTION;
  856. }
  857. if (empty($language)) {
  858. $language = api_get_interface_language(false, true);
  859. }
  860. if (!isset($order[$format][$language])) {
  861. $test_name = api_get_person_name('%f', '%l', '%t', $format, $language);
  862. $order[$format][$language] = stripos($test_name, '%f') <= stripos($test_name, '%l');
  863. }
  864. return $order[$format][$language];
  865. }
  866. /**
  867. * Returns a directive for sorting person names depending on a given language and based on the options in the internationalization "database".
  868. * @param string $language (optional) The input language. If it is omitted, the current interface language is assumed.
  869. * @return bool Returns boolean value. TRUE means ORDER BY first_name, last_name; FALSE means ORDER BY last_name, first_name.
  870. * Note: You may use this function:
  871. * 2. for constructing the ORDER clause of SQL queries, related to first_name and last_name;
  872. * 3. for adjusting php-implemented sorting in tables and reports.
  873. * @author Ivan Tcholakov
  874. */
  875. function api_sort_by_first_name($language = null) {
  876. $userNameSortBy = api_get_setting('user_name_sort_by');
  877. if (!empty($userNameSortBy) && in_array($userNameSortBy, array('firstname', 'lastname'))) {
  878. return $userNameSortBy == 'firstname' ? true : false;
  879. }
  880. static $sort_by_first_name = array();
  881. if (empty($language)) {
  882. $language = api_get_interface_language(false, true);
  883. }
  884. if (!isset($sort_by_first_name[$language])) {
  885. $sort_by_first_name[$language] = _api_get_person_name_convention($language, 'sort_by');
  886. }
  887. return $sort_by_first_name[$language];
  888. }
  889. /**
  890. * Multibyte string conversion functions
  891. */
  892. /**
  893. * Converts character encoding of a given string.
  894. * @param string $string The string being converted.
  895. * @param string $to_encoding The encoding that $string is being converted to.
  896. * @param string $from_encoding (optional) The encoding that $string is being converted from.
  897. * If it is omitted, the platform character set is assumed.
  898. * @return string Returns the converted string.
  899. * This function is aimed at replacing the function mb_convert_encoding() for human-language strings.
  900. * @link http://php.net/manual/en/function.mb-convert-encoding
  901. */
  902. function api_convert_encoding($string, $to_encoding, $from_encoding = 'UTF-8')
  903. {
  904. return mb_convert_encoding($string, $to_encoding, $from_encoding);
  905. }
  906. /**
  907. * Converts a given string into UTF-8 encoded string.
  908. * @param string $string The string being converted.
  909. * @param string $from_encoding (optional) The encoding that $string is being converted from.
  910. * If it is omitted, the platform character set is assumed.
  911. * @return string Returns the converted string.
  912. * This function is aimed at replacing the function utf8_encode() for human-language strings.
  913. * @link http://php.net/manual/en/function.utf8-encode
  914. */
  915. function api_utf8_encode($string, $from_encoding = 'UTF-8')
  916. {
  917. return mb_convert_encoding($string, 'UTF-8', $from_encoding);
  918. }
  919. /**
  920. * Converts a given string from UTF-8 encoding to a specified encoding.
  921. * @param string $string The string being converted.
  922. * @param string $to_encoding (optional) The encoding that $string is being converted to.
  923. * If it is omitted, the platform character set is assumed.
  924. * @return string Returns the converted string.
  925. * This function is aimed at replacing the function utf8_decode() for human-language strings.
  926. * @link http://php.net/manual/en/function.utf8-decode
  927. */
  928. function api_utf8_decode($string, $to_encoding = null)
  929. {
  930. return mb_convert_encoding($string, $to_encoding, 'UTF-8');
  931. }
  932. /**
  933. * Converts a given string into the system ecoding (or platform character set).
  934. * When $from encoding is omited on UTF-8 platforms then language dependent encoding
  935. * is guessed/assumed. On non-UTF-8 platforms omited $from encoding is assumed as UTF-8.
  936. * When the parameter $check_utf8_validity is true the function checks string's
  937. * UTF-8 validity and decides whether to try to convert it or not.
  938. * This function is useful for problem detection or making workarounds.
  939. * @param string $string The string being converted.
  940. * @param string $from_encoding (optional) The encoding that $string is being converted from.
  941. * It is guessed when it is omitted.
  942. * @param bool $check_utf8_validity (optional) A flag for UTF-8 validity check as condition for making conversion.
  943. * @return string Returns the converted string.
  944. */
  945. function api_to_system_encoding($string, $from_encoding = null, $check_utf8_validity = false)
  946. {
  947. $system_encoding = api_get_system_encoding();
  948. return api_convert_encoding($string, $system_encoding, $from_encoding);
  949. }
  950. /**
  951. * Converts all applicable characters to HTML entities.
  952. * @param string $string The input string.
  953. * @param int $quote_style (optional) The quote style - ENT_COMPAT (default), ENT_QUOTES, ENT_NOQUOTES.
  954. * @param string $encoding (optional) The encoding (of the input string) used in conversion.
  955. * If it is omitted, the platform character set is assumed.
  956. * @return string Returns the converted string.
  957. * This function is aimed at replacing the function htmlentities() for human-language strings.
  958. * @link http://php.net/manual/en/function.htmlentities
  959. */
  960. function api_htmlentities($string, $quote_style = ENT_COMPAT, $encoding = 'UTF-8')
  961. {
  962. switch ($quote_style) {
  963. case ENT_COMPAT:
  964. $string = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string);
  965. break;
  966. case ENT_QUOTES:
  967. $string = str_replace(array('&', '\'', '"', '<', '>'), array('&amp;', '&#039;', '&quot;', '&lt;', '&gt;'), $string);
  968. break;
  969. }
  970. return mb_convert_encoding($string, 'HTML-ENTITIES', 'UTF-8');
  971. /*
  972. return html_entity_decode($string, $quote_style, $encoding);
  973. return mb_convert_encoding($string, 'HTML-ENTITIES', 'UTF-8');*/
  974. }
  975. /**
  976. * Converts HTML entities into normal characters.
  977. * @param string $string The input string.
  978. * @param int $quote_style (optional) The quote style - ENT_COMPAT (default), ENT_QUOTES, ENT_NOQUOTES.
  979. * @param string $encoding (optional) The encoding (of the result) used in conversion.
  980. * If it is omitted, the platform character set is assumed.
  981. * @return string Returns the converted string.
  982. * This function is aimed at replacing the function html_entity_decode() for human-language strings.
  983. * @link http://php.net/html_entity_decode
  984. */
  985. function api_html_entity_decode($string, $quote_style = ENT_COMPAT, $encoding = 'UTF-8') {
  986. if (empty($encoding)) {
  987. $encoding = _api_mb_internal_encoding();
  988. }
  989. if (api_is_encoding_supported($encoding)) {
  990. if (!api_is_utf8($encoding)) {
  991. $string = api_utf8_encode($string, $encoding);
  992. }
  993. $string = html_entity_decode($string, $quote_style, 'UTF-8');
  994. if (!api_is_utf8($encoding)) {
  995. return api_utf8_decode($string, $encoding);
  996. }
  997. return $string;
  998. }
  999. return $string; // Here the function gives up.
  1000. }
  1001. /**
  1002. * This function encodes (conditionally) a given string to UTF-8 if XmlHttp-request has been detected.
  1003. * @param string $string The string being converted.
  1004. * @param string $from_encoding (optional) The encoding that $string is being converted from.
  1005. * If it is omitted, the platform character set is assumed.
  1006. * @return string Returns the converted string.
  1007. */
  1008. function api_xml_http_response_encode($string, $from_encoding = 'UTF8')
  1009. {
  1010. if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
  1011. if (empty($from_encoding)) {
  1012. $from_encoding = _api_mb_internal_encoding();
  1013. }
  1014. if (!api_is_utf8($from_encoding)) {
  1015. return api_utf8_encode($string, $from_encoding);
  1016. }
  1017. }
  1018. return $string;
  1019. }
  1020. /**
  1021. * Transliterates a string with arbitrary encoding into a plain ASCII string.
  1022. *
  1023. * Example:
  1024. * echo api_transliterate(api_html_entity_decode(
  1025. * '&#1060;&#1105;&#1076;&#1086;&#1088; '.
  1026. * '&#1052;&#1080;&#1093;&#1072;&#1081;&#1083;&#1086;&#1074;&#1080;&#1095; '.
  1027. * '&#1044;&#1086;&#1089;&#1090;&#1086;&#1077;&#1074;&#1082;&#1080;&#1081;',
  1028. * ENT_QUOTES, 'UTF-8'), 'X', 'UTF-8');
  1029. * The output should be: Fyodor Mihaylovich Dostoevkiy
  1030. *
  1031. * @param string $string The input string.
  1032. * @param string $unknown (optional) Replacement character for unknown characters and illegal UTF-8 sequences.
  1033. * @param string $from_encoding (optional) The encoding of the input string.
  1034. * If it is omitted, the platform character set is assumed.
  1035. * @return string Plain ASCII output.
  1036. *
  1037. */
  1038. function api_transliterate($string, $unknown = '?', $from_encoding = null)
  1039. {
  1040. return URLify::transliterate($string);
  1041. }
  1042. /**
  1043. * Takes the first character in a string and returns its Unicode codepoint.
  1044. * @param string $character The input string.
  1045. * @param string $encoding (optional) The encoding of the input string. If it is omitted, the platform character set will be used by default.
  1046. * @return int Returns: the codepoint of the first character; or 0xFFFD (unknown character) when the input string is empty.
  1047. * This is a multibyte aware version of the function ord().
  1048. * @link http://php.net/manual/en/function.ord.php
  1049. * Note the difference with the original funtion ord(): ord('') returns 0, api_ord('') returns 0xFFFD (unknown character).
  1050. */
  1051. function api_ord($character, $encoding) {
  1052. return Patchwork\Utf8::ord(api_utf8_encode($character, $encoding));
  1053. }
  1054. /**
  1055. * This function returns a string or an array with all occurrences of search in subject (ignoring case) replaced with the given replace value.
  1056. * @param mixed $search String or array of strings to be found.
  1057. * @param mixed $replace String or array of strings used for replacement.
  1058. * @param mixed $subject String or array of strings being searched.
  1059. * @param int $count (optional) The number of matched and replaced needles will be returned in count, which is passed by reference.
  1060. * @param string $encoding (optional) The used internally by this function character encoding.
  1061. * If it is omitted, the platform character set will be used by default.
  1062. * @return mixed String or array as a result.
  1063. * Notes:
  1064. * If $subject is an array, then the search and replace is performed with every entry of subject, the return value is an array.
  1065. * If $search and $replace are arrays, then the function takes a value from each array and uses it to do search and replace on subject.
  1066. * If $replace has fewer values than search, then an empty string is used for the rest of replacement values.
  1067. * If $search is an array and $replace is a string, then this replacement string is used for every value of search.
  1068. * This function is aimed at replacing the function str_ireplace() for human-language strings.
  1069. * @link http://php.net/manual/en/function.str-ireplace
  1070. * @author Henri Sivonen, mailto:hsivonen@iki.fi
  1071. * @link http://hsivonen.iki.fi/php-utf8/
  1072. * Adaptation for Chamilo 1.8.7, 2010
  1073. * Initial implementation Dokeos LMS, August 2009
  1074. * @author Ivan Tcholakov
  1075. */
  1076. function api_str_ireplace($search, $replace, $subject, & $count = null, $encoding = null)
  1077. {
  1078. return Utf8::str_ireplace($search, $replace, $subject, $count);
  1079. }
  1080. /**
  1081. * Converts a string to an array.
  1082. * @param string $string The input string.
  1083. * @param int $split_length Maximum character-length of the chunk, one character by default.
  1084. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1085. * @return array The result array of chunks with the spcified length.
  1086. * Notes:
  1087. * If the optional split_length parameter is specified, the returned array will be broken down into chunks
  1088. * with each being split_length in length, otherwise each chunk will be one character in length.
  1089. * FALSE is returned if split_length is less than 1.
  1090. * If the split_length length exceeds the length of string, the entire string is returned as the first (and only) array element.
  1091. * This function is aimed at replacing the function str_split() for human-language strings.
  1092. * @link http://php.net/str_split
  1093. */
  1094. function api_str_split($string, $split_length = 1, $encoding = null)
  1095. {
  1096. return Utf8::str_split($string, $split_length);
  1097. }
  1098. /**
  1099. * Finds position of first occurrence of a string within another, case insensitive.
  1100. * @param string $haystack The string from which to get the position of the first occurrence.
  1101. * @param string $needle The string to be found.
  1102. * @param int $offset The position in $haystack to start searching from. If it is omitted, searching starts from the beginning.
  1103. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1104. * @return mixed Returns the numeric position of the first occurrence of $needle in the $haystack, or FALSE if $needle is not found.
  1105. * Note: The first character's position is 0, the second character position is 1, and so on.
  1106. * This function is aimed at replacing the functions stripos() and mb_stripos() for human-language strings.
  1107. * @link http://php.net/manual/en/function.stripos
  1108. * @link http://php.net/manual/en/function.mb-stripos
  1109. */
  1110. function api_stripos($haystack, $needle, $offset = 0, $encoding = null)
  1111. {
  1112. return Utf8::stripos($haystack, $needle, $offset);
  1113. }
  1114. /**
  1115. * Finds first occurrence of a string within another, case insensitive.
  1116. * @param string $haystack The string from which to get the first occurrence.
  1117. * @param mixed $needle The string to be found.
  1118. * @param bool $before_needle (optional) Determines which portion of $haystack this function returns. The default value is FALSE.
  1119. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1120. * @return mixed Returns the portion of $haystack, or FALSE if $needle is not found.
  1121. * Notes:
  1122. * If $needle is not a string, it is converted to an integer and applied as the ordinal value (codepoint if the encoding is UTF-8) of a character.
  1123. * If $before_needle is set to TRUE, the function returns all of $haystack from the beginning to the first occurrence of $needle.
  1124. * If $before_needle is set to FALSE, the function returns all of $haystack from the first occurrence of $needle to the end.
  1125. * This function is aimed at replacing the functions stristr() and mb_stristr() for human-language strings.
  1126. * @link http://php.net/manual/en/function.stristr
  1127. * @link http://php.net/manual/en/function.mb-stristr
  1128. */
  1129. function api_stristr($haystack, $needle, $before_needle = false, $encoding = null)
  1130. {
  1131. return Utf8::stristr($haystack, $needle, $before_needle);
  1132. }
  1133. /**
  1134. * Returns length of the input string.
  1135. * @param string $string The string which length is to be calculated.
  1136. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1137. * @return int Returns the number of characters within the string. A multi-byte character is counted as 1.
  1138. * This function is aimed at replacing the functions strlen() and mb_strlen() for human-language strings.
  1139. * @link http://php.net/manual/en/function.strlen
  1140. * @link http://php.net/manual/en/function.mb-strlen
  1141. * Note: When you use strlen() to test for an empty string, you needn't change it to api_strlen().
  1142. * For example, in lines like the following:
  1143. * if (strlen($string) > 0)
  1144. * if (strlen($string) != 0)
  1145. * there is no need the original function strlen() to be changed, it works correctly and faster for these cases.
  1146. */
  1147. function api_strlen($string, $encoding = null)
  1148. {
  1149. return Utf8::strlen($string);
  1150. }
  1151. /**
  1152. * Finds position of first occurrence of a string within another.
  1153. * @param string $haystack The string from which to get the position of the first occurrence.
  1154. * @param string $needle The string to be found.
  1155. * @param int $offset (optional) The position in $haystack to start searching from. If it is omitted, searching starts from the beginning.
  1156. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1157. * @return mixed Returns the numeric position of the first occurrence of $needle in the $haystack, or FALSE if $needle is not found.
  1158. * Note: The first character's position is 0, the second character position is 1, and so on.
  1159. * This function is aimed at replacing the functions strpos() and mb_strpos() for human-language strings.
  1160. * @link http://php.net/manual/en/function.strpos
  1161. * @link http://php.net/manual/en/function.mb-strpos
  1162. */
  1163. function api_strpos($haystack, $needle, $offset = 0, $encoding = null)
  1164. {
  1165. return Utf8::strpos($haystack, $needle, $offset);
  1166. }
  1167. /**
  1168. * Finds the last occurrence of a character in a string.
  1169. * @param string $haystack The string from which to get the last occurrence.
  1170. * @param mixed $needle The string which first character is to be found.
  1171. * @param bool $before_needle (optional) Determines which portion of $haystack this function returns. The default value is FALSE.
  1172. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1173. * @return mixed Returns the portion of $haystack, or FALSE if the first character from $needle is not found.
  1174. * Notes:
  1175. * If $needle is not a string, it is converted to an integer and applied as the ordinal value (codepoint if the encoding is UTF-8) of a character.
  1176. * If $before_needle is set to TRUE, the function returns all of $haystack from the beginning to the first occurrence.
  1177. * If $before_needle is set to FALSE, the function returns all of $haystack from the first occurrence to the end.
  1178. * This function is aimed at replacing the functions strrchr() and mb_strrchr() for human-language strings.
  1179. * @link http://php.net/manual/en/function.strrchr
  1180. * @link http://php.net/manual/en/function.mb-strrchr
  1181. */
  1182. function api_strrchr($haystack, $needle, $before_needle = false, $encoding = null)
  1183. {
  1184. return Utf8::strrchr($haystack, $needle);
  1185. }
  1186. /**
  1187. * Reverses a string.
  1188. * @param string $string The string to be reversed.
  1189. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1190. * @return string Returns the reversed string.
  1191. * This function is aimed at replacing the function strrev() for human-language strings.
  1192. * @link http://php.net/manual/en/function.strrev
  1193. */
  1194. function api_strrev($string, $encoding = null)
  1195. {
  1196. return Utf8::strrev($string);
  1197. }
  1198. /**
  1199. * Finds the position of last occurrence (case insensitive) of a string in a string.
  1200. * @param string $haystack The string from which to get the position of the last occurrence.
  1201. * @param string $needle The string to be found.
  1202. * @param int $offset (optional) $offset may be specified to begin searching an arbitrary position. Negative values will stop searching at an arbitrary point prior to the end of the string.
  1203. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1204. * @return mixed Returns the numeric position of the first occurrence (case insensitive) of $needle in the $haystack, or FALSE if $needle is not found.
  1205. * Note: The first character's position is 0, the second character position is 1, and so on.
  1206. * This function is aimed at replacing the functions strripos() and mb_strripos() for human-language strings.
  1207. * @link http://php.net/manual/en/function.strripos
  1208. * @link http://php.net/manual/en/function.mb-strripos
  1209. */
  1210. function api_strripos($haystack, $needle, $offset = 0, $encoding = null)
  1211. {
  1212. return Utf8::strripos($haystack, $needle, $offset);
  1213. }
  1214. /**
  1215. * Finds the position of last occurrence of a string in a string.
  1216. * @param string $haystack The string from which to get the position of the last occurrence.
  1217. * @param string $needle The string to be found.
  1218. * @param int $offset (optional) $offset may be specified to begin searching an arbitrary position. Negative values will stop searching at an arbitrary point prior to the end of the string.
  1219. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1220. * @return mixed Returns the numeric position of the first occurrence of $needle in the $haystack, or FALSE if $needle is not found.
  1221. * Note: The first character's position is 0, the second character position is 1, and so on.
  1222. * This function is aimed at replacing the functions strrpos() and mb_strrpos() for human-language strings.
  1223. * @link http://php.net/manual/en/function.strrpos
  1224. * @link http://php.net/manual/en/function.mb-strrpos
  1225. */
  1226. function api_strrpos($haystack, $needle, $offset = 0, $encoding = null)
  1227. {
  1228. return Utf8::strrpos($haystack, $needle, $offset);
  1229. }
  1230. /**
  1231. * Finds first occurrence of a string within another.
  1232. * @param string $haystack The string from which to get the first occurrence.
  1233. * @param mixed $needle The string to be found.
  1234. * @param bool $before_needle (optional) Determines which portion of $haystack this function returns. The default value is FALSE.
  1235. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1236. * @return mixed Returns the portion of $haystack, or FALSE if $needle is not found.
  1237. * Notes:
  1238. * If $needle is not a string, it is converted to an integer and applied as the ordinal value (codepoint if the encoding is UTF-8) of a character.
  1239. * If $before_needle is set to TRUE, the function returns all of $haystack from the beginning to the first occurrence of $needle.
  1240. * If $before_needle is set to FALSE, the function returns all of $haystack from the first occurrence of $needle to the end.
  1241. * This function is aimed at replacing the functions strstr() and mb_strstr() for human-language strings.
  1242. * @link http://php.net/manual/en/function.strstr
  1243. * @link http://php.net/manual/en/function.mb-strstr
  1244. */
  1245. function api_strstr($haystack, $needle, $before_needle = false, $encoding = null)
  1246. {
  1247. return Utf8::strstr($haystack, $needle, $before_needle);
  1248. }
  1249. /**
  1250. * Makes a string lowercase.
  1251. * @param string $string The string being lowercased.
  1252. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1253. * @return string Returns the string with all alphabetic characters converted to lowercase.
  1254. * This function is aimed at replacing the functions strtolower() and mb_strtolower() for human-language strings.
  1255. * @link http://php.net/manual/en/function.strtolower
  1256. * @link http://php.net/manual/en/function.mb-strtolower
  1257. */
  1258. function api_strtolower($string, $encoding = null)
  1259. {
  1260. return Utf8::strtolower($string);
  1261. }
  1262. /**
  1263. * Makes a string uppercase.
  1264. * @param string $string The string being uppercased.
  1265. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1266. * @return string Returns the string with all alphabetic characters converted to uppercase.
  1267. * This function is aimed at replacing the functions strtoupper() and mb_strtoupper() for human-language strings.
  1268. * @link http://php.net/manual/en/function.strtoupper
  1269. * @link http://php.net/manual/en/function.mb-strtoupper
  1270. */
  1271. function api_strtoupper($string, $encoding = null)
  1272. {
  1273. return Utf8::strtoupper($string);
  1274. }
  1275. /**
  1276. // Gets part of a string.
  1277. * @param string $string The input string.
  1278. * @param int $start The first position from which the extracted part begins.
  1279. * @param int $length The length in character of the extracted part.
  1280. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1281. * @return string Returns the part of the string specified by the start and length parameters.
  1282. * Note: First character's position is 0. Second character position is 1, and so on.
  1283. * This function is aimed at replacing the functions substr() and mb_substr() for human-language strings.
  1284. * @link http://php.net/manual/en/function.substr
  1285. * @link http://php.net/manual/en/function.mb-substr
  1286. */
  1287. function api_substr($string, $start, $length = null, $encoding = null)
  1288. {
  1289. if (is_null($length)) {
  1290. $length = api_strlen($string, $encoding);
  1291. }
  1292. return Utf8::substr($string, $start, $length);
  1293. }
  1294. /**
  1295. * Counts the number of substring occurrences.
  1296. * @param string $haystack The string being checked.
  1297. * @param string $needle The string being found.
  1298. * @param string $encoding (optional) The used internally by this function character encoding.
  1299. * If it is omitted, the platform character set will be used by default.
  1300. * @return int The number of times the needle substring occurs in the haystack string.
  1301. * @link http://php.net/manual/en/function.mb-substr-count.php
  1302. */
  1303. function api_substr_count($haystack, $needle, $encoding = null)
  1304. {
  1305. return Utf8::substr_count($haystack, $needle);
  1306. }
  1307. /**
  1308. * Replaces text within a portion of a string.
  1309. * @param string $string The input string.
  1310. * @param string $replacement The replacement string.
  1311. * @param int $start The position from which replacing will begin.
  1312. * Notes:
  1313. * If $start is positive, the replacing will begin at the $start'th offset into the string.
  1314. * If $start is negative, the replacing will begin at the $start'th character from the end of the string.
  1315. * @param int $length (optional) The position where replacing will end.
  1316. * Notes:
  1317. * If given and is positive, it represents the length of the portion of the string which is to be replaced.
  1318. * If it is negative, it represents the number of characters from the end of string at which to stop replacing.
  1319. * If it is not given, then it will default to api_strlen($string); i.e. end the replacing at the end of string.
  1320. * If $length is zero, then this function will have the effect of inserting replacement into the string at the given start offset.
  1321. * @param string $encoding (optional) The used internally by this function character encoding.
  1322. * If it is omitted, the platform character set will be used by default.
  1323. * @return string The result string is returned.
  1324. * This function is aimed at replacing the function substr_replace() for human-language strings.
  1325. * @link http://php.net/manual/function.substr-replace
  1326. */
  1327. function api_substr_replace($string, $replacement, $start, $length = null, $encoding = null)
  1328. {
  1329. if (is_null($length)) {
  1330. $length = api_strlen($string);
  1331. }
  1332. return UTf8::substr_replace($string, $replacement, $start, $length);
  1333. }
  1334. /**
  1335. * Makes a string's first character uppercase.
  1336. * @param string $string The input string.
  1337. * @param string $encoding (optional) The used internally by this function character encoding.
  1338. * If it is omitted, the platform character set will be used by default.
  1339. * @return string Returns a string with the first character capitalized, if that character is alphabetic.
  1340. * This function is aimed at replacing the function ucfirst() for human-language strings.
  1341. * @link http://php.net/manual/en/function.ucfirst
  1342. */
  1343. function api_ucfirst($string, $encoding = null)
  1344. {
  1345. return Utf8::ucfirst($string);
  1346. }
  1347. /**
  1348. * Uppercases the first character of each word in a string.
  1349. * @param string $string The input string.
  1350. * @param string $encoding (optional) The used internally by this function character encoding.
  1351. * If it is omitted, the platform character set will be used by default.
  1352. * @return string Returns the modified string.
  1353. * This function is aimed at replacing the function ucwords() for human-language strings.
  1354. * @link http://php.net/manual/en/function.ucwords
  1355. */
  1356. function api_ucwords($string, $encoding = null)
  1357. {
  1358. return Utf8::ucwords($string);
  1359. }
  1360. /**
  1361. * Performs a regular expression match, UTF-8 aware when it is applicable.
  1362. * @param string $pattern The pattern to search for, as a string.
  1363. * @param string $subject The input string.
  1364. * @param array &$matches (optional) If matches is provided, then it is filled with the results of search (as an array).
  1365. * $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.
  1366. * @param int $flags (optional) Could be PREG_OFFSET_CAPTURE. If this flag is passed, for every occurring match the appendant string offset will also be returned.
  1367. * Note that this changes the return value in an array where every element is an array consisting of the matched string at index 0 and its string offset into subject at index 1.
  1368. * @param int $offset (optional) Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search.
  1369. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1370. * @return int|boolean Returns the number of times pattern matches or FALSE if an error occurred.
  1371. * @link http://php.net/preg_match
  1372. */
  1373. function api_preg_match($pattern, $subject, &$matches = null, $flags = 0, $offset = 0, $encoding = null) {
  1374. if (empty($encoding)) {
  1375. $encoding = _api_mb_internal_encoding();
  1376. }
  1377. return preg_match(api_is_utf8($encoding) ? $pattern.'u' : $pattern, $subject, $matches, $flags, $offset);
  1378. }
  1379. /**
  1380. * Performs a global regular expression match, UTF-8 aware when it is applicable.
  1381. * @param string $pattern The pattern to search for, as a string.
  1382. * @param string $subject The input string.
  1383. * @param array &$matches (optional) Array of all matches in multi-dimensional array ordered according to $flags.
  1384. * @param int $flags (optional) Can be a combination of the following flags (note that it doesn't make sense to use PREG_PATTERN_ORDER together with PREG_SET_ORDER):
  1385. * PREG_PATTERN_ORDER - orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on;
  1386. * PREG_SET_ORDER - orders results so that $matches[0] is an array of first set of matches, $matches[1] is an array of second set of matches, and so on;
  1387. * PREG_OFFSET_CAPTURE - If this flag is passed, for every occurring match the appendant string offset will also be returned. Note that this changes the value of matches
  1388. * in an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.
  1389. * If no order flag is given, PREG_PATTERN_ORDER is assumed.
  1390. * @param int $offset (optional) Normally, the search starts from the beginning of the subject string. The optional parameter offset can be used to specify the alternate place from which to start the search.
  1391. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1392. * @return int|boolean Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred.
  1393. * @link http://php.net/preg_match_all
  1394. */
  1395. function api_preg_match_all($pattern, $subject, &$matches, $flags = PREG_PATTERN_ORDER, $offset = 0, $encoding = null) {
  1396. if (empty($encoding)) {
  1397. $encoding = _api_mb_internal_encoding();
  1398. }
  1399. if (is_null($flags)) {
  1400. $flags = PREG_PATTERN_ORDER;
  1401. }
  1402. return preg_match_all(api_is_utf8($encoding) ? $pattern.'u' : $pattern, $subject, $matches, $flags, $offset);
  1403. }
  1404. /**
  1405. * Performs a regular expression search and replace, UTF-8 aware when it is applicable.
  1406. * @param string|array $pattern The pattern to search for. It can be either a string or an array with strings.
  1407. * @param string|array $replacement The string or an array with strings to replace.
  1408. * @param string|array $subject The string or an array with strings to search and replace.
  1409. * @param int $limit The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).
  1410. * @param int &$count If specified, this variable will be filled with the number of replacements done.
  1411. * @param string $encoding (optional) The used internally by this function character encoding.
  1412. * If it is omitted, the platform character set will be used by default.
  1413. * @return array|string|null returns an array if the subject parameter is an array, or a string otherwise.
  1414. * If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or NULL if an error occurred.
  1415. * @link http://php.net/preg_replace
  1416. */
  1417. function api_preg_replace($pattern, $replacement, $subject, $limit = -1, &$count = 0, $encoding = null) {
  1418. if (empty($encoding)) {
  1419. $encoding = _api_mb_internal_encoding();
  1420. }
  1421. $is_utf8 = api_is_utf8($encoding);
  1422. if (is_array($pattern)) {
  1423. foreach ($pattern as &$p) {
  1424. $p = $is_utf8 ? $p.'u' : $p;
  1425. }
  1426. } else {
  1427. $pattern = $is_utf8 ? $pattern.'u' : $pattern;
  1428. }
  1429. return preg_replace($pattern, $replacement, $subject, $limit, $count);
  1430. }
  1431. /**
  1432. * Splits a string by a regular expression, UTF-8 aware when it is applicable.
  1433. * @param string $pattern The pattern to search for, as a string.
  1434. * @param string $subject The input string.
  1435. * @param int $limit (optional) If specified, then only substrings up to $limit are returned with the rest of the string being placed in the last substring. A limit of -1, 0 or null means "no limit" and, as is standard across PHP.
  1436. * @param int $flags (optional) $flags can be any combination of the following flags (combined with bitwise | operator):
  1437. * PREG_SPLIT_NO_EMPTY - if this flag is set, only non-empty pieces will be returned;
  1438. * PREG_SPLIT_DELIM_CAPTURE - if this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well;
  1439. * PREG_SPLIT_OFFSET_CAPTURE - If this flag is set, for every occurring match the appendant string offset will also be returned.
  1440. * Note that this changes the return value in an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.
  1441. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1442. * @return array Returns an array containing substrings of $subject split along boundaries matched by $pattern.
  1443. * @link http://php.net/preg_split
  1444. */
  1445. function api_preg_split($pattern, $subject, $limit = -1, $flags = 0, $encoding = null) {
  1446. if (empty($encoding)) {
  1447. $encoding = _api_mb_internal_encoding();
  1448. }
  1449. return preg_split(api_is_utf8($encoding) ? $pattern.'u' : $pattern, $subject, $limit, $flags);
  1450. }
  1451. /**
  1452. * String comparison
  1453. */
  1454. /**
  1455. * Performs string comparison, case insensitive, language sensitive, with extended multibyte support.
  1456. * @param string $string1 The first string.
  1457. * @param string $string2 The second string.
  1458. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  1459. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1460. * @return int Returns < 0 if $string1 is less than $string2; > 0 if $string1 is greater than $string2; and 0 if the strings are equal.
  1461. * This function is aimed at replacing the function strcasecmp() for human-language strings.
  1462. * @link http://php.net/manual/en/function.strcasecmp
  1463. */
  1464. function api_strcasecmp($string1, $string2, $language = null, $encoding = null) {
  1465. return api_strcmp(api_strtolower($string1, $encoding), api_strtolower($string2, $encoding), $language, $encoding);
  1466. }
  1467. /**
  1468. * Performs string comparison, case sensitive, language sensitive, with extended multibyte support.
  1469. * @param string $string1 The first string.
  1470. * @param string $string2 The second string.
  1471. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  1472. * @param string $encoding (optional) The used internally by this function character encoding.
  1473. * If it is omitted, the platform character set will be used by default.
  1474. * @return int Returns < 0 if $string1 is less than $string2; > 0 if $string1 is greater than $string2; and 0 if the strings are equal.
  1475. * This function is aimed at replacing the function strcmp() for human-language strings.
  1476. * @link http://php.net/manual/en/function.strcmp.php
  1477. * @link http://php.net/manual/en/collator.compare.php
  1478. */
  1479. function api_strcmp($string1, $string2, $language = null, $encoding = null)
  1480. {
  1481. return strcmp($string1, $string2);
  1482. }
  1483. /**
  1484. * Performs string comparison in so called "natural order", case sensitive, language sensitive, with extended multibyte support.
  1485. * @param string $string1 The first string.
  1486. * @param string $string2 The second string.
  1487. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  1488. * @param string $encoding (optional) The used internally by this function character encoding.
  1489. * If it is omitted, the platform character set will be used by default.
  1490. * @return int Returns < 0 if $string1 is less than $string2; > 0 if $string1 is greater than $string2; and 0 if the strings are equal.
  1491. * This function is aimed at replacing the function strnatcmp() for human-language strings.
  1492. * @link http://php.net/manual/en/function.strnatcmp.php
  1493. * @link http://php.net/manual/en/collator.compare.php
  1494. */
  1495. function api_strnatcmp($string1, $string2, $language = null, $encoding = null)
  1496. {
  1497. return strnatcmp($string1, $string2);
  1498. }
  1499. /**
  1500. * Sorting arrays
  1501. */
  1502. /**
  1503. * Sorts an array using natural order algorithm.
  1504. * @param array $array The input array.
  1505. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  1506. * @param string $encoding (optional) The used internally by this function character encoding.
  1507. * If it is omitted, the platform character set will be used by default.
  1508. * @return bool Returns TRUE on success, FALSE on error.
  1509. * This function is aimed at replacing the function natsort() for sorting human-language strings.
  1510. * @link http://php.net/manual/en/function.natsort.php
  1511. */
  1512. function api_natsort(&$array, $language = null, $encoding = null)
  1513. {
  1514. return natsort($array);
  1515. }
  1516. /**
  1517. * Sorts an array using natural order algorithm in reverse order.
  1518. * @param array $array The input array.
  1519. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  1520. * @param string $encoding (optional) The used internally by this function character encoding.
  1521. * If it is omitted, the platform character set will be used by default.
  1522. * @return bool Returns TRUE on success, FALSE on error.
  1523. */
  1524. function api_natrsort(&$array, $language = null, $encoding = null)
  1525. {
  1526. return uasort($array, '_api_strnatrcmp');
  1527. }
  1528. /**
  1529. * Encoding management functions
  1530. */
  1531. /**
  1532. * This function unifies the encoding identificators, so they could be compared.
  1533. * @param string/array $encoding The specified encoding.
  1534. * @return string Returns the encoding identificator modified in suitable for comparison way.
  1535. */
  1536. function api_refine_encoding_id($encoding) {
  1537. if (is_array($encoding)){
  1538. return array_map('api_refine_encoding_id', $encoding);
  1539. }
  1540. return strtoupper(str_replace('_', '-', $encoding));
  1541. }
  1542. /**
  1543. * This function checks whether two $encoding are equal (same, equvalent).
  1544. * @param string/array $encoding1 The first encoding
  1545. * @param string/array $encoding2 The second encoding
  1546. * @param bool $strict When this parameter is TRUE the comparison ignores aliases of encodings.
  1547. * When the parameter is FALSE, aliases are taken into account.
  1548. * @return bool Returns TRUE if the encodings are equal, FALSE otherwise.
  1549. */
  1550. function api_equal_encodings($encoding1, $encoding2, $strict = false) {
  1551. static $equal_encodings = array();
  1552. if (is_array($encoding1)) {
  1553. foreach ($encoding1 as $encoding) {
  1554. if (api_equal_encodings($encoding, $encoding2, $strict)) {
  1555. return true;
  1556. }
  1557. }
  1558. return false;
  1559. }
  1560. elseif (is_array($encoding2)) {
  1561. foreach ($encoding2 as $encoding) {
  1562. if (api_equal_encodings($encoding1, $encoding, $strict)) {
  1563. return true;
  1564. }
  1565. }
  1566. return false;
  1567. }
  1568. if (!isset($equal_encodings[$encoding1][$encoding2][$strict])) {
  1569. $encoding_1 = api_refine_encoding_id($encoding1);
  1570. $encoding_2 = api_refine_encoding_id($encoding2);
  1571. if ($encoding_1 == $encoding_2) {
  1572. $result = true;
  1573. } else {
  1574. if ($strict) {
  1575. $result = false;
  1576. } else {
  1577. $alias1 = _api_get_character_map_name($encoding_1);
  1578. $alias2 = _api_get_character_map_name($encoding_2);
  1579. $result = !empty($alias1) && !empty($alias2) && $alias1 == $alias2;
  1580. }
  1581. }
  1582. $equal_encodings[$encoding1][$encoding2][$strict] = $result;
  1583. }
  1584. return $equal_encodings[$encoding1][$encoding2][$strict];
  1585. }
  1586. /**
  1587. * This function checks whether a given encoding is UTF-8.
  1588. * @param string $encoding The tested encoding.
  1589. * @return bool Returns TRUE if the given encoding id means UTF-8, otherwise returns false.
  1590. */
  1591. function api_is_utf8($encoding)
  1592. {
  1593. static $result = array();
  1594. if (!isset($result[$encoding])) {
  1595. $result[$encoding] = api_equal_encodings($encoding, 'UTF-8');
  1596. }
  1597. return $result[$encoding];
  1598. }
  1599. /**
  1600. * This function returns the encoding, currently used by the system.
  1601. * @return string The system's encoding.
  1602. * Note: The value of api_get_setting('platform_charset') is tried to be returned first,
  1603. * on the second place the global variable $charset is tried to be returned. If for some
  1604. * reason both attempts fail, then the libraly's internal value will be returned.
  1605. */
  1606. function api_get_system_encoding()
  1607. {
  1608. return 'UTF-8';
  1609. }
  1610. /**
  1611. * Checks whether a specified encoding is supported by this API.
  1612. * @param string $encoding The specified encoding.
  1613. * @return bool Returns TRUE when the specified encoding is supported, FALSE othewise.
  1614. */
  1615. function api_is_encoding_supported($encoding) {
  1616. static $supported = array();
  1617. if (!isset($supported[$encoding])) {
  1618. $supported[$encoding] = _api_mb_supports($encoding) || _api_iconv_supports($encoding) || _api_convert_encoding_supports($encoding);
  1619. }
  1620. return $supported[$encoding];
  1621. }
  1622. /**
  1623. * Detects encoding of plain text.
  1624. * @param string $string The input text.
  1625. * @param string $language (optional) The language of the input text, provided if it is known.
  1626. * @return string Returns the detected encoding.
  1627. */
  1628. function api_detect_encoding($string, $language = null) {
  1629. // Testing against valid UTF-8 first.
  1630. if (api_is_valid_utf8($string)) {
  1631. return 'UTF-8';
  1632. }
  1633. return mb_detect_encoding($string);
  1634. }
  1635. /**
  1636. * String validation functions concerning certain encodings
  1637. */
  1638. /**
  1639. * Checks a string for UTF-8 validity.
  1640. *
  1641. */
  1642. function api_is_valid_utf8(&$string)
  1643. {
  1644. return Utf8::isUtf8($string);
  1645. }
  1646. /**
  1647. * Checks whether a string contains 7-bit ASCII characters only.
  1648. * @param string $string The string to be tested/validated.
  1649. * @return bool Returns TRUE when the tested string contains 7-bit ASCII characters only, FALSE othewise.
  1650. */
  1651. function api_is_valid_ascii(&$string)
  1652. {
  1653. return mb_detect_encoding($string, 'ASCII', true) == 'ASCII' ? true : false;
  1654. }
  1655. /**
  1656. * Return true a date is valid
  1657. * @param string $date example: 2014-06-30 13:05:05
  1658. * @param string $format example: "Y-m-d H:i:s"
  1659. *
  1660. * @return bool
  1661. */
  1662. function api_is_valid_date($date, $format = 'Y-m-d H:i:s')
  1663. {
  1664. $d = DateTime::createFromFormat($format, $date);
  1665. return $d && $d->format($format) == $date;
  1666. }
  1667. /**
  1668. * Returns the variable translated
  1669. * @param string $variable the string to translate
  1670. * @param string $pluginName the Plugin name
  1671. * @return string the variable translated
  1672. */
  1673. function get_plugin_lang($variable, $pluginName) {
  1674. $plugin = $pluginName::create();
  1675. return $plugin->get_lang($variable);
  1676. }
  1677. /**
  1678. * Returns an array of translated week days and months, short and normal names.
  1679. * @param string $language (optional) Language id. If it is omitted, the current interface language is assumed.
  1680. * @return array Returns a multidimensional array with translated week days and months.
  1681. */
  1682. function &_api_get_day_month_names($language = null) {
  1683. static $date_parts = array();
  1684. if (empty($language)) {
  1685. $language = api_get_interface_language();
  1686. }
  1687. if (!isset($date_parts[$language])) {
  1688. $week_day = array(
  1689. 'Sunday',
  1690. 'Monday',
  1691. 'Tuesday',
  1692. 'Wednesday',
  1693. 'Thursday',
  1694. 'Friday',
  1695. 'Saturday',
  1696. );
  1697. $month = array(
  1698. 'January',
  1699. 'February',
  1700. 'March',
  1701. 'April',
  1702. 'May',
  1703. 'June',
  1704. 'July',
  1705. 'August',
  1706. 'September',
  1707. 'October',
  1708. 'November',
  1709. 'December',
  1710. );
  1711. for ($i = 0; $i < 7; $i++) {
  1712. $date_parts[$language]['days_short'][] = get_lang($week_day[$i].'Short', '', $language);
  1713. $date_parts[$language]['days_long'][] = get_lang($week_day[$i].'Long', '', $language);
  1714. }
  1715. for ($i = 0; $i < 12; $i++) {
  1716. $date_parts[$language]['months_short'][] = get_lang($month[$i].'Short', '', $language);
  1717. $date_parts[$language]['months_long'][] = get_lang($month[$i].'Long', '', $language);
  1718. }
  1719. }
  1720. return $date_parts[$language];
  1721. }
  1722. /**
  1723. * Returns returns person name convention for a given language.
  1724. * @param string $language The input language.
  1725. * @param string $type The type of the requested convention.
  1726. * It may be 'format' for name order convention or 'sort_by' for name sorting convention.
  1727. * @return mixed Depending of the requested type,
  1728. * the returned result may be string or boolean; null is returned on error;
  1729. */
  1730. function _api_get_person_name_convention($language, $type)
  1731. {
  1732. static $conventions;
  1733. $language = api_purify_language_id($language);
  1734. if (!isset($conventions)) {
  1735. $file = dirname(__FILE__).'/internationalization_database/name_order_conventions.php';
  1736. if (file_exists($file)) {
  1737. $conventions = include ($file);
  1738. } else {
  1739. $conventions = array(
  1740. 'english' => array(
  1741. 'format' => 'title first_name last_name',
  1742. 'sort_by' => 'first_name'
  1743. )
  1744. );
  1745. }
  1746. // Overwrite classic conventions
  1747. $customConventions = api_get_configuration_value('name_order_conventions');
  1748. if (!empty($customConventions)) {
  1749. foreach ($customConventions as $key => $data) {
  1750. $conventions[$key] = $data;
  1751. }
  1752. }
  1753. $search1 = array('FIRST_NAME', 'LAST_NAME', 'TITLE');
  1754. $replacement1 = array('%F', '%L', '%T');
  1755. $search2 = array('first_name', 'last_name', 'title');
  1756. $replacement2 = array('%f', '%l', '%t');
  1757. foreach (array_keys($conventions) as $key) {
  1758. $conventions[$key]['format'] = str_replace($search1, $replacement1, $conventions[$key]['format']);
  1759. $conventions[$key]['format'] = _api_validate_person_name_format(_api_clean_person_name(str_replace('%', ' %', str_ireplace($search2, $replacement2, $conventions[$key]['format']))));
  1760. $conventions[$key]['sort_by'] = strtolower($conventions[$key]['sort_by']) != 'last_name' ? true : false;
  1761. }
  1762. }
  1763. switch ($type) {
  1764. case 'format':
  1765. return is_string($conventions[$language]['format']) ? $conventions[$language]['format'] : '%t %f %l';
  1766. case 'sort_by':
  1767. return is_bool($conventions[$language]['sort_by']) ? $conventions[$language]['sort_by'] : true;
  1768. }
  1769. return null;
  1770. }
  1771. /**
  1772. * Replaces non-valid formats for person names with the default (English) format.
  1773. * @param string $format The input format to be verified.
  1774. * @return bool Returns the same format if is is valid, otherwise returns a valid English format.
  1775. */
  1776. function _api_validate_person_name_format($format) {
  1777. if (empty($format) || stripos($format, '%f') === false || stripos($format, '%l') === false) {
  1778. return '%t %f %l';
  1779. }
  1780. return $format;
  1781. }
  1782. /**
  1783. * Removes leading, trailing and duplicate whitespace and/or commas in a full person name.
  1784. * 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.
  1785. * @param string $person_name The input person name.
  1786. * @return string Returns cleaned person name.
  1787. */
  1788. function _api_clean_person_name($person_name) {
  1789. return preg_replace(array('/\s+/', '/, ,/', '/,+/', '/^[ ,]/', '/[ ,]$/'), array(' ', ', ', ',', '', ''), $person_name);
  1790. }
  1791. /**
  1792. * Appendix to "Multibyte string conversion functions"
  1793. */
  1794. /**
  1795. * This is a php-implementation of a function that is similar to mb_convert_encoding() from mbstring extension.
  1796. * The function converts a given string from one to another character encoding.
  1797. * @param string $string The string being converted.
  1798. * @param string $to_encoding The encoding that $string is being converted to.
  1799. * @param string $from_encoding The encoding that $string is being converted from.
  1800. * @return string Returns the converted string.
  1801. */
  1802. function _api_convert_encoding(&$string, $to_encoding, $from_encoding)
  1803. {
  1804. return mb_convert_encoding($string, $to_encoding, $from_encoding);
  1805. }
  1806. /**
  1807. * This function determines the name of corresponding to a given encoding conversion table.
  1808. * It is able to deal with some aliases of the encoding.
  1809. * @param string $encoding The given encoding identificator, for example 'WINDOWS-1252'.
  1810. * @return string Returns the name of the corresponding conversion table, for the same example - 'CP1252'.
  1811. */
  1812. function _api_get_character_map_name($encoding) {
  1813. static $character_map_selector;
  1814. if (!isset($character_map_selector)) {
  1815. $file = dirname(__FILE__).'/internationalization_database/conversion/character_map_selector.php';
  1816. if (file_exists($file)) {
  1817. $character_map_selector = include ($file);
  1818. } else {
  1819. $character_map_selector = array();
  1820. }
  1821. }
  1822. return isset($character_map_selector[$encoding]) ? $character_map_selector[$encoding] : '';
  1823. }
  1824. /**
  1825. * Appendix to "String comparison"
  1826. */
  1827. /**
  1828. * A reverse function from php-core function strnatcmp(), performs string comparison in reverse natural (alpha-numerical) order.
  1829. * @param string $string1 The first string.
  1830. * @param string $string2 The second string.
  1831. * @return int Returns 0 if $string1 = $string2; >0 if $string1 < $string2; <0 if $string1 > $string2.
  1832. */
  1833. function _api_strnatrcmp($string1, $string2)
  1834. {
  1835. return strnatcmp($string2, $string1);
  1836. }
  1837. /**
  1838. * Sets/Gets internal character encoding of the common string functions within the PHP mbstring extension.
  1839. * @param string $encoding (optional) When this parameter is given, the function sets the internal encoding.
  1840. * @return string When $encoding parameter is not given, the function returns the internal encoding.
  1841. * Note: This function is used in the global initialization script for setting the internal encoding to the platform's character set.
  1842. * @link http://php.net/manual/en/function.mb-internal-encoding
  1843. */
  1844. function _api_mb_internal_encoding($encoding = 'UTF-8')
  1845. {
  1846. return mb_internal_encoding($encoding);
  1847. }
  1848. /**
  1849. * Checks whether the specified encoding is supported by the PHP mbstring extension.
  1850. * @param string $encoding The specified encoding.
  1851. * @return bool Returns TRUE when the specified encoding is supported, FALSE othewise.
  1852. */
  1853. function _api_mb_supports($encoding) {
  1854. static $supported = array();
  1855. if (!isset($supported[$encoding])) {
  1856. if (MBSTRING_INSTALLED) {
  1857. $supported[$encoding] = api_equal_encodings($encoding, mb_list_encodings(), true);
  1858. } else {
  1859. $supported[$encoding] = false;
  1860. }
  1861. }
  1862. return $supported[$encoding];
  1863. }
  1864. /**
  1865. * Checks whether the specified encoding is supported by the PHP iconv extension.
  1866. * @param string $encoding The specified encoding.
  1867. * @return bool Returns TRUE when the specified encoding is supported, FALSE othewise.
  1868. */
  1869. function _api_iconv_supports($encoding) {
  1870. static $supported = array();
  1871. if (!isset($supported[$encoding])) {
  1872. if (ICONV_INSTALLED) {
  1873. $enc = api_refine_encoding_id($encoding);
  1874. if ($enc != 'HTML-ENTITIES') {
  1875. $test_string = '';
  1876. for ($i = 32; $i < 128; $i++) {
  1877. $test_string .= chr($i);
  1878. }
  1879. $supported[$encoding] = (@iconv_strlen($test_string, $enc)) ? true : false;
  1880. } else {
  1881. $supported[$encoding] = false;
  1882. }
  1883. } else {
  1884. $supported[$encoding] = false;
  1885. }
  1886. }
  1887. return $supported[$encoding];
  1888. }
  1889. // This function checks whether the function _api_convert_encoding() (the php-
  1890. // implementation) is able to convert from/to a given encoding.
  1891. function _api_convert_encoding_supports($encoding) {
  1892. static $supports = array();
  1893. if (!isset($supports[$encoding])) {
  1894. $supports[$encoding] = _api_get_character_map_name(api_refine_encoding_id($encoding)) != '';
  1895. }
  1896. return $supports[$encoding];
  1897. }