internationalization.lib.php 87 KB

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