internationalization.lib.php 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233
  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. }