internationalization.lib.php 138 KB

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