internationalization.lib.test.php 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * This is a test of internationalization.lib.php which is
  5. * a common purpose library for supporting internationalization
  6. * related functions. Only the public API is tested here.
  7. * @author Ricardo Rodriguez Salazar, 2009.
  8. * @author Ivan Tcholakov, 2009-2010.
  9. *
  10. * Notes:
  11. * 1. While saving this file, please, preserve its UTF-8 encoding.
  12. * Othewise this test would be broken.
  13. * 2. While running this test, send a header declaring UTF-8 encoding.
  14. * Then you would see variable dumps correctly.
  15. * 3. Tests about string comparison and sorting might give false results
  16. * if the intl extension has not been installed.
  17. */
  18. class TestInternationalization extends UnitTestCase {
  19. private $language_strings = array( // All these strings are UTF-8 encoded.
  20. 'afrikaans' => "Hy laat my in groen weivelde rus. Hy bring my by waters waar daar vrede is.",
  21. 'albanian' => "Çdokush prej jush mund të kontribuojë vullnetarisht me dijen e tij për zgjerimin e mëtejshëm të kësaj enciklopedie të lirë.",
  22. 'alemannic' => "Das bedütet, dass a dem Projekt alli chöi teilnä, wo en alemannischi Dialektspilart beherrsche, wo da gredt wird.",
  23. 'amharic' => "ዳግማዊ ፡ ምኒልክ ፡ ንጉሠ ፡ ነገሥት ፡ ዘኢትዮጵያ ።",
  24. 'arabic' => "ما اسمك؟",
  25. 'armenian' => "Ընդհանուր տեղեկություններ, կառավարման համակարգ, ժողովրդագրություն և աշխարհագրական տվյալներ:",
  26. 'asturian' => "La ortografía nun ye fonolóxica sinon histórica, tando considerada como una de les llingües más abegoses d'aprender de les qu'usen esi alfabetu.",
  27. 'belarusian' => "Умоўным часам пачатку гісторыі сучаснай беларускай літаратурнай мовы лічыцца пачатак 19 стагоддзя.",
  28. 'bosnian' => "Engleski jezik je nastao iz jezika germanskih plemena koja su se u kasnom starom vijeku naselila na jugoistoku otoka Velike Britanije.",
  29. 'brazilian' => "O governo federal irá zerar o número de municípios sem bibliotecas este ano. De acordo com o Sistema Nacional de Bibliotecas Públicas, 661 municípios ainda não têm esses equipamentos. Se sua cidade não estiver nesta relação e não possuir biblioteca pública municipal, informe aqui. A cultura é um direito de todo o cidadão!",
  30. 'breton' => "Hon Tad, c'hwi hag a zo en Neñv, ra vo santelaet hoc'h ano. Ra zeuio ho Rouantelezh.",
  31. 'bulgarian' => "Глобалното затопляне ще освободи Северния ледовит океан от ледовете през лятото през следващите 20 години.",
  32. 'catalan' => "Els drets juridicolingüístics dels catalanoparlants són ben diferents segons l'indret geogràfic, podem parlar de catalanoparlants de primera i de segona.",
  33. 'croatian' => "Oče naš, koji jesi na nebesima, sveti se ime Tvoje. Dođi kraljevstvo Tvoje, budi volja Tvoja, kako na Nebu, tako i na Zemlji.",
  34. 'czech' => "V převážné většině mezinárodních škol je vyučovacím jazykem angličtina.",
  35. 'danish' => "Et ganske særligt kendetegn ved dansk er stød.",
  36. 'dari' => "جمعیت افغانستان حدود ۳۰ میلیون نفر برآورد می‌شود. براساس سرشماری مقدماتی کمیته ملی احصائیه کشور، جمعیت افغانستان در سال ۱۳۸۵، ۲۴ میلیون",
  37. 'dutch' => "De officiële taal, zoals die wordt onderwezen op scholen en gebruikt wordt door de autoriteiten, wordt Standaardnederlands genoemd.",
  38. 'english' => "Approximately 375 million people speak English as their first language.",
  39. 'esperanto' => "La vortprovizo de Esperanto devenas plejparte el la okcidenteŭropaj lingvoj, dum ĝia sintakso kaj morfologio montras ankaŭ slavlingvan influon.",
  40. 'estonian' => "Ta eelistab lubjarikast pinnast, kuid kasvab ka settelistel muldadel ja väheviljakal pinnasel, kus teisi puittaimi ei leidu.",
  41. 'basque' => "Euskaren gramatika zailtasun handikoa da, horrez gain, hizkuntza indoeuroparra ez izanik, eratze edo joskera bereziak ditu, beste hizkuntzetan aurkitu ez ditzakegunak.",
  42. 'finnish' => "Nominit taipuvat sijoissa eli sijamuodoissa yleensä sekä yksikössä että monikossa.",
  43. 'french' => "La majorité du fonds lexical français provient du latin (en tant que langue-mère) ou bien est construit à partir des racines gréco-latines.",
  44. 'frisian' => "Us Heit, dy't yn de himelen is jins namme wurde hillige. Jins keninkryk komme.",
  45. 'friulian' => "Mandi, jo mi clami Jacum! Vuê al è propite cjalt! O scugni propite lâ cumò, ariviodisi.",
  46. 'galician' => "Se borrarán todos los comentarios que, con criterio subjetivo como en toda web, se consideren inadecuados.",
  47. 'georgian' => "საკუთარ პერიოდში ბუგერო მსოფლიოს ერთ-ერთ უდიდეს მხატვრად იყო აღიარებული, თუმცა მე-20 საუკუნის დასაწყისში მას უკვე არაფრად აგდებდნენ, შესაძლოა მისი იმპრესიონისტთა მიმართ აგრესიულობის გამო. მიუხედავად ამისა, დღეს მას თაყვანისმცემლების ახალი დიდი ტალღა შეემატა - მისი ნამუშევრები მსოფლიოს ასზე მეტ უდიდეს მუზეუმშია გამოფენილი.",
  48. 'german' => "Durch ihre zentrale Lage in Europa wurde die deutsche Sprache über die Jahrhunderte durch andere Sprachen beeinflusst.",
  49. 'greek' => "Η ναυτική βιομηχανία αποτέλεσε ένα σημαντικό στοιχείο της Ελληνικής οικονομικής δραστηριότητας από τα αρχαία χρόνια.",
  50. 'hawaiian' => "A ma mua o ka hō'ea 'ana i Tahiti, ua ho'okele maila lākou mai Sāmoa a Tonga paha.",
  51. 'hebrew' => "שימו לב: אם עדיין לא נרשמתם, ייתכן כי חלק מהתכונות אינן זמינות לכם. במקרה זה רצוי ליצור חשבון חדש, פעולה האורכת מספר דקות בלבד. ראו איך ליצור חשבון חדש.",
  52. 'hindi' => "साइट का लिंक लगाने के लिए निम्नांकित फार्मेट में उपयुक्त कक्ष में/या नया कक्ष बना कर लिखें :",
  53. 'hungarian' => "A magyar nyelv az uráli nyelvcsalád tagja, a finnugor nyelvek közé tartozó ugor nyelvek egyike.",
  54. 'icelandic' => "Margir Íslendingar telja íslenskuna vera „upprunalegra“ mál en flest önnur og að hún hafi breyst minna.",
  55. 'indonesian' => "Selain itu, Baristand senantiasa meningkatkan kualitas personil dan berbagai fasilitas pendukung industri, serta fasilitas lainnya yaitu perpustakaan dengan buku-buku ilmiah, laporan hasil penelitian, dan majalah ilmiah.",
  56. 'irish' => "háinig críoch dheifnideach lena chuid scríbhneoireachta nuair a cuireadh i dteach na ngealt é agus síocóis dhúlagrach ag luí ar a intinn.",
  57. 'italian' => "Tuttavia l'assetto attuale della lingua è in sostanza quello del fiorentino trecentesco, ripulito dei tratti più marcatamente locali.",
  58. 'japanese' => "日本語(にほんご、にっぽんご)は、主として、日本で使用されてきた言語である。日本国は法令上、公用語を明記していないが、事実上の公用語となっており、学校教育の「国語」で教えられる。",
  59. 'korean' => "이 문서는 삭제되었습니다. 이 문서의 삭제/이동 기록은 다음과 같습니다.",
  60. 'latin' => "Architecti est scientia pluribus disciplinis et variis eruditionibus ornata, cuius iudicio probantur omnia quae ab ceteris artibus perficiuntur opera.",
  61. 'latvian' => "Tas visvairāk ir vērojams jaunu terminu darināšanā, kas bieži izsauc arī negatīvu reakciju.",
  62. 'lithuanian' => "Dabartinės literatūrinės kalbos pagrindas remiasi vakarų aukštaičių pietiečių (suvalkiečių) tarme, išlaikiusia senesnes fonetikos ir morfologijos lytis.",
  63. 'macedonian' => "Залагањето за создавање на македонски литературен јазик датира уште од почетокот на XIX век, со појавата на Просветителите.",
  64. 'malay' => "Suntingan yang tidak sesuai akan dikeluarkan segera, dan pesalah yang berulang boleh disekat daripada menyunting. Harap maklum.",
  65. 'manx' => "Haink ram cooney da aavioghey ny Gaelgey liorish yn obbyr recortyssagh jeant liorish aahirreyderyn 'sy 20oo eash.",
  66. 'marathi' => "समस्त विकिपीडिया वाचक आणि संपादकांना दीपावलीच्या हार्दीक शुभेच्छा !",
  67. 'middle_frisian' => "30 beest van en wief dat er gen schrift van is dy plæge hem Kom krod my ney de Verman ta.",
  68. 'mingo' => "Kakwékö nêkê ne'hu niyawë'ö, ne n-u'kaiwayeí ne' thusnye'ö N-awëníyu', ne' húkwa huwënitkëhtahkö haya'tatek, n- utukëstaniak, háwê,",
  69. 'nepali' => "तपाईंको/तिम्रो नाम के हो?",
  70. 'norwegian' => "Språksamfunn lånar ord frå meir prestisjefylte språksamfunn, via tospråklege talarar. Studium av lånordslag i norsk speglar dermed samfunnsmessige tilhøve i Europa opp gjennom hundreåra.",
  71. 'occitan' => "Ara s'estima que sus una populacion de 14 o 15 milions d'occitans, son entre 500 000 e 2 000 000 los que son capables de parlar l'occitan correntament, mas las ocasions de lo parlar dins la societat son raras.",
  72. 'pashto' => "د راجيت سيتارام پنډت په قول ميلنده پڼهو اصلي نسخه په زړه پښتو ليکل شويده - موړ کتاب چې د",
  73. 'persian' => "زبان فارسی (پارسی، دری، یا تاجیکی) زبانی است که در کشورهای ایران، افغانستان[۲]، تاجیکستان[۳] و",
  74. 'polish' => "Język polski wywodzi się z języka praindoeuropejskiego za pośrednictwem języka prasłowiańskiego.",
  75. 'portuguese' => "Assim como os outros idiomas, o português sofreu uma evolução histórica, sendo influenciado por vários idiomas e dialetos, até chegar ao estágio conhecido atualmente. Deve-se considerar, porém, que o português de hoje compreende vários dialetos e subdialetos, falares e subfalares, muitas vezes bastante distintos, além de dois padrões reconhecidos internacionalmente (português brasileiro e português europeu).",
  76. 'quechua_cusco' => "Simi yachaqkunaqa rimanakun, qhichwa simi hukllachu achkachu rimay. SIL International nisqa tantanakuy ninmi, 42 rimaymi, nispa.",
  77. 'romanian' => "Limba română este vorbită în toată lumea de aproximativ 26 de milioane de persoane.",
  78. 'rumantsch' => "Mintga idiom ha sviluppà sia atgna lingua da scrittira ch'è dentant savens era puspè in cumpromiss tranter ils differents dialects regiunals e locals.",
  79. 'russian' => "Русский язык — один из восточнославянских языков, один из крупнейших языков мира, в том числе самый распространённый из славянских языков и самый распространённый язык Европы, как географически, так и по числу носителей языка как родного (хотя также значительная и географически большая часть русского языкового ареала находится в Азии).",
  80. 'sanskrit' => "एयं भाषा न केवलं भारतस्‍य अपितु विश्‍वस्‍यप्राचीनतमा भाषा मन्‍यते। इयं भाषा एतावती समृद्घा अस्‍ति यत्‌ प्राय: सर्वासु भारतीयभाषासु न्‍यूनाधिकरूपेण अस्‍या: शब्‍दा: प्रयुज्‍यन्‍ते. अत: भाषाविदां मते इयं सर्वासां भाषाणां जननी मन्‍यते। पुरा संस्कृतं लोकभाषा आसीत्‌। जना: संस्कृतं वदन्ति स्म॥ विश्‍वस्‍य आदिम: ग्रन्‍थ: ऋग्‍वेद: संस्‍कृतभाषायामेवास्‍ति। अन्‍ये च वेदा: यथा यजुर्वेद:, सामवेद:, अथर्ववेदश्‍च संस्‍कृतभाषायामेव सन्‍ति। आयुर्वेद धनुर्वेद गन्‍धर्ववेदार्थवेदाख्‍या: चत्‍वार: उपवेदा: अपि संस्‍कृते एव विरचिता:॥ सर्वा: उपनिषद: संस्‍कृते उपनिबद्घाः। अन्‍ये ग्रन्‍था: - शिक्षा, कल्‍प, निरुक्त, ज्‍योतिष, छन्‍द, व्‍याकरण, वेदाङ्ग, दर्शन, इतिहास, पुराण, काव्‍य, शास्‍त्र: चेत्यादयः ॥ महर्षि-पाणिनिना विरचिता अष्‍टाध्‍यायी इति संस्‍कृतव्‍याकरणम्‌ अधुनापि भारते विदेशेषु च भाषाविज्ञानिनां प्रेरणास्‍थानं वर्तते ॥ वाक्यकारं वररुचिं भाष्यकारं पतंजलिम् | पाणिनिं सूत्रकारं च प्रणतोस्मि मुनित्रयम् ॥",
  81. 'scots' => "Anglian speakers wis weel staiblisht in sooth-east Scotland by the 7t century. In the 13t century Norman landawners an thair reteeners, speakin Northumbrian Middle Inglis, wis inveetit tae come an sattle by the Keeng.",
  82. 'scots_gaelic' => "Ciamar a tha thu? Dè an t-ainm a tha ort? Dè a tha seo?",
  83. 'serbian' => "Gajica je objavljena je 1830. godine u Zagrebu u „kratkoj osnovi horvatsko-slavonskoga pravopisa“. Razvio ju je Ljudevit Gaj.",
  84. 'serbian_cyrillic' => "Као и када су други језици у питању, неопходно је разграничити појам језичких система којим се Срби како етницитет служе од стандардног језика који се употребљава у државним и културним институцијама.",
  85. 'simpl_chinese' => "现代标准汉语,是普通话、国语、华语的统称,指通行于中国大陆和香港、澳门、台湾、海外华人的共通语文,为现代汉语共通的交际口语与书面语,是联合国官方语言之一,是国际人士学习汉语言的主要参照。",
  86. 'slovak' => "Ak ste nedávno napísali tento článok, skúste vyčistiť jeho vyrovnávaciu pamäť alebo chvíľu počkať predtým, než ho znova vytvoríte.",
  87. 'slovenian' => "Slovénščina je južnoslovanski jezik z okoli 2,2 milijonoma govorcev po svetu, od katerih jih večina živi v Sloveniji. Je eden redkih indoevropskih jezikov, ki je še ohranil dvojino.",
  88. 'spanish' => "El castellano es lengua oficial de España. También se habla en Gibraltar[70] y en Andorra (donde es la lengua materna mayoritaria debido a la inmigración, pero no es la lengua propia y oficial como sí lo es el catalán[71] ).",
  89. 'swahili' => "Lugha hii ina utajiri mkubwa wa misamiati na misemo na mithali na mashairi na mafumbo na vitendawili na nyimbo.",
  90. 'swedish' => "Hej. Hur är det? Bara bra, tack. Förlåt, jag har glömt, varifrån kommer du nu igen?",
  91. 'tagalog' => "Ang Wikibooks ay isang ambagang proyekto sa pagkagawa ng isang koleksyon ng mga libre at malayang-kontentong pang-araling aklat na pwede mong baguhin.",
  92. 'tamil' => "நீங்கள் ஆங்கிலம் பேசுவீர்களா?",
  93. 'thai' => "ภาษาไทย เป็นภาษาราชการของประเทศไทย และภาษาแม่ของชาวไทย และชนเชื้อสายอื่นในประเทศไทย ภาษาไทยเป็นภาษาในกลุ่มภาษาไต ซึ่งเป็นกลุ่มย่อยของตระกูลภาษาไท-กะได สันนิษฐานว่า",
  94. 'trad_chinese' => "中華民國,在亞東之極,本都南京,因事失地泰半,暫遷於臺北。其東以鴨綠江界朝鮮國,隔東海望日本。其北與俄羅斯相接。其西有大山,天下至高者也。而皆失於內戰,今僅得臺灣及其周圍矣。",
  95. 'turkish' => "Bu kitapta Türkçe konuşmak, yazmak ve okumak için gereken her şeyi bulacaksınız.",
  96. 'ukrainian' => "Українська мова є мовою найбільшого корінного етносу України і невід'ємною базовою ознакою його ідентичності протягом багатьох століть.",
  97. 'vietnamese' => "Tiếng Việt là ngôn ngữ chính thức tại Việt Nam, và cũng là ngôn ngữ phổ thông đối với các dân tộc thiểu số tại Việt Nam.",
  98. 'welsh' => "Gan nad oedd y Frythoneg yn iaith ysgrifenedig tystiolaeth anuniongyrchol yn unig sydd i'r newidiadau a ddigwyddodd iddi.",
  99. 'yiddish' => "יידיש אדער אידיש (Yiddish) גערופֿן ביי אידן אלס מאַמע לשון, איז אַ שפּראַך װאָס װערט הײַנט גערעדט ביי 1.5 מיליאָן יידן[1] און באַקאַנט ביי 3,142,560 מיליאָן [2] מענטשן איבער דער װעלט, בעיקר פֿונעם אַשכנזישן אָפּשטאַם.",
  100. 'yoruba' => "Èdè Yorùbá Ní báyìí, tí a bá wo èdè Yorùbá, àwon onímò pín èdè náà sábée èyà wa nínú e bí èdè Niger-Congo. Wón tún fìdí rè múlè pé èyà wa yìí ló wópò jùlo ní síso, ní ìwò oòrùn aláwò dúdú fún egbe-egbèrún odún."
  101. );
  102. function TestInternationalization() {
  103. $this->UnitTestCase('Internationalization library - main/inc/lib/internationalization.lib.test.php');
  104. }
  105. /**
  106. * ----------------------------------------------------------------------------
  107. * Multibyte string conversion functions
  108. * ----------------------------------------------------------------------------
  109. */
  110. public function test_api_convert_encoding() {
  111. $string = 'xxxáéíóú?€'; // UTF-8
  112. $from_encoding = 'UTF-8';
  113. $to_encoding = 'ISO-8859-15';
  114. $res = api_convert_encoding($string, $to_encoding, $from_encoding);
  115. $this->assertTrue(is_string($res));
  116. $this->assertTrue(api_convert_encoding($res, $from_encoding, $to_encoding) == $string);
  117. //var_dump($res);
  118. //var_dump(api_convert_encoding($res, $from_encoding, $to_encoding));
  119. }
  120. public function test_api_utf8_encode() {
  121. $string = 'xxxáéíóú?€'; // UTF-8
  122. $from_encoding = 'ISO-8859-15';
  123. $string1 = api_utf8_decode($string, $from_encoding);
  124. $res = api_utf8_encode($string1, $from_encoding);
  125. $this->assertTrue(is_string($res));
  126. $this->assertTrue($res == $string);
  127. //var_dump($res);
  128. }
  129. public function test_api_utf8_decode() {
  130. $string = 'xxxx1ws?!áéíóú@€'; // UTF-8
  131. $to_encoding = 'ISO-8859-15';
  132. $res = api_utf8_decode($string, $to_encoding);
  133. $this->assertTrue(is_string($res));
  134. $this->assertTrue(api_utf8_encode($res, $to_encoding) == $string);
  135. //var_dump($res);
  136. }
  137. public function test_api_to_system_encoding() {
  138. $string = api_utf8_encode(get_lang('Title'), api_get_system_encoding());
  139. $from_encoding = 'UTF-8';
  140. $check_utf8_validity = false;
  141. $res = api_to_system_encoding($string, $from_encoding, $check_utf8_validity);
  142. $this->assertTrue(is_string($res));
  143. $this->assertTrue(api_convert_encoding($res, $from_encoding, api_get_system_encoding()) == $string);
  144. //var_dump(api_utf8_encode($res, api_get_system_encoding()));
  145. }
  146. public function test_api_htmlentities() {
  147. $string = 'áéíóú@!?/\-_`*ç´`'; // UTF-8
  148. $quote_style = ENT_QUOTES;
  149. $encoding = 'UTF-8';
  150. $res = api_htmlentities($string, $quote_style, $encoding);
  151. $this->assertTrue(is_string($res));
  152. $this->assertTrue(api_convert_encoding($res, $encoding, 'HTML-ENTITIES') == $string);
  153. //var_dump($res);
  154. }
  155. public function test_api_html_entity_decode() {
  156. $string = 'áéíóú@/\!?Ç´`+*?-_ '; // UTF-8
  157. $quote_style = ENT_QUOTES;
  158. $encoding = 'UTF-8';
  159. $res = api_html_entity_decode(api_convert_encoding($string, 'HTML-ENTITIES', $encoding), $quote_style, $encoding);
  160. $this->assertTrue(is_string($res));
  161. $this->assertTrue($res == $string);
  162. //var_dump($res);
  163. }
  164. public function test_api_xml_http_response_encode() {
  165. $string='áéíóú@/\!?Ç´`+*?-_'; // UTF-8
  166. $from_encoding = 'UTF-8';
  167. $res = api_xml_http_response_encode($string, $from_encoding);
  168. $this->assertTrue(is_string($res));
  169. //var_dump($res);
  170. }
  171. public function test_api_transliterate() {
  172. $string = 'Фёдор Михайлович Достоевкий'; // UTF-8
  173. /*
  174. // If you have broken by mistake UTF-8 encoding of this source, try the following equivalent:
  175. $string = api_html_entity_decode(
  176. '&#1060;&#1105;&#1076;&#1086;&#1088; '.
  177. '&#1052;&#1080;&#1093;&#1072;&#1081;&#1083;&#1086;&#1074;&#1080;&#1095; '.
  178. '&#1044;&#1086;&#1089;&#1090;&#1086;&#1077;&#1074;&#1082;&#1080;&#1081;',
  179. ENT_QUOTES, 'UTF-8');
  180. */
  181. $unknown = 'X';
  182. $from_encoding = 'UTF-8';
  183. $res = api_transliterate($string, $unknown, $from_encoding);
  184. $this->assertTrue($res);
  185. $this->assertTrue(is_string($res));
  186. $this->assertTrue($res == 'Fyodor Mihaylovich Dostoevkiy');
  187. //var_dump($string);
  188. //var_dump($res);
  189. }
  190. /**
  191. * ----------------------------------------------------------------------------
  192. * Common multibyte string functions
  193. * ----------------------------------------------------------------------------
  194. */
  195. public function test_api_ord() {
  196. $encoding = 'UTF-8';
  197. $characters = array('И', 'в', 'а', 'н', ' ', 'I', 'v', 'a', 'n'); // UTF-8
  198. $codepoints = array(1048, 1074, 1072, 1085, 32, 73, 118, 97, 110);
  199. $res = array();
  200. foreach ($characters as $character) {
  201. $res[] = api_ord($character, $encoding);
  202. }
  203. $this->assertTrue($res == $codepoints);
  204. //var_dump($res);
  205. }
  206. public function test_api_str_ireplace() {
  207. $search = 'Á'; // UTF-8
  208. $replace = 'a';
  209. $subject = 'bájando'; // UTF-8
  210. $count = null;
  211. $encoding = 'UTF-8';
  212. $res = api_str_ireplace($search, $replace, $subject, & $count, $encoding);
  213. $this->assertTrue($res);
  214. $this->assertTrue(is_string($res));
  215. $this->assertTrue($res == 'bajando');
  216. //var_dump($res);
  217. }
  218. public function test_api_str_split() {
  219. $string = 'áéíóúº|\/?Ç][ç]'; // UTF-8
  220. $split_length = 1;
  221. $encoding = 'UTF-8';
  222. $res = api_str_split($string, $split_length, $encoding);
  223. $this->assertTrue(is_array($res));
  224. $this->assertTrue(count($res) == 15);
  225. //var_dump($res);
  226. }
  227. public function test_api_stripos() {
  228. $haystack = 'bájando'; // UTF-8
  229. $needle = 'Á';
  230. $offset = 0;
  231. $encoding = 'UTF-8';
  232. $res = api_stripos($haystack, $needle, $offset, $encoding);
  233. $this->assertTrue(is_numeric($res)|| is_bool($res));
  234. $this->assertTrue($res == 1);
  235. //var_dump($res);
  236. }
  237. public function test_api_stristr() {
  238. $haystack = 'bájando'; // UTF-8
  239. $needle = 'Á';
  240. $part = false;
  241. $encoding = 'UTF-8';
  242. $res = api_stristr($haystack, $needle, $part, $encoding);
  243. $this->assertTrue(is_bool($res) || is_string($res));
  244. $this->assertTrue($res == 'ájando');
  245. //var_dump($res);
  246. }
  247. public function test_api_strlen() {
  248. $string='áéíóúº|\/?Ç][ç]'; // UTF-8
  249. $encoding = 'UTF-8';
  250. $res = api_strlen($string, $encoding);
  251. $this->assertTrue(is_numeric($res));
  252. $this->assertTrue($res == 15);
  253. //var_dump($res);
  254. }
  255. public function test_api_strpos() {
  256. $haystack = 'bájando'; // UTF-8
  257. $needle = 'á';
  258. $offset = 0;
  259. $encoding = 'UTF-8';
  260. $res = api_strpos($haystack, $needle, $offset, $encoding);
  261. $this->assertTrue(is_numeric($res)|| is_bool($res));
  262. $this->assertTrue($res == 1);
  263. //var_dump($res);
  264. }
  265. public function test_api_strrchr() {
  266. $haystack = 'aviación aviación'; // UTF-8
  267. $needle = 'ó';
  268. $part = false;
  269. $encoding = 'UTF-8';
  270. $res = api_strrchr($haystack, $needle, $part, $encoding);
  271. $this->assertTrue(is_string($res)|| is_bool($res));
  272. $this->assertTrue($res == 'ón');
  273. //var_dump($res);
  274. }
  275. public function test_api_strrev() {
  276. $string = 'áéíóúº|\/?Ç][ç]'; // UTF-8
  277. $encoding = 'UTF-8';
  278. $res = api_strrev($string, $encoding);
  279. $this->assertTrue(is_string($res));
  280. $this->assertTrue($res == ']ç[]Ç?/\|ºúóíéá');
  281. //var_dump($res);
  282. }
  283. public function test_api_strripos() {
  284. $haystack = 'aviación aviación'; // UTF-8
  285. $needle = 'Ó';
  286. $offset = 0;
  287. $encoding = 'UTF-8';
  288. $res = api_strripos($haystack, $needle, $offset, $encoding);
  289. $this->assertTrue(is_numeric($res) || is_bool($res));
  290. $this->assertTrue($res == 15);
  291. //var_dump($res);
  292. }
  293. public function test_api_strrpos() {
  294. $haystack = 'aviación aviación'; // UTF-8
  295. $needle = 'ó';
  296. $offset = 0;
  297. $encoding = 'UTF-8';
  298. $res = api_strrpos($haystack, $needle, $offset, $encoding);
  299. $this->assertTrue(is_numeric($res) || is_bool($res));
  300. $this->assertTrue($res == 15);
  301. //var_dump($res);
  302. }
  303. public function test_api_strstr() {
  304. $haystack = 'aviación'; // UTF-8
  305. $needle = 'ó';
  306. $part = false;
  307. $encoding = 'UTF-8';
  308. $res = api_strstr($haystack, $needle, $part, $encoding);
  309. $this->assertTrue(is_bool($res)|| is_string($res));
  310. $this->assertTrue($res == 'ón');
  311. //var_dump($res);
  312. }
  313. public function test_api_strtolower() {
  314. $string = 'áéíóúº|\/?Ç][ç]'; // UTF-8
  315. $encoding = 'UTF-8';
  316. $res = api_strtolower($string, $encoding);
  317. $this->assertTrue(is_string($res));
  318. $this->assertTrue($res == 'áéíóúº|\/?ç][ç]');
  319. //var_dump($res);
  320. }
  321. public function test_api_strtoupper() {
  322. $string='áéíóúº|\/?Ç][ç]'; // UTF-8
  323. $encoding = 'UTF-8';
  324. $res = api_strtoupper($string, $encoding);
  325. $this->assertTrue(is_string($res));
  326. $this->assertTrue($res =='ÁÉÍÓÚº|\/?Ç][Ç]');
  327. //var_dump($res);
  328. }
  329. public function test_api_substr() {
  330. $string = 'áéíóúº|\/?Ç][ç]'; // UTF-8
  331. $start = 10;
  332. $length = 4;
  333. $encoding = 'UTF-8';
  334. $res = api_substr($string, $start, $length, $encoding);
  335. $this->assertTrue(is_string($res));
  336. $this->assertTrue($res == 'Ç][ç');
  337. //var_dump($res);
  338. }
  339. public function test_api_substr_replace() {
  340. $string = 'áéíóúº|\/?Ç][ç]'; // UTF-8
  341. $replacement = 'eiou';
  342. $start= 1;
  343. $length = 4;
  344. $encoding = 'UTF-8';
  345. $res = api_substr_replace($string, $replacement, $start, $length, $encoding);
  346. $this->assertTrue(is_string($res));
  347. $this->assertTrue($res == 'áeiouº|\/?Ç][ç]');
  348. //var_dump($res);
  349. }
  350. public function test_api_ucfirst() {
  351. $string = 'áéíóúº|\/? xx ][ xx ]'; // UTF-8
  352. $encoding = 'UTF-8';
  353. $res = api_ucfirst($string, $encoding);
  354. $this->assertTrue($res);
  355. $this->assertTrue(is_string($res));
  356. $this->assertTrue($res == 'Áéíóúº|\/? xx ][ xx ]');
  357. //var_dump($res);
  358. }
  359. public function test_api_ucwords() {
  360. $string = 'áéíóúº|\/? xx ][ xx ]'; // UTF-8
  361. $encoding = 'UTF-8';
  362. $res = api_ucwords($string, $encoding);
  363. $this->assertTrue($res);
  364. $this->assertTrue(is_string($res));
  365. $this->assertTrue($res == 'Áéíóúº|\/? Xx ][ Xx ]');
  366. //var_dump($res);
  367. }
  368. /**
  369. * ----------------------------------------------------------------------------
  370. * String operations using regular expressions
  371. * ----------------------------------------------------------------------------
  372. */
  373. public function test_api_preg_match() {
  374. $pattern = '/иван/i'; // UTF-8
  375. $subject = '-- Ivan (en) -- Иван (bg) --'; // UTF-8
  376. $matches = null;
  377. $flags = 0;
  378. $offset = 0;
  379. $encoding = 'UTF-8';
  380. $res = api_preg_match($pattern, $subject, $matches, $flags, $offset, $encoding);
  381. $this->assertTrue($res == 1);
  382. //var_dump($res);
  383. //var_dump($matches);
  384. }
  385. public function test_api_preg_match_all() {
  386. $pattern = '/иван/i'; // UTF-8
  387. $subject = '-- Ivan (en) -- Иван (bg) -- иван --'; // UTF-8
  388. $matches = null;
  389. $flags = PREG_PATTERN_ORDER;
  390. $offset = 0;
  391. $encoding = 'UTF-8';
  392. $res = api_preg_match_all($pattern, $subject, $matches, $flags, $offset, $encoding);
  393. $this->assertTrue($res == 2);
  394. //var_dump($res);
  395. //var_dump($matches);
  396. }
  397. public function test_api_preg_replace() {
  398. $pattern = '/иван/i'; // UTF-8
  399. $replacement = 'ИВАН'; // UTF-8
  400. $subject = '-- Ivan (en) -- Иван (bg) -- иван --'; // UTF-8
  401. $limit = -1;
  402. $count = null;
  403. $encoding = 'UTF-8';
  404. $res = api_preg_replace($pattern, $replacement, $subject, $limit, $count, $encoding);
  405. $this->assertTrue($res == '-- Ivan (en) -- ИВАН (bg) -- ИВАН --'); // UTF-8
  406. //var_dump($res);
  407. }
  408. public function test_api_preg_split() {
  409. $pattern = '/иван/i'; // UTF-8
  410. $subject = '-- Ivan (en) -- Иван (bg) -- иван --'; // UTF-8
  411. $limit = -1;
  412. $count = null;
  413. $encoding = 'UTF-8';
  414. $res = api_preg_split($pattern, $subject, $limit, $count, $encoding);
  415. $this->assertTrue($res[0] == '-- Ivan (en) -- '); // UTF-8
  416. //var_dump($res);
  417. }
  418. /**
  419. * ----------------------------------------------------------------------------
  420. * Obsolete string operations using regular expressions, to be deprecated
  421. * ----------------------------------------------------------------------------
  422. */
  423. public function test_api_ereg() {
  424. $pattern = 'scorm/showinframes.php([^"\'&]*)(&|&amp;)file=([^"\'&]*)$';
  425. $string = 'http://localhost/dokeos/main/scorm/showinframes.php?id=5&amp;file=test.php';
  426. $regs = array();
  427. $res = api_ereg($pattern, $string, $regs);
  428. $this->assertTrue(is_numeric($res));
  429. //var_dump($regs);
  430. //var_dump($res);
  431. }
  432. public function test_api_eregi() {
  433. $pattern = 'scorm/showinframes.php([^"\'&]*)(&|&amp;)file=([^"\'&]*)$';
  434. $string = 'http://localhost/dokeos/main/scorm/showinframes.php?id=5&amp;file=test.php';
  435. $regs = array();
  436. $res = api_eregi($pattern, $string, $regs);
  437. $this->assertTrue(is_numeric($res));
  438. //var_dump($regs);
  439. //var_dump($res);
  440. }
  441. /**
  442. * ----------------------------------------------------------------------------
  443. * String comparison
  444. * ----------------------------------------------------------------------------
  445. */
  446. public function test_api_strcasecmp() {
  447. $string1 = 'áéíóu'; // UTF-8
  448. $string2 = 'Áéíóu'; // UTF-8
  449. $language = 'english';
  450. $encoding = 'UTF-8';
  451. $res = api_strcasecmp($string1, $string2, $language, $encoding);
  452. $this->assertTrue(is_numeric($res));
  453. $this->assertTrue($res == 0);
  454. //var_dump($res);
  455. }
  456. public function test_api_strcmp() {
  457. $string1 = 'áéíóu'; // UTF-8
  458. $string2 = 'Áéíóu'; // UTF-8
  459. $language = 'english';
  460. $encoding = 'UTF-8';
  461. $res = api_strcmp($string1, $string2, $language, $encoding);
  462. $this->assertTrue(is_numeric($res));
  463. $this->assertTrue($res == 1);
  464. //var_dump($res);
  465. }
  466. public function test_api_strnatcmp() {
  467. $string1 = '201áéíóu.txt'; // UTF-8
  468. $string2 = '30áéíóu.TXT'; // UTF-8
  469. $language = 'english';
  470. $encoding = 'UTF-8';
  471. $res = api_strnatcmp($string1, $string2, $language, $encoding);
  472. $this->assertTrue(is_numeric($res));
  473. $this->assertTrue($res == 1);
  474. //var_dump($res);
  475. }
  476. /**
  477. * ----------------------------------------------------------------------------
  478. * Sorting arrays
  479. * ----------------------------------------------------------------------------
  480. */
  481. public function test_api_natsort() {
  482. $array = array('img12.png', 'img10.png', 'img2.png', 'img1.png'); // UTF-8
  483. $language = 'english';
  484. $encoding = 'UTF-8';
  485. $res = api_natsort($array, $language, $encoding);
  486. $keys = array_keys($array);
  487. $this->assertTrue(is_bool($res));
  488. $this->assertTrue($array[$keys[0]] == 'img1.png');
  489. //var_dump($array);
  490. //var_dump($res);
  491. }
  492. public function test_api_natrsort() {
  493. $array = array('img2.png', 'img10.png', 'img12.png', 'img1.png'); // UTF-8
  494. $language = 'english';
  495. $encoding = 'UTF-8';
  496. $res = api_natrsort($array, $language, $encoding);
  497. $keys = array_keys($array);
  498. $this->assertTrue(is_bool($res));
  499. $this->assertTrue($array[$keys[0]] == 'img12.png');
  500. //var_dump($array);
  501. //var_dump($res);
  502. }
  503. public function test_api_is_utf8() {
  504. $encoding = 'cp65001'; // This an alias of UTF-8.
  505. $res = api_is_utf8($encoding);
  506. $this->assertTrue(is_bool($res));
  507. $this->assertTrue($res);
  508. //var_dump($res);
  509. }
  510. public function test_api_get_system_encoding() {
  511. $res = api_get_system_encoding();
  512. $this->assertTrue(is_string($res));
  513. $this->assertTrue($res);
  514. //var_dump($res);
  515. }
  516. public function test_api_detect_encoding_html() {
  517. $meta = '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15" />'."\n";
  518. $head1 = '<head>'."\n".'<title>Sample Document</title>'."\n".'</head>'."\n";
  519. $head2 = '<head>'."\n".'<title>Sample Document</title>'."\n".$meta.'</head>'."\n";
  520. $body1 = '<p>This is a sample document for testing encoding detection.</p>'."\n";
  521. $body2 = '<body>'."\n".$body1.'</body>';
  522. $html1 = $body1; // A html-snippet, see for example some log-files created by the "Chat" tool.
  523. $html2 = '<html>'."\n".$head1.$body2."\n".'</html>'; // A full html-document, no encoding has been declared.
  524. $html3 = '<html>'."\n".$head2.$body2."\n".'</html>'; // A full html-document, encoding has been declared.
  525. $res1 = api_detect_encoding_html($html1);
  526. $res2 = api_detect_encoding_html($html2);
  527. $res3 = api_detect_encoding_html($html3);
  528. $this->assertTrue(
  529. $res1 === 'UTF-8'
  530. && $res2 === 'UTF-8'
  531. && $res3 === 'ISO-8859-15'
  532. );
  533. //var_dump($res1);
  534. //var_dump($res2);
  535. //var_dump($res3);
  536. }
  537. public function test_api_detect_encoding_xml() {
  538. $xml1 = '
  539. <Users>
  540. <User>
  541. <Username>username1</Username>
  542. <Lastname>xxx</Lastname>
  543. <Firstname>xxx</Firstname>
  544. <Password>xxx</Password>
  545. <Email>xxx@xx.xx</Email>
  546. <OfficialCode>xxx</OfficialCode>
  547. <Phone>xxx</Phone>
  548. <Status>student</Status>
  549. </User>
  550. </Users>'; // US-ASCII
  551. $xml2 = '<?xml version="1.0" encoding="ISO-8859-15"?>'.$xml1;
  552. $xml3 = '<?xml version="1.0" encoding="utf-8"?>'.$xml1;
  553. $xml4 = str_replace('<Lastname>xxx</Lastname>', '<Lastname>x'.chr(192).'x</Lastname>', $xml1); // A non-UTF-8 character has been inserted.
  554. $res1 = api_detect_encoding_xml($xml1);
  555. $res2 = api_detect_encoding_xml($xml2);
  556. $res3 = api_detect_encoding_xml($xml3);
  557. $res4 = api_detect_encoding_xml($xml4);
  558. $res5 = api_detect_encoding_xml($xml4, 'windows-1251');
  559. $this->assertTrue(
  560. $res1 === 'UTF-8'
  561. && $res2 === 'ISO-8859-15'
  562. && $res3 === 'UTF-8'
  563. && api_equal_encodings($res4, api_get_system_encoding())
  564. && $res5 === 'WINDOWS-1251'
  565. );
  566. //var_dump($res1);
  567. //var_dump($res2);
  568. //var_dump($res3);
  569. //var_dump($res4);
  570. //var_dump($res5);
  571. }
  572. public function test_api_convert_encoding_xml() {
  573. $xml = '
  574. <?xml version="1.0" encoding="UTF-8"?>
  575. <Users>
  576. <User>
  577. <Username>username1</Username>
  578. <Lastname>xxx</Lastname>
  579. <Firstname>Иван</Firstname>
  580. <Password>xxx</Password>
  581. <Email>xxx@xx.xx</Email>
  582. <OfficialCode>xxx</OfficialCode>
  583. <Phone>xxx</Phone>
  584. <Status>student</Status>
  585. </User>
  586. </Users>'; // UTF-8
  587. $res1 = api_convert_encoding_xml($xml, 'WINDOWS-1251', 'UTF-8');
  588. $res2 = api_convert_encoding_xml($xml, 'WINDOWS-1251');
  589. $res3 = api_convert_encoding_xml($res1, 'UTF-8', 'WINDOWS-1251');
  590. $res4 = api_convert_encoding_xml($res2, 'UTF-8');
  591. $this->assertTrue(
  592. $res3 === $xml
  593. && $res4 === $xml
  594. );
  595. //var_dump(preg_replace(array('/\r?\n/m', '/\t/m'), array('<br />', '&nbsp;&nbsp;&nbsp;&nbsp;'), htmlspecialchars($res1)));
  596. //var_dump(preg_replace(array('/\r?\n/m', '/\t/m'), array('<br />', '&nbsp;&nbsp;&nbsp;&nbsp;'), htmlspecialchars($res2)));
  597. //var_dump(preg_replace(array('/\r?\n/m', '/\t/m'), array('<br />', '&nbsp;&nbsp;&nbsp;&nbsp;'), htmlspecialchars($res3)));
  598. //var_dump(preg_replace(array('/\r?\n/m', '/\t/m'), array('<br />', '&nbsp;&nbsp;&nbsp;&nbsp;'), htmlspecialchars($res4)));
  599. }
  600. public function test_api_utf8_encode_xml() {
  601. $xml1 = '
  602. <?xml version="1.0" encoding="UTF-8"?>
  603. <Users>
  604. <User>
  605. <Username>username1</Username>
  606. <Lastname>xxx</Lastname>
  607. <Firstname>Иван</Firstname>
  608. <Password>xxx</Password>
  609. <Email>xxx@xx.xx</Email>
  610. <OfficialCode>xxx</OfficialCode>
  611. <Phone>xxx</Phone>
  612. <Status>student</Status>
  613. </User>
  614. </Users>'; // UTF-8
  615. $xml2 = '
  616. <?xml version="1.0" encoding="WINDOWS-1251"?>
  617. <Users>
  618. <User>
  619. <Username>username1</Username>
  620. <Lastname>xxx</Lastname>
  621. <Firstname>'.chr(200).chr(226).chr(224).chr(237).'</Firstname>
  622. <Password>xxx</Password>
  623. <Email>xxx@xx.xx</Email>
  624. <OfficialCode>xxx</OfficialCode>
  625. <Phone>xxx</Phone>
  626. <Status>student</Status>
  627. </User>
  628. </Users>'; // WINDOWS-1251
  629. $res1 = api_utf8_encode_xml($xml2);
  630. $this->assertTrue($res1 === $xml1);
  631. //var_dump(preg_replace(array('/\r?\n/m', '/\t/m'), array('<br />', '&nbsp;&nbsp;&nbsp;&nbsp;'), htmlspecialchars($res1)));
  632. }
  633. public function test_api_utf8_decode_xml() {
  634. $xml1 = '
  635. <?xml version="1.0" encoding="UTF-8"?>
  636. <Users>
  637. <User>
  638. <Username>username1</Username>
  639. <Lastname>xxx</Lastname>
  640. <Firstname>Иван</Firstname>
  641. <Password>xxx</Password>
  642. <Email>xxx@xx.xx</Email>
  643. <OfficialCode>xxx</OfficialCode>
  644. <Phone>xxx</Phone>
  645. <Status>student</Status>
  646. </User>
  647. </Users>'; // UTF-8
  648. $xml2 = '
  649. <?xml version="1.0" encoding="WINDOWS-1251"?>
  650. <Users>
  651. <User>
  652. <Username>username1</Username>
  653. <Lastname>xxx</Lastname>
  654. <Firstname>'.chr(200).chr(226).chr(224).chr(237).'</Firstname>
  655. <Password>xxx</Password>
  656. <Email>xxx@xx.xx</Email>
  657. <OfficialCode>xxx</OfficialCode>
  658. <Phone>xxx</Phone>
  659. <Status>student</Status>
  660. </User>
  661. </Users>'; // WINDOWS-1251
  662. $res1 = api_utf8_decode_xml($xml1, 'WINDOWS-1251');
  663. $this->assertTrue($res1 === $xml2);
  664. //var_dump(preg_replace(array('/\r?\n/m', '/\t/m'), array('<br />', '&nbsp;&nbsp;&nbsp;&nbsp;'), htmlspecialchars($res1)));
  665. }
  666. /**
  667. * ----------------------------------------------------------------------------
  668. * String validation functions concerning certain encodings
  669. * ----------------------------------------------------------------------------
  670. */
  671. public function test_api_is_valid_utf8() {
  672. $string = 'áéíóú1@\/-ḉ`´';
  673. $res = api_is_valid_utf8($string);
  674. $this->assertTrue(is_bool($res));
  675. $this->assertTrue($res);
  676. //var_dump($res);
  677. }
  678. public function test_api_is_valid_ascii() {
  679. $string = 'áéíóú'; // UTF-8
  680. $res = api_is_valid_ascii($string);
  681. $this->assertTrue(is_bool($res));
  682. $this->assertTrue(!$res);
  683. //var_dump($res);
  684. }
  685. public function test_api_get_valid_language() {
  686. $enabled_languages_info = api_get_languages();
  687. $enabled_languages = $enabled_languages_info['folder'];
  688. $language = array();
  689. $language[] = ' '.strtoupper(api_get_language_isocode()).' ';
  690. $language[] = " \t ".strtoupper(api_get_setting('language.platform_language'))." \t ";
  691. $language[] = 'xxxxxxxxxxxxxx';
  692. $language[] = ' \t'.strtoupper('bulgarian').' ';
  693. $res = array();
  694. $res[] = api_get_valid_language($language[1]);
  695. $res[] = api_get_valid_language($language[2]);
  696. $res[] = api_get_valid_language($language[3]);
  697. $res[] = api_get_valid_language($language[4]);
  698. $expected = array();
  699. foreach ($language as $value) {
  700. $value = str_replace('_km', '_KM', strtolower(trim($value)));
  701. if (empty($value) || !in_array($value, $enabled_languages) || !api_is_language_supported($value)) {
  702. $value = api_get_setting('language.platform_language');
  703. }
  704. $expected = $value;
  705. }
  706. $is_ok = true;
  707. foreach ($language as $key => $value) {
  708. $is_ok = $is_ok && ($value === $res[$key]);
  709. }
  710. //var_dump($res);
  711. //var_dump($expected);
  712. }
  713. function test_api_get_language_isocode() {
  714. $test_language_table = array(
  715. '*** invalid entry ***' => 'en', // An invalid entry.
  716. 'arabic' => 'ar',
  717. 'arabic_unicode' => 'ar',
  718. 'asturian' => 'ast',
  719. 'bosnian' => 'bs',
  720. 'brazilian' => 'pt-BR',
  721. 'bulgarian' => 'bg',
  722. 'catalan' => 'ca',
  723. 'croatian' => 'hr',
  724. 'czech' => 'cs',
  725. 'danish' => 'da',
  726. 'dari' => 'prs',
  727. 'dutch' => 'nl',
  728. 'dutch_corporate' => 'nl',
  729. 'english' => 'en',
  730. 'english_org' => 'en',
  731. 'esperanto' => 'eo',
  732. 'basque' => 'eu',
  733. 'finnish' => 'fi',
  734. 'french' => 'fr',
  735. 'french_corporate' => 'fr',
  736. 'french_KM' => 'fr',
  737. 'french_org' => 'fr',
  738. 'french_unicode' => 'fr',
  739. 'friulian' => 'fur',
  740. 'galician' => 'gl',
  741. 'georgian' => 'ka',
  742. 'german' => 'de',
  743. 'greek' => 'el',
  744. 'hebrew' => 'he',
  745. 'hungarian' => 'hu',
  746. 'indonesian' => 'id',
  747. 'italian' => 'it',
  748. 'japanese' => 'ja',
  749. 'japanese_unicode' => 'ja',
  750. 'korean' => 'ko',
  751. 'latvian' => 'lv',
  752. 'lithuanian' => 'lt',
  753. 'macedonian' => 'mk',
  754. 'malay' => 'ms',
  755. 'norwegian' => 'no',
  756. 'occitan' => 'oc',
  757. 'pashto' => 'ps',
  758. 'persian' => 'fa',
  759. 'polish' => 'pl',
  760. 'portuguese' => 'pt',
  761. 'quechua_cusco' => 'qu',
  762. 'romanian' => 'ro',
  763. 'russian' => 'ru',
  764. 'russian_unicode' => 'ru',
  765. 'serbian' => 'sr',
  766. 'simpl_chinese' => 'zh',
  767. 'simpl_chinese_unicode' => 'zh',
  768. 'slovak' => 'sk',
  769. 'slovenian' => 'sl',
  770. 'slovenian_unicode' => 'sl',
  771. 'spanish' => 'es',
  772. 'spanish_latin' => 'es',
  773. 'swahili' => 'sw',
  774. 'swedish' => 'sv',
  775. 'thai' => 'th',
  776. 'trad_chinese' => 'zh-TW',
  777. 'trad_chinese_unicode' => 'zh-TW',
  778. 'turkish' => 'tr',
  779. 'ukrainian' => 'uk',
  780. 'vietnamese' => 'vi',
  781. 'yoruba' => 'yo'
  782. );
  783. $res = array();
  784. foreach ($test_language_table as $language => $expected_result) {
  785. $test_result = api_get_language_isocode($language);
  786. $res[$language] = array(
  787. 'expected_result' => $expected_result,
  788. 'test_result' => $test_result,
  789. 'is_ok' => $expected_result === $test_result
  790. );
  791. }
  792. $this->assertTrue(is_array($res));
  793. $is_ok = true;
  794. foreach ($res as $language => $test_case) {
  795. $is_ok = $is_ok && $test_case['is_ok'];
  796. }
  797. $this->assertTrue($is_ok);
  798. //var_dump($res);
  799. //foreach ($res as $language => $test_case) { echo ($test_case['is_ok'] ? '<span style="color: green; font-weight: bold;">Ok</span>' : '<span style="color: red; font-weight: bold;">Failed</span>').' '.$language.' => '.(is_null($test_case['test_result']) ? 'NULL' : $test_case['test_result']).'<br />'; }
  800. }
  801. public function test_api_get_text_direction() {
  802. $languages = array('english', 'en', 'arabic', 'ar');
  803. $expected_results = array('ltr', 'ltr', 'rtl', 'rtl');
  804. $res = array();
  805. foreach ($languages as $language) {
  806. $res[] = api_get_text_direction($language);
  807. }
  808. $this->assertTrue($res === $expected_results);
  809. }
  810. // The second function for testing api_detect_encoding().
  811. public function test_api_detect_encoding_2() {
  812. $string_utf8 = 'Това е тест на български език'; // Bulgarian language, UTF-8
  813. $string_utf8_broken = $string_utf8.chr(198); // Intentionaly broken UTF-8, it should be detected as UTF-8
  814. $res1 = api_detect_encoding($string_utf8, 'bulgarian');
  815. $res2 = api_detect_encoding($string_utf8_broken, 'bulgarian');
  816. $this->assertTrue(api_is_utf8($res1) && api_is_utf8($res2));
  817. //var_dump($res1);
  818. //var_dump($res2);
  819. }
  820. public function test_api_get_local_time_with_datetime() {
  821. $datetime_not_converted = '2010-03-13 16:24:02';
  822. $datetime_gmtplus1 = api_get_local_time($datetime_not_converted, 'Europe/Paris', 'America/Lima');
  823. $this->assertEqual($datetime_gmtplus1, '2010-03-13 22:24:02');
  824. }
  825. public function test_api_get_local_time_with_timestamp() {
  826. $current_timestamp = time();
  827. $datetime = api_get_local_time($current_timestamp, 'Europe/Paris');
  828. $system_timezone = date_default_timezone_get();
  829. date_default_timezone_set('Europe/Paris');
  830. $this->assertEqual($datetime, date('Y-m-d H:i:s', $current_timestamp));
  831. date_default_timezone_set($system_timezone);
  832. }
  833. public function test_api_get_utc_datetime_with_string() {
  834. $timestamp = time();
  835. $timezone = _api_get_timezone();
  836. $system_timezone = date_default_timezone_get();
  837. date_default_timezone_set($timezone);
  838. $datetime = date('Y-m-d H:i:s', $timestamp);
  839. $datetime_utc = api_get_utc_datetime($datetime);
  840. $this->assertEqual($datetime_utc, gmdate('Y-m-d H:i:s', $timestamp));
  841. date_default_timezone_set($system_timezone);
  842. }
  843. public function test_api_get_utc_datetime_with_timestamp() {
  844. $timestamp = time();
  845. $this->assertEqual(api_get_utc_datetime($timestamp), gmdate("Y-m-d H:i:s", $timestamp));
  846. }
  847. /*
  848. // Enable the following test when you need to run it.
  849. // Testing whether all the language files load successfully. This means that their php-syntax is correct.
  850. public function test_all_the_language_files() {
  851. $files = array( // Only files with these names will be loaded/tested.
  852. 'trad4all.inc.php',
  853. );
  854. $languages = test_get_language_folder_list();
  855. $lang_dir = api_get_path(SYS_LANG_PATH);
  856. foreach ($languages as $language) {
  857. echo 'Language: <strong>'.ucwords($language).'</strong><br />';
  858. echo '-------------------------------------------------------------------------<br />';
  859. foreach ($files as $file) {
  860. echo 'Loading '.$lang_dir.$language.'/<strong>'.$file.'</strong> ...<br />';
  861. test_load_php_language_file($lang_dir.$language.'/'.$file);
  862. }
  863. echo '<br />';
  864. }
  865. $this->assertTrue(true); // Once we arrived here, the test is Ok.
  866. }
  867. */
  868. }
  869. // An isolated namespace for testing whether language files load successfully.
  870. function test_load_php_language_file($filename) {
  871. include $filename;
  872. }
  873. // A helper function.
  874. function test_get_language_folder_list() {
  875. $result = array();
  876. $exceptions = array('.', '..', 'CVS', '.svn');
  877. $dirname = api_get_path(SYS_LANG_PATH);
  878. $handle = opendir($dirname);
  879. while ($entries = readdir($handle)) {
  880. if (in_array($entries, $exceptions)) {
  881. continue;
  882. }
  883. if (is_dir($dirname.$entries)) {
  884. $result[] = $entries;
  885. }
  886. }
  887. closedir($handle);
  888. sort($result);
  889. return $result;
  890. }
  891. ?>