internationalization.lib.test.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  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. /**
  504. * ----------------------------------------------------------------------------
  505. * Encoding management functions
  506. * ----------------------------------------------------------------------------
  507. */
  508. public function test_api_refine_encoding_id() {
  509. $encoding = 'koI8-r';
  510. $res = api_refine_encoding_id($encoding);
  511. $this->assertTrue($res);
  512. $this->assertTrue(is_string($res));
  513. $this->assertTrue($res == 'KOI8-R');
  514. //var_dump($res);
  515. }
  516. public function test_api_equal_encodings() {
  517. $encoding1 = 'cp65001';
  518. $encoding2 = 'utf-8';
  519. $encoding3 = 'WINDOWS-1251';
  520. $encoding4 = 'WINDOWS-1252';
  521. $encoding5 = 'win-1250';
  522. $encoding6 = 'windows-1250';
  523. $res1 = api_equal_encodings($encoding1, $encoding2);
  524. $res2 = api_equal_encodings($encoding3, $encoding4);
  525. $res3 = api_equal_encodings($encoding5, $encoding6);
  526. $res4 = api_equal_encodings($encoding5, $encoding6, true);
  527. $this->assertTrue(is_bool($res1));
  528. $this->assertTrue(is_bool($res2));
  529. $this->assertTrue(is_bool($res3));
  530. $this->assertTrue(is_bool($res4));
  531. $this->assertTrue($res1);
  532. $this->assertTrue(!$res2);
  533. $this->assertTrue($res3);
  534. $this->assertTrue(!$res4);
  535. //var_dump($res1);
  536. //var_dump($res2);
  537. //var_dump($res3);
  538. //var_dump($res4);
  539. }
  540. public function test_api_is_utf8() {
  541. $encoding = 'cp65001'; // This an alias of UTF-8.
  542. $res = api_is_utf8($encoding);
  543. $this->assertTrue(is_bool($res));
  544. $this->assertTrue($res);
  545. //var_dump($res);
  546. }
  547. public function test_api_get_system_encoding() {
  548. $res = api_get_system_encoding();
  549. $this->assertTrue(is_string($res));
  550. $this->assertTrue($res);
  551. //var_dump($res);
  552. }
  553. public function test_api_is_encoding_supported() {
  554. $encoding1 = 'UTF-8';
  555. $encoding2 = 'XXXX#%#%VR^%BBDNdjlrsg;d';
  556. $res1 = api_is_encoding_supported($encoding1);
  557. $res2 = api_is_encoding_supported($encoding2);
  558. $this->assertTrue(is_bool($res1) && is_bool($res2));
  559. $this->assertTrue($res1 && !$res2);
  560. //var_dump($res1);
  561. //var_dump($res2);
  562. }
  563. public function test_api_get_non_utf8_encoding() {
  564. $language = 'bulgarian';
  565. $res = api_get_non_utf8_encoding($language);
  566. $this->assertTrue($res);
  567. $this->assertTrue(is_string($res));
  568. $this->assertTrue($res == 'WINDOWS-1251');
  569. //var_dump($res);
  570. }
  571. public function test_api_detect_encoding_html() {
  572. $meta = '<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15" />'."\n";
  573. $head1 = '<head>'."\n".'<title>Sample Document</title>'."\n".'</head>'."\n";
  574. $head2 = '<head>'."\n".'<title>Sample Document</title>'."\n".$meta.'</head>'."\n";
  575. $body1 = '<p>This is a sample document for testing encoding detection.</p>'."\n";
  576. $body2 = '<body>'."\n".$body1.'</body>';
  577. $html1 = $body1; // A html-snippet, see for example some log-files created by the "Chat" tool.
  578. $html2 = '<html>'."\n".$head1.$body2."\n".'</html>'; // A full html-document, no encoding has been declared.
  579. $html3 = '<html>'."\n".$head2.$body2."\n".'</html>'; // A full html-document, encoding has been declared.
  580. $res1 = api_detect_encoding_html($html1);
  581. $res2 = api_detect_encoding_html($html2);
  582. $res3 = api_detect_encoding_html($html3);
  583. $this->assertTrue(
  584. $res1 === 'UTF-8'
  585. && $res2 === 'UTF-8'
  586. && $res3 === 'ISO-8859-15'
  587. );
  588. //var_dump($res1);
  589. //var_dump($res2);
  590. //var_dump($res3);
  591. }
  592. public function test_api_detect_encoding_xml() {
  593. $xml1 = '
  594. <Users>
  595. <User>
  596. <Username>username1</Username>
  597. <Lastname>xxx</Lastname>
  598. <Firstname>xxx</Firstname>
  599. <Password>xxx</Password>
  600. <Email>xxx@xx.xx</Email>
  601. <OfficialCode>xxx</OfficialCode>
  602. <Phone>xxx</Phone>
  603. <Status>student</Status>
  604. </User>
  605. </Users>'; // US-ASCII
  606. $xml2 = '<?xml version="1.0" encoding="ISO-8859-15"?>'.$xml1;
  607. $xml3 = '<?xml version="1.0" encoding="utf-8"?>'.$xml1;
  608. $xml4 = str_replace('<Lastname>xxx</Lastname>', '<Lastname>x'.chr(192).'x</Lastname>', $xml1); // A non-UTF-8 character has been inserted.
  609. $res1 = api_detect_encoding_xml($xml1);
  610. $res2 = api_detect_encoding_xml($xml2);
  611. $res3 = api_detect_encoding_xml($xml3);
  612. $res4 = api_detect_encoding_xml($xml4);
  613. $res5 = api_detect_encoding_xml($xml4, 'windows-1251');
  614. $this->assertTrue(
  615. $res1 === 'UTF-8'
  616. && $res2 === 'ISO-8859-15'
  617. && $res3 === 'UTF-8'
  618. && api_equal_encodings($res4, api_get_system_encoding())
  619. && $res5 === 'WINDOWS-1251'
  620. );
  621. //var_dump($res1);
  622. //var_dump($res2);
  623. //var_dump($res3);
  624. //var_dump($res4);
  625. //var_dump($res5);
  626. }
  627. public function test_api_convert_encoding_xml() {
  628. $xml = '
  629. <?xml version="1.0" encoding="UTF-8"?>
  630. <Users>
  631. <User>
  632. <Username>username1</Username>
  633. <Lastname>xxx</Lastname>
  634. <Firstname>Иван</Firstname>
  635. <Password>xxx</Password>
  636. <Email>xxx@xx.xx</Email>
  637. <OfficialCode>xxx</OfficialCode>
  638. <Phone>xxx</Phone>
  639. <Status>student</Status>
  640. </User>
  641. </Users>'; // UTF-8
  642. $res1 = api_convert_encoding_xml($xml, 'WINDOWS-1251', 'UTF-8');
  643. $res2 = api_convert_encoding_xml($xml, 'WINDOWS-1251');
  644. $res3 = api_convert_encoding_xml($res1, 'UTF-8', 'WINDOWS-1251');
  645. $res4 = api_convert_encoding_xml($res2, 'UTF-8');
  646. $this->assertTrue(
  647. $res3 === $xml
  648. && $res4 === $xml
  649. );
  650. //var_dump(preg_replace(array('/\r?\n/m', '/\t/m'), array('<br />', '&nbsp;&nbsp;&nbsp;&nbsp;'), htmlspecialchars($res1)));
  651. //var_dump(preg_replace(array('/\r?\n/m', '/\t/m'), array('<br />', '&nbsp;&nbsp;&nbsp;&nbsp;'), htmlspecialchars($res2)));
  652. //var_dump(preg_replace(array('/\r?\n/m', '/\t/m'), array('<br />', '&nbsp;&nbsp;&nbsp;&nbsp;'), htmlspecialchars($res3)));
  653. //var_dump(preg_replace(array('/\r?\n/m', '/\t/m'), array('<br />', '&nbsp;&nbsp;&nbsp;&nbsp;'), htmlspecialchars($res4)));
  654. }
  655. public function test_api_utf8_encode_xml() {
  656. $xml1 = '
  657. <?xml version="1.0" encoding="UTF-8"?>
  658. <Users>
  659. <User>
  660. <Username>username1</Username>
  661. <Lastname>xxx</Lastname>
  662. <Firstname>Иван</Firstname>
  663. <Password>xxx</Password>
  664. <Email>xxx@xx.xx</Email>
  665. <OfficialCode>xxx</OfficialCode>
  666. <Phone>xxx</Phone>
  667. <Status>student</Status>
  668. </User>
  669. </Users>'; // UTF-8
  670. $xml2 = '
  671. <?xml version="1.0" encoding="WINDOWS-1251"?>
  672. <Users>
  673. <User>
  674. <Username>username1</Username>
  675. <Lastname>xxx</Lastname>
  676. <Firstname>'.chr(200).chr(226).chr(224).chr(237).'</Firstname>
  677. <Password>xxx</Password>
  678. <Email>xxx@xx.xx</Email>
  679. <OfficialCode>xxx</OfficialCode>
  680. <Phone>xxx</Phone>
  681. <Status>student</Status>
  682. </User>
  683. </Users>'; // WINDOWS-1251
  684. $res1 = api_utf8_encode_xml($xml2);
  685. $this->assertTrue($res1 === $xml1);
  686. //var_dump(preg_replace(array('/\r?\n/m', '/\t/m'), array('<br />', '&nbsp;&nbsp;&nbsp;&nbsp;'), htmlspecialchars($res1)));
  687. }
  688. public function test_api_utf8_decode_xml() {
  689. $xml1 = '
  690. <?xml version="1.0" encoding="UTF-8"?>
  691. <Users>
  692. <User>
  693. <Username>username1</Username>
  694. <Lastname>xxx</Lastname>
  695. <Firstname>Иван</Firstname>
  696. <Password>xxx</Password>
  697. <Email>xxx@xx.xx</Email>
  698. <OfficialCode>xxx</OfficialCode>
  699. <Phone>xxx</Phone>
  700. <Status>student</Status>
  701. </User>
  702. </Users>'; // UTF-8
  703. $xml2 = '
  704. <?xml version="1.0" encoding="WINDOWS-1251"?>
  705. <Users>
  706. <User>
  707. <Username>username1</Username>
  708. <Lastname>xxx</Lastname>
  709. <Firstname>'.chr(200).chr(226).chr(224).chr(237).'</Firstname>
  710. <Password>xxx</Password>
  711. <Email>xxx@xx.xx</Email>
  712. <OfficialCode>xxx</OfficialCode>
  713. <Phone>xxx</Phone>
  714. <Status>student</Status>
  715. </User>
  716. </Users>'; // WINDOWS-1251
  717. $res1 = api_utf8_decode_xml($xml1, 'WINDOWS-1251');
  718. $this->assertTrue($res1 === $xml2);
  719. //var_dump(preg_replace(array('/\r?\n/m', '/\t/m'), array('<br />', '&nbsp;&nbsp;&nbsp;&nbsp;'), htmlspecialchars($res1)));
  720. }
  721. /**
  722. * ----------------------------------------------------------------------------
  723. * String validation functions concerning certain encodings
  724. * ----------------------------------------------------------------------------
  725. */
  726. public function test_api_is_valid_utf8() {
  727. $string = 'áéíóú1@\/-ḉ`´';
  728. $res = api_is_valid_utf8($string);
  729. $this->assertTrue(is_bool($res));
  730. $this->assertTrue($res);
  731. //var_dump($res);
  732. }
  733. public function test_api_is_valid_ascii() {
  734. $string = 'áéíóú'; // UTF-8
  735. $res = api_is_valid_ascii($string);
  736. $this->assertTrue(is_bool($res));
  737. $this->assertTrue(!$res);
  738. //var_dump($res);
  739. }
  740. public function test_api_get_valid_language() {
  741. $enabled_languages_info = api_get_languages();
  742. $enabled_languages = $enabled_languages_info['folder'];
  743. $language = array();
  744. $language[] = ' '.strtoupper(api_get_interface_language()).' ';
  745. $language[] = " \t ".strtoupper(api_get_setting('platformLanguage'))." \t ";
  746. $language[] = 'xxxxxxxxxxxxxx';
  747. $language[] = ' \t'.strtoupper('bulgarian').' ';
  748. $res = array();
  749. $res[] = api_get_valid_language($language[1]);
  750. $res[] = api_get_valid_language($language[2]);
  751. $res[] = api_get_valid_language($language[3]);
  752. $res[] = api_get_valid_language($language[4]);
  753. $expected = array();
  754. foreach ($language as $value) {
  755. $value = str_replace('_km', '_KM', strtolower(trim($value)));
  756. if (empty($value) || !in_array($value, $enabled_languages) || !api_is_language_supported($value)) {
  757. $value = api_get_setting('platformLanguage');
  758. }
  759. $expected = $value;
  760. }
  761. $is_ok = true;
  762. foreach ($language as $key => $value) {
  763. $is_ok = $is_ok && ($value === $res[$key]);
  764. }
  765. //var_dump($res);
  766. //var_dump($expected);
  767. }
  768. public function test_api_purify_language_id() {
  769. $language = 'english_org';
  770. $res = api_purify_language_id($language);
  771. $this->assertTrue(is_string($res));
  772. $this->assertTrue($res == 'english');
  773. //var_dump($res);
  774. }
  775. function test_api_get_language_isocode() {
  776. $test_language_table = array(
  777. '*** invalid entry ***' => 'en', // An invalid entry.
  778. 'arabic' => 'ar',
  779. 'arabic_unicode' => 'ar',
  780. 'asturian' => 'ast',
  781. 'bosnian' => 'bs',
  782. 'brazilian' => 'pt-BR',
  783. 'bulgarian' => 'bg',
  784. 'catalan' => 'ca',
  785. 'croatian' => 'hr',
  786. 'czech' => 'cs',
  787. 'danish' => 'da',
  788. 'dari' => 'prs',
  789. 'dutch' => 'nl',
  790. 'dutch_corporate' => 'nl',
  791. 'english' => 'en',
  792. 'english_org' => 'en',
  793. 'esperanto' => 'eo',
  794. 'basque' => 'eu',
  795. 'finnish' => 'fi',
  796. 'french' => 'fr',
  797. 'french_corporate' => 'fr',
  798. 'french_KM' => 'fr',
  799. 'french_org' => 'fr',
  800. 'french_unicode' => 'fr',
  801. 'friulian' => 'fur',
  802. 'galician' => 'gl',
  803. 'georgian' => 'ka',
  804. 'german' => 'de',
  805. 'greek' => 'el',
  806. 'hebrew' => 'he',
  807. 'hungarian' => 'hu',
  808. 'indonesian' => 'id',
  809. 'italian' => 'it',
  810. 'japanese' => 'ja',
  811. 'japanese_unicode' => 'ja',
  812. 'korean' => 'ko',
  813. 'latvian' => 'lv',
  814. 'lithuanian' => 'lt',
  815. 'macedonian' => 'mk',
  816. 'malay' => 'ms',
  817. 'norwegian' => 'no',
  818. 'occitan' => 'oc',
  819. 'pashto' => 'ps',
  820. 'persian' => 'fa',
  821. 'polish' => 'pl',
  822. 'portuguese' => 'pt',
  823. 'quechua_cusco' => 'qu',
  824. 'romanian' => 'ro',
  825. 'russian' => 'ru',
  826. 'russian_unicode' => 'ru',
  827. 'serbian' => 'sr',
  828. 'simpl_chinese' => 'zh',
  829. 'simpl_chinese_unicode' => 'zh',
  830. 'slovak' => 'sk',
  831. 'slovenian' => 'sl',
  832. 'slovenian_unicode' => 'sl',
  833. 'spanish' => 'es',
  834. 'spanish_latin' => 'es',
  835. 'swahili' => 'sw',
  836. 'swedish' => 'sv',
  837. 'thai' => 'th',
  838. 'trad_chinese' => 'zh-TW',
  839. 'trad_chinese_unicode' => 'zh-TW',
  840. 'turkish' => 'tr',
  841. 'ukrainian' => 'uk',
  842. 'vietnamese' => 'vi',
  843. 'yoruba' => 'yo'
  844. );
  845. $res = array();
  846. foreach ($test_language_table as $language => $expected_result) {
  847. $test_result = api_get_language_isocode($language);
  848. $res[$language] = array(
  849. 'expected_result' => $expected_result,
  850. 'test_result' => $test_result,
  851. 'is_ok' => $expected_result === $test_result
  852. );
  853. }
  854. $this->assertTrue(is_array($res));
  855. $is_ok = true;
  856. foreach ($res as $language => $test_case) {
  857. $is_ok = $is_ok && $test_case['is_ok'];
  858. }
  859. $this->assertTrue($is_ok);
  860. //var_dump($res);
  861. //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 />'; }
  862. }
  863. public function test_api_get_text_direction() {
  864. $languages = array('english', 'en', 'arabic', 'ar');
  865. $expected_results = array('ltr', 'ltr', 'rtl', 'rtl');
  866. $res = array();
  867. foreach ($languages as $language) {
  868. $res[] = api_get_text_direction($language);
  869. }
  870. $this->assertTrue($res === $expected_results);
  871. }
  872. // The second function for testing api_detect_encoding().
  873. public function test_api_detect_encoding_2() {
  874. $string_utf8 = 'Това е тест на български език'; // Bulgarian language, UTF-8
  875. $string_utf8_broken = $string_utf8.chr(198); // Intentionaly broken UTF-8, it should be detected as UTF-8
  876. $res1 = api_detect_encoding($string_utf8, 'bulgarian');
  877. $res2 = api_detect_encoding($string_utf8_broken, 'bulgarian');
  878. $this->assertTrue(api_is_utf8($res1) && api_is_utf8($res2));
  879. //var_dump($res1);
  880. //var_dump($res2);
  881. }
  882. public function test_api_get_local_time_with_datetime() {
  883. $datetime_not_converted = '2010-03-13 16:24:02';
  884. $datetime_gmtplus1 = api_get_local_time($datetime_not_converted, 'Europe/Paris', 'America/Lima');
  885. $this->assertEqual($datetime_gmtplus1, '2010-03-13 22:24:02');
  886. }
  887. public function test_api_get_local_time_with_timestamp() {
  888. $current_timestamp = time();
  889. $datetime = api_get_local_time($current_timestamp, 'Europe/Paris');
  890. $system_timezone = date_default_timezone_get();
  891. date_default_timezone_set('Europe/Paris');
  892. $this->assertEqual($datetime, date('Y-m-d H:i:s', $current_timestamp));
  893. date_default_timezone_set($system_timezone);
  894. }
  895. public function test_api_get_utc_datetime_with_string() {
  896. $timestamp = time();
  897. $timezone = _api_get_timezone();
  898. $system_timezone = date_default_timezone_get();
  899. date_default_timezone_set($timezone);
  900. $datetime = date('Y-m-d H:i:s', $timestamp);
  901. $datetime_utc = api_get_utc_datetime($datetime);
  902. $this->assertEqual($datetime_utc, gmdate('Y-m-d H:i:s', $timestamp));
  903. date_default_timezone_set($system_timezone);
  904. }
  905. public function test_api_get_utc_datetime_with_timestamp() {
  906. $timestamp = time();
  907. $this->assertEqual(api_get_utc_datetime($timestamp), gmdate("Y-m-d H:i:s", $timestamp));
  908. }
  909. /*
  910. // Enable the following test when you need to run it.
  911. // Testing whether all the language files load successfully. This means that their php-syntax is correct.
  912. public function test_all_the_language_files() {
  913. $files = array( // Only files with these names will be loaded/tested.
  914. 'trad4all.inc.php',
  915. );
  916. $languages = test_get_language_folder_list();
  917. $lang_dir = api_get_path(SYS_LANG_PATH);
  918. foreach ($languages as $language) {
  919. echo 'Language: <strong>'.ucwords($language).'</strong><br />';
  920. echo '-------------------------------------------------------------------------<br />';
  921. foreach ($files as $file) {
  922. echo 'Loading '.$lang_dir.$language.'/<strong>'.$file.'</strong> ...<br />';
  923. test_load_php_language_file($lang_dir.$language.'/'.$file);
  924. }
  925. echo '<br />';
  926. }
  927. $this->assertTrue(true); // Once we arrived here, the test is Ok.
  928. }
  929. */
  930. }
  931. // An isolated namespace for testing whether language files load successfully.
  932. function test_load_php_language_file($filename) {
  933. include $filename;
  934. }
  935. // A helper function.
  936. function test_get_language_folder_list() {
  937. $result = array();
  938. $exceptions = array('.', '..', 'CVS', '.svn');
  939. $dirname = api_get_path(SYS_LANG_PATH);
  940. $handle = opendir($dirname);
  941. while ($entries = readdir($handle)) {
  942. if (in_array($entries, $exceptions)) {
  943. continue;
  944. }
  945. if (is_dir($dirname.$entries)) {
  946. $result[] = $entries;
  947. }
  948. }
  949. closedir($handle);
  950. sort($result);
  951. return $result;
  952. }
  953. ?>