internationalization.lib.php 154 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * File: internationalization.lib.php
  5. * Internationalization library for Chamilo 1.8.7 LMS
  6. * A library implementing internationalization related functions.
  7. * License: GNU General Public License Version 3 (Free Software Foundation)
  8. * @author Ivan Tcholakov, <ivantcholakov@gmail.com>, 2009, 2010
  9. * @author More authors, mentioned in the correpsonding fragments of this source.
  10. * @package chamilo.library
  11. */
  12. /**
  13. * Constants
  14. */
  15. // Special tags for marking untranslated variables.
  16. define('SPECIAL_OPENING_TAG', '[=');
  17. define('SPECIAL_CLOSING_TAG', '=]');
  18. // Predefined date formats in Chamilo provided by the language sub-system.
  19. // To be used as a parameter for the function api_format_date()
  20. define('TIME_NO_SEC_FORMAT', 0); // 15:23
  21. define('DATE_FORMAT_SHORT', 1); // Aug 25, 09
  22. define('DATE_FORMAT_LONG', 2); // Monday August 25, 09
  23. define('DATE_FORMAT_LONG_NO_DAY', 10); // August 25, 2009
  24. define('DATE_TIME_FORMAT_LONG', 3); // Monday August 25, 2009 at 03:28 PM
  25. define('DATE_FORMAT_NUMBER', 4); // 25.08.09
  26. define('DATE_TIME_FORMAT_LONG_24H', 5); // August 25, 2009 at 15:28
  27. define('DATE_TIME_FORMAT_SHORT', 6); // Aug 25, 2009 at 03:28 PM
  28. define('DATE_TIME_FORMAT_SHORT_TIME_FIRST', 7); // 03:28 PM, Aug 25 2009
  29. define('DATE_FORMAT_NUMBER_NO_YEAR', 8); // 25.08 dd-mm
  30. define('DATE_FORMAT_ONLY_DAYNAME', 9); // Monday, Sunday, etc
  31. // Formatting person's name.
  32. // Formatting a person's name using the pattern as it has been
  33. // configured in the internationalization database for every language.
  34. // This (default) option would be the most used.
  35. define('PERSON_NAME_COMMON_CONVENTION', 0);
  36. // The following options may be used in limited number of places for overriding the common convention:
  37. // Formatting a person's name in Western order: first_name last_name
  38. define('PERSON_NAME_WESTERN_ORDER', 1);
  39. // Formatting a person's name in Eastern order: last_name first_name
  40. define('PERSON_NAME_EASTERN_ORDER', 2);
  41. // Contextual: formatting person's name in library order: last_name, first_name
  42. define('PERSON_NAME_LIBRARY_ORDER', 3);
  43. // Contextual: formatting a person's name assotiated with an email-address. Ivan: I am not sure how seems email servers an clients would interpret name order, so I assign the Western order.
  44. define('PERSON_NAME_EMAIL_ADDRESS', PERSON_NAME_WESTERN_ORDER);
  45. // Contextual: formatting a person's name for data-exporting operations. For backward compatibility this format has been set to Eastern order.
  46. define('PERSON_NAME_DATA_EXPORT', PERSON_NAME_EASTERN_ORDER);
  47. // The following constants are used for tuning language detection functionality.
  48. // We reduce the text for language detection to the given number of characters
  49. // for increasing speed and to decrease memory consumption.
  50. define ('LANGUAGE_DETECT_MAX_LENGTH', 2000);
  51. // Maximum allowed difference in so called delta-points for aborting certain language detection.
  52. // The value 80000 is good enough for speed and detection accuracy.
  53. // If you set the value of $max_delta too low, no language will be recognized.
  54. // $max_delta = 400 * 350 = 140000 is the best detection with lowest speed.
  55. define ('LANGUAGE_DETECT_MAX_DELTA', 140000);
  56. /**
  57. * Initialization of some internal default values in the internationalization library.
  58. * @return void
  59. * Note: This function should be called only once in the global initialization script.
  60. */
  61. function api_initialize_internationalization()
  62. {
  63. if (MBSTRING_INSTALLED) {
  64. @ini_set('mbstring.func_overload', 0);
  65. @ini_set('mbstring.encoding_translation', 0);
  66. @ini_set('mbstring.http_input', 'pass');
  67. @ini_set('mbstring.http_output', 'pass');
  68. @ini_set('mbstring.language', 'neutral');
  69. }
  70. api_set_internationalization_default_encoding('UTF-8');
  71. }
  72. /**
  73. * Sets the internal default encoding for the multi-byte string functions.
  74. * @param string $encoding The specified default encoding.
  75. * @return string Returns the old value of the default encoding.
  76. */
  77. function api_set_internationalization_default_encoding($encoding) {
  78. $encoding = api_refine_encoding_id($encoding);
  79. $result = _api_mb_internal_encoding();
  80. _api_mb_internal_encoding($encoding);
  81. _api_mb_regex_encoding($encoding);
  82. _api_iconv_set_encoding('iconv_internal_encoding', $encoding);
  83. return $result;
  84. }
  85. /**
  86. * Language support
  87. */
  88. // These variables are for internal purposes only, they serve the function api_is_translated().
  89. $_api_is_translated = false;
  90. $_api_is_translated_call = false;
  91. /**
  92. * Returns a translated (localized) string, called by its identificator.
  93. * @param string $variable This is the identificator (name) of the translated string to be retrieved.
  94. * @param string $reserved This parameter has been reserved for future use.
  95. * @param string $language (optional) Language indentificator. If it is omited, the current interface language is assumed.
  96. * @return string Returns the requested string in the correspondent language.
  97. *
  98. * @author Roan Embrechts
  99. * @author Patrick Cool
  100. * @author Ivan Tcholakov, 2009-2010 (caching functionality, additional parameter $language, other adaptations).
  101. *
  102. * Notes:
  103. * 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').
  104. * 2. Untranslated variables might be indicated by special opening and closing tags - [= =]
  105. * The special tags do not show up in these two cases:
  106. * - when the system has been switched to "production server mode";
  107. * - when a special platform setting 'hide_dltt_markup' is set to "true" (the name of this setting comes from history);
  108. * 3. Translations are created many contributors through using a special tool: Chamilo Translation Application.
  109. * @link http://translate.chamilo.org/
  110. */
  111. function get_lang($variable, $reserved = null, $language = null) {
  112. global
  113. // For serving some old hacks:
  114. // By manipulating this global variable the translation may be done in different languages too (not the elegant way).
  115. $language_interface,
  116. // Because of possibility for manipulations of the global variable $language_interface, we need its initial value.
  117. $language_interface_initial_value,
  118. // For serving the function is_translated()
  119. $_api_is_translated, $_api_is_translated_call;
  120. global $used_lang_vars, $_configuration;
  121. // add language_measure_frequency to your main/inc/conf/configuration.php in order to generate language
  122. // variables frequency measurements (you can then see them trhough main/cron/lang/langstats.php)
  123. // The $langstats object is instanciated at the end of main/inc/global.inc.php
  124. if (isset($_configuration['language_measure_frequency']) && $_configuration['language_measure_frequency'] == 1) {
  125. require_once api_get_path(SYS_CODE_PATH).'/cron/lang/langstats.class.php';
  126. global $langstats;
  127. $langstats->add_use($variable,'');
  128. }
  129. if (!isset ($used_lang_vars)) {
  130. $used_lang_vars = array();
  131. }
  132. // Caching results from some API functions, for speed.
  133. static $initialized, $encoding, $is_utf8_encoding, $langpath, $test_server_mode, $show_special_markup;
  134. if (!isset($initialized)) {
  135. $encoding = api_get_system_encoding();
  136. $is_utf8_encoding = api_is_utf8($encoding);
  137. $langpath = api_get_path(SYS_LANG_PATH);
  138. $test_server_mode = api_get_setting('server_type') == 'test';
  139. $show_special_markup = api_get_setting('hide_dltt_markup') != 'true' || $test_server_mode;
  140. $initialized = true;
  141. }
  142. // Combining both ways for requesting specific language.
  143. if (empty($language)) {
  144. $language = $language_interface;
  145. }
  146. $lang_postfix = isset($is_interface_language) && $is_interface_language ? '' : '('.$language.')';
  147. $is_interface_language = $language == $language_interface_initial_value;
  148. // This is a cache for already translated language variables. By using it, we avoid repetitive translations, gaining speed.
  149. static $cache;
  150. // Looking up into the cache for existing translation.
  151. if (isset($cache[$language][$variable]) && !$_api_is_translated_call) {
  152. // There is a previously saved translation, returning it.
  153. //return $cache[$language][$variable];
  154. $ret = $cache[$language][$variable];
  155. $used_lang_vars[$variable.$lang_postfix] = $ret;
  156. return $ret;
  157. }
  158. $_api_is_translated = false;
  159. // There is no cached translation, we have to retrieve it:
  160. // - from a global variable (the faster way) - on production server mode;
  161. // - from a local variable after reloading the language files - on test server mode or when requested language is different than the genuine interface language.
  162. $read_global_variables = $is_interface_language && !$test_server_mode && !$_api_is_translated_call;
  163. // Reloading the language files when it is necessary.
  164. if (!$read_global_variables) {
  165. global $language_files;
  166. if (isset($language_files)) {
  167. $parent_language = null;
  168. if (api_get_setting('allow_use_sub_language') == 'true') {
  169. require_once api_get_path(SYS_CODE_PATH).'admin/sub_language.class.php';
  170. $parent_language = SubLanguageManager::get_parent_language_path($language);
  171. }
  172. if (!is_array($language_files)) {
  173. if (isset($parent_language)) {
  174. @include "$langpath$parent_language/$language_files.inc.php";
  175. }
  176. @include "$langpath$language/$language_files.inc.php";
  177. } else {
  178. foreach ($language_files as &$language_file) {
  179. if (isset($parent_language)) {
  180. @include "$langpath$parent_language/$language_file.inc.php";
  181. }
  182. @include "$langpath$language/$language_file.inc.php";
  183. }
  184. }
  185. }
  186. }
  187. // Translation mode for production servers.
  188. if (!$test_server_mode) {
  189. if ($read_global_variables) {
  190. if (isset($GLOBALS[$variable])) {
  191. $langvar = $GLOBALS[$variable];
  192. $_api_is_translated = true;
  193. } elseif (isset($GLOBALS["lang$variable"])) {
  194. $langvar = $GLOBALS["lang$variable"];
  195. $_api_is_translated = true;
  196. } else {
  197. $langvar = $show_special_markup ? SPECIAL_OPENING_TAG.$variable.SPECIAL_CLOSING_TAG : $variable;
  198. }
  199. } else {
  200. if (isset($$variable)) {
  201. $langvar = $$variable;
  202. $_api_is_translated = true;
  203. } elseif (isset(${"lang$variable"})) {
  204. $langvar = ${"lang$variable"};
  205. $_api_is_translated = true;
  206. } else {
  207. $langvar = $show_special_markup ? SPECIAL_OPENING_TAG.$variable.SPECIAL_CLOSING_TAG : $variable;
  208. }
  209. }
  210. if (empty($langvar) || !is_string($langvar)) {
  211. $_api_is_translated = false;
  212. $langvar = $show_special_markup ? SPECIAL_OPENING_TAG.$variable.SPECIAL_CLOSING_TAG : $variable;
  213. }
  214. //return $cache[$language][$variable] = $is_utf8_encoding ? $langvar : api_utf8_decode($langvar, $encoding);
  215. $ret = $cache[$language][$variable] = $is_utf8_encoding ? $langvar : api_utf8_decode($langvar, $encoding);
  216. $used_lang_vars[$variable.$lang_postfix] = $ret;
  217. return $ret;
  218. }
  219. // Translation mode for test/development servers.
  220. if (!is_string($variable)) {
  221. //return $cache[$language][$variable] = SPECIAL_OPENING_TAG.'get_lang(?)'.SPECIAL_CLOSING_TAG;
  222. $ret = $cache[$language][$variable] = SPECIAL_OPENING_TAG.'get_lang(?)'.SPECIAL_CLOSING_TAG;
  223. $used_lang_vars[$variable.$lang_postfix] = $ret;
  224. return $ret;
  225. }
  226. if (isset($$variable)) {
  227. $langvar = $$variable;
  228. $_api_is_translated = true;
  229. } elseif (isset(${"lang$variable"})) {
  230. $langvar = ${"lang$variable"};
  231. $_api_is_translated = true;
  232. } else {
  233. $langvar = $show_special_markup ? SPECIAL_OPENING_TAG.$variable.SPECIAL_CLOSING_TAG : $variable;
  234. }
  235. if (empty($langvar) || !is_string($langvar)) {
  236. $_api_is_translated = false;
  237. $langvar = $show_special_markup ? SPECIAL_OPENING_TAG.$variable.SPECIAL_CLOSING_TAG : $variable;
  238. }
  239. //return $cache[$language][$variable] = $is_utf8_encoding ? $langvar : api_utf8_decode($langvar, $encoding);
  240. $ret = $cache[$language][$variable] = $is_utf8_encoding ? $langvar : api_utf8_decode($langvar, $encoding);
  241. $used_lang_vars[$variable.$lang_postfix] = $ret;
  242. return $ret;
  243. }
  244. /**
  245. * Checks whether exists a translated (localized) string.
  246. * @param string $variable This is the identificator (name) of the translated string to be checked.
  247. * @param string $language (optional) Language indentificator. If it is omited, the current interface language is assumed.
  248. * @return bool Returns TRUE if translation exists, FALSE otherwise.
  249. * @author Ivan Tcholakov, 2010.
  250. */
  251. function api_is_translated($variable, $language = null) {
  252. global $_api_is_translated, $_api_is_translated_call;
  253. $_api_is_translated_call = true;
  254. get_lang($variable, $language);
  255. $_api_is_translated_call = false;
  256. return $_api_is_translated;
  257. }
  258. /**
  259. * Gets the current interface language.
  260. * @param bool $purified (optional) When it is true, a purified (refined) language value will be returned, for example 'french' instead of 'french_unicode'.
  261. * @return string The current language of the interface.
  262. */
  263. function api_get_interface_language($purified = false, $check_sub_language = false) {
  264. global $language_interface;
  265. if (empty($language_interface)) {
  266. return 'english';
  267. }
  268. //1. Checking if current language is supported
  269. $language_is_supported = api_is_language_supported($language_interface);
  270. if ($check_sub_language && !$language_is_supported) {
  271. static $parent_language_name = null;
  272. if (!isset($parent_language_name)) {
  273. //2. The current language is a sub language so we grab the father's setting according to the internalization_database/name_order_convetions.php file
  274. $language_id = api_get_language_id($language_interface);
  275. $language_info = api_get_language_info($language_id);
  276. if (!empty($language_id) && !empty($language_info)) {
  277. $language_info = api_get_language_info($language_info['parent_id']);
  278. $parent_language_name = $language_info['english_name'];
  279. if (!empty($parent_language_name)) {
  280. return $parent_language_name;
  281. }
  282. }
  283. return 'english';
  284. } else {
  285. return $parent_language_name;
  286. }
  287. } else {
  288. //2. Normal way
  289. $interface_language = $purified ? api_purify_language_id($language_interface) : $language_interface;
  290. }
  291. return $interface_language;
  292. }
  293. /**
  294. * Checks whether a given language identificator represents supported by *this library* language.
  295. * @param string $language The language identificator to be checked ('english', 'french', 'spanish', ...).
  296. * @return bool $language TRUE if the language is supported, FALSE otherwise.
  297. */
  298. function api_is_language_supported($language) {
  299. static $supported = array();
  300. if (!isset($supported[$language])) {
  301. $supported[$language] = in_array(api_purify_language_id($language), array_keys(_api_non_utf8_encodings()));
  302. }
  303. return $supported[$language];
  304. }
  305. /**
  306. * Validates the input language identificator in order always to return a language that is enabled in the system.
  307. * This function is to be used for data import when provided language identificators should be validated.
  308. * @param string $language The language identificator to be validated.
  309. * @return string Returns the input language identificator. If the input language is not enabled, platform language is returned then.
  310. */
  311. function api_get_valid_language($language) {
  312. static $enabled_languages;
  313. if (!isset($enabled_languages)) {
  314. $enabled_languages_info = api_get_languages();
  315. $enabled_languages = $enabled_languages_info['folder'];
  316. }
  317. $language = str_replace('_km', '_KM', strtolower(trim($language)));
  318. if (empty($language) || !in_array($language, $enabled_languages) || !api_is_language_supported($language)) {
  319. $language = api_get_setting('platformLanguage');
  320. }
  321. return $language;
  322. }
  323. /**
  324. * Returns a purified language id, without possible suffixes that will disturb language identification in certain cases.
  325. * @param string $language The input language identificator, for example 'french_unicode'.
  326. * @param string The same purified or filtered language identificator, for example 'french'.
  327. */
  328. function api_purify_language_id($language) {
  329. static $purified = array();
  330. if (!isset($purified[$language])) {
  331. $purified[$language] = trim(str_replace(array('_unicode', '_latin', '_corporate', '_org', '_km'), '', strtolower($language)));
  332. }
  333. return $purified[$language];
  334. }
  335. /**
  336. * Gets language isocode column from the language table, taking the given language as a query parameter.
  337. * @param string $language This is the name of the folder containing translations for the corresponding language (e.g arabic, english).
  338. * @param string $default_code This is the value to be returned if there was no code found corresponding to the given language.
  339. * If $language is omitted, interface language is assumed then.
  340. * @return string The found isocode or null on error.
  341. * Returned codes are according to the following standards (in order of preference):
  342. * - ISO 639-1 : Alpha-2 code (two-letters code - en, fr, es, ...)
  343. * - RFC 4646 : five-letter code based on the ISO 639 two-letter language codes
  344. * and the ISO 3166 two-letter territory codes (pt-BR, ...)
  345. * - ISO 639-2 : Alpha-3 code (three-letters code - ast, fur, ...)
  346. */
  347. function api_get_language_isocode($language = null, $default_code = 'en') {
  348. static $iso_code = array();
  349. if (empty($language)) {
  350. $language = api_get_interface_language(false, true);
  351. }
  352. if (!isset($iso_code[$language])) {
  353. if (!class_exists('Database')) {
  354. return $default_code; // This might happen, in case of calling this function early during the global initialization.
  355. }
  356. $sql_result = Database::query("SELECT isocode FROM ".Database::get_main_table(TABLE_MAIN_LANGUAGE)." WHERE dokeos_folder = '$language'");
  357. if (Database::num_rows($sql_result)) {
  358. $result = Database::fetch_array($sql_result);
  359. $iso_code[$language] = trim($result['isocode']);
  360. } else {
  361. $language_purified_id = api_purify_language_id($language);
  362. $iso_code[$language] = isset($iso_code[$language_purified_id]) ? $iso_code[$language_purified_id] : null;
  363. }
  364. if (empty($iso_code[$language])) {
  365. $iso_code[$language] = $default_code;
  366. }
  367. }
  368. return $iso_code[$language];
  369. }
  370. /**
  371. * Gets language isocode column from the language table
  372. *
  373. * @return array An array with the current isocodes
  374. *
  375. * */
  376. function api_get_platform_isocodes() {
  377. $iso_code = array();
  378. $sql_result = Database::query("SELECT isocode FROM ".Database::get_main_table(TABLE_MAIN_LANGUAGE)." ORDER BY isocode ");
  379. if (Database::num_rows($sql_result)) {
  380. while ($row = Database::fetch_array($sql_result)) {;
  381. $iso_code[] = trim($row['isocode']);
  382. }
  383. }
  384. return $iso_code;
  385. }
  386. /**
  387. * Gets text direction according to the given language.
  388. * @param string $language This is the name of the folder containing translations for the corresponding language (e.g 'arabic', 'english', ...).
  389. * ISO-codes are acceptable too ('ar', 'en', ...). If $language is omitted, interface language is assumed then.
  390. * @return string The correspondent to the language text direction ('ltr' or 'rtl').
  391. */
  392. function api_get_text_direction($language = null) {
  393. static $text_direction = array();
  394. /*
  395. * Not necessary to validate the language because the list if rtl/ltr is harcoded
  396. *
  397. /*
  398. $language_is_supported = api_is_language_supported($language);
  399. if (!$language_is_supported || empty($language)) {
  400. $language = api_get_interface_language(false, true);
  401. }*/
  402. if (empty($language)) {
  403. $language = api_get_interface_language();
  404. }
  405. if (!isset($text_direction[$language])) {
  406. $text_direction[$language] = in_array(api_purify_language_id($language),
  407. array(
  408. 'arabic',
  409. 'ar',
  410. 'dari',
  411. 'prs',
  412. 'hebrew',
  413. 'he',
  414. 'iw',
  415. 'pashto',
  416. 'ps',
  417. 'persian',
  418. 'fa',
  419. 'ur',
  420. 'yiddish',
  421. 'yid'
  422. )
  423. ) ? 'rtl' : 'ltr';
  424. }
  425. return $text_direction[$language];
  426. }
  427. /**
  428. * This function checks whether a given language can use Latin 1 encoding.
  429. * In the past (Chamilo 1.8.6.2), the function was used in the installation script only once.
  430. * It is not clear whether this function would be use useful for something else in the future.
  431. * @param string $language The checked language.
  432. * @return bool TRUE if the given language can use Latin 1 encoding (ISO-8859-15, ISO-8859-1, WINDOWS-1252, ...), FALSE otherwise.
  433. */
  434. function api_is_latin1_compatible($language) {
  435. static $latin1_languages;
  436. if (!isset($latin1_languages)) {
  437. $latin1_languages = _api_get_latin1_compatible_languages();
  438. }
  439. $language = api_purify_language_id($language);
  440. return in_array($language, $latin1_languages);
  441. }
  442. /**
  443. * Language recognition
  444. * Based on the publication:
  445. * W. B. Cavnar and J. M. Trenkle. N-gram-based text categorization.
  446. * Proceedings of SDAIR-94, 3rd Annual Symposium on Document Analysis
  447. * and Information Retrieval, 1994.
  448. * @link http://citeseer.ist.psu.edu/cache/papers/cs/810/http:zSzzSzwww.info.unicaen.frzSz~giguetzSzclassifzSzcavnar_trenkle_ngram.pdf/n-gram-based-text.pdf
  449. */
  450. function api_detect_language(&$string, $encoding = null) {
  451. if (empty($encoding)) {
  452. $encoding = _api_mb_internal_encoding();
  453. }
  454. if (empty($string)) {
  455. return false;
  456. }
  457. $result_array = &_api_compare_n_grams(_api_generate_n_grams(api_substr($string, 0, LANGUAGE_DETECT_MAX_LENGTH, $encoding), $encoding), $encoding);
  458. if (empty($result_array)) {
  459. return false;
  460. }
  461. list($key, $delta_points) = each($result_array);
  462. return strstr($key, ':', true);
  463. }
  464. /**
  465. * Date and time conversions and formats
  466. */
  467. /**
  468. * Returns an alphabetized list of timezones in an associative array that can be used to populate a select
  469. *
  470. * @return array List of timezone identifiers
  471. *
  472. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  473. */
  474. function api_get_timezones()
  475. {
  476. $timezone_identifiers = DateTimeZone::listIdentifiers();
  477. sort($timezone_identifiers);
  478. $out = array();
  479. foreach ($timezone_identifiers as $tz) {
  480. $out[$tz] = $tz;
  481. }
  482. $null_option = array('' => '');
  483. $result = array_merge($null_option, $out);
  484. return $result;
  485. }
  486. /**
  487. * Returns the timezone to be converted to/from, based on user or admin preferences
  488. *
  489. * @return string The timezone chosen
  490. */
  491. function _api_get_timezone() {
  492. global $_user;
  493. // First, get the default timezone of the server
  494. $to_timezone = date_default_timezone_get();
  495. // Second, see if a timezone has been chosen for the platform
  496. $timezone_value = api_get_setting('timezone_value', 'timezones');
  497. if ($timezone_value != null) {
  498. $to_timezone = $timezone_value;
  499. }
  500. // If allowed by the administrator
  501. $use_users_timezone = api_get_setting('use_users_timezone', 'timezones');
  502. if ($use_users_timezone == 'true') {
  503. // Get the timezone based on user preference, if it exists
  504. $timezone_user = UserManager::get_extra_user_data_by_field($_user['user_id'],'timezone');
  505. if (isset($timezone_user['timezone']) && $timezone_user['timezone'] != null) {
  506. $to_timezone = $timezone_user['timezone'];
  507. }
  508. }
  509. return $to_timezone;
  510. }
  511. /**
  512. * Returns the given date as a DATETIME in UTC timezone. This function should be used before entering any date in the DB.
  513. *
  514. * @param mixed The date to be converted (can be a string supported by date() or a timestamp)
  515. * @param bool if the date is not correct return null instead of the current date
  516. * @return string The DATETIME in UTC to be inserted in the DB, or null if the format of the argument is not supported
  517. *
  518. * @author Julio Montoya - Adding the 2nd parameter
  519. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  520. */
  521. function api_get_utc_datetime($time = null, $return_null_if_invalid_date = false) {
  522. $from_timezone = _api_get_timezone();
  523. $to_timezone = 'UTC';
  524. if (is_null($time) || empty($time) || $time == '0000-00-00 00:00:00') {
  525. if ($return_null_if_invalid_date) {
  526. return null;
  527. }
  528. return gmdate('Y-m-d H:i:s');
  529. }
  530. if (preg_match('/__@(.*)@__/', $time)) {
  531. // unfilter special security fix for SQL injection, see Database::fixQuery()
  532. $time = str_replace(array("__@","@__"), "", $time);
  533. }
  534. // If time is a timestamp, return directly in utc
  535. if (is_numeric($time)) {
  536. $time = intval($time);
  537. return gmdate('Y-m-d H:i:s', $time);
  538. }
  539. try {
  540. $date = new DateTime($time, new DateTimezone($from_timezone));
  541. $date->setTimezone(new DateTimeZone($to_timezone));
  542. return $date->format('Y-m-d H:i:s');
  543. } catch (Exception $e) {
  544. return null;
  545. }
  546. }
  547. /**
  548. * Returns a DATETIME string converted to the right timezone
  549. * @param mixed The time to be converted
  550. * @param string The timezone to be converted to.
  551. * If null, the timezone will be determined based on user preference,
  552. * or timezone chosen by the admin for the platform.
  553. * @param string The timezone to be converted from. If null, UTC will be assumed.
  554. * @return string The converted time formatted as Y-m-d H:i:s
  555. *
  556. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  557. */
  558. function api_get_local_time($time = null, $to_timezone = null, $from_timezone = null, $return_null_if_invalid_date = false)
  559. {
  560. // Determining the timezone to be converted from
  561. if (is_null($from_timezone)) {
  562. $from_timezone = 'UTC';
  563. }
  564. // Determining the timezone to be converted to
  565. if (is_null($to_timezone)) {
  566. $to_timezone = _api_get_timezone();
  567. }
  568. // If time is a timestamp, convert it to a string
  569. if (is_null($time) || empty($time) || $time == '0000-00-00 00:00:00') {
  570. if ($return_null_if_invalid_date) {
  571. return null;
  572. }
  573. $from_timezone = 'UTC';
  574. $time = gmdate('Y-m-d H:i:s');
  575. }
  576. if (is_numeric($time)) {
  577. $time = intval($time);
  578. $from_timezone = 'UTC';
  579. $time = gmdate('Y-m-d H:i:s', $time);
  580. }
  581. try {
  582. $date = new DateTime($time, new DateTimezone($from_timezone));
  583. $date->setTimezone(new DateTimeZone($to_timezone));
  584. return $date->format('Y-m-d H:i:s');
  585. } catch (Exception $e) {
  586. return null;
  587. }
  588. }
  589. /**
  590. * Converts a string into a timestamp safely (handling timezones), using strtotime
  591. *
  592. * @param string String to be converted
  593. * @param string Timezone (if null, the timezone will be determined based on user preference, or timezone chosen by the admin for the platform)
  594. * @return int Timestamp
  595. *
  596. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  597. */
  598. function api_strtotime($time, $timezone = null) {
  599. $system_timezone = date_default_timezone_get();
  600. if (!empty($timezone)) {
  601. date_default_timezone_set($timezone);
  602. }
  603. $timestamp = strtotime($time);
  604. date_default_timezone_set($system_timezone);
  605. return $timestamp;
  606. }
  607. /**
  608. * Returns formated date/time, correspondent to a given language.
  609. * The given date should be in the timezone chosen by the administrator and/or user. Use api_get_local_time to get it.
  610. *
  611. * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
  612. * @author Christophe Gesche<gesche@ipm.ucl.ac.be>
  613. * originally inspired from from PhpMyAdmin
  614. * @author Ivan Tcholakov, 2009, code refactoring, adding support for predefined date/time formats.
  615. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  616. *
  617. * @param mixed Timestamp or datetime string
  618. * @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)
  619. * @param string $language (optional) Language indentificator. If it is omited, the current interface language is assumed.
  620. * @return string Returns the formatted date.
  621. *
  622. * @link http://php.net/manual/en/function.strftime.php
  623. */
  624. function api_format_date($time, $format = null, $language = null) {
  625. $system_timezone = date_default_timezone_get();
  626. date_default_timezone_set(_api_get_timezone());
  627. if (is_string($time)) {
  628. $time = strtotime($time);
  629. }
  630. if (is_null($format)) {
  631. $format = DATE_TIME_FORMAT_LONG;
  632. }
  633. $datetype = null;
  634. $timetype = null;
  635. if (is_int($format)) {
  636. switch ($format) {
  637. case DATE_FORMAT_ONLY_DAYNAME:
  638. $date_format = get_lang('dateFormatOnlyDayName', '', $language);
  639. if (INTL_INSTALLED) {
  640. $datetype = IntlDateFormatter::SHORT;
  641. $timetype = IntlDateFormatter::NONE;
  642. }
  643. break;
  644. case DATE_FORMAT_NUMBER_NO_YEAR:
  645. $date_format = get_lang('dateFormatShortNumberNoYear', '', $language);
  646. if (INTL_INSTALLED) {
  647. $datetype = IntlDateFormatter::SHORT;
  648. $timetype = IntlDateFormatter::NONE;
  649. }
  650. break;
  651. case DATE_FORMAT_NUMBER:
  652. $date_format = get_lang('dateFormatShortNumber', '', $language);
  653. if (INTL_INSTALLED) {
  654. $datetype = IntlDateFormatter::SHORT;
  655. $timetype = IntlDateFormatter::NONE;
  656. }
  657. break;
  658. case TIME_NO_SEC_FORMAT:
  659. $date_format = get_lang('timeNoSecFormat', '', $language);
  660. if (INTL_INSTALLED) {
  661. $datetype = IntlDateFormatter::NONE;
  662. $timetype = IntlDateFormatter::SHORT;
  663. }
  664. break;
  665. case DATE_FORMAT_SHORT:
  666. $date_format = get_lang('dateFormatShort', '', $language);
  667. if (INTL_INSTALLED) {
  668. $datetype = IntlDateFormatter::LONG;
  669. $timetype = IntlDateFormatter::NONE;
  670. }
  671. break;
  672. case DATE_FORMAT_LONG:
  673. $date_format = get_lang('dateFormatLong', '', $language);
  674. if (INTL_INSTALLED) {
  675. $datetype = IntlDateFormatter::FULL;
  676. $timetype = IntlDateFormatter::NONE;
  677. }
  678. break;
  679. case DATE_TIME_FORMAT_LONG:
  680. $date_format = get_lang('dateTimeFormatLong', '', $language);
  681. if (INTL_INSTALLED) {
  682. $datetype = IntlDateFormatter::FULL;
  683. $timetype = IntlDateFormatter::SHORT;
  684. }
  685. break;
  686. case DATE_FORMAT_LONG_NO_DAY:
  687. $date_format = get_lang('dateFormatLongNoDay', '', $language);
  688. if (INTL_INSTALLED) {
  689. $datetype = IntlDateFormatter::FULL;
  690. $timetype = IntlDateFormatter::SHORT;
  691. }
  692. break;
  693. case DATE_TIME_FORMAT_SHORT:
  694. $date_format = get_lang('dateTimeFormatShort', '', $language);
  695. if (INTL_INSTALLED) {
  696. $datetype = IntlDateFormatter::FULL;
  697. $timetype = IntlDateFormatter::SHORT;
  698. }
  699. break;
  700. case DATE_TIME_FORMAT_SHORT_TIME_FIRST:
  701. $date_format = get_lang('dateTimeFormatShortTimeFirst', '', $language);
  702. if (INTL_INSTALLED) {
  703. $datetype = IntlDateFormatter::FULL;
  704. $timetype = IntlDateFormatter::SHORT;
  705. }
  706. break;
  707. case DATE_TIME_FORMAT_LONG_24H:
  708. $date_format = get_lang('dateTimeFormatLong24H', '', $language);
  709. if (INTL_INSTALLED) {
  710. $datetype = IntlDateFormatter::FULL;
  711. $timetype = IntlDateFormatter::SHORT;
  712. }
  713. break;
  714. default:
  715. $date_format = get_lang('dateTimeFormatLong', '', $language);
  716. if (INTL_INSTALLED) {
  717. $datetype = IntlDateFormatter::FULL;
  718. $timetype = IntlDateFormatter::SHORT;
  719. }
  720. }
  721. } else {
  722. $date_format = $format;
  723. }
  724. if (0) {
  725. //if using PHP 5.3 format dates like: $dateFormatShortNumber, can't be used
  726. //
  727. // Use ICU
  728. if (is_null($language)) {
  729. $language = api_get_language_isocode();
  730. }
  731. $date_formatter = new IntlDateFormatter($language, $datetype, $timetype, date_default_timezone_get());
  732. //$date_formatter->setPattern($date_format);
  733. $formatted_date = api_to_system_encoding($date_formatter->format($time), 'UTF-8');
  734. } else {
  735. // We replace %a %A %b %B masks of date format with translated strings
  736. $translated = &_api_get_day_month_names($language);
  737. $date_format = str_replace(array('%A', '%a', '%B', '%b'),
  738. array($translated['days_long'][(int)strftime('%w', $time )],
  739. $translated['days_short'][(int)strftime('%w', $time)],
  740. $translated['months_long'][(int)strftime('%m', $time) - 1],
  741. $translated['months_short'][(int)strftime('%m', $time) - 1]),
  742. $date_format);
  743. $formatted_date = api_to_system_encoding(strftime($date_format, $time), 'UTF-8');
  744. }
  745. date_default_timezone_set($system_timezone);
  746. return $formatted_date;
  747. }
  748. /**
  749. * Returns the difference between the current date (date(now)) with the parameter $date in a string format like "2 days, 1 hour"
  750. * Example: $date = '2008-03-07 15:44:08';
  751. * date_to_str($date) it will return 3 days, 20 hours
  752. * The given date should be in the timezone chosen by the user or administrator. Use api_get_local_time() to get it...
  753. *
  754. * @param string The string has to be the result of a date function in this format -> date('Y-m-d H:i:s', time());
  755. * @return string The difference between the current date and the parameter in a literal way "3 days, 2 hour" *
  756. * @author Julio Montoya
  757. */
  758. function date_to_str_ago($date) {
  759. static $initialized = false;
  760. static $today, $yesterday;
  761. static $min_decade, $min_year, $min_month, $min_week, $min_day, $min_hour, $min_minute;
  762. static $min_decades, $min_years, $min_months, $min_weeks, $min_days, $min_hours, $min_minutes;
  763. static $sec_time_time, $sec_time_sing, $sec_time_plu;
  764. $system_timezone = date_default_timezone_get();
  765. date_default_timezone_set(_api_get_timezone());
  766. if (!$initialized) {
  767. $today = get_lang('Today');
  768. $yesterday = get_lang('Yesterday');
  769. $min_decade = get_lang('MinDecade');
  770. $min_year = get_lang('MinYear');
  771. $min_month = get_lang('MinMonth');
  772. $min_week = get_lang('MinWeek');
  773. $min_day = get_lang('MinDay');
  774. $min_hour = get_lang('MinHour');
  775. $min_minute = get_lang('MinMinute');
  776. $min_decades = get_lang('MinDecades');
  777. $min_years = get_lang('MinYears');
  778. $min_months = get_lang('MinMonths');
  779. $min_weeks = get_lang('MinWeeks');
  780. $min_days = get_lang('MinDays');
  781. $min_hours = get_lang('MinHours');
  782. $min_minutes = get_lang('MinMinutes');
  783. // original 1
  784. //$sec_time=array('century'=>3.1556926*pow(10,9),'decade'=>315569260,'year'=>31556926,'month'=>2629743.83,'week'=>604800,'day'=>86400,'hour'=>3600,'minute'=>60,'second'=>1);
  785. //$sec_time=array(get_lang('MinDecade')=>315569260,get_lang('MinYear')=>31556926,get_lang('MinMonth')=>2629743.83,get_lang('MinWeek')=>604800,get_lang('MinDay')=>86400,get_lang('MinHour')=>3600,get_lang('MinMinute')=>60);
  786. $sec_time_time = array(315569260, 31556926, 2629743.83, 604800, 86400, 3600, 60);
  787. $sec_time_sing = array($min_decade, $min_year, $min_month, $min_week, $min_day, $min_hour, $min_minute);
  788. $sec_time_plu = array($min_decades, $min_years, $min_months, $min_weeks, $min_days, $min_hours, $min_minutes);
  789. $initialized = true;
  790. }
  791. $dst_date = is_string($date) ? strtotime($date) : $date;
  792. // For avoiding calling date() several times
  793. $date_array = date('s/i/G/j/n/Y', $dst_date);
  794. $date_split = explode('/', $date_array);
  795. $dst_s = $date_split[0];
  796. $dst_m = $date_split[1];
  797. $dst_h = $date_split[2];
  798. $dst_day = $date_split[3];
  799. $dst_mth = $date_split[4];
  800. $dst_yr = $date_split[5];
  801. $dst_date = mktime($dst_h, $dst_m, $dst_s, $dst_mth, $dst_day, $dst_yr);
  802. $time = $offset = time() - $dst_date; // Seconds between current days and today.
  803. // Here start the functions sec_to_str()
  804. $act_day = date('d');
  805. $act_mth = date('n');
  806. $act_yr = date('Y');
  807. if ($dst_day == $act_day && $dst_mth == $act_mth && $dst_yr == $act_yr) {
  808. return $today;
  809. }
  810. if ($dst_day == $act_day - 1 && $dst_mth == $act_mth && $dst_yr == $act_yr) {
  811. return $yesterday;
  812. }
  813. $str_result = array();
  814. $time_result = array();
  815. $key_result = array();
  816. $str = '';
  817. $i = 0;
  818. for ($i = 0; $i < count($sec_time_time); $i++) {
  819. $seconds = $sec_time_time[$i];
  820. if ($seconds > $time) {
  821. continue;
  822. }
  823. $current_value = intval($time/$seconds);
  824. if ($current_value != 1) {
  825. $date_str = $sec_time_plu[$i];
  826. } else {
  827. $date_str = $sec_time_sing[$i];
  828. }
  829. $key_result[] = $sec_time_sing[$i];
  830. $str_result[] = $current_value.' '.$date_str;
  831. $time_result[] = $current_value;
  832. $str .= $current_value.$date_str;
  833. $time %= $seconds;
  834. }
  835. if ($key_result[0] == $min_day && $key_result[1]== $min_minute) {
  836. $key_result[1] = ' 0 '.$min_hours;
  837. $str_result[0] = $time_result[0].' '.$key_result[0];
  838. $str_result[1] = $key_result[1];
  839. }
  840. if ($key_result[0] == $min_year && ($key_result[1] == $min_day || $key_result[1] == $min_week)) {
  841. $key_result[1] = ' 0 '.$min_months;
  842. $str_result[0] = $time_result[0].' '.$key_result[0];
  843. $str_result[1] = $key_result[1];
  844. }
  845. if (!empty($str_result[1])) {
  846. $str = $str_result[0].', '.$str_result[1];
  847. } else {
  848. $str = $str_result[0];
  849. }
  850. date_default_timezone_set($system_timezone);
  851. return $str;
  852. }
  853. /**
  854. * Converts a date to the right timezone and localizes it in the format given as an argument
  855. * @param mixed The time to be converted
  856. * @param mixed Format to be used (TIME_NO_SEC_FORMAT, DATE_FORMAT_SHORT, DATE_FORMAT_LONG, DATE_TIME_FORMAT_LONG)
  857. * @param string Timezone to be converted from. If null, UTC will be assumed.
  858. * @return string Converted and localized date
  859. *
  860. * @author Guillaume Viguier <guillaume.viguier@beeznest.com>
  861. */
  862. function api_convert_and_format_date($time = null, $format = null, $from_timezone = null) {
  863. // First, convert the datetime to the right timezone
  864. $time = api_get_local_time($time, null, $from_timezone);
  865. // Second, localize the date
  866. return api_format_date($time, $format);
  867. }
  868. /**
  869. * Returns an array of translated week days in short names.
  870. * @param string $language (optional) Language indentificator. If it is omited, the current interface language is assumed.
  871. * @return string Returns an array of week days (short names).
  872. * Example: api_get_week_days_short('english') means array('Sun', 'Mon', ... 'Sat').
  873. * Note: For all languges returned days are in the English order.
  874. */
  875. function api_get_week_days_short($language = null) {
  876. $days = &_api_get_day_month_names($language);
  877. return $days['days_short'];
  878. }
  879. /**
  880. * Returns an array of translated week days.
  881. * @param string $language (optional) Language indentificator. If it is omited, the current interface language is assumed.
  882. * @return string Returns an array of week days.
  883. * Example: api_get_week_days_long('english') means array('Sunday, 'Monday', ... 'Saturday').
  884. * Note: For all languges returned days are in the English order.
  885. */
  886. function api_get_week_days_long($language = null) {
  887. $days = &_api_get_day_month_names($language);
  888. return $days['days_long'];
  889. }
  890. /**
  891. * Returns an array of translated months in short names.
  892. * @param string $language (optional) Language indentificator. If it is omited, the current interface language is assumed.
  893. * @return string Returns an array of months (short names).
  894. * Example: api_get_months_short('english') means array('Jan', 'Feb', ... 'Dec').
  895. */
  896. function api_get_months_short($language = null) {
  897. $months = &_api_get_day_month_names($language);
  898. return $months['months_short'];
  899. }
  900. /**
  901. * Returns an array of translated months.
  902. * @param string $language (optional) Language indentificator. If it is omited, the current interface language is assumed.
  903. * @return string Returns an array of months.
  904. * Example: api_get_months_long('english') means array('January, 'February' ... 'December').
  905. */
  906. function api_get_months_long($language = null) {
  907. $months = &_api_get_day_month_names($language);
  908. return $months['months_long'];
  909. }
  910. /**
  911. * Name order conventions
  912. */
  913. /**
  914. * Builds a person (full) name depending on the convention for a given language.
  915. * @param string $first_name The first name of the preson.
  916. * @param string $last_name The last name of the person.
  917. * @param string $title The title of the person.
  918. * @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.
  919. * @param string $language (optional) The language indentificator. If it is omited, the current interface language is assumed. This parameter has meaning with the format PERSON_NAME_COMMON_CONVENTION only.
  920. * @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.
  921. * @return bool The result is sort of full name of the person.
  922. * Sample results:
  923. * Peter Ustinoff or Dr. Peter Ustinoff - the Western order
  924. * Ustinoff Peter or Dr. Ustinoff Peter - the Eastern order
  925. * Ustinoff, Peter or - Dr. Ustinoff, Peter - the library order
  926. * Note: See the file chamilo/main/inc/lib/internationalization_database/name_order_conventions.php where you can revise the convention for your language.
  927. * @author Carlos Vargas <carlos.vargas@dokeos.com> - initial implementation.
  928. * @author Ivan Tcholakov
  929. */
  930. function api_get_person_name(
  931. $first_name,
  932. $last_name,
  933. $title = null,
  934. $format = null,
  935. $language = null,
  936. $encoding = null,
  937. $username = null
  938. ) {
  939. static $valid = array();
  940. if (empty($format)) {
  941. $format = PERSON_NAME_COMMON_CONVENTION;
  942. }
  943. //We check if the language is supported, otherwise we check the interface language of the parent language of sublanguage
  944. $language_is_supported = api_is_language_supported($language);
  945. if (!$language_is_supported || empty($language)) {
  946. $language = api_get_interface_language(false, true);
  947. }
  948. if (empty($encoding)) {
  949. $encoding = _api_mb_internal_encoding();
  950. }
  951. if (!isset($valid[$format][$language])) {
  952. if (is_int($format)) {
  953. switch ($format) {
  954. case PERSON_NAME_COMMON_CONVENTION:
  955. $valid[$format][$language] = _api_get_person_name_convention($language, 'format');
  956. $usernameOrderFromDatabase = api_get_setting('user_name_order');
  957. if (isset($usernameOrderFromDatabase) && !empty($usernameOrderFromDatabase)) {
  958. $valid[$format][$language] = $usernameOrderFromDatabase;
  959. }
  960. break;
  961. case PERSON_NAME_WESTERN_ORDER:
  962. $valid[$format][$language] = '%t %f %l';
  963. break;
  964. case PERSON_NAME_EASTERN_ORDER:
  965. $valid[$format][$language] = '%t %l %f';
  966. break;
  967. case PERSON_NAME_LIBRARY_ORDER:
  968. $valid[$format][$language] = '%t %l, %f';
  969. break;
  970. default:
  971. $valid[$format][$language] = '%t %f %l';
  972. break;
  973. }
  974. } else {
  975. $valid[$format][$language] = _api_validate_person_name_format($format);
  976. }
  977. }
  978. $format = $valid[$format][$language];
  979. $keywords = array('%firstname', '%f', '%F', '%lastname', '%l', '%L', '%title', '%t', '%T', '%username', '%u', '%U');
  980. $values = array(
  981. $first_name,
  982. $first_name,
  983. api_strtoupper($first_name, $encoding),
  984. $last_name,
  985. $last_name,
  986. api_strtoupper($last_name, $encoding),
  987. $title,
  988. $title,
  989. api_strtoupper($title, $encoding),
  990. $username,
  991. $username,
  992. api_strtoupper($username, $encoding),
  993. );
  994. $person_name = str_replace($keywords, $values, $format);
  995. return _api_clean_person_name($person_name);
  996. }
  997. /**
  998. * Checks whether a given format represents person name in Western order (for which first name is first).
  999. * @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.
  1000. * @param string $language (optional) The language identificator. If it is omited, the current interface language is assumed. This parameter has meaning with the format PERSON_NAME_COMMON_CONVENTION only.
  1001. * @return bool The result TRUE means that the order is first_name last_name, FALSE means last_name first_name.
  1002. * Note: You may use this function for determing the order of the fields or columns "First name" and "Last name" in forms, tables and reports.
  1003. * @author Ivan Tcholakov
  1004. */
  1005. function api_is_western_name_order($format = null, $language = null) {
  1006. static $order = array();
  1007. if (empty($format)) {
  1008. $format = PERSON_NAME_COMMON_CONVENTION;
  1009. }
  1010. $language_is_supported = api_is_language_supported($language);
  1011. if (!$language_is_supported || empty($language)) {
  1012. $language = api_get_interface_language(false, true);
  1013. }
  1014. if (!isset($order[$format][$language])) {
  1015. $test_name = api_get_person_name('%f', '%l', '%t', $format, $language);
  1016. $order[$format][$language] = stripos($test_name, '%f') <= stripos($test_name, '%l');
  1017. }
  1018. return $order[$format][$language];
  1019. }
  1020. /**
  1021. * Returns a directive for sorting person names depending on a given language and based on the options in the internationalization "database".
  1022. * @param string $language (optional) The input language. If it is omited, the current interface language is assumed.
  1023. * @return bool Returns boolean value. TRUE means ORDER BY first_name, last_name; FALSE means ORDER BY last_name, first_name.
  1024. * Note: You may use this function:
  1025. * 2. for constructing the ORDER clause of SQL queries, related to first_name and last_name;
  1026. * 3. for adjusting php-implemented sorting in tables and reports.
  1027. * @author Ivan Tcholakov
  1028. */
  1029. function api_sort_by_first_name($language = null) {
  1030. $userNameSortBy = api_get_setting('user_name_sort_by');
  1031. if (!empty($userNameSortBy) && in_array($userNameSortBy, array('firstname', 'lastname'))) {
  1032. return $userNameSortBy == 'firstname' ? true : false;
  1033. }
  1034. static $sort_by_first_name = array();
  1035. $language_is_supported = api_is_language_supported($language);
  1036. if (!$language_is_supported || empty($language)) {
  1037. $language = api_get_interface_language(false, true);
  1038. }
  1039. if (!isset($sort_by_first_name[$language])) {
  1040. $sort_by_first_name[$language] = _api_get_person_name_convention($language, 'sort_by');
  1041. }
  1042. return $sort_by_first_name[$language];
  1043. }
  1044. /**
  1045. * A safe way to calculate binary lenght of a string (as number of bytes)
  1046. */
  1047. /**
  1048. * Calculates binary lenght of a string, as number of bytes, regardless the php-setting mbstring.func_overload.
  1049. * This function should work for all multi-byte related changes of PHP5 configuration.
  1050. * @param string $string The input string.
  1051. * @return int Returns the length of the input string (or binary data) as number of bytes.
  1052. */
  1053. function api_byte_count(& $string) {
  1054. static $use_mb_strlen;
  1055. if (!isset($use_mb_strlen)) {
  1056. $use_mb_strlen = MBSTRING_INSTALLED && ((int) ini_get('mbstring.func_overload') & 2);
  1057. }
  1058. if ($use_mb_strlen) {
  1059. return mb_strlen($string, '8bit');
  1060. }
  1061. return strlen($string);
  1062. }
  1063. /**
  1064. * Multibyte string conversion functions
  1065. */
  1066. /**
  1067. * Converts character encoding of a given string.
  1068. * @param string $string The string being converted.
  1069. * @param string $to_encoding The encoding that $string is being converted to.
  1070. * @param string $from_encoding (optional) The encoding that $string is being converted from. If it is omited, the platform character set is assumed.
  1071. * @return string Returns the converted string.
  1072. * This function is aimed at replacing the function mb_convert_encoding() for human-language strings.
  1073. * @link http://php.net/manual/en/function.mb-convert-encoding
  1074. */
  1075. function api_convert_encoding($string, $to_encoding, $from_encoding = null) {
  1076. if (empty($from_encoding)) {
  1077. $from_encoding = _api_mb_internal_encoding();
  1078. }
  1079. if (api_equal_encodings($to_encoding, $from_encoding)) {
  1080. return $string; // When conversion is not needed, the string is returned directly, without validation.
  1081. }
  1082. if (_api_mb_supports($to_encoding) && _api_mb_supports($from_encoding)) {
  1083. return @mb_convert_encoding($string, $to_encoding, $from_encoding);
  1084. }
  1085. if (_api_iconv_supports($to_encoding) && _api_iconv_supports($from_encoding)) {
  1086. return @iconv($from_encoding, $to_encoding, $string);
  1087. }
  1088. if (api_is_utf8($to_encoding) && api_is_latin1($from_encoding, true)) {
  1089. return utf8_encode($string);
  1090. }
  1091. if (api_is_latin1($to_encoding, true) && api_is_utf8($from_encoding)) {
  1092. return utf8_decode($string);
  1093. }
  1094. if (_api_convert_encoding_supports($to_encoding) && _api_convert_encoding_supports($from_encoding)) {
  1095. return _api_convert_encoding($string, $to_encoding, $from_encoding);
  1096. }
  1097. return $string; // Here the function gives up.
  1098. }
  1099. /**
  1100. * Converts a given string into UTF-8 encoded string.
  1101. * @param string $string The string being converted.
  1102. * @param string $from_encoding (optional) The encoding that $string is being converted from. If it is omited, the platform character set is assumed.
  1103. * @return string Returns the converted string.
  1104. * This function is aimed at replacing the function utf8_encode() for human-language strings.
  1105. * @link http://php.net/manual/en/function.utf8-encode
  1106. */
  1107. function api_utf8_encode($string, $from_encoding = null) {
  1108. if (empty($from_encoding)) {
  1109. $from_encoding = _api_mb_internal_encoding();
  1110. }
  1111. if (api_is_utf8($from_encoding)) {
  1112. return $string; // When conversion is not needed, the string is returned directly, without validation.
  1113. }
  1114. if (_api_mb_supports($from_encoding)) {
  1115. return @mb_convert_encoding($string, 'UTF-8', $from_encoding);
  1116. }
  1117. if (_api_iconv_supports($from_encoding)) {
  1118. return @iconv($from_encoding, 'UTF-8', $string);
  1119. }
  1120. if (api_is_latin1($from_encoding, true)) {
  1121. return utf8_encode($string);
  1122. }
  1123. if (_api_convert_encoding_supports($from_encoding)) {
  1124. return _api_convert_encoding($string, 'UTF-8', $from_encoding);
  1125. }
  1126. return $string; // Here the function gives up.
  1127. }
  1128. /**
  1129. * Converts a given string from UTF-8 encoding to a specified encoding.
  1130. * @param string $string The string being converted.
  1131. * @param string $to_encoding (optional) The encoding that $string is being converted to. If it is omited, the platform character set is assumed.
  1132. * @return string Returns the converted string.
  1133. * This function is aimed at replacing the function utf8_decode() for human-language strings.
  1134. * @link http://php.net/manual/en/function.utf8-decode
  1135. */
  1136. function api_utf8_decode($string, $to_encoding = null) {
  1137. if (empty($to_encoding)) {
  1138. $to_encoding = _api_mb_internal_encoding();
  1139. }
  1140. if (api_is_utf8($to_encoding)) {
  1141. return $string; // When conversion is not needed, the string is returned directly, without validation.
  1142. }
  1143. if (_api_mb_supports($to_encoding)) {
  1144. return @mb_convert_encoding($string, $to_encoding, 'UTF-8');
  1145. }
  1146. if (_api_iconv_supports($to_encoding)) {
  1147. return @iconv('UTF-8', $to_encoding, $string);
  1148. }
  1149. if (api_is_latin1($to_encoding, true)) {
  1150. return utf8_decode($string);
  1151. }
  1152. if (_api_convert_encoding_supports($to_encoding)) {
  1153. return _api_convert_encoding($string, $to_encoding, 'UTF-8');
  1154. }
  1155. return $string; // Here the function gives up.
  1156. }
  1157. /**
  1158. * Converts a given string into the system ecoding (or platform character set).
  1159. * When $from encoding is omited on UTF-8 platforms then language dependent encoding
  1160. * is guessed/assumed. On non-UTF-8 platforms omited $from encoding is assumed as UTF-8.
  1161. * When the parameter $check_utf8_validity is true the function checks string's
  1162. * UTF-8 validity and decides whether to try to convert it or not.
  1163. * This function is useful for problem detection or making workarounds.
  1164. * @param string $string The string being converted.
  1165. * @param string $from_encoding (optional) The encoding that $string is being converted from. It is guessed when it is omited.
  1166. * @param bool $check_utf8_validity (optional) A flag for UTF-8 validity check as condition for making conversion.
  1167. * @return string Returns the converted string.
  1168. */
  1169. function api_to_system_encoding($string, $from_encoding = null, $check_utf8_validity = false) {
  1170. $system_encoding = api_get_system_encoding();
  1171. if (empty($from_encoding)) {
  1172. if (api_is_utf8($system_encoding)) {
  1173. $from_encoding = api_get_non_utf8_encoding();
  1174. } else {
  1175. $from_encoding = 'UTF-8';
  1176. }
  1177. }
  1178. if (api_equal_encodings($system_encoding, $from_encoding)) {
  1179. return $string;
  1180. }
  1181. if ($check_utf8_validity) {
  1182. if (api_is_utf8($system_encoding)) {
  1183. if (api_is_valid_utf8($string)) {
  1184. return $string;
  1185. }
  1186. } elseif (api_is_utf8($from_encoding)) {
  1187. if (!api_is_valid_utf8($string)) {
  1188. return $string;
  1189. }
  1190. }
  1191. }
  1192. return api_convert_encoding($string, $system_encoding, $from_encoding);
  1193. }
  1194. /**
  1195. * Converts all applicable characters to HTML entities.
  1196. * @param string $string The input string.
  1197. * @param int $quote_style (optional) The quote style - ENT_COMPAT (default), ENT_QUOTES, ENT_NOQUOTES.
  1198. * @param string $encoding (optional) The encoding (of the input string) used in conversion. If it is omited, the platform character set is assumed.
  1199. * @return string Returns the converted string.
  1200. * This function is aimed at replacing the function htmlentities() for human-language strings.
  1201. * @link http://php.net/manual/en/function.htmlentities
  1202. */
  1203. function api_htmlentities($string, $quote_style = ENT_COMPAT, $encoding = null) {
  1204. if (empty($encoding)) {
  1205. $encoding = _api_mb_internal_encoding();
  1206. }
  1207. if (!api_is_utf8($encoding) && _api_html_entity_supports($encoding)) {
  1208. return htmlentities($string, $quote_style, $encoding);
  1209. }
  1210. switch($quote_style) {
  1211. case ENT_COMPAT:
  1212. $string = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string);
  1213. break;
  1214. case ENT_QUOTES:
  1215. $string = str_replace(array('&', '\'', '"', '<', '>'), array('&amp;', '&#039;', '&quot;', '&lt;', '&gt;'), $string);
  1216. break;
  1217. }
  1218. if (_api_mb_supports($encoding)) {
  1219. if (!api_is_utf8($encoding)) {
  1220. $string = api_utf8_encode($string, $encoding);
  1221. }
  1222. $string = @mb_convert_encoding(api_utf8_encode($string, $encoding), 'HTML-ENTITIES', 'UTF-8');
  1223. if (!api_is_utf8($encoding)) { // Just in case.
  1224. $string = api_utf8_decode($string, $encoding);
  1225. }
  1226. } elseif (_api_convert_encoding_supports($encoding)) {
  1227. if (!api_is_utf8($encoding)) {
  1228. $string = _api_convert_encoding($string, 'UTF-8', $encoding);
  1229. }
  1230. $string = implode(array_map('_api_html_entity_from_unicode', _api_utf8_to_unicode($string)));
  1231. if (!api_is_utf8($encoding)) { // Just in case.
  1232. $string = _api_convert_encoding($string, $encoding, 'UTF-8');
  1233. }
  1234. }
  1235. return $string;
  1236. }
  1237. /**
  1238. * Converts HTML entities into normal characters.
  1239. * @param string $string The input string.
  1240. * @param int $quote_style (optional) The quote style - ENT_COMPAT (default), ENT_QUOTES, ENT_NOQUOTES.
  1241. * @param string $encoding (optional) The encoding (of the result) used in conversion. If it is omited, the platform character set is assumed.
  1242. * @return string Returns the converted string.
  1243. * This function is aimed at replacing the function html_entity_decode() for human-language strings.
  1244. * @link http://php.net/html_entity_decode
  1245. */
  1246. function api_html_entity_decode($string, $quote_style = ENT_COMPAT, $encoding = null) {
  1247. if (empty($encoding)) {
  1248. $encoding = _api_mb_internal_encoding();
  1249. }
  1250. if (_api_html_entity_supports($encoding)) {
  1251. return html_entity_decode($string, $quote_style, $encoding);
  1252. }
  1253. if (api_is_encoding_supported($encoding)) {
  1254. if (!api_is_utf8($encoding)) {
  1255. $string = api_utf8_encode($string, $encoding);
  1256. }
  1257. $string = html_entity_decode($string, $quote_style, 'UTF-8');
  1258. if (!api_is_utf8($encoding)) {
  1259. return api_utf8_decode($string, $encoding);
  1260. }
  1261. return $string;
  1262. }
  1263. return $string; // Here the function gives up.
  1264. }
  1265. /**
  1266. * This function encodes (conditionally) a given string to UTF-8 if XmlHttp-request has been detected.
  1267. * @param string $string The string being converted.
  1268. * @param string $from_encoding (optional) The encoding that $string is being converted from. If it is omited, the platform character set is assumed.
  1269. * @return string Returns the converted string.
  1270. */
  1271. function api_xml_http_response_encode($string, $from_encoding = null) {
  1272. if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
  1273. if (empty($from_encoding)) {
  1274. $from_encoding = _api_mb_internal_encoding();
  1275. }
  1276. if (!api_is_utf8($from_encoding)) {
  1277. return api_utf8_encode($string, $from_encoding);
  1278. }
  1279. }
  1280. return $string;
  1281. }
  1282. /**
  1283. * This function converts a given string to the encoding that filesystem uses for representing file/folder names.
  1284. * @param string $string The string being converted.
  1285. * @param string $from_encoding (optional) The encoding that $string is being converted from. If it is omited, the platform character set is assumed.
  1286. * @return string Returns the converted string.
  1287. */
  1288. function api_file_system_encode($string, $from_encoding = null) {
  1289. if (empty($from_encoding)) {
  1290. $from_encoding = _api_mb_internal_encoding();
  1291. }
  1292. return api_convert_encoding($string, api_get_file_system_encoding(), $from_encoding);
  1293. }
  1294. /**
  1295. * This function converts a given string from the encoding that filesystem uses for representing file/folder names.
  1296. * @param string $string The string being converted.
  1297. * @param string $from_encoding (optional) The encoding that $string is being converted from. If it is omited, the platform character set is assumed.
  1298. * @return string Returns the converted string.
  1299. */
  1300. function api_file_system_decode($string, $to_encoding = null) {
  1301. if (empty($to_encoding)) {
  1302. $to_encoding = _api_mb_internal_encoding();
  1303. }
  1304. return api_convert_encoding($string, $to_encoding, api_get_file_system_encoding());
  1305. }
  1306. /**
  1307. * Transliterates a string with arbitrary encoding into a plain ASCII string.
  1308. *
  1309. * Example:
  1310. * echo api_transliterate(api_html_entity_decode(
  1311. * '&#1060;&#1105;&#1076;&#1086;&#1088; '.
  1312. * '&#1052;&#1080;&#1093;&#1072;&#1081;&#1083;&#1086;&#1074;&#1080;&#1095; '.
  1313. * '&#1044;&#1086;&#1089;&#1090;&#1086;&#1077;&#1074;&#1082;&#1080;&#1081;',
  1314. * ENT_QUOTES, 'UTF-8'), 'X', 'UTF-8');
  1315. * The output should be: Fyodor Mihaylovich Dostoevkiy
  1316. *
  1317. * @param string $string The input string.
  1318. * @param string $unknown (optional) Replacement character for unknown characters and illegal UTF-8 sequences.
  1319. * @param string $from_encoding (optional) The encoding of the input string. If it is omited, the platform character set is assumed.
  1320. * @return string Plain ASCII output.
  1321. *
  1322. * Based on Drupal's module "Transliteration", version 6.x-2.1, 09-JUN-2009:
  1323. * @author Stefan M. Kudwien (smk-ka)
  1324. * @author Daniel F. Kudwien (sun)
  1325. * @link http://drupal.org/project/transliteration
  1326. *
  1327. * See also MediaWiki's UtfNormal.php and CPAN's Text::Unidecode library
  1328. * @link http://www.mediawiki.org
  1329. * @link http://search.cpan.org/~sburke/Text-Unidecode-0.04/lib/Text/Unidecode.pm).
  1330. *
  1331. * Adaptation for Chamilo 1.8.7, 2010
  1332. * Initial implementation for Dokeos 1.8.6.1, 12-JUN-2009
  1333. * @author Ivan Tcholakov
  1334. */
  1335. function api_transliterate($string, $unknown = '?', $from_encoding = null) {
  1336. static $map = array();
  1337. $string = api_utf8_encode($string, $from_encoding);
  1338. // Screen out some characters that eg won't be allowed in XML.
  1339. $string = preg_replace('/[\x00-\x08\x0b\x0c\x0e-\x1f]/', $unknown, $string);
  1340. // ASCII is always valid NFC!
  1341. // If we're only ever given plain ASCII, we can avoid the overhead
  1342. // of initializing the decomposition tables by skipping out early.
  1343. if (api_is_valid_ascii($string)) {
  1344. return $string;
  1345. }
  1346. static $tail_bytes;
  1347. if (!isset($tail_bytes)) {
  1348. // Each UTF-8 head byte is followed by a certain
  1349. // number of tail bytes.
  1350. $tail_bytes = array();
  1351. for ($n = 0; $n < 256; $n++) {
  1352. if ($n < 0xc0) {
  1353. $remaining = 0;
  1354. }
  1355. elseif ($n < 0xe0) {
  1356. $remaining = 1;
  1357. }
  1358. elseif ($n < 0xf0) {
  1359. $remaining = 2;
  1360. }
  1361. elseif ($n < 0xf8) {
  1362. $remaining = 3;
  1363. }
  1364. elseif ($n < 0xfc) {
  1365. $remaining = 4;
  1366. }
  1367. elseif ($n < 0xfe) {
  1368. $remaining = 5;
  1369. } else {
  1370. $remaining = 0;
  1371. }
  1372. $tail_bytes[chr($n)] = $remaining;
  1373. }
  1374. }
  1375. // Chop the text into pure-ASCII and non-ASCII areas;
  1376. // large ASCII parts can be handled much more quickly.
  1377. // Don't chop up Unicode areas for punctuation, though,
  1378. // that wastes energy.
  1379. preg_match_all('/[\x00-\x7f]+|[\x80-\xff][\x00-\x40\x5b-\x5f\x7b-\xff]*/', $string, $matches);
  1380. $result = '';
  1381. foreach ($matches[0] as $str) {
  1382. if ($str{0} < "\x80") {
  1383. // ASCII chunk: guaranteed to be valid UTF-8
  1384. // and in normal form C, so skip over it.
  1385. $result .= $str;
  1386. continue;
  1387. }
  1388. // We'll have to examine the chunk byte by byte to ensure
  1389. // that it consists of valid UTF-8 sequences, and to see
  1390. // if any of them might not be normalized.
  1391. //
  1392. // Since PHP is not the fastest language on earth, some of
  1393. // this code is a little ugly with inner loop optimizations.
  1394. $head = '';
  1395. $chunk = api_byte_count($str);
  1396. // Counting down is faster. I'm *so* sorry.
  1397. $len = $chunk + 1;
  1398. for ($i = -1; --$len; ) {
  1399. $c = $str{++$i};
  1400. if ($remaining = $tail_bytes[$c]) {
  1401. // UTF-8 head byte!
  1402. $sequence = $head = $c;
  1403. do {
  1404. // Look for the defined number of tail bytes...
  1405. if (--$len && ($c = $str{++$i}) >= "\x80" && $c < "\xc0") {
  1406. // Legal tail bytes are nice.
  1407. $sequence .= $c;
  1408. } else {
  1409. if ($len == 0) {
  1410. // Premature end of string!
  1411. // Drop a replacement character into output to
  1412. // represent the invalid UTF-8 sequence.
  1413. $result .= $unknown;
  1414. break 2;
  1415. } else {
  1416. // Illegal tail byte; abandon the sequence.
  1417. $result .= $unknown;
  1418. // Back up and reprocess this byte; it may itself
  1419. // be a legal ASCII or UTF-8 sequence head.
  1420. --$i;
  1421. ++$len;
  1422. continue 2;
  1423. }
  1424. }
  1425. } while (--$remaining);
  1426. $n = ord($head);
  1427. if ($n <= 0xdf) {
  1428. $ord = ($n - 192) * 64 + (ord($sequence{1}) - 128);
  1429. }
  1430. else if ($n <= 0xef) {
  1431. $ord = ($n - 224) * 4096 + (ord($sequence{1}) - 128) * 64 + (ord($sequence{2}) - 128);
  1432. }
  1433. else if ($n <= 0xf7) {
  1434. $ord = ($n - 240) * 262144 + (ord($sequence{1}) - 128) * 4096 + (ord($sequence{2}) - 128) * 64 + (ord($sequence{3}) - 128);
  1435. }
  1436. else if ($n <= 0xfb) {
  1437. $ord = ($n - 248) * 16777216 + (ord($sequence{1}) - 128) * 262144 + (ord($sequence{2}) - 128) * 4096 + (ord($sequence{3}) - 128) * 64 + (ord($sequence{4}) - 128);
  1438. }
  1439. else if ($n <= 0xfd) {
  1440. $ord = ($n - 252) * 1073741824 + (ord($sequence{1}) - 128) * 16777216 + (ord($sequence{2}) - 128) * 262144 + (ord($sequence{3}) - 128) * 4096 + (ord($sequence{4}) - 128) * 64 + (ord($sequence{5}) - 128);
  1441. }
  1442. // Lookup and replace a character from the transliteration database.
  1443. $bank = $ord >> 8;
  1444. // Check if we need to load a new bank
  1445. if (!isset($map[$bank])) {
  1446. $file = dirname(__FILE__).'/internationalization_database/transliteration/' . sprintf('x%02x', $bank) . '.php';
  1447. if (file_exists($file)) {
  1448. $map[$bank] = include ($file);
  1449. } else {
  1450. $map[$bank] = array('en' => array());
  1451. }
  1452. }
  1453. $ord = $ord & 255;
  1454. $result .= isset($map[$bank]['en'][$ord]) ? $map[$bank]['en'][$ord] : $unknown;
  1455. $head = '';
  1456. } elseif ($c < "\x80") {
  1457. // ASCII byte.
  1458. $result .= $c;
  1459. $head = '';
  1460. } elseif ($c < "\xc0") {
  1461. // Illegal tail bytes.
  1462. if ($head == '') {
  1463. $result .= $unknown;
  1464. }
  1465. } else {
  1466. // Miscellaneous freaks.
  1467. $result .= $unknown;
  1468. $head = '';
  1469. }
  1470. }
  1471. }
  1472. return $result;
  1473. }
  1474. /**
  1475. * Common multibyte string functions
  1476. */
  1477. /**
  1478. * Takes the first character in a string and returns its Unicode codepoint.
  1479. * @param string $character The input string.
  1480. * @param string $encoding (optional) The encoding of the input string. If it is omitted, the platform character set will be used by default.
  1481. * @return int Returns: the codepoint of the first character; or 0xFFFD (unknown character) when the input string is empty.
  1482. * This is a multibyte aware version of the function ord().
  1483. * @link http://php.net/manual/en/function.ord.php
  1484. * Note the difference with the original funtion ord(): ord('') returns 0, api_ord('') returns 0xFFFD (unknown character).
  1485. */
  1486. function api_ord($character, $encoding) {
  1487. return _api_utf8_ord(api_utf8_encode($character, $encoding));
  1488. }
  1489. /**
  1490. * Takes a Unicode codepoint and returns its correspondent character, encoded in given encoding.
  1491. * @param int $codepoint The Unicode codepoint.
  1492. * @param string $encoding (optional) The encoding of the returned character. If it is omitted, the platform character set will be used by default.
  1493. * @return string Returns the corresponding character, encoded as it has been requested.
  1494. * This is a multibyte aware version of the function chr().
  1495. * @link http://php.net/manual/en/function.chr.php
  1496. */
  1497. function api_chr($codepoint, $encoding) {
  1498. return api_utf8_decode(_api_utf8_chr($codepoint), $encoding);
  1499. }
  1500. /**
  1501. * This function returns a string or an array with all occurrences of search in subject (ignoring case) replaced with the given replace value.
  1502. * @param mixed $search String or array of strings to be found.
  1503. * @param mixed $replace String or array of strings used for replacement.
  1504. * @param mixed $subject String or array of strings being searced.
  1505. * @param int $count (optional) The number of matched and replaced needles will be returned in count, which is passed by reference.
  1506. * @param string $encoding (optional) The used internally by this function character encoding. If it is omitted, the platform character set will be used by default.
  1507. * @return mixed String or array as a result.
  1508. * Notes:
  1509. * If $subject is an array, then the search and replace is performed with every entry of subject, the return value is an array.
  1510. * 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.
  1511. * If $replace has fewer values than search, then an empty string is used for the rest of replacement values.
  1512. * If $search is an array and $replace is a string, then this replacement string is used for every value of search.
  1513. * This function is aimed at replacing the function str_ireplace() for human-language strings.
  1514. * @link http://php.net/manual/en/function.str-ireplace
  1515. * @author Henri Sivonen, mailto:hsivonen@iki.fi
  1516. * @link http://hsivonen.iki.fi/php-utf8/
  1517. * Adaptation for Chamilo 1.8.7, 2010
  1518. * Initial implementation Dokeos LMS, August 2009
  1519. * @author Ivan Tcholakov
  1520. */
  1521. function api_str_ireplace($search, $replace, $subject, & $count = null, $encoding = null) {
  1522. if (empty($encoding)) {
  1523. $encoding = _api_mb_internal_encoding();
  1524. }
  1525. if (api_is_encoding_supported($encoding)) {
  1526. if (!is_array($search) && !is_array($replace)) {
  1527. if (!api_is_utf8($encoding)) {
  1528. $search = api_utf8_encode($search, $encoding);
  1529. }
  1530. $slen = api_byte_count($search);
  1531. if ( $slen == 0 ) {
  1532. return $subject;
  1533. }
  1534. if (!api_is_utf8($encoding)) {
  1535. $replace = api_utf8_encode($replace, $encoding);
  1536. $subject = api_utf8_encode($subject, $encoding);
  1537. }
  1538. $lendif = api_byte_count($replace) - api_byte_count($search);
  1539. $search = api_strtolower($search, 'UTF-8');
  1540. $search = preg_quote($search);
  1541. $lstr = api_strtolower($subject, 'UTF-8');
  1542. $i = 0;
  1543. $matched = 0;
  1544. while (preg_match('/(.*)'.$search.'/Us', $lstr, $matches) ) {
  1545. if ($i === $count) {
  1546. break;
  1547. }
  1548. $mlen = api_byte_count($matches[0]);
  1549. $lstr = substr($lstr, $mlen);
  1550. $subject = substr_replace($subject, $replace, $matched + api_byte_count($matches[1]), $slen);
  1551. $matched += $mlen + $lendif;
  1552. $i++;
  1553. }
  1554. if (!api_is_utf8($encoding)) {
  1555. $subject = api_utf8_decode($subject, $encoding);
  1556. }
  1557. return $subject;
  1558. } else {
  1559. foreach (array_keys($search) as $k) {
  1560. if (is_array($replace)) {
  1561. if (array_key_exists($k, $replace)) {
  1562. $subject = api_str_ireplace($search[$k], $replace[$k], $subject, $count);
  1563. } else {
  1564. $subject = api_str_ireplace($search[$k], '', $subject, $count);
  1565. }
  1566. } else {
  1567. $subject = api_str_ireplace($search[$k], $replace, $subject, $count);
  1568. }
  1569. }
  1570. return $subject;
  1571. }
  1572. }
  1573. if (is_null($count)) {
  1574. return str_ireplace($search, $replace, $subject);
  1575. }
  1576. return str_ireplace($search, $replace, $subject, $count);
  1577. }
  1578. /**
  1579. * Converts a string to an array.
  1580. * @param string $string The input string.
  1581. * @param int $split_length Maximum character-length of the chunk, one character by default.
  1582. * @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.
  1583. * @return array The result array of chunks with the spcified length.
  1584. * Notes:
  1585. * If the optional split_length parameter is specified, the returned array will be broken down into chunks
  1586. * with each being split_length in length, otherwise each chunk will be one character in length.
  1587. * FALSE is returned if split_length is less than 1.
  1588. * If the split_length length exceeds the length of string, the entire string is returned as the first (and only) array element.
  1589. * This function is aimed at replacing the function str_split() for human-language strings.
  1590. * @link http://php.net/str_split
  1591. */
  1592. function api_str_split($string, $split_length = 1, $encoding = null) {
  1593. if (empty($encoding)) {
  1594. $encoding = _api_mb_internal_encoding();
  1595. }
  1596. if (empty($string)) {
  1597. return array();
  1598. }
  1599. if ($split_length < 1) {
  1600. return false;
  1601. }
  1602. if (_api_is_single_byte_encoding($encoding)) {
  1603. return str_split($string, $split_length);
  1604. }
  1605. if (api_is_encoding_supported($encoding)) {
  1606. $len = api_strlen($string);
  1607. if ($len <= $split_length) {
  1608. return array($string);
  1609. }
  1610. if (!api_is_utf8($encoding)) {
  1611. $string = api_utf8_encode($string, $encoding);
  1612. }
  1613. if (preg_match_all('/.{'.$split_length.'}|[^\x00]{1,'.$split_length.'}$/us', $string, $result) === false) {
  1614. return array();
  1615. }
  1616. if (!api_is_utf8($encoding)) {
  1617. global $_api_encoding;
  1618. $_api_encoding = $encoding;
  1619. $result = _api_array_utf8_decode($result[0]);
  1620. }
  1621. return $result[0];
  1622. }
  1623. return str_split($string, $split_length);
  1624. }
  1625. /**
  1626. * Finds position of first occurrence of a string within another, case insensitive.
  1627. * @param string $haystack The string from which to get the position of the first occurrence.
  1628. * @param string $needle The string to be found.
  1629. * @param int $offset The position in $haystack to start searching from. If it is omitted, searching starts from the beginning.
  1630. * @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.
  1631. * @return mixed Returns the numeric position of the first occurrence of $needle in the $haystack, or FALSE if $needle is not found.
  1632. * Note: The first character's position is 0, the second character position is 1, and so on.
  1633. * This function is aimed at replacing the functions stripos() and mb_stripos() for human-language strings.
  1634. * @link http://php.net/manual/en/function.stripos
  1635. * @link http://php.net/manual/en/function.mb-stripos
  1636. */
  1637. function api_stripos($haystack, $needle, $offset = 0, $encoding = null) {
  1638. if (_api_mb_supports($encoding)) {
  1639. if (empty($encoding)) {
  1640. $encoding = _api_mb_internal_encoding();
  1641. }
  1642. return mb_stripos($haystack, $needle, $offset, $encoding);
  1643. }
  1644. return stripos($haystack, $needle, $offset);
  1645. }
  1646. /**
  1647. * Finds first occurrence of a string within another, case insensitive.
  1648. * @param string $haystack The string from which to get the first occurrence.
  1649. * @param mixed $needle The string to be found.
  1650. * @param bool $before_needle (optional) Determines which portion of $haystack this function returns. The default value is FALSE.
  1651. * @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.
  1652. * @return mixed Returns the portion of $haystack, or FALSE if $needle is not found.
  1653. * Notes:
  1654. * 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.
  1655. * If $before_needle is set to TRUE, the function returns all of $haystack from the beginning to the first occurrence of $needle.
  1656. * If $before_needle is set to FALSE, the function returns all of $haystack from the first occurrence of $needle to the end.
  1657. * This function is aimed at replacing the functions stristr() and mb_stristr() for human-language strings.
  1658. * @link http://php.net/manual/en/function.stristr
  1659. * @link http://php.net/manual/en/function.mb-stristr
  1660. */
  1661. function api_stristr($haystack, $needle, $before_needle = false, $encoding = null) {
  1662. if (_api_mb_supports($encoding)) {
  1663. if (empty($encoding)) {
  1664. $encoding = _api_mb_internal_encoding();
  1665. }
  1666. return mb_stristr($haystack, $needle, $before_needle, $encoding);
  1667. }
  1668. return stristr($haystack, $needle, $before_needle);
  1669. }
  1670. /**
  1671. * Returns length of the input string.
  1672. * @param string $string The string which length is to be calculated.
  1673. * @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.
  1674. * @return int Returns the number of characters within the string. A multi-byte character is counted as 1.
  1675. * This function is aimed at replacing the functions strlen() and mb_strlen() for human-language strings.
  1676. * @link http://php.net/manual/en/function.strlen
  1677. * @link http://php.net/manual/en/function.mb-strlen
  1678. * Note: When you use strlen() to test for an empty string, you needn't change it to api_strlen().
  1679. * For example, in lines like the following:
  1680. * if (strlen($string) > 0)
  1681. * if (strlen($string) != 0)
  1682. * there is no need the original function strlen() to be changed, it works correctly and faster for these cases.
  1683. */
  1684. function api_strlen($string, $encoding = null) {
  1685. if (empty($encoding)) {
  1686. $encoding = _api_mb_internal_encoding();
  1687. }
  1688. if (_api_is_single_byte_encoding($encoding)) {
  1689. return strlen($string);
  1690. }
  1691. if (_api_mb_supports($encoding)) {
  1692. return @mb_strlen($string, $encoding);
  1693. }
  1694. if (_api_iconv_supports($encoding)) {
  1695. return @iconv_strlen($string, $encoding);
  1696. }
  1697. return strlen($string);
  1698. }
  1699. /**
  1700. * Finds position of first occurrence of a string within another.
  1701. * @param string $haystack The string from which to get the position of the first occurrence.
  1702. * @param string $needle The string to be found.
  1703. * @param int $offset (optional) The position in $haystack to start searching from. If it is omitted, searching starts from the beginning.
  1704. * @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.
  1705. * @return mixed Returns the numeric position of the first occurrence of $needle in the $haystack, or FALSE if $needle is not found.
  1706. * Note: The first character's position is 0, the second character position is 1, and so on.
  1707. * This function is aimed at replacing the functions strpos() and mb_strpos() for human-language strings.
  1708. * @link http://php.net/manual/en/function.strpos
  1709. * @link http://php.net/manual/en/function.mb-strpos
  1710. */
  1711. function api_strpos($haystack, $needle, $offset = 0, $encoding = null) {
  1712. if (empty($encoding)) {
  1713. $encoding = _api_mb_internal_encoding();
  1714. }
  1715. if (_api_is_single_byte_encoding($encoding)) {
  1716. return strpos($haystack, $needle, $offset);
  1717. } elseif (_api_mb_supports($encoding)) {
  1718. return mb_strpos($haystack, $needle, $offset, $encoding);
  1719. }
  1720. return strpos($haystack, $needle, $offset);
  1721. }
  1722. /**
  1723. * Finds the last occurrence of a character in a string.
  1724. * @param string $haystack The string from which to get the last occurrence.
  1725. * @param mixed $needle The string which first character is to be found.
  1726. * @param bool $before_needle (optional) Determines which portion of $haystack this function returns. The default value is FALSE.
  1727. * @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.
  1728. * @return mixed Returns the portion of $haystack, or FALSE if the first character from $needle is not found.
  1729. * Notes:
  1730. * 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.
  1731. * If $before_needle is set to TRUE, the function returns all of $haystack from the beginning to the first occurrence.
  1732. * If $before_needle is set to FALSE, the function returns all of $haystack from the first occurrence to the end.
  1733. * This function is aimed at replacing the functions strrchr() and mb_strrchr() for human-language strings.
  1734. * @link http://php.net/manual/en/function.strrchr
  1735. * @link http://php.net/manual/en/function.mb-strrchr
  1736. */
  1737. function api_strrchr($haystack, $needle, $before_needle = false, $encoding = null) {
  1738. if (empty($encoding)) {
  1739. $encoding = _api_mb_internal_encoding();
  1740. }
  1741. if (_api_is_single_byte_encoding($encoding)) {
  1742. if (!$before_needle) {
  1743. return strrchr($haystack, $needle);
  1744. }
  1745. $result = strrchr($haystack, $needle);
  1746. if ($result === false) {
  1747. return false;
  1748. }
  1749. return api_substr($haystack, 0, api_strlen($haystack, $encoding) - api_strlen($result, $encoding), $encoding);
  1750. } elseif (_api_mb_supports($encoding)) {
  1751. return mb_strrchr($haystack, $needle, $before_needle, $encoding);
  1752. }
  1753. $result = strrchr($haystack, $needle);
  1754. if ($result === false) {
  1755. return false;
  1756. }
  1757. return api_substr($haystack, 0, api_strlen($haystack, $encoding) - api_strlen($result, $encoding), $encoding);
  1758. }
  1759. /**
  1760. * Reverses a string.
  1761. * @param string $string The string to be reversed.
  1762. * @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.
  1763. * @return string Returns the reversed string.
  1764. * This function is aimed at replacing the function strrev() for human-language strings.
  1765. * @link http://php.net/manual/en/function.strrev
  1766. */
  1767. function api_strrev($string, $encoding = null) {
  1768. if (empty($encoding)) {
  1769. $encoding = _api_mb_internal_encoding();
  1770. }
  1771. if (empty($string)) {
  1772. return '';
  1773. }
  1774. if (_api_is_single_byte_encoding($encoding)) {
  1775. return strrev($string);
  1776. }
  1777. if (api_is_encoding_supported($encoding)) {
  1778. return implode(array_reverse(api_str_split($string, 1, $encoding)));
  1779. }
  1780. return strrev($string);
  1781. }
  1782. /**
  1783. * Finds the position of last occurrence (case insensitive) of a string in a string.
  1784. * @param string $haystack The string from which to get the position of the last occurrence.
  1785. * @param string $needle The string to be found.
  1786. * @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.
  1787. * @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.
  1788. * @return mixed Returns the numeric position of the first occurrence (case insensitive) of $needle in the $haystack, or FALSE if $needle is not found.
  1789. * Note: The first character's position is 0, the second character position is 1, and so on.
  1790. * This function is aimed at replacing the functions strripos() and mb_strripos() for human-language strings.
  1791. * @link http://php.net/manual/en/function.strripos
  1792. * @link http://php.net/manual/en/function.mb-strripos
  1793. */
  1794. function api_strripos($haystack, $needle, $offset = 0, $encoding = null)
  1795. {
  1796. return api_strrpos(api_strtolower($haystack, $encoding), api_strtolower($needle, $encoding), $offset, $encoding);
  1797. }
  1798. /**
  1799. * Finds the position of last occurrence of a string in a string.
  1800. * @param string $haystack The string from which to get the position of the last occurrence.
  1801. * @param string $needle The string to be found.
  1802. * @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.
  1803. * @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.
  1804. * @return mixed Returns the numeric position of the first occurrence of $needle in the $haystack, or FALSE if $needle is not found.
  1805. * Note: The first character's position is 0, the second character position is 1, and so on.
  1806. * This function is aimed at replacing the functions strrpos() and mb_strrpos() for human-language strings.
  1807. * @link http://php.net/manual/en/function.strrpos
  1808. * @link http://php.net/manual/en/function.mb-strrpos
  1809. */
  1810. function api_strrpos($haystack, $needle, $offset = 0, $encoding = null)
  1811. {
  1812. if (_api_mb_supports($encoding)) {
  1813. if (empty($encoding)) {
  1814. $encoding = _api_mb_internal_encoding();
  1815. }
  1816. return mb_strrpos($haystack, $needle, $offset, $encoding);
  1817. }
  1818. return strrpos($haystack, $needle, $offset);
  1819. }
  1820. /**
  1821. * Finds first occurrence of a string within another.
  1822. * @param string $haystack The string from which to get the first occurrence.
  1823. * @param mixed $needle The string to be found.
  1824. * @param bool $before_needle (optional) Determines which portion of $haystack this function returns. The default value is FALSE.
  1825. * @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.
  1826. * @return mixed Returns the portion of $haystack, or FALSE if $needle is not found.
  1827. * Notes:
  1828. * 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.
  1829. * If $before_needle is set to TRUE, the function returns all of $haystack from the beginning to the first occurrence of $needle.
  1830. * If $before_needle is set to FALSE, the function returns all of $haystack from the first occurrence of $needle to the end.
  1831. * This function is aimed at replacing the functions strstr() and mb_strstr() for human-language strings.
  1832. * @link http://php.net/manual/en/function.strstr
  1833. * @link http://php.net/manual/en/function.mb-strstr
  1834. */
  1835. function api_strstr($haystack, $needle, $before_needle = false, $encoding = null) {
  1836. if (empty($encoding)) {
  1837. $encoding = _api_mb_internal_encoding();
  1838. }
  1839. if (!is_string($needle)) {
  1840. $needle = (int)$needle;
  1841. if (api_is_utf8($encoding)) {
  1842. $needle = _api_utf8_chr($needle);
  1843. } else {
  1844. $needle = chr($needle);
  1845. }
  1846. }
  1847. if ($needle == '') {
  1848. return false;
  1849. }
  1850. if (_api_is_single_byte_encoding($encoding)) {
  1851. return strstr($haystack, $needle, $before_needle);
  1852. }
  1853. if (_api_mb_supports($encoding)) {
  1854. return mb_strstr($haystack, $needle, $before_needle, $encoding);
  1855. }
  1856. return strstr($haystack, $needle, $before_needle);
  1857. }
  1858. /**
  1859. * Makes a string lowercase.
  1860. * @param string $string The string being lowercased.
  1861. * @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.
  1862. * @return string Returns the string with all alphabetic characters converted to lowercase.
  1863. * This function is aimed at replacing the functions strtolower() and mb_strtolower() for human-language strings.
  1864. * @link http://php.net/manual/en/function.strtolower
  1865. * @link http://php.net/manual/en/function.mb-strtolower
  1866. */
  1867. function api_strtolower($string, $encoding = null) {
  1868. if (empty($encoding)) {
  1869. $encoding = _api_mb_internal_encoding();
  1870. }
  1871. if (_api_mb_supports($encoding)) {
  1872. return mb_strtolower($string, $encoding);
  1873. }
  1874. return strtolower($string);
  1875. }
  1876. /**
  1877. * Makes a string uppercase.
  1878. * @param string $string The string being uppercased.
  1879. * @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.
  1880. * @return string Returns the string with all alphabetic characters converted to uppercase.
  1881. * This function is aimed at replacing the functions strtoupper() and mb_strtoupper() for human-language strings.
  1882. * @link http://php.net/manual/en/function.strtoupper
  1883. * @link http://php.net/manual/en/function.mb-strtoupper
  1884. */
  1885. function api_strtoupper($string, $encoding = null) {
  1886. if (empty($encoding)) {
  1887. $encoding = _api_mb_internal_encoding();
  1888. }
  1889. if (_api_mb_supports($encoding)) {
  1890. return mb_strtoupper($string, $encoding);
  1891. }
  1892. return strtoupper($string);
  1893. }
  1894. /**
  1895. // Gets part of a string.
  1896. * @param string $string The input string.
  1897. * @param int $start The first position from which the extracted part begins.
  1898. * @param int $length The length in character of the extracted part.
  1899. * @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.
  1900. * @return string Returns the part of the string specified by the start and length parameters.
  1901. * Note: First character's position is 0. Second character position is 1, and so on.
  1902. * This function is aimed at replacing the functions substr() and mb_substr() for human-language strings.
  1903. * @link http://php.net/manual/en/function.substr
  1904. * @link http://php.net/manual/en/function.mb-substr
  1905. */
  1906. function api_substr($string, $start, $length = null, $encoding = null) {
  1907. if (empty($encoding)) {
  1908. $encoding = _api_mb_internal_encoding();
  1909. }
  1910. // Passing null as $length would mean 0. This behaviour has been corrected here.
  1911. if (is_null($length)) {
  1912. $length = api_strlen($string, $encoding);
  1913. }
  1914. if (_api_is_single_byte_encoding($encoding)) {
  1915. return substr($string, $start, $length);
  1916. }
  1917. if (_api_mb_supports($encoding)) {
  1918. return mb_substr($string, $start, $length, $encoding);
  1919. }
  1920. return substr($string, $start, $length);
  1921. }
  1922. /**
  1923. * Counts the number of substring occurrences.
  1924. * @param string $haystack The string being checked.
  1925. * @param string $needle The string being found.
  1926. * @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.
  1927. * @return int The number of times the needle substring occurs in the haystack string.
  1928. * @link http://php.net/manual/en/function.mb-substr-count.php
  1929. */
  1930. function api_substr_count($haystack, $needle, $encoding = null) {
  1931. if (empty($encoding)) {
  1932. $encoding = _api_mb_internal_encoding();
  1933. }
  1934. if (_api_mb_supports($encoding)) {
  1935. return mb_substr_count($haystack, $needle, $encoding);
  1936. }
  1937. return substr_count($haystack, $needle);
  1938. }
  1939. /**
  1940. * Replaces text within a portion of a string.
  1941. * @param string $string The input string.
  1942. * @param string $replacement The replacement string.
  1943. * @param int $start The position from which replacing will begin.
  1944. * Notes:
  1945. * If $start is positive, the replacing will begin at the $start'th offset into the string.
  1946. * If $start is negative, the replacing will begin at the $start'th character from the end of the string.
  1947. * @param int $length (optional) The position where replacing will end.
  1948. * Notes:
  1949. * If given and is positive, it represents the length of the portion of the string which is to be replaced.
  1950. * If it is negative, it represents the number of characters from the end of string at which to stop replacing.
  1951. * If it is not given, then it will default to api_strlen($string); i.e. end the replacing at the end of string.
  1952. * If $length is zero, then this function will have the effect of inserting replacement into the string at the given start offset.
  1953. * @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.
  1954. * @return string The result string is returned.
  1955. * This function is aimed at replacing the function substr_replace() for human-language strings.
  1956. * @link http://php.net/manual/function.substr-replace
  1957. */
  1958. function api_substr_replace($string, $replacement, $start, $length = null, $encoding = null) {
  1959. if (empty($encoding)) {
  1960. $encoding = _api_mb_internal_encoding();
  1961. }
  1962. if (_api_is_single_byte_encoding($encoding)) {
  1963. if (is_null($length)) {
  1964. return substr_replace($string, $replacement, $start);
  1965. }
  1966. return substr_replace($string, $replacement, $start, $length);
  1967. }
  1968. if (api_is_encoding_supported($encoding)) {
  1969. if (is_null($length)) {
  1970. $length = api_strlen($string);
  1971. }
  1972. if (!api_is_utf8($encoding)) {
  1973. $string = api_utf8_encode($string, $encoding);
  1974. $replacement = api_utf8_encode($replacement, $encoding);
  1975. }
  1976. $string = _api_utf8_to_unicode($string);
  1977. array_splice($string, $start, $length, _api_utf8_to_unicode($replacement));
  1978. $string = _api_utf8_from_unicode($string);
  1979. if (!api_is_utf8($encoding)) {
  1980. $string = api_utf8_decode($string, $encoding);
  1981. }
  1982. return $string;
  1983. }
  1984. if (is_null($length)) {
  1985. return substr_replace($string, $replacement, $start);
  1986. }
  1987. return substr_replace($string, $replacement, $start, $length);
  1988. }
  1989. /**
  1990. * Makes a string's first character uppercase.
  1991. * @param string $string The input string.
  1992. * @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.
  1993. * @return string Returns a string with the first character capitalized, if that character is alphabetic.
  1994. * This function is aimed at replacing the function ucfirst() for human-language strings.
  1995. * @link http://php.net/manual/en/function.ucfirst
  1996. */
  1997. function api_ucfirst($string, $encoding = null) {
  1998. if (empty($encoding)) {
  1999. $encoding = _api_mb_internal_encoding();
  2000. }
  2001. return api_strtoupper(api_substr($string, 0, 1, $encoding), $encoding) . api_substr($string, 1, api_strlen($string, $encoding), $encoding);
  2002. }
  2003. /**
  2004. * Uppercases the first character of each word in a string.
  2005. * @param string $string The input string.
  2006. * @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.
  2007. * @return string Returns the modified string.
  2008. * This function is aimed at replacing the function ucwords() for human-language strings.
  2009. * @link http://php.net/manual/en/function.ucwords
  2010. */
  2011. function api_ucwords($string, $encoding = null) {
  2012. if (_api_mb_supports($encoding)) {
  2013. if (empty($encoding)) {
  2014. $encoding = _api_mb_internal_encoding();
  2015. }
  2016. return mb_convert_case($string, MB_CASE_TITLE, $encoding);
  2017. }
  2018. return ucwords($string);
  2019. }
  2020. /**
  2021. * String operations using regular expressions
  2022. */
  2023. /**
  2024. * Performs a regular expression match, UTF-8 aware when it is applicable.
  2025. * @param string $pattern The pattern to search for, as a string.
  2026. * @param string $subject The input string.
  2027. * @param array &$matches (optional) If matches is provided, then it is filled with the results of search (as an array).
  2028. * $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.
  2029. * @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.
  2030. * 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.
  2031. * @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.
  2032. * @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.
  2033. * @return int|boolean Returns the number of times pattern matches or FALSE if an error occurred.
  2034. * @link http://php.net/preg_match
  2035. */
  2036. function api_preg_match($pattern, $subject, &$matches = null, $flags = 0, $offset = 0, $encoding = null) {
  2037. if (empty($encoding)) {
  2038. $encoding = _api_mb_internal_encoding();
  2039. }
  2040. return preg_match(api_is_utf8($encoding) ? $pattern.'u' : $pattern, $subject, $matches, $flags, $offset);
  2041. }
  2042. /**
  2043. * Performs a global regular expression match, UTF-8 aware when it is applicable.
  2044. * @param string $pattern The pattern to search for, as a string.
  2045. * @param string $subject The input string.
  2046. * @param array &$matches (optional) Array of all matches in multi-dimensional array ordered according to $flags.
  2047. * @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):
  2048. * 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;
  2049. * 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;
  2050. * 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
  2051. * 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.
  2052. * If no order flag is given, PREG_PATTERN_ORDER is assumed.
  2053. * @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.
  2054. * @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.
  2055. * @return int|boolean Returns the number of full pattern matches (which might be zero), or FALSE if an error occurred.
  2056. * @link http://php.net/preg_match_all
  2057. */
  2058. function api_preg_match_all($pattern, $subject, &$matches, $flags = PREG_PATTERN_ORDER, $offset = 0, $encoding = null) {
  2059. if (empty($encoding)) {
  2060. $encoding = _api_mb_internal_encoding();
  2061. }
  2062. if (is_null($flags)) {
  2063. $flags = PREG_PATTERN_ORDER;
  2064. }
  2065. return preg_match_all(api_is_utf8($encoding) ? $pattern.'u' : $pattern, $subject, $matches, $flags, $offset);
  2066. }
  2067. /**
  2068. * Performs a regular expression search and replace, UTF-8 aware when it is applicable.
  2069. * @param string|array $pattern The pattern to search for. It can be either a string or an array with strings.
  2070. * @param string|array $replacement The string or an array with strings to replace.
  2071. * @param string|array $subject The string or an array with strings to search and replace.
  2072. * @param int $limit The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).
  2073. * @param int &$count If specified, this variable will be filled with the number of replacements done.
  2074. * @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.
  2075. * @return array|string|null returns an array if the subject parameter is an array, or a string otherwise.
  2076. * If matches are found, the new subject will be returned, otherwise subject will be returned unchanged or NULL if an error occurred.
  2077. * @link http://php.net/preg_replace
  2078. */
  2079. function api_preg_replace($pattern, $replacement, $subject, $limit = -1, &$count = 0, $encoding = null) {
  2080. if (empty($encoding)) {
  2081. $encoding = _api_mb_internal_encoding();
  2082. }
  2083. $is_utf8 = api_is_utf8($encoding);
  2084. if (is_array($pattern)) {
  2085. foreach ($pattern as &$p) {
  2086. $p = $is_utf8 ? $p.'u' : $p;
  2087. }
  2088. } else {
  2089. $pattern = $is_utf8 ? $pattern.'u' : $pattern;
  2090. }
  2091. return preg_replace($pattern, $replacement, $subject, $limit, $count);
  2092. }
  2093. /**
  2094. * Performs a regular expression search and replace using a callback function, UTF-8 aware when it is applicable.
  2095. * @param string|array $pattern The pattern to search for. It can be either a string or an array with strings.
  2096. * @param function $callback A callback that will be called and passed an array of matched elements in the $subject string. The callback should return the replacement string.
  2097. * @param string|array $subject The string or an array with strings to search and replace.
  2098. * @param int $limit (optional) The maximum possible replacements for each pattern in each subject string. Defaults to -1 (no limit).
  2099. * @param int &$count (optional) If specified, this variable will be filled with the number of replacements done.
  2100. * @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.
  2101. * @return array|string Returns an array if the subject parameter is an array, or a string otherwise.
  2102. * @link http://php.net/preg_replace_callback
  2103. */
  2104. function api_preg_replace_callback($pattern, $callback, $subject, $limit = -1, &$count = 0, $encoding = null) {
  2105. if (empty($encoding)) {
  2106. $encoding = _api_mb_internal_encoding();
  2107. }
  2108. if (is_array($pattern)) {
  2109. foreach ($pattern as &$p) {
  2110. $p = api_is_utf8($encoding) ? $p.'u' : $p;
  2111. }
  2112. } else {
  2113. $pattern = api_is_utf8($encoding) ? $pattern.'u' : $pattern;
  2114. }
  2115. return preg_replace_callback($pattern, $callback, $subject, $limit, $count);
  2116. }
  2117. /**
  2118. * Splits a string by a regular expression, UTF-8 aware when it is applicable.
  2119. * @param string $pattern The pattern to search for, as a string.
  2120. * @param string $subject The input string.
  2121. * @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.
  2122. * @param int $flags (optional) $flags can be any combination of the following flags (combined with bitwise | operator):
  2123. * PREG_SPLIT_NO_EMPTY - if this flag is set, only non-empty pieces will be returned;
  2124. * PREG_SPLIT_DELIM_CAPTURE - if this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well;
  2125. * PREG_SPLIT_OFFSET_CAPTURE - If this flag is set, for every occurring match the appendant string offset will also be returned.
  2126. * 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.
  2127. * @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.
  2128. * @return array Returns an array containing substrings of $subject split along boundaries matched by $pattern.
  2129. * @link http://php.net/preg_split
  2130. */
  2131. function api_preg_split($pattern, $subject, $limit = -1, $flags = 0, $encoding = null) {
  2132. if (empty($encoding)) {
  2133. $encoding = _api_mb_internal_encoding();
  2134. }
  2135. return preg_split(api_is_utf8($encoding) ? $pattern.'u' : $pattern, $subject, $limit, $flags);
  2136. }
  2137. /**
  2138. * Obsolete string operations using regular expressions, to be deprecated
  2139. */
  2140. /**
  2141. * Note: Try to avoid using this function. Use api_preg_match() with Perl-compatible regular expression syntax.
  2142. *
  2143. * Executes a regular expression match with extended multibyte support.
  2144. * By default this function uses the platform character set.
  2145. * @param string $pattern The regular expression pattern.
  2146. * @param string $string The searched string.
  2147. * @param array $regs (optional) If specified, by this passed by reference parameter an array containing found match and its substrings is returned.
  2148. * @return mixed 1 if match is found, FALSE if not. If $regs has been specified, byte-length of the found match is returned, or FALSE if no match has been found.
  2149. * This function is aimed at replacing the functions ereg() and mb_ereg() for human-language strings.
  2150. * @link http://php.net/manual/en/function.ereg
  2151. * @link http://php.net/manual/en/function.mb-ereg
  2152. */
  2153. function api_ereg($pattern, $string, & $regs = null) {
  2154. $count = func_num_args();
  2155. $encoding = _api_mb_regex_encoding();
  2156. if (_api_mb_supports($encoding)) {
  2157. if ($count < 3) {
  2158. return @mb_ereg($pattern, $string);
  2159. }
  2160. return @mb_ereg($pattern, $string, $regs);
  2161. }
  2162. if (MBSTRING_INSTALLED && api_is_encoding_supported($encoding)) {
  2163. global $_api_encoding;
  2164. $_api_encoding = $encoding;
  2165. _api_mb_regex_encoding('UTF-8');
  2166. if ($count < 3) {
  2167. $result = @mb_ereg(api_utf8_encode($pattern, $encoding), api_utf8_encode($string, $encoding));
  2168. } else {
  2169. $result = @mb_ereg(api_utf8_encode($pattern, $encoding), api_utf8_encode($string, $encoding), $regs);
  2170. $regs = _api_array_utf8_decode($regs);
  2171. }
  2172. _api_mb_regex_encoding($encoding);
  2173. return $result;
  2174. }
  2175. if ($count < 3) {
  2176. return ereg($pattern, $string);
  2177. }
  2178. return ereg($pattern, $string, $regs);
  2179. }
  2180. /**
  2181. * Note: Try to avoid using this function. Use api_preg_replace() with Perl-compatible regular expression syntax.
  2182. *
  2183. * Scans string for matches to pattern, then replaces the matched text with replacement, with extended multibyte support.
  2184. * By default this function uses the platform character set.
  2185. * @param string $pattern The regular expression pattern.
  2186. * @param string $replacement The replacement text.
  2187. * @param string $string The searched string.
  2188. * @param string $option (optional) Matching condition.
  2189. * If i is specified for the matching condition parameter, the case will be ignored.
  2190. * If x is specified, white space will be ignored.
  2191. * If m is specified, match will be executed in multiline mode and line break will be included in '.'.
  2192. * If p is specified, match will be executed in POSIX mode, line break will be considered as normal character.
  2193. * If e is specified, replacement string will be evaluated as PHP expression.
  2194. * @return mixed The modified string is returned. If no matches are found within the string, then it will be returned unchanged. FALSE will be returned on error.
  2195. * This function is aimed at replacing the functions ereg_replace() and mb_ereg_replace() for human-language strings.
  2196. * @link http://php.net/manual/en/function.ereg-replace
  2197. * @link http://php.net/manual/en/function.mb-ereg-replace
  2198. */
  2199. function api_ereg_replace($pattern, $replacement, $string, $option = null) {
  2200. $encoding = _api_mb_regex_encoding();
  2201. if (_api_mb_supports($encoding)) {
  2202. if (is_null($option)) {
  2203. return @mb_ereg_replace($pattern, $replacement, $string);
  2204. }
  2205. return @mb_ereg_replace($pattern, $replacement, $string, $option);
  2206. }
  2207. if (MBSTRING_INSTALLED && api_is_encoding_supported($encoding)) {
  2208. _api_mb_regex_encoding('UTF-8');
  2209. if (is_null($option)) {
  2210. $result = api_utf8_decode(@mb_ereg_replace(api_utf8_encode($pattern, $encoding), api_utf8_encode($replacement, $encoding), api_utf8_encode($string, $encoding)), $encoding);
  2211. } else {
  2212. $result = api_utf8_decode(@mb_ereg_replace(api_utf8_encode($pattern, $encoding), api_utf8_encode($replacement, $encoding), api_utf8_encode($string, $encoding), $option), $encoding);
  2213. }
  2214. _api_mb_regex_encoding($encoding);
  2215. return $result;
  2216. }
  2217. return ereg_replace($pattern, $replacement, $string);
  2218. }
  2219. /**
  2220. * Note: Try to avoid using this function. Use api_preg_match() with Perl-compatible regular expression syntax.
  2221. *
  2222. * Executes a regular expression match, ignoring case, with extended multibyte support.
  2223. * By default this function uses the platform character set.
  2224. * @param string $pattern The regular expression pattern.
  2225. * @param string $string The searched string.
  2226. * @param array $regs (optional) If specified, by this passed by reference parameter an array containing found match and its substrings is returned.
  2227. * @return mixed 1 if match is found, FALSE if not. If $regs has been specified, byte-length of the found match is returned, or FALSE if no match has been found.
  2228. * This function is aimed at replacing the functions eregi() and mb_eregi() for human-language strings.
  2229. * @link http://php.net/manual/en/function.eregi
  2230. * @link http://php.net/manual/en/function.mb-eregi
  2231. */
  2232. function api_eregi($pattern, $string, & $regs = null) {
  2233. $count = func_num_args();
  2234. $encoding = _api_mb_regex_encoding();
  2235. if (_api_mb_supports($encoding)) {
  2236. if ($count < 3) {
  2237. return @mb_eregi($pattern, $string);
  2238. }
  2239. return @mb_eregi($pattern, $string, $regs);
  2240. }
  2241. if (MBSTRING_INSTALLED && api_is_encoding_supported($encoding)) {
  2242. global $_api_encoding;
  2243. $_api_encoding = $encoding;
  2244. _api_mb_regex_encoding('UTF-8');
  2245. if ($count < 3) {
  2246. $result = @mb_eregi(api_utf8_encode($pattern, $encoding), api_utf8_encode($string, $encoding));
  2247. } else {
  2248. $result = @mb_eregi(api_utf8_encode($pattern, $encoding), api_utf8_encode($string, $encoding), $regs);
  2249. $regs = _api_array_utf8_decode($regs);
  2250. }
  2251. _api_mb_regex_encoding($encoding);
  2252. return $result;
  2253. }
  2254. if ($count < 3) {
  2255. return eregi($pattern, $string);
  2256. }
  2257. return eregi($pattern, $string, $regs);
  2258. }
  2259. /**
  2260. * Note: Try to avoid using this function. Use api_preg_replace() with Perl-compatible regular expression syntax.
  2261. *
  2262. * Scans string for matches to pattern, then replaces the matched text with replacement, ignoring case, with extended multibyte support.
  2263. * By default this function uses the platform character set.
  2264. * @param string $pattern The regular expression pattern.
  2265. * @param string $replacement The replacement text.
  2266. * @param string $string The searched string.
  2267. * @param string $option (optional) Matching condition.
  2268. * If i is specified for the matching condition parameter, the case will be ignored.
  2269. * If x is specified, white space will be ignored.
  2270. * If m is specified, match will be executed in multiline mode and line break will be included in '.'.
  2271. * If p is specified, match will be executed in POSIX mode, line break will be considered as normal character.
  2272. * If e is specified, replacement string will be evaluated as PHP expression.
  2273. * @return mixed The modified string is returned. If no matches are found within the string, then it will be returned unchanged. FALSE will be returned on error.
  2274. * This function is aimed at replacing the functions eregi_replace() and mb_eregi_replace() for human-language strings.
  2275. * @link http://php.net/manual/en/function.eregi-replace
  2276. * @link http://php.net/manual/en/function.mb-eregi-replace
  2277. */
  2278. function api_eregi_replace($pattern, $replacement, $string, $option = null) {
  2279. $encoding = _api_mb_regex_encoding();
  2280. if (_api_mb_supports($encoding)) {
  2281. if (is_null($option)) {
  2282. return @mb_eregi_replace($pattern, $replacement, $string);
  2283. }
  2284. return @mb_eregi_replace($pattern, $replacement, $string, $option);
  2285. }
  2286. if (MBSTRING_INSTALLED && api_is_encoding_supported($encoding)) {
  2287. _api_mb_regex_encoding('UTF-8');
  2288. if (is_null($option)) {
  2289. $result = api_utf8_decode(@mb_eregi_replace(api_utf8_encode($pattern, $encoding), api_utf8_encode($replacement, $encoding), api_utf8_encode($string, $encoding)), $encoding);
  2290. } else {
  2291. $result = api_utf8_decode(@mb_eregi_replace(api_utf8_encode($pattern, $encoding), api_utf8_encode($replacement, $encoding), api_utf8_encode($string, $encoding), $option), $encoding);
  2292. }
  2293. _api_mb_regex_encoding($encoding);
  2294. return $result;
  2295. }
  2296. return eregi_replace($pattern, $replacement, $string);
  2297. }
  2298. /**
  2299. * Note: Try to avoid using this function. Use api_preg_split() with Perl-compatible regular expression syntax.
  2300. *
  2301. * Splits a multibyte string using regular expression pattern and returns the result as an array.
  2302. * By default this function uses the platform character set.
  2303. * @param string $pattern The regular expression pattern.
  2304. * @param string $string The string being split.
  2305. * @param int $limit (optional) If this optional parameter $limit is specified, the string will be split in $limit elements as maximum.
  2306. * @return array The result as an array.
  2307. * This function is aimed at replacing the functions split() and mb_split() for human-language strings.
  2308. * @link http://php.net/manual/en/function.split
  2309. * @link http://php.net/manual/en/function.mb-split
  2310. */
  2311. function api_split($pattern, $string, $limit = null) {
  2312. $encoding = _api_mb_regex_encoding();
  2313. if (_api_mb_supports($encoding)) {
  2314. if (is_null($limit)) {
  2315. return @mb_split($pattern, $string);
  2316. }
  2317. return @mb_split($pattern, $string, $limit);
  2318. }
  2319. if (MBSTRING_INSTALLED && api_is_encoding_supported($encoding)) {
  2320. global $_api_encoding;
  2321. $_api_encoding = $encoding;
  2322. _api_mb_regex_encoding('UTF-8');
  2323. if (is_null($limit)) {
  2324. $result = @mb_split(api_utf8_encode($pattern, $encoding), api_utf8_encode($string, $encoding));
  2325. } else {
  2326. $result = @mb_split(api_utf8_encode($pattern, $encoding), api_utf8_encode($string, $encoding), $limit);
  2327. }
  2328. $result = _api_array_utf8_decode($result);
  2329. _api_mb_regex_encoding($encoding);
  2330. return $result;
  2331. }
  2332. if (is_null($limit)) {
  2333. return split($pattern, $string);
  2334. }
  2335. return split($pattern, $string, $limit);
  2336. }
  2337. /**
  2338. * String comparison
  2339. */
  2340. /**
  2341. * Performs string comparison, case insensitive, language sensitive, with extended multibyte support.
  2342. * @param string $string1 The first string.
  2343. * @param string $string2 The second string.
  2344. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2345. * @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.
  2346. * @return int Returns < 0 if $string1 is less than $string2; > 0 if $string1 is greater than $string2; and 0 if the strings are equal.
  2347. * This function is aimed at replacing the function strcasecmp() for human-language strings.
  2348. * @link http://php.net/manual/en/function.strcasecmp
  2349. */
  2350. function api_strcasecmp($string1, $string2, $language = null, $encoding = null) {
  2351. return api_strcmp(api_strtolower($string1, $encoding), api_strtolower($string2, $encoding), $language, $encoding);
  2352. }
  2353. /**
  2354. * Performs string comparison, case sensitive, language sensitive, with extended multibyte support.
  2355. * @param string $string1 The first string.
  2356. * @param string $string2 The second string.
  2357. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2358. * @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.
  2359. * @return int Returns < 0 if $string1 is less than $string2; > 0 if $string1 is greater than $string2; and 0 if the strings are equal.
  2360. * This function is aimed at replacing the function strcmp() for human-language strings.
  2361. * @link http://php.net/manual/en/function.strcmp.php
  2362. * @link http://php.net/manual/en/collator.compare.php
  2363. */
  2364. function api_strcmp($string1, $string2, $language = null, $encoding = null)
  2365. {
  2366. if (INTL_INSTALLED) {
  2367. $collator = _api_get_collator($language);
  2368. if (is_object($collator)) {
  2369. $result = collator_compare($collator, api_utf8_encode($string1, $encoding), api_utf8_encode($string2, $encoding));
  2370. return $result === false ? 0 : $result;
  2371. }
  2372. }
  2373. return strcmp($string1, $string2);
  2374. }
  2375. /**
  2376. * Performs string comparison in so called "natural order", case insensitive, language sensitive, with extended multibyte support.
  2377. * @param string $string1 The first string.
  2378. * @param string $string2 The second string.
  2379. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2380. * @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.
  2381. * @return int Returns < 0 if $string1 is less than $string2; > 0 if $string1 is greater than $string2; and 0 if the strings are equal.
  2382. * This function is aimed at replacing the function strnatcasecmp() for human-language strings.
  2383. * @link http://php.net/manual/en/function.strnatcasecmp
  2384. */
  2385. function api_strnatcasecmp($string1, $string2, $language = null, $encoding = null) {
  2386. return api_strnatcmp(api_strtolower($string1, $encoding), api_strtolower($string2, $encoding), $language, $encoding);
  2387. }
  2388. /**
  2389. * Performs string comparison in so called "natural order", case sensitive, language sensitive, with extended multibyte support.
  2390. * @param string $string1 The first string.
  2391. * @param string $string2 The second string.
  2392. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2393. * @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.
  2394. * @return int Returns < 0 if $string1 is less than $string2; > 0 if $string1 is greater than $string2; and 0 if the strings are equal.
  2395. * This function is aimed at replacing the function strnatcmp() for human-language strings.
  2396. * @link http://php.net/manual/en/function.strnatcmp.php
  2397. * @link http://php.net/manual/en/collator.compare.php
  2398. */
  2399. function api_strnatcmp($string1, $string2, $language = null, $encoding = null) {
  2400. if (INTL_INSTALLED) {
  2401. $collator = _api_get_alpha_numerical_collator($language);
  2402. if (is_object($collator)) {
  2403. $result = collator_compare($collator, api_utf8_encode($string1, $encoding), api_utf8_encode($string2, $encoding));
  2404. return $result === false ? 0 : $result;
  2405. }
  2406. }
  2407. return strnatcmp($string1, $string2);
  2408. }
  2409. /**
  2410. * Sorting arrays
  2411. */
  2412. /**
  2413. * Sorts an array with maintaining index association, elements will be arranged from the lowest to the highest.
  2414. * @param array $array The input array.
  2415. * @param int $sort_flag (optional) Shows how elements of the array to be compared.
  2416. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2417. * @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.
  2418. * @return bool Returns TRUE on success, FALSE on error.
  2419. * Note: $sort_flag may have the following values:
  2420. * SORT_REGULAR - internal PHP-rules for comparison will be applied, without preliminary changing types;
  2421. * SORT_NUMERIC - items will be compared as numbers;
  2422. * SORT_STRING - items will be compared as strings. If intl extension is enabled, then comparison will be language-sensitive using internally a created ICU locale;
  2423. * SORT_LOCALE_STRING - items will be compared as strings depending on the current POSIX locale. If intl extension is enabled, then comparison will be language-sensitive using internally a created ICU locale.
  2424. * This function is aimed at replacing the function asort() for sorting human-language strings.
  2425. * @link http://php.net/manual/en/function.asort.php
  2426. * @link http://php.net/manual/en/collator.asort.php
  2427. */
  2428. function api_asort(&$array, $sort_flag = SORT_REGULAR, $language = null, $encoding = null) {
  2429. if (INTL_INSTALLED) {
  2430. if (empty($encoding)) {
  2431. $encoding = _api_mb_internal_encoding();
  2432. }
  2433. $collator = _api_get_collator($language);
  2434. if (is_object($collator)) {
  2435. if (api_is_utf8($encoding)) {
  2436. $sort_flag = ($sort_flag == SORT_LOCALE_STRING) ? SORT_STRING : $sort_flag;
  2437. return collator_asort($collator, $array, _api_get_collator_sort_flag($sort_flag));
  2438. }
  2439. elseif ($sort_flag == SORT_STRING || $sort_flag == SORT_LOCALE_STRING) {
  2440. global $_api_collator, $_api_encoding;
  2441. $_api_collator = $collator;
  2442. $_api_encoding = $encoding;
  2443. return uasort($array, '_api_cmp');
  2444. }
  2445. }
  2446. }
  2447. return asort($array, $sort_flag);
  2448. }
  2449. /**
  2450. * Sorts an array with maintaining index association, elements will be arranged from the highest to the lowest (in reverse order).
  2451. * @param array $array The input array.
  2452. * @param int $sort_flag (optional) Shows how elements of the array to be compared.
  2453. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2454. * @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.
  2455. * @return bool Returns TRUE on success, FALSE on error.
  2456. * Note: $sort_flag may have the following values:
  2457. * SORT_REGULAR - internal PHP-rules for comparison will be applied, without preliminary changing types;
  2458. * SORT_NUMERIC - items will be compared as numbers;
  2459. * SORT_STRING - items will be compared as strings. If intl extension is enabled, then comparison will be language-sensitive using internally a created ICU locale;
  2460. * SORT_LOCALE_STRING - items will be compared as strings depending on the current POSIX locale. If intl extension is enabled, then comparison will be language-sensitive using internally a created ICU locale.
  2461. * This function is aimed at replacing the function arsort() for sorting human-language strings.
  2462. * @link http://php.net/manual/en/function.arsort.php
  2463. */
  2464. function api_arsort(&$array, $sort_flag = SORT_REGULAR, $language = null, $encoding = null) {
  2465. if (INTL_INSTALLED) {
  2466. if (empty($encoding)) {
  2467. $encoding = _api_mb_internal_encoding();
  2468. }
  2469. $collator = _api_get_collator($language);
  2470. if (is_object($collator)) {
  2471. if ($sort_flag == SORT_STRING || $sort_flag == SORT_LOCALE_STRING) {
  2472. global $_api_collator, $_api_encoding;
  2473. $_api_collator = $collator;
  2474. $_api_encoding = $encoding;
  2475. return uasort($array, '_api_rcmp');
  2476. }
  2477. }
  2478. }
  2479. return arsort($array, $sort_flag);
  2480. }
  2481. /**
  2482. * Sorts an array using natural order algorithm.
  2483. * @param array $array The input array.
  2484. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2485. * @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.
  2486. * @return bool Returns TRUE on success, FALSE on error.
  2487. * This function is aimed at replacing the function natsort() for sorting human-language strings.
  2488. * @link http://php.net/manual/en/function.natsort.php
  2489. */
  2490. function api_natsort(&$array, $language = null, $encoding = null) {
  2491. if (INTL_INSTALLED) {
  2492. if (empty($encoding)) {
  2493. $encoding = _api_mb_internal_encoding();
  2494. }
  2495. $collator = _api_get_alpha_numerical_collator($language);
  2496. if (is_object($collator)) {
  2497. global $_api_collator, $_api_encoding;
  2498. $_api_collator = $collator;
  2499. $_api_encoding = $encoding;
  2500. return uasort($array, '_api_cmp');
  2501. }
  2502. }
  2503. return natsort($array);
  2504. }
  2505. /**
  2506. * Sorts an array using natural order algorithm in reverse order.
  2507. * @param array $array The input array.
  2508. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2509. * @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.
  2510. * @return bool Returns TRUE on success, FALSE on error.
  2511. */
  2512. function api_natrsort(&$array, $language = null, $encoding = null) {
  2513. if (INTL_INSTALLED) {
  2514. if (empty($encoding)) {
  2515. $encoding = _api_mb_internal_encoding();
  2516. }
  2517. $collator = _api_get_alpha_numerical_collator($language);
  2518. if (is_object($collator)) {
  2519. global $_api_collator, $_api_encoding;
  2520. $_api_collator = $collator;
  2521. $_api_encoding = $encoding;
  2522. return uasort($array, '_api_rcmp');
  2523. }
  2524. }
  2525. return uasort($array, '_api_strnatrcmp');
  2526. }
  2527. /**
  2528. * Sorts an array using natural order algorithm, case-insensitive.
  2529. * @param array $array The input array.
  2530. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2531. * @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.
  2532. * @return bool Returns TRUE on success, FALSE on error.
  2533. * This function is aimed at replacing the function natcasesort() for sorting human-language strings.
  2534. * @link http://php.net/manual/en/function.natcasesort.php
  2535. */
  2536. function api_natcasesort(&$array, $language = null, $encoding = null) {
  2537. if (INTL_INSTALLED) {
  2538. if (empty($encoding)) {
  2539. $encoding = _api_mb_internal_encoding();
  2540. }
  2541. $collator = _api_get_alpha_numerical_collator($language);
  2542. if (is_object($collator)) {
  2543. global $_api_collator, $_api_encoding;
  2544. $_api_collator = $collator;
  2545. $_api_encoding = $encoding;
  2546. return uasort($array, '_api_casecmp');
  2547. }
  2548. }
  2549. return natcasesort($array);
  2550. }
  2551. /**
  2552. * Sorts an array using natural order algorithm, case-insensitive, reverse order.
  2553. * @param array $array The input array.
  2554. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2555. * @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.
  2556. * @return bool Returns TRUE on success, FALSE on error.
  2557. */
  2558. function api_natcasersort(&$array, $language = null, $encoding = null) {
  2559. if (INTL_INSTALLED) {
  2560. if (empty($encoding)) {
  2561. $encoding = _api_mb_internal_encoding();
  2562. }
  2563. $collator = _api_get_alpha_numerical_collator($language);
  2564. if (is_object($collator)) {
  2565. global $_api_collator, $_api_encoding;
  2566. $_api_collator = $collator;
  2567. $_api_encoding = $encoding;
  2568. return uasort($array, '_api_casercmp');
  2569. }
  2570. }
  2571. return uasort($array, '_api_strnatcasercmp');
  2572. }
  2573. /**
  2574. * Sorts an array by keys, elements will be arranged from the lowest key to the highest key.
  2575. * @param array $array The input array.
  2576. * @param int $sort_flag (optional) Shows how keys of the array to be compared.
  2577. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2578. * @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.
  2579. * @return bool Returns TRUE on success, FALSE on error.
  2580. * Note: $sort_flag may have the following values:
  2581. * SORT_REGULAR - internal PHP-rules for comparison will be applied, without preliminary changing types;
  2582. * SORT_NUMERIC - keys will be compared as numbers;
  2583. * SORT_STRING - keys will be compared as strings. If intl extension is enabled, then comparison will be language-sensitive using internally a created ICU locale;
  2584. * SORT_LOCALE_STRING - keys will be compared as strings depending on the current POSIX locale. If intl extension is enabled, then comparison will be language-sensitive using internally a created ICU locale.
  2585. * This function is aimed at replacing the function ksort() for sorting human-language key strings.
  2586. * @link http://php.net/manual/en/function.ksort.php
  2587. */
  2588. function api_ksort(&$array, $sort_flag = SORT_REGULAR, $language = null, $encoding = null) {
  2589. if (INTL_INSTALLED) {
  2590. if (empty($encoding)) {
  2591. $encoding = _api_mb_internal_encoding();
  2592. }
  2593. $collator = _api_get_collator($language);
  2594. if (is_object($collator)) {
  2595. if ($sort_flag == SORT_STRING || $sort_flag == SORT_LOCALE_STRING) {
  2596. global $_api_collator, $_api_encoding;
  2597. $_api_collator = $collator;
  2598. $_api_encoding = $encoding;
  2599. return uksort($array, '_api_cmp');
  2600. }
  2601. }
  2602. }
  2603. return ksort($array, $sort_flag);
  2604. }
  2605. /**
  2606. * Sorts an array by keys, elements will be arranged from the highest key to the lowest key (in reverse order).
  2607. * @param array $array The input array.
  2608. * @param int $sort_flag (optional) Shows how keys of the array to be compared.
  2609. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2610. * @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.
  2611. * @return bool Returns TRUE on success, FALSE on error.
  2612. * Note: $sort_flag may have the following values:
  2613. * SORT_REGULAR - internal PHP-rules for comparison will be applied, without preliminary changing types;
  2614. * SORT_NUMERIC - keys will be compared as numbers;
  2615. * SORT_STRING - keys will be compared as strings. If intl extension is enabled, then comparison will be language-sensitive using internally a created ICU locale;
  2616. * SORT_LOCALE_STRING - keys will be compared as strings depending on the current POSIX locale. If intl extension is enabled, then comparison will be language-sensitive using internally a created ICU locale.
  2617. * This function is aimed at replacing the function krsort() for sorting human-language key strings.
  2618. * @link http://php.net/manual/en/function.krsort.php
  2619. */
  2620. function api_krsort(&$array, $sort_flag = SORT_REGULAR, $language = null, $encoding = null) {
  2621. if (INTL_INSTALLED) {
  2622. if (empty($encoding)) {
  2623. $encoding = _api_mb_internal_encoding();
  2624. }
  2625. $collator = _api_get_collator($language);
  2626. if (is_object($collator)) {
  2627. if ($sort_flag == SORT_STRING || $sort_flag == SORT_LOCALE_STRING) {
  2628. global $_api_collator, $_api_encoding;
  2629. $_api_collator = $collator;
  2630. $_api_encoding = $encoding;
  2631. return uksort($array, '_api_rcmp');
  2632. }
  2633. }
  2634. }
  2635. return krsort($array, $sort_flag);
  2636. }
  2637. /**
  2638. * Sorts an array by keys using natural order algorithm.
  2639. * @param array $array The input array.
  2640. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2641. * @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.
  2642. * @return bool Returns TRUE on success, FALSE on error.
  2643. */
  2644. function api_knatsort(&$array, $language = null, $encoding = null) {
  2645. if (INTL_INSTALLED) {
  2646. if (empty($encoding)) {
  2647. $encoding = _api_mb_internal_encoding();
  2648. }
  2649. $collator = _api_get_alpha_numerical_collator($language);
  2650. if (is_object($collator)) {
  2651. global $_api_collator, $_api_encoding;
  2652. $_api_collator = $collator;
  2653. $_api_encoding = $encoding;
  2654. return uksort($array, '_api_cmp');
  2655. }
  2656. }
  2657. return uksort($array, 'strnatcmp');
  2658. }
  2659. /**
  2660. * Sorts an array by keys using natural order algorithm in reverse order.
  2661. * @param array $array The input array.
  2662. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2663. * @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.
  2664. * @return bool Returns TRUE on success, FALSE on error.
  2665. */
  2666. function api_knatrsort(&$array, $language = null, $encoding = null) {
  2667. if (INTL_INSTALLED) {
  2668. if (empty($encoding)) {
  2669. $encoding = _api_mb_internal_encoding();
  2670. }
  2671. $collator = _api_get_alpha_numerical_collator($language);
  2672. if (is_object($collator)) {
  2673. global $_api_collator, $_api_encoding;
  2674. $_api_collator = $collator;
  2675. $_api_encoding = $encoding;
  2676. return uksort($array, '_api_rcmp');
  2677. }
  2678. }
  2679. return uksort($array, '_api_strnatrcmp');
  2680. }
  2681. /**
  2682. * Sorts an array by keys using natural order algorithm, case insensitive.
  2683. * @param array $array The input array.
  2684. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2685. * @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.
  2686. * @return bool Returns TRUE on success, FALSE on error.
  2687. */
  2688. function api_knatcasesort(&$array, $language = null, $encoding = null) {
  2689. if (INTL_INSTALLED) {
  2690. if (empty($encoding)) {
  2691. $encoding = _api_mb_internal_encoding();
  2692. }
  2693. $collator = _api_get_alpha_numerical_collator($language);
  2694. if (is_object($collator)) {
  2695. global $_api_collator, $_api_encoding;
  2696. $_api_collator = $collator;
  2697. $_api_encoding = $encoding;
  2698. return uksort($array, '_api_casecmp');
  2699. }
  2700. }
  2701. return uksort($array, 'strnatcasecmp');
  2702. }
  2703. /**
  2704. * Sorts an array by keys using natural order algorithm, case insensitive, reverse order.
  2705. * @param array $array The input array.
  2706. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2707. * @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.
  2708. * @return bool Returns TRUE on success, FALSE on error.
  2709. */
  2710. function api_knatcasersort(&$array, $language = null, $encoding = null) {
  2711. if (INTL_INSTALLED) {
  2712. if (empty($encoding)) {
  2713. $encoding = _api_mb_internal_encoding();
  2714. }
  2715. $collator = _api_get_alpha_numerical_collator($language);
  2716. if (is_object($collator)) {
  2717. global $_api_collator, $_api_encoding;
  2718. $_api_collator = $collator;
  2719. $_api_encoding = $encoding;
  2720. return uksort($array, '_api_casercmp');
  2721. }
  2722. }
  2723. return uksort($array, '_api_strnatcasercmp');
  2724. }
  2725. /**
  2726. * Sorts an array, elements will be arranged from the lowest to the highest.
  2727. * @param array $array The input array.
  2728. * @param int $sort_flag (optional) Shows how elements of the array to be compared.
  2729. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2730. * @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.
  2731. * @return bool Returns TRUE on success, FALSE on error.
  2732. * Note: $sort_flag may have the following values:
  2733. * SORT_REGULAR - internal PHP-rules for comparison will be applied, without preliminary changing types;
  2734. * SORT_NUMERIC - items will be compared as numbers;
  2735. * SORT_STRING - items will be compared as strings. If intl extension is enabled, then comparison will be language-sensitive using internally a created ICU locale;
  2736. * SORT_LOCALE_STRING - items will be compared as strings depending on the current POSIX locale. If intl extension is enabled, then comparison will be language-sensitive using internally a created ICU locale.
  2737. * This function is aimed at replacing the function sort() for sorting human-language strings.
  2738. * @link http://php.net/manual/en/function.sort.php
  2739. * @link http://php.net/manual/en/collator.sort.php
  2740. */
  2741. function api_sort(&$array, $sort_flag = SORT_REGULAR, $language = null, $encoding = null) {
  2742. if (INTL_INSTALLED) {
  2743. if (empty($encoding)) {
  2744. $encoding = _api_mb_internal_encoding();
  2745. }
  2746. $collator = _api_get_collator($language);
  2747. if (is_object($collator)) {
  2748. if (api_is_utf8($encoding)) {
  2749. $sort_flag = ($sort_flag == SORT_LOCALE_STRING) ? SORT_STRING : $sort_flag;
  2750. return collator_sort($collator, $array, _api_get_collator_sort_flag($sort_flag));
  2751. } elseif ($sort_flag == SORT_STRING || $sort_flag == SORT_LOCALE_STRING) {
  2752. global $_api_collator, $_api_encoding;
  2753. $_api_collator = $collator;
  2754. $_api_encoding = $encoding;
  2755. return usort($array, '_api_cmp');
  2756. }
  2757. }
  2758. }
  2759. return sort($array, $sort_flag);
  2760. }
  2761. /**
  2762. * Sorts an array, elements will be arranged from the highest to the lowest (in reverse order).
  2763. * @param array $array The input array.
  2764. * @param int $sort_flag (optional) Shows how elements of the array to be compared.
  2765. * @param string $language (optional) The language in which comparison is to be made. If language is omitted, interface language is assumed then.
  2766. * @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.
  2767. * @return bool Returns TRUE on success, FALSE on error.
  2768. * Note: $sort_flag may have the following values:
  2769. * SORT_REGULAR - internal PHP-rules for comparison will be applied, without preliminary changing types;
  2770. * SORT_NUMERIC - items will be compared as numbers;
  2771. * SORT_STRING - items will be compared as strings. If intl extension is enabled, then comparison will be language-sensitive using internally a created ICU locale;
  2772. * SORT_LOCALE_STRING - items will be compared as strings depending on the current POSIX locale. If intl extension is enabled, then comparison will be language-sensitive using internally a created ICU locale.
  2773. * This function is aimed at replacing the function rsort() for sorting human-language strings.
  2774. * @link http://php.net/manual/en/function.rsort.php
  2775. */
  2776. function api_rsort(&$array, $sort_flag = SORT_REGULAR, $language = null, $encoding = null) {
  2777. if (INTL_INSTALLED) {
  2778. if (empty($encoding)) {
  2779. $encoding = _api_mb_internal_encoding();
  2780. }
  2781. $collator = _api_get_collator($language);
  2782. if (is_object($collator)) {
  2783. if ($sort_flag == SORT_STRING || $sort_flag == SORT_LOCALE_STRING) {
  2784. global $_api_collator, $_api_encoding;
  2785. $_api_collator = $collator;
  2786. $_api_encoding = $encoding;
  2787. return usort($array, '_api_rcmp');
  2788. }
  2789. }
  2790. }
  2791. return rsort($array, $sort_flag);
  2792. }
  2793. /**
  2794. * Common sting operations with arrays
  2795. */
  2796. /**
  2797. * Checks if a value exists in an array, a case insensitive version of in_array() function with extended multibyte support.
  2798. * @param mixed $needle The searched value. If needle is a string, the comparison is done in a case-insensitive manner.
  2799. * @param array $haystack The array.
  2800. * @param bool $strict (optional) If is set to TRUE then the function will also check the types of the $needle in the $haystack. The default value if FALSE.
  2801. * @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.
  2802. * @return bool Returns TRUE if $needle is found in the array, FALSE otherwise.
  2803. * @link http://php.net/manual/en/function.in-array.php
  2804. */
  2805. function api_in_array_nocase($needle, $haystack, $strict = false, $encoding = null) {
  2806. if (is_array($needle)) {
  2807. foreach ($needle as $item) {
  2808. if (api_in_array_nocase($item, $haystack, $strict, $encoding)) return true;
  2809. }
  2810. return false;
  2811. }
  2812. if (!is_string($needle)) {
  2813. return in_array($needle, $haystack, $strict);
  2814. }
  2815. $needle = api_strtolower($needle, $encoding);
  2816. if (!is_array($haystack)) {
  2817. return false;
  2818. }
  2819. foreach ($haystack as $item) {
  2820. if ($strict && !is_string($item)) {
  2821. continue;
  2822. }
  2823. if (api_strtolower($item, $encoding) == $needle) {
  2824. return true;
  2825. }
  2826. }
  2827. return false;
  2828. }
  2829. /**
  2830. * Encoding management functions
  2831. */
  2832. /**
  2833. * This function unifies the encoding identificators, so they could be compared.
  2834. * @param string/array $encoding The specified encoding.
  2835. * @return string Returns the encoding identificator modified in suitable for comparison way.
  2836. */
  2837. function api_refine_encoding_id($encoding) {
  2838. if (is_array($encoding)){
  2839. return array_map('api_refine_encoding_id', $encoding);
  2840. }
  2841. return strtoupper(str_replace('_', '-', $encoding));
  2842. }
  2843. /**
  2844. * This function checks whether two $encoding are equal (same, equvalent).
  2845. * @param string/array $encoding1 The first encoding
  2846. * @param string/array $encoding2 The second encoding
  2847. * @param bool $strict When this parameter is TRUE the comparison ignores aliases of encodings. When the parameter is FALSE, aliases are taken into account.
  2848. * @return bool Returns TRUE if the encodings are equal, FALSE otherwise.
  2849. */
  2850. function api_equal_encodings($encoding1, $encoding2, $strict = false) {
  2851. static $equal_encodings = array();
  2852. if (is_array($encoding1)) {
  2853. foreach ($encoding1 as $encoding) {
  2854. if (api_equal_encodings($encoding, $encoding2, $strict)) {
  2855. return true;
  2856. }
  2857. }
  2858. return false;
  2859. }
  2860. elseif (is_array($encoding2)) {
  2861. foreach ($encoding2 as $encoding) {
  2862. if (api_equal_encodings($encoding1, $encoding, $strict)) {
  2863. return true;
  2864. }
  2865. }
  2866. return false;
  2867. }
  2868. if (!isset($equal_encodings[$encoding1][$encoding2][$strict])) {
  2869. $encoding_1 = api_refine_encoding_id($encoding1);
  2870. $encoding_2 = api_refine_encoding_id($encoding2);
  2871. if ($encoding_1 == $encoding_2) {
  2872. $result = true;
  2873. } else {
  2874. if ($strict) {
  2875. $result = false;
  2876. } else {
  2877. $alias1 = _api_get_character_map_name($encoding_1);
  2878. $alias2 = _api_get_character_map_name($encoding_2);
  2879. $result = !empty($alias1) && !empty($alias2) && $alias1 == $alias2;
  2880. }
  2881. }
  2882. $equal_encodings[$encoding1][$encoding2][$strict] = $result;
  2883. }
  2884. return $equal_encodings[$encoding1][$encoding2][$strict];
  2885. }
  2886. /**
  2887. * This function checks whether a given encoding is UTF-8.
  2888. * @param string $encoding The tested encoding.
  2889. * @return bool Returns TRUE if the given encoding id means UTF-8, otherwise returns false.
  2890. */
  2891. function api_is_utf8($encoding) {
  2892. static $result = array();
  2893. if (!isset($result[$encoding])) {
  2894. $result[$encoding] = api_equal_encodings($encoding, 'UTF-8');
  2895. }
  2896. return $result[$encoding];
  2897. }
  2898. /**
  2899. * This function checks whether a given encoding represents (is an alias of) ISO Latin 1 character set.
  2900. * @param string/array $encoding The tested encoding.
  2901. * @param bool $strict Flag for check precision. ISO-8859-1 is always Latin 1. When $strict is false, ISO-8859-15 is assumed as Latin 1 too.
  2902. * @return bool Returns TRUE if the given encoding id means Latin 1 character set, otherwise returns false.
  2903. */
  2904. function api_is_latin1($encoding, $strict = false) {
  2905. static $latin1 = array();
  2906. static $latin1_strict = array();
  2907. if ($strict) {
  2908. if (!isset($latin1_strict[$encoding])) {
  2909. $latin1_strict[$encoding] = api_equal_encodings($encoding, array('ISO-8859-1', 'ISO8859-1', 'CP819', 'LATIN1'));
  2910. }
  2911. return $latin1_strict[$encoding];
  2912. }
  2913. if (!isset($latin1[$encoding])) {
  2914. $latin1[$encoding] = api_equal_encodings($encoding, array(
  2915. 'ISO-8859-1', 'ISO8859-1', 'CP819', 'LATIN1',
  2916. 'ISO-8859-15', 'ISO8859-15', 'CP923', 'LATIN0', 'LATIN-9',
  2917. 'WINDOWS-1252', 'CP1252', 'WIN-1252', 'WIN1252'
  2918. ));
  2919. }
  2920. return $latin1[$encoding];
  2921. }
  2922. /**
  2923. * This function returns the encoding, currently used by the system.
  2924. * @return string The system's encoding.
  2925. * Note: The value of api_get_setting('platform_charset') is tried to be returned first,
  2926. * on the second place the global variable $charset is tried to be returned. If for some
  2927. * reason both attempts fail, then the libraly's internal value will be returned.
  2928. */
  2929. function api_get_system_encoding() {
  2930. static $system_encoding;
  2931. if (!isset($system_encoding)) {
  2932. $encoding_setting = api_get_setting('platform_charset');
  2933. if (empty($encoding_setting)) {
  2934. global $charset;
  2935. if (empty($charset)) {
  2936. return _api_mb_internal_encoding();
  2937. }
  2938. return $charset;
  2939. }
  2940. $system_encoding = $encoding_setting;
  2941. }
  2942. return $system_encoding;
  2943. }
  2944. /**
  2945. * This function returns the encoding, currently used by the file system.
  2946. * @return string The file system's encoding, it depends on the locale that OS currently uses.
  2947. * @link http://php.net/manual/en/function.setlocale.php
  2948. * Note: For Linux systems, to see all installed locales type in a terminal locale -a
  2949. */
  2950. function api_get_file_system_encoding() {
  2951. static $file_system_encoding;
  2952. if (!isset($file_system_encoding)) {
  2953. $locale = setlocale(LC_CTYPE, '0');
  2954. $seek_pos = strpos($locale, '.');
  2955. if ($seek_pos !== false) {
  2956. $file_system_encoding = substr($locale, $seek_pos + 1);
  2957. if (IS_WINDOWS_OS) {
  2958. $file_system_encoding = 'CP'.$file_system_encoding;
  2959. }
  2960. }
  2961. // Dealing with some aliases.
  2962. $file_system_encoding = str_ireplace('utf8', 'UTF-8', $file_system_encoding);
  2963. $file_system_encoding = preg_replace('/^CP65001$/', 'UTF-8', $file_system_encoding);
  2964. $file_system_encoding = preg_replace('/^CP(125[0-9])$/', 'WINDOWS-\1', $file_system_encoding);
  2965. $file_system_encoding = str_replace('WINDOWS-1252', 'ISO-8859-15', $file_system_encoding);
  2966. if (empty($file_system_encoding)) {
  2967. if (IS_WINDOWS_OS) {
  2968. // Not expected for Windows, this assignment is here just in case.
  2969. $file_system_encoding = api_get_system_encoding();
  2970. } else {
  2971. // For Ububntu and other UTF-8 enabled Linux systems this fits with the default settings.
  2972. $file_system_encoding = 'UTF-8';
  2973. }
  2974. }
  2975. }
  2976. return $file_system_encoding;
  2977. }
  2978. /**
  2979. * Checks whether a specified encoding is supported by this API.
  2980. * @param string $encoding The specified encoding.
  2981. * @return bool Returns TRUE when the specified encoding is supported, FALSE othewise.
  2982. */
  2983. function api_is_encoding_supported($encoding) {
  2984. static $supported = array();
  2985. if (!isset($supported[$encoding])) {
  2986. $supported[$encoding] = _api_mb_supports($encoding) || _api_iconv_supports($encoding) || _api_convert_encoding_supports($encoding);
  2987. }
  2988. return $supported[$encoding];
  2989. }
  2990. /**
  2991. * Returns in an array the most-probably used non-UTF-8 encoding for the given language.
  2992. * The first (leading) value is actually used by the system at the moment.
  2993. * @param string $language (optional) The specified language, the default value is the user intrface language.
  2994. * @return string The correspondent encoding to the specified language.
  2995. * Note: See the file chamilo/main/inc/lib/internationalization_database/non_utf8_encodings.php
  2996. * if you wish to revise the leading non-UTF-8 encoding for your language.
  2997. */
  2998. function api_get_non_utf8_encoding($language = null)
  2999. {
  3000. $language_is_supported = api_is_language_supported($language);
  3001. if (!$language_is_supported || empty($language)) {
  3002. $language = api_get_interface_language(false, true);
  3003. }
  3004. $language = api_purify_language_id($language);
  3005. $encodings = & _api_non_utf8_encodings();
  3006. if (is_array($encodings[$language])) {
  3007. if (!empty($encodings[$language][0])) {
  3008. return $encodings[$language][0];
  3009. }
  3010. return null;
  3011. }
  3012. return null;
  3013. }
  3014. /**
  3015. * Return a list of valid encodings for setting platform character set.
  3016. * @return array List of valid encodings, preferably IANA-registared.
  3017. */
  3018. function api_get_valid_encodings() {
  3019. $encodings = & _api_non_utf8_encodings();
  3020. if (!is_array($encodings)) {
  3021. $encodings = array('english', array('ISO-8859-15'));
  3022. }
  3023. $result1 = array();
  3024. $result2 = array();
  3025. $result3 = array();
  3026. foreach ($encodings as $value) {
  3027. if (!empty($value)) {
  3028. $encoding = api_refine_encoding_id(trim($value[0]));
  3029. if (!empty($encoding)) {
  3030. if (strpos($encoding, 'ISO-') === 0) {
  3031. $result1[] = $encoding;
  3032. } elseif (strpos($encoding, 'WINDOWS-') === 0) {
  3033. $result2[] = $encoding;
  3034. } else {
  3035. $result3[] = $encoding;
  3036. }
  3037. }
  3038. }
  3039. }
  3040. $result1 = array_unique($result1);
  3041. $result2 = array_unique($result2);
  3042. $result3 = array_unique($result3);
  3043. natsort($result1);
  3044. natsort($result2);
  3045. natsort($result3);
  3046. return array_merge(array('UTF-8'), $result1, $result2, $result3);
  3047. }
  3048. /**
  3049. * Detects encoding of plain text.
  3050. * @param string $string The input text.
  3051. * @param string $language (optional) The language of the input text, provided if it is known.
  3052. * @return string Returns the detected encoding.
  3053. */
  3054. function api_detect_encoding($string, $language = null) {
  3055. // Testing against valid UTF-8 first.
  3056. if (api_is_valid_utf8($string)) {
  3057. return 'UTF-8';
  3058. }
  3059. $result = null;
  3060. $delta_points_min = LANGUAGE_DETECT_MAX_DELTA;
  3061. // Testing non-UTF-8 encodings.
  3062. $encodings = api_get_valid_encodings();
  3063. foreach ($encodings as & $encoding) {
  3064. if (api_is_encoding_supported($encoding) && !api_is_utf8($encoding)) {
  3065. $stringToParse = api_substr($string, 0, LANGUAGE_DETECT_MAX_LENGTH, $encoding);
  3066. $strintToParse2 = _api_generate_n_grams(
  3067. $stringToParse,
  3068. $encoding
  3069. );
  3070. $result_array = _api_compare_n_grams(
  3071. $strintToParse2,
  3072. $encoding
  3073. );
  3074. if (!empty($result_array)) {
  3075. list($key, $delta_points) = each($result_array);
  3076. if ($delta_points < $delta_points_min) {
  3077. $pos = strpos($key, ':');
  3078. $result_encoding = api_refine_encoding_id(substr($key, $pos + 1));
  3079. if (api_equal_encodings($encoding, $result_encoding)) {
  3080. if ($string == api_utf8_decode(api_utf8_encode($string, $encoding), $encoding)) {
  3081. $delta_points_min = $delta_points;
  3082. $result = $encoding;
  3083. }
  3084. }
  3085. }
  3086. }
  3087. }
  3088. }
  3089. // "Broken" UTF-8 texts are to be detected as UTF-8.
  3090. // This functionality is enabled when language of the text is known.
  3091. $language = api_purify_language_id((string)$language);
  3092. if (!empty($language)) {
  3093. $encoding = 'UTF-8';
  3094. $result_array = & _api_compare_n_grams(_api_generate_n_grams(api_substr($string, 0, LANGUAGE_DETECT_MAX_LENGTH, $encoding), $encoding), $encoding);
  3095. if (!empty($result_array)) {
  3096. list($key, $delta_points) = each($result_array);
  3097. if ($delta_points < $delta_points_min) {
  3098. $pos = strpos($key, ':');
  3099. $result_encoding = api_refine_encoding_id(substr($key, $pos + 1));
  3100. $result_language = substr($key, 0, $pos);
  3101. if ($language == $result_language && api_is_utf8($result_encoding)) {
  3102. $delta_points_min = $delta_points;
  3103. $result = $encoding;
  3104. }
  3105. }
  3106. }
  3107. }
  3108. return $result;
  3109. }
  3110. /**
  3111. * String validation functions concerning certain encodings
  3112. */
  3113. /**
  3114. * Checks a string for UTF-8 validity.
  3115. *
  3116. * @deprecated Use Encoding::utf8()->is_valid() instead
  3117. */
  3118. function api_is_valid_utf8(&$string) {
  3119. return Encoding::utf8()->is_valid($string);
  3120. }
  3121. /**
  3122. * Checks whether a string contains 7-bit ASCII characters only.
  3123. * @param string $string The string to be tested/validated.
  3124. * @return bool Returns TRUE when the tested string contains 7-bit ASCII characters only, FALSE othewise.
  3125. */
  3126. function api_is_valid_ascii(&$string) {
  3127. if (MBSTRING_INSTALLED) {
  3128. return @mb_detect_encoding($string, 'ASCII', true) == 'ASCII' ? true : false;
  3129. }
  3130. return !preg_match('/[^\x00-\x7F]/S', $string);
  3131. }
  3132. /**
  3133. * Return true a date is valid
  3134. * @param string $date example: 2014-06-30 13:05:05
  3135. * @param string $format example: "Y-m-d H:i:s"
  3136. *
  3137. * @return bool
  3138. */
  3139. function api_is_valid_date($date, $format = 'Y-m-d H:i:s') {
  3140. $d = DateTime::createFromFormat($format, $date);
  3141. return $d && $d->format($format) == $date;
  3142. }
  3143. /**
  3144. * Return the encoding country code for jquery datepicker
  3145. * used for exemple in main/exercice/exercise_report.php
  3146. */
  3147. function get_datepicker_langage_code() {
  3148. $languaje = 'en-GB';
  3149. $platform_isocode = strtolower(api_get_language_isocode());
  3150. // languages supported by jqgrid see files in main/inc/lib/javascript/jqgrid/js/i18n
  3151. $datapicker_langs = array('af', 'ar', 'ar-DZ', 'az', 'bg', 'bs', 'ca', 'cs', 'cy-GB', 'da', 'de', 'el', 'en-AU', 'en-GB', 'en-NZ', 'eo', 'es', 'et', 'eu', 'fa', 'fi', 'fo', 'fr', 'fr-CH', 'gl', 'he', 'hi', 'hr', 'hu', 'hy', 'id', 'is', 'it', 'ja', 'ka', 'kk', 'km', 'ko', 'lb', 'lt', 'lv', 'mk', 'ml', 'ms', 'nl', 'nl-BE', 'no', 'pl', 'pt', 'pt-BR', 'rm', 'ro', 'ru', 'sk', 'sl', 'sq', 'sr', 'sr-SR', 'sv', 'ta', 'th', 'tj', 'tr', 'uk', 'vi', 'zh-CN', 'zh-HK', 'zh-TW');
  3152. if (in_array($platform_isocode, $datapicker_langs)) {
  3153. $languaje = $platform_isocode;
  3154. }
  3155. return $languaje;
  3156. }
  3157. /**
  3158. * Returns the variable translated
  3159. * @param $variable the string to translate
  3160. * @param $pluginName the Plugin name
  3161. * @return string the variable translated
  3162. */
  3163. function get_plugin_lang($variable, $pluginName) {
  3164. eval("\$plugin = {$pluginName}::create();");
  3165. return $plugin->get_lang($variable);
  3166. }
  3167. /**
  3168. * Functions for internal use behind this API
  3169. */
  3170. require_once dirname(__FILE__).'/internationalization_internal.lib.php';