internationalization.lib.php 92 KB

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