internationalization.lib.php 92 KB

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