internationalization.lib.php 87 KB

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