internationalization.lib.php 84 KB

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