locale.test 121 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143
  1. <?php
  2. /**
  3. * @file
  4. * Tests for locale.module.
  5. *
  6. * The test file includes:
  7. * - a functional test for the language configuration forms;
  8. * - functional tests for the translation functionalities, including searching;
  9. * - a functional test for the PO files import feature, including validation;
  10. * - functional tests for translations and templates export feature;
  11. * - functional tests for the uninstall process;
  12. * - a functional test for the language switching feature;
  13. * - a functional test for a user's ability to change their default language;
  14. * - a functional test for configuring a different path alias per language;
  15. * - a functional test for configuring a different path alias per language;
  16. * - a functional test for multilingual support by content type and on nodes.
  17. * - a functional test for multilingual fields.
  18. * - a functional test for comment language.
  19. * - a functional test fot language types/negotiation info.
  20. */
  21. /**
  22. * Functional tests for the language configuration forms.
  23. */
  24. class LocaleConfigurationTest extends DrupalWebTestCase {
  25. public static function getInfo() {
  26. return array(
  27. 'name' => 'Language configuration',
  28. 'description' => 'Adds a new locale and tests changing its status and the default language.',
  29. 'group' => 'Locale',
  30. );
  31. }
  32. function setUp() {
  33. parent::setUp('locale');
  34. }
  35. /**
  36. * Functional tests for adding, editing and deleting languages.
  37. */
  38. function testLanguageConfiguration() {
  39. global $base_url;
  40. // User to add and remove language.
  41. $admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages'));
  42. $this->drupalLogin($admin_user);
  43. // Add predefined language.
  44. $edit = array(
  45. 'langcode' => 'fr',
  46. );
  47. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add language'));
  48. $this->assertText('fr', 'Language added successfully.');
  49. $this->assertEqual($this->getUrl(), url('admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.');
  50. // Add custom language.
  51. // Code for the language.
  52. $langcode = 'xx';
  53. // The English name for the language.
  54. $name = $this->randomName(16);
  55. // The native name for the language.
  56. $native = $this->randomName(16);
  57. // The domain prefix.
  58. $prefix = $langcode;
  59. $edit = array(
  60. 'langcode' => $langcode,
  61. 'name' => $name,
  62. 'native' => $native,
  63. 'prefix' => $prefix,
  64. 'direction' => '0',
  65. );
  66. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
  67. $this->assertEqual($this->getUrl(), url('admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.');
  68. $this->assertText($langcode, 'Language code found.');
  69. $this->assertText($name, 'Name found.');
  70. $this->assertText($native, 'Native found.');
  71. $this->assertText($native, 'Test language added.');
  72. // Check if we can change the default language.
  73. $path = 'admin/config/regional/language';
  74. $this->drupalGet($path);
  75. $this->assertFieldChecked('edit-site-default-en', 'English is the default language.');
  76. // Change the default language.
  77. $edit = array(
  78. 'site_default' => $langcode,
  79. );
  80. $this->drupalPost(NULL, $edit, t('Save configuration'));
  81. $this->assertNoFieldChecked('edit-site-default-en', 'Default language updated.');
  82. $this->assertEqual($this->getUrl(), url('admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.');
  83. // Check if a valid language prefix is added after changing the default
  84. // language.
  85. $this->drupalGet('admin/config/regional/language/edit/en');
  86. $this->assertFieldByXPath('//input[@name="prefix"]', 'en', 'A valid path prefix has been added to the previous default language.');
  87. // Ensure we can't delete the default language.
  88. $this->drupalGet('admin/config/regional/language/delete/' . $langcode);
  89. $this->assertEqual($this->getUrl(), url('admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.');
  90. $this->assertText(t('The default language cannot be deleted.'), 'Failed to delete the default language.');
  91. // Check if we can disable a language.
  92. $edit = array(
  93. 'enabled[en]' => FALSE,
  94. );
  95. $this->drupalPost($path, $edit, t('Save configuration'));
  96. $this->assertNoFieldChecked('edit-enabled-en', 'Language disabled.');
  97. // Set disabled language to be the default and ensure it is re-enabled.
  98. $edit = array(
  99. 'site_default' => 'en',
  100. );
  101. $this->drupalPost(NULL, $edit, t('Save configuration'));
  102. $this->assertFieldChecked('edit-enabled-en', 'Default language re-enabled.');
  103. // Ensure 'edit' link works.
  104. $this->clickLink(t('edit'));
  105. $this->assertTitle(t('Edit language | Drupal'), 'Page title is "Edit language".');
  106. // Edit a language.
  107. $name = $this->randomName(16);
  108. $edit = array(
  109. 'name' => $name,
  110. );
  111. $this->drupalPost('admin/config/regional/language/edit/' . $langcode, $edit, t('Save language'));
  112. $this->assertRaw($name, 'The language has been updated.');
  113. $this->assertEqual($this->getUrl(), url('admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.');
  114. // Ensure 'delete' link works.
  115. $this->drupalGet('admin/config/regional/language');
  116. $this->clickLink(t('delete'));
  117. $this->assertText(t('Are you sure you want to delete the language'), '"delete" link is correct.');
  118. // Delete an enabled language.
  119. $this->drupalGet('admin/config/regional/language/delete/' . $langcode);
  120. // First test the 'cancel' link.
  121. $this->clickLink(t('Cancel'));
  122. $this->assertEqual($this->getUrl(), url('admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.');
  123. $this->assertRaw($name, 'The language was not deleted.');
  124. // Delete the language for real. This a confirm form, we do not need any
  125. // fields changed.
  126. $this->drupalPost('admin/config/regional/language/delete/' . $langcode, array(), t('Delete'));
  127. // We need raw here because %locale will add HTML.
  128. $this->assertRaw(t('The language %locale has been removed.', array('%locale' => $name)), 'The test language has been removed.');
  129. $this->assertEqual($this->getUrl(), url('admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.');
  130. // Verify that language is no longer found.
  131. $this->drupalGet('admin/config/regional/language/delete/' . $langcode);
  132. $this->assertResponse(404, 'Language no longer found.');
  133. // Make sure the "language_count" variable has been updated correctly.
  134. drupal_static_reset('language_list');
  135. $enabled = language_list('enabled');
  136. $this->assertEqual(variable_get('language_count', 1), count($enabled[1]), 'Language count is correct.');
  137. // Delete a disabled language.
  138. // Disable an enabled language.
  139. $edit = array(
  140. 'enabled[fr]' => FALSE,
  141. );
  142. $this->drupalPost($path, $edit, t('Save configuration'));
  143. $this->assertNoFieldChecked('edit-enabled-fr', 'French language disabled.');
  144. // Get the count of enabled languages.
  145. drupal_static_reset('language_list');
  146. $enabled = language_list('enabled');
  147. // Delete the disabled language.
  148. $this->drupalPost('admin/config/regional/language/delete/fr', array(), t('Delete'));
  149. // We need raw here because %locale will add HTML.
  150. $this->assertRaw(t('The language %locale has been removed.', array('%locale' => 'French')), 'Disabled language has been removed.');
  151. $this->assertEqual($this->getUrl(), url('admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.');
  152. // Verify that language is no longer found.
  153. $this->drupalGet('admin/config/regional/language/delete/fr');
  154. $this->assertResponse(404, 'Language no longer found.');
  155. // Make sure the "language_count" variable has not changed.
  156. $this->assertEqual(variable_get('language_count', 1), count($enabled[1]), 'Language count is correct.');
  157. // Ensure we can't delete the English language.
  158. $this->drupalGet('admin/config/regional/language/delete/en');
  159. $this->assertEqual($this->getUrl(), url('admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.');
  160. $this->assertText(t('The English language cannot be deleted.'), 'Failed to delete English language.');
  161. }
  162. }
  163. /**
  164. * Tests localization of the JavaScript libraries.
  165. *
  166. * Currently, only the jQuery datepicker is localized using Drupal translations.
  167. */
  168. class LocaleLibraryInfoAlterTest extends DrupalWebTestCase {
  169. public static function getInfo() {
  170. return array(
  171. 'name' => 'Javascript library localisation',
  172. 'description' => 'Tests the localisation of JavaScript libraries.',
  173. 'group' => 'Locale',
  174. );
  175. }
  176. function setUp() {
  177. parent::setUp('locale', 'locale_test');
  178. }
  179. /**
  180. * Verifies that the datepicker can be localized.
  181. *
  182. * @see locale_library_info_alter()
  183. */
  184. public function testLibraryInfoAlter() {
  185. drupal_add_library('system', 'ui.datepicker');
  186. $scripts = drupal_get_js();
  187. $this->assertTrue(strpos($scripts, 'locale.datepicker.js'), 'locale.datepicker.js added to scripts.');
  188. }
  189. }
  190. /**
  191. * Functional tests for JavaScript parsing for translatable strings.
  192. */
  193. class LocaleJavascriptTranslationTest extends DrupalWebTestCase {
  194. public static function getInfo() {
  195. return array(
  196. 'name' => 'Javascript translation',
  197. 'description' => 'Tests parsing js files for translatable strings',
  198. 'group' => 'Locale',
  199. );
  200. }
  201. function setUp() {
  202. parent::setUp('locale', 'locale_test');
  203. }
  204. function testFileParsing() {
  205. $filename = drupal_get_path('module', 'locale_test') . '/locale_test.js';
  206. // Parse the file to look for source strings.
  207. _locale_parse_js_file($filename);
  208. // Get all of the source strings that were found.
  209. $source_strings = db_select('locales_source', 's')
  210. ->fields('s', array('source', 'context'))
  211. ->condition('s.location', $filename)
  212. ->execute()
  213. ->fetchAllKeyed();
  214. // List of all strings that should be in the file.
  215. $test_strings = array(
  216. "Standard Call t" => '',
  217. "Whitespace Call t" => '',
  218. "Single Quote t" => '',
  219. "Single Quote \\'Escaped\\' t" => '',
  220. "Single Quote Concat strings t" => '',
  221. "Double Quote t" => '',
  222. "Double Quote \\\"Escaped\\\" t" => '',
  223. "Double Quote Concat strings t" => '',
  224. "Context !key Args t" => "Context string",
  225. "Context Unquoted t" => "Context string unquoted",
  226. "Context Single Quoted t" => "Context string single quoted",
  227. "Context Double Quoted t" => "Context string double quoted",
  228. "Standard Call plural" => '',
  229. "Standard Call @count plural" => '',
  230. "Whitespace Call plural" => '',
  231. "Whitespace Call @count plural" => '',
  232. "Single Quote plural" => '',
  233. "Single Quote @count plural" => '',
  234. "Single Quote \\'Escaped\\' plural" => '',
  235. "Single Quote \\'Escaped\\' @count plural" => '',
  236. "Double Quote plural" => '',
  237. "Double Quote @count plural" => '',
  238. "Double Quote \\\"Escaped\\\" plural" => '',
  239. "Double Quote \\\"Escaped\\\" @count plural" => '',
  240. "Context !key Args plural" => "Context string",
  241. "Context !key Args @count plural" => "Context string",
  242. "Context Unquoted plural" => "Context string unquoted",
  243. "Context Unquoted @count plural" => "Context string unquoted",
  244. "Context Single Quoted plural" => "Context string single quoted",
  245. "Context Single Quoted @count plural" => "Context string single quoted",
  246. "Context Double Quoted plural" => "Context string double quoted",
  247. "Context Double Quoted @count plural" => "Context string double quoted",
  248. );
  249. // Assert that all strings were found properly.
  250. foreach ($test_strings as $str => $context) {
  251. $args = array('%source' => $str, '%context' => $context);
  252. // Make sure that the string was found in the file.
  253. $this->assertTrue(isset($source_strings[$str]), format_string('Found source string: %source', $args));
  254. // Make sure that the proper context was matched.
  255. $this->assertTrue(isset($source_strings[$str]) && $source_strings[$str] === $context, strlen($context) > 0 ? format_string('Context for %source is %context', $args) : format_string('Context for %source is blank', $args));
  256. }
  257. $this->assertEqual(count($source_strings), count($test_strings), 'Found correct number of source strings.');
  258. }
  259. }
  260. /**
  261. * Functional test for string translation and validation.
  262. */
  263. class LocaleTranslationFunctionalTest extends DrupalWebTestCase {
  264. public static function getInfo() {
  265. return array(
  266. 'name' => 'String translate, search and validate',
  267. 'description' => 'Adds a new locale and translates its name. Checks the validation of translation strings and search results.',
  268. 'group' => 'Locale',
  269. );
  270. }
  271. function setUp() {
  272. parent::setUp('locale');
  273. }
  274. /**
  275. * Adds a language and tests string translation by users with the appropriate permissions.
  276. */
  277. function testStringTranslation() {
  278. global $base_url;
  279. // User to add and remove language.
  280. $admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages'));
  281. // User to translate and delete string.
  282. $translate_user = $this->drupalCreateUser(array('translate interface', 'access administration pages'));
  283. // Code for the language.
  284. $langcode = 'xx';
  285. // The English name for the language. This will be translated.
  286. $name = $this->randomName(16);
  287. // The native name for the language.
  288. $native = $this->randomName(16);
  289. // The domain prefix.
  290. $prefix = $langcode;
  291. // This is the language indicator on the translation search screen for
  292. // untranslated strings. Copied straight from locale.inc.
  293. $language_indicator = "<em class=\"locale-untranslated\">$langcode</em> ";
  294. // This will be the translation of $name.
  295. $translation = $this->randomName(16);
  296. // Add custom language.
  297. $this->drupalLogin($admin_user);
  298. $edit = array(
  299. 'langcode' => $langcode,
  300. 'name' => $name,
  301. 'native' => $native,
  302. 'prefix' => $prefix,
  303. 'direction' => '0',
  304. );
  305. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
  306. // Add string.
  307. t($name, array(), array('langcode' => $langcode));
  308. // Reset locale cache.
  309. locale_reset();
  310. $this->assertText($langcode, 'Language code found.');
  311. $this->assertText($name, 'Name found.');
  312. $this->assertText($native, 'Native found.');
  313. // No t() here, we do not want to add this string to the database and it's
  314. // surely not translated yet.
  315. $this->assertText($native, 'Test language added.');
  316. $this->drupalLogout();
  317. // Search for the name and translate it.
  318. $this->drupalLogin($translate_user);
  319. $search = array(
  320. 'string' => $name,
  321. 'language' => 'all',
  322. 'translation' => 'all',
  323. 'group' => 'all',
  324. );
  325. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  326. // assertText() seems to remove the input field where $name always could be
  327. // found, so this is not a false assert. See how assertNoText succeeds
  328. // later.
  329. $this->assertText($name, 'Search found the name.');
  330. $this->assertRaw($language_indicator, 'Name is untranslated.');
  331. // Assume this is the only result, given the random name.
  332. $this->clickLink(t('edit'));
  333. // We save the lid from the path.
  334. $matches = array();
  335. preg_match('!admin/config/regional/translate/edit/(\d+)!', $this->getUrl(), $matches);
  336. $lid = $matches[1];
  337. // No t() here, it's surely not translated yet.
  338. $this->assertText($name, 'name found on edit screen.');
  339. $edit = array(
  340. "translations[$langcode]" => $translation,
  341. );
  342. $this->drupalPost(NULL, $edit, t('Save translations'));
  343. $this->assertText(t('The string has been saved.'), 'The string has been saved.');
  344. $this->assertEqual($this->getUrl(), url('admin/config/regional/translate/translate', array('absolute' => TRUE)), 'Correct page redirection.');
  345. $this->assertTrue($name != $translation && t($name, array(), array('langcode' => $langcode)) == $translation, 't() works.');
  346. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  347. // The indicator should not be here.
  348. $this->assertNoRaw($language_indicator, 'String is translated.');
  349. // Try to edit a non-existent string and ensure we're redirected correctly.
  350. // Assuming we don't have 999,999 strings already.
  351. $random_lid = 999999;
  352. $this->drupalGet('admin/config/regional/translate/edit/' . $random_lid);
  353. $this->assertText(t('String not found'), 'String not found.');
  354. $this->assertEqual($this->getUrl(), url('admin/config/regional/translate/translate', array('absolute' => TRUE)), 'Correct page redirection.');
  355. $this->drupalLogout();
  356. // Delete the language.
  357. $this->drupalLogin($admin_user);
  358. $path = 'admin/config/regional/language/delete/' . $langcode;
  359. // This a confirm form, we do not need any fields changed.
  360. $this->drupalPost($path, array(), t('Delete'));
  361. // We need raw here because %locale will add HTML.
  362. $this->assertRaw(t('The language %locale has been removed.', array('%locale' => $name)), 'The test language has been removed.');
  363. // Reload to remove $name.
  364. $this->drupalGet($path);
  365. // Verify that language is no longer found.
  366. $this->assertResponse(404, 'Language no longer found.');
  367. $this->drupalLogout();
  368. // Delete the string.
  369. $this->drupalLogin($translate_user);
  370. $search = array(
  371. 'string' => $name,
  372. 'language' => 'all',
  373. 'translation' => 'all',
  374. 'group' => 'all',
  375. );
  376. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  377. // Assume this is the only result, given the random name.
  378. $this->clickLink(t('delete'));
  379. $this->assertText(t('Are you sure you want to delete the string'), '"delete" link is correct.');
  380. // Delete the string.
  381. $path = 'admin/config/regional/translate/delete/' . $lid;
  382. $this->drupalGet($path);
  383. // First test the 'cancel' link.
  384. $this->clickLink(t('Cancel'));
  385. $this->assertEqual($this->getUrl(), url('admin/config/regional/translate/translate', array('absolute' => TRUE)), 'Correct page redirection.');
  386. $this->assertRaw($name, 'The string was not deleted.');
  387. // Delete the name string.
  388. $this->drupalPost('admin/config/regional/translate/delete/' . $lid, array(), t('Delete'));
  389. $this->assertText(t('The string has been removed.'), 'The string has been removed message.');
  390. $this->assertEqual($this->getUrl(), url('admin/config/regional/translate/translate', array('absolute' => TRUE)), 'Correct page redirection.');
  391. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  392. $this->assertNoText($name, 'Search now can not find the name.');
  393. }
  394. /*
  395. * Adds a language and checks that the JavaScript translation files are
  396. * properly created and rebuilt on deletion.
  397. */
  398. function testJavaScriptTranslation() {
  399. $user = $this->drupalCreateUser(array('translate interface', 'administer languages', 'access administration pages'));
  400. $this->drupalLogin($user);
  401. $langcode = 'xx';
  402. // The English name for the language. This will be translated.
  403. $name = $this->randomName(16);
  404. // The native name for the language.
  405. $native = $this->randomName(16);
  406. // The domain prefix.
  407. $prefix = $langcode;
  408. // Add custom language.
  409. $edit = array(
  410. 'langcode' => $langcode,
  411. 'name' => $name,
  412. 'native' => $native,
  413. 'prefix' => $prefix,
  414. 'direction' => '0',
  415. );
  416. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
  417. drupal_static_reset('language_list');
  418. // Build the JavaScript translation file.
  419. $this->drupalGet('admin/config/regional/translate/translate');
  420. // Retrieve the id of the first string available in the {locales_source}
  421. // table and translate it.
  422. $query = db_select('locales_source', 'l');
  423. $query->addExpression('min(l.lid)', 'lid');
  424. $result = $query->condition('l.location', '%.js%', 'LIKE')
  425. ->condition('l.textgroup', 'default')
  426. ->execute();
  427. $url = 'admin/config/regional/translate/edit/' . $result->fetchObject()->lid;
  428. $edit = array('translations['. $langcode .']' => $this->randomName());
  429. $this->drupalPost($url, $edit, t('Save translations'));
  430. // Trigger JavaScript translation parsing and building.
  431. require_once DRUPAL_ROOT . '/includes/locale.inc';
  432. _locale_rebuild_js($langcode);
  433. // Retrieve the JavaScript translation hash code for the custom language to
  434. // check that the translation file has been properly built.
  435. $file = db_select('languages', 'l')
  436. ->fields('l', array('javascript'))
  437. ->condition('language', $langcode)
  438. ->execute()
  439. ->fetchObject();
  440. $js_file = 'public://' . variable_get('locale_js_directory', 'languages') . '/' . $langcode . '_' . $file->javascript . '.js';
  441. $this->assertTrue($result = file_exists($js_file), format_string('JavaScript file created: %file', array('%file' => $result ? $js_file : 'not found')));
  442. // Test JavaScript translation rebuilding.
  443. file_unmanaged_delete($js_file);
  444. $this->assertTrue($result = !file_exists($js_file), format_string('JavaScript file deleted: %file', array('%file' => $result ? $js_file : 'found')));
  445. cache_clear_all();
  446. _locale_rebuild_js($langcode);
  447. $this->assertTrue($result = file_exists($js_file), format_string('JavaScript file rebuilt: %file', array('%file' => $result ? $js_file : 'not found')));
  448. }
  449. /**
  450. * Tests the validation of the translation input.
  451. */
  452. function testStringValidation() {
  453. global $base_url;
  454. // User to add language and strings.
  455. $admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages', 'translate interface'));
  456. $this->drupalLogin($admin_user);
  457. $langcode = 'xx';
  458. // The English name for the language. This will be translated.
  459. $name = $this->randomName(16);
  460. // The native name for the language.
  461. $native = $this->randomName(16);
  462. // The domain prefix.
  463. $prefix = $langcode;
  464. // This is the language indicator on the translation search screen for
  465. // untranslated strings. Copied straight from locale.inc.
  466. $language_indicator = "<em class=\"locale-untranslated\">$langcode</em> ";
  467. // These will be the invalid translations of $name.
  468. $key = $this->randomName(16);
  469. $bad_translations[$key] = "<script>alert('xss');</script>" . $key;
  470. $key = $this->randomName(16);
  471. $bad_translations[$key] = '<img SRC="javascript:alert(\'xss\');">' . $key;
  472. $key = $this->randomName(16);
  473. $bad_translations[$key] = '<<SCRIPT>alert("xss");//<</SCRIPT>' . $key;
  474. $key = $this->randomName(16);
  475. $bad_translations[$key] ="<BODY ONLOAD=alert('xss')>" . $key;
  476. // Add custom language.
  477. $edit = array(
  478. 'langcode' => $langcode,
  479. 'name' => $name,
  480. 'native' => $native,
  481. 'prefix' => $prefix,
  482. 'direction' => '0',
  483. );
  484. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
  485. // Add string.
  486. t($name, array(), array('langcode' => $langcode));
  487. // Reset locale cache.
  488. $search = array(
  489. 'string' => $name,
  490. 'language' => 'all',
  491. 'translation' => 'all',
  492. 'group' => 'all',
  493. );
  494. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  495. // Find the edit path.
  496. $content = $this->drupalGetContent();
  497. $this->assertTrue(preg_match('@(admin/config/regional/translate/edit/[0-9]+)@', $content, $matches), 'Found the edit path.');
  498. $path = $matches[0];
  499. foreach ($bad_translations as $key => $translation) {
  500. $edit = array(
  501. "translations[$langcode]" => $translation,
  502. );
  503. $this->drupalPost($path, $edit, t('Save translations'));
  504. // Check for a form error on the textarea.
  505. $form_class = $this->xpath('//form[@id="locale-translate-edit-form"]//textarea/@class');
  506. $this->assertNotIdentical(FALSE, strpos($form_class[0], 'error'), 'The string was rejected as unsafe.');
  507. $this->assertNoText(t('The string has been saved.'), 'The string was not saved.');
  508. }
  509. }
  510. /**
  511. * Tests translation search form.
  512. */
  513. function testStringSearch() {
  514. global $base_url;
  515. // User to add and remove language.
  516. $admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages'));
  517. // User to translate and delete string.
  518. $translate_user = $this->drupalCreateUser(array('translate interface', 'access administration pages'));
  519. // Code for the language.
  520. $langcode = 'xx';
  521. // The English name for the language. This will be translated.
  522. $name = $this->randomName(16);
  523. // The native name for the language.
  524. $native = $this->randomName(16);
  525. // The domain prefix.
  526. $prefix = $langcode;
  527. // This is the language indicator on the translation search screen for
  528. // untranslated strings. Copied straight from locale.inc.
  529. $language_indicator = "<em class=\"locale-untranslated\">$langcode</em> ";
  530. // This will be the translation of $name.
  531. $translation = $this->randomName(16);
  532. // Add custom language.
  533. $this->drupalLogin($admin_user);
  534. $edit = array(
  535. 'langcode' => $langcode,
  536. 'name' => $name,
  537. 'native' => $native,
  538. 'prefix' => $prefix,
  539. 'direction' => '0',
  540. );
  541. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
  542. // Add string.
  543. t($name, array(), array('langcode' => $langcode));
  544. // Reset locale cache.
  545. locale_reset();
  546. $this->drupalLogout();
  547. // Search for the name.
  548. $this->drupalLogin($translate_user);
  549. $search = array(
  550. 'string' => $name,
  551. 'language' => 'all',
  552. 'translation' => 'all',
  553. 'group' => 'all',
  554. );
  555. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  556. // assertText() seems to remove the input field where $name always could be
  557. // found, so this is not a false assert. See how assertNoText succeeds
  558. // later.
  559. $this->assertText($name, 'Search found the string.');
  560. // Ensure untranslated string doesn't appear if searching on 'only
  561. // translated strings'.
  562. $search = array(
  563. 'string' => $name,
  564. 'language' => 'all',
  565. 'translation' => 'translated',
  566. 'group' => 'all',
  567. );
  568. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  569. $this->assertText(t('No strings available.'), "Search didn't find the string.");
  570. // Ensure untranslated string appears if searching on 'only untranslated
  571. // strings' in "all" (hasn't been translated to any language).
  572. $search = array(
  573. 'string' => $name,
  574. 'language' => 'all',
  575. 'translation' => 'untranslated',
  576. 'group' => 'all',
  577. );
  578. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  579. $this->assertNoText(t('No strings available.'), 'Search found the string.');
  580. // Ensure untranslated string appears if searching on 'only untranslated
  581. // strings' in the custom language (hasn't been translated to that specific language).
  582. $search = array(
  583. 'string' => $name,
  584. 'language' => $langcode,
  585. 'translation' => 'untranslated',
  586. 'group' => 'all',
  587. );
  588. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  589. $this->assertNoText(t('No strings available.'), 'Search found the string.');
  590. // Add translation.
  591. // Assume this is the only result, given the random name.
  592. $this->clickLink(t('edit'));
  593. // We save the lid from the path.
  594. $matches = array();
  595. preg_match('!admin/config/regional/translate/edit/(\d)+!', $this->getUrl(), $matches);
  596. $lid = $matches[1];
  597. $edit = array(
  598. "translations[$langcode]" => $translation,
  599. );
  600. $this->drupalPost(NULL, $edit, t('Save translations'));
  601. // Ensure translated string does appear if searching on 'only
  602. // translated strings'.
  603. $search = array(
  604. 'string' => $translation,
  605. 'language' => 'all',
  606. 'translation' => 'translated',
  607. 'group' => 'all',
  608. );
  609. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  610. $this->assertNoText(t('No strings available.'), 'Search found the translation.');
  611. // Ensure translated source string doesn't appear if searching on 'only
  612. // untranslated strings'.
  613. $search = array(
  614. 'string' => $name,
  615. 'language' => 'all',
  616. 'translation' => 'untranslated',
  617. 'group' => 'all',
  618. );
  619. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  620. $this->assertText(t('No strings available.'), "Search didn't find the source string.");
  621. // Ensure translated string doesn't appear if searching on 'only
  622. // untranslated strings'.
  623. $search = array(
  624. 'string' => $translation,
  625. 'language' => 'all',
  626. 'translation' => 'untranslated',
  627. 'group' => 'all',
  628. );
  629. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  630. $this->assertText(t('No strings available.'), "Search didn't find the translation.");
  631. // Ensure translated string does appear if searching on the custom language.
  632. $search = array(
  633. 'string' => $translation,
  634. 'language' => $langcode,
  635. 'translation' => 'all',
  636. 'group' => 'all',
  637. );
  638. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  639. $this->assertNoText(t('No strings available.'), 'Search found the translation.');
  640. // Ensure translated string doesn't appear if searching on English.
  641. $search = array(
  642. 'string' => $translation,
  643. 'language' => 'en',
  644. 'translation' => 'all',
  645. 'group' => 'all',
  646. );
  647. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  648. $this->assertText(t('No strings available.'), "Search didn't find the translation.");
  649. // Search for a string that isn't in the system.
  650. $unavailable_string = $this->randomName(16);
  651. $search = array(
  652. 'string' => $unavailable_string,
  653. 'language' => 'all',
  654. 'translation' => 'all',
  655. 'group' => 'all',
  656. );
  657. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  658. $this->assertText(t('No strings available.'), "Search didn't find the invalid string.");
  659. }
  660. }
  661. /**
  662. * Tests plural index computation functionality.
  663. */
  664. class LocalePluralFormatTest extends DrupalWebTestCase {
  665. public static function getInfo() {
  666. return array(
  667. 'name' => 'Plural formula evaluation',
  668. 'description' => 'Tests plural formula evaluation for various languages.',
  669. 'group' => 'Locale',
  670. );
  671. }
  672. function setUp() {
  673. parent::setUp('locale', 'locale_test');
  674. $admin_user = $this->drupalCreateUser(array('administer languages', 'translate interface', 'access administration pages'));
  675. $this->drupalLogin($admin_user);
  676. // Import some .po files with formulas to set up the environment.
  677. // These will also add the languages to the system and enable them.
  678. $this->importPoFile($this->getPoFileWithSimplePlural(), array(
  679. 'langcode' => 'fr',
  680. ));
  681. $this->importPoFile($this->getPoFileWithComplexPlural(), array(
  682. 'langcode' => 'hr',
  683. ));
  684. }
  685. /**
  686. * Tests locale_get_plural() functionality.
  687. */
  688. function testGetPluralFormat() {
  689. $this->drupalGet('locale_test_plural_format_page');
  690. $tests = _locale_test_plural_format_tests();
  691. $result = array();
  692. foreach ($tests as $test) {
  693. $this->assertPluralFormat($test['count'], $test['language'], $test['expected-result']);
  694. }
  695. }
  696. /**
  697. * Helper assert to test locale_get_plural page.
  698. *
  699. * @param $count
  700. * Number for testing.
  701. * @param $lang
  702. * Language for testing
  703. * @param $expected_result
  704. * Expected result.
  705. * @param $message
  706. */
  707. function assertPluralFormat($count, $lang, $expected_result) {
  708. $message_param = array(
  709. '@lang' => $lang,
  710. '@count' => $count,
  711. '@expected_result' => $expected_result,
  712. );
  713. $message = t("Computed plural index for '@lang' with count @count is @expected_result.", $message_param);
  714. $message_param = array(
  715. '@lang' => $lang,
  716. '@expected_result' => $expected_result,
  717. );
  718. $this->assertText(format_string('Language: @lang, locale_get_plural: @expected_result.', $message_param, $message));
  719. }
  720. /**
  721. * Imports a standalone .po file in a given language.
  722. *
  723. * @param $contents
  724. * Contents of the .po file to import.
  725. * @param $options
  726. * Additional options to pass to the translation import form.
  727. */
  728. function importPoFile($contents, array $options = array()) {
  729. $name = tempnam('temporary://', "po_") . '.po';
  730. file_put_contents($name, $contents);
  731. $options['files[file]'] = $name;
  732. $this->drupalPost('admin/config/regional/translate/import', $options, t('Import'));
  733. drupal_unlink($name);
  734. }
  735. /**
  736. * Returns a .po file with a simple plural formula.
  737. */
  738. function getPoFileWithSimplePlural() {
  739. return <<< EOF
  740. msgid ""
  741. msgstr ""
  742. "Project-Id-Version: Drupal 7\\n"
  743. "MIME-Version: 1.0\\n"
  744. "Content-Type: text/plain; charset=UTF-8\\n"
  745. "Content-Transfer-Encoding: 8bit\\n"
  746. "Plural-Forms: nplurals=2; plural=(n!=1);\\n"
  747. msgid "One sheep"
  748. msgid_plural "@count sheep"
  749. msgstr[0] "un mouton"
  750. msgstr[1] "@count moutons"
  751. msgid "Monday"
  752. msgstr "lundi"
  753. EOF;
  754. }
  755. /**
  756. * Returns a .po file with a complex plural formula.
  757. */
  758. function getPoFileWithComplexPlural() {
  759. return <<< EOF
  760. msgid ""
  761. msgstr ""
  762. "Project-Id-Version: Drupal 7\\n"
  763. "MIME-Version: 1.0\\n"
  764. "Content-Type: text/plain; charset=UTF-8\\n"
  765. "Content-Transfer-Encoding: 8bit\\n"
  766. "Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\\n"
  767. msgid "1 hour"
  768. msgid_plural "@count hours"
  769. msgstr[0] "@count sat"
  770. msgstr[1] "@count sata"
  771. msgstr[2] "@count sati"
  772. msgid "Monday"
  773. msgstr "Ponedjeljak"
  774. EOF;
  775. }
  776. }
  777. /**
  778. * Functional tests for the import of translation files.
  779. */
  780. class LocaleImportFunctionalTest extends DrupalWebTestCase {
  781. public static function getInfo() {
  782. return array(
  783. 'name' => 'Translation import',
  784. 'description' => 'Tests the import of locale files.',
  785. 'group' => 'Locale',
  786. );
  787. }
  788. /**
  789. * A user able to create languages and import translations.
  790. */
  791. protected $admin_user = NULL;
  792. function setUp() {
  793. parent::setUp('locale', 'locale_test');
  794. $this->admin_user = $this->drupalCreateUser(array('administer languages', 'translate interface', 'access administration pages'));
  795. $this->drupalLogin($this->admin_user);
  796. }
  797. /**
  798. * Test import of standalone .po files.
  799. */
  800. function testStandalonePoFile() {
  801. // Try importing a .po file.
  802. $this->importPoFile($this->getPoFile(), array(
  803. 'langcode' => 'fr',
  804. ));
  805. // The import should automatically create the corresponding language.
  806. $this->assertRaw(t('The language %language has been created.', array('%language' => 'French')), 'The language has been automatically created.');
  807. // The import should have created 7 strings.
  808. $this->assertRaw(t('The translation was successfully imported. There are %number newly created translated strings, %update strings were updated and %delete strings were removed.', array('%number' => 9, '%update' => 0, '%delete' => 0)), 'The translation file was successfully imported.');
  809. // This import should have saved plural forms to have 2 variants.
  810. $this->assert(db_query("SELECT plurals FROM {languages} WHERE language = 'fr'")->fetchField() == 2, 'Plural number initialized.');
  811. // Ensure we were redirected correctly.
  812. $this->assertEqual($this->getUrl(), url('admin/config/regional/translate', array('absolute' => TRUE)), 'Correct page redirection.');
  813. // Try importing a .po file with invalid tags in the default text group.
  814. $this->importPoFile($this->getBadPoFile(), array(
  815. 'langcode' => 'fr',
  816. ));
  817. // The import should have created 1 string and rejected 2.
  818. $this->assertRaw(t('The translation was successfully imported. There are %number newly created translated strings, %update strings were updated and %delete strings were removed.', array('%number' => 1, '%update' => 0, '%delete' => 0)), 'The translation file was successfully imported.');
  819. $skip_message = format_plural(2, 'One translation string was skipped because it contains disallowed HTML.', '@count translation strings were skipped because they contain disallowed HTML.');
  820. $this->assertRaw($skip_message, 'Unsafe strings were skipped.');
  821. // Try importing a .po file with invalid tags in a non default text group.
  822. $this->importPoFile($this->getBadPoFile(), array(
  823. 'langcode' => 'fr',
  824. 'group' => 'custom',
  825. ));
  826. // The import should have created 3 strings.
  827. $this->assertRaw(t('The translation was successfully imported. There are %number newly created translated strings, %update strings were updated and %delete strings were removed.', array('%number' => 3, '%update' => 0, '%delete' => 0)), 'The translation file was successfully imported.');
  828. // Try importing a .po file which doesn't exist.
  829. $name = $this->randomName(16);
  830. $this->drupalPost('admin/config/regional/translate/import', array(
  831. 'langcode' => 'fr',
  832. 'files[file]' => $name,
  833. 'group' => 'custom',
  834. ), t('Import'));
  835. $this->assertEqual($this->getUrl(), url('admin/config/regional/translate/import', array('absolute' => TRUE)), 'Correct page redirection.');
  836. $this->assertText(t('File to import not found.'), 'File to import not found message.');
  837. // Try importing a .po file with overriding strings, and ensure existing
  838. // strings are kept.
  839. $this->importPoFile($this->getOverwritePoFile(), array(
  840. 'langcode' => 'fr',
  841. 'mode' => 1, // Existing strings are kept, only new strings are added.
  842. ));
  843. // The import should have created 1 string.
  844. $this->assertRaw(t('The translation was successfully imported. There are %number newly created translated strings, %update strings were updated and %delete strings were removed.', array('%number' => 1, '%update' => 0, '%delete' => 0)), 'The translation file was successfully imported.');
  845. // Ensure string wasn't overwritten.
  846. $search = array(
  847. 'string' => 'Montag',
  848. 'language' => 'fr',
  849. 'translation' => 'translated',
  850. 'group' => 'all',
  851. );
  852. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  853. $this->assertText(t('No strings available.'), 'String not overwritten by imported string.');
  854. // This import should not have changed number of plural forms.
  855. $this->assert(db_query("SELECT plurals FROM {languages} WHERE language = 'fr'")->fetchField() == 2, 'Plural numbers untouched.');
  856. $this->importPoFile($this->getPoFileWithBrokenPlural(), array(
  857. 'langcode' => 'fr',
  858. 'mode' => 1, // Existing strings are kept, only new strings are added.
  859. ));
  860. // Attempt to import broken .po file as well to prove that this
  861. // will not overwrite the proper plural formula imported above.
  862. $this->assert(db_query("SELECT plurals FROM {languages} WHERE language = 'fr'")->fetchField() == 2, 'Broken plurals: plural numbers untouched.');
  863. $this->importPoFile($this->getPoFileWithMissingPlural(), array(
  864. 'langcode' => 'fr',
  865. 'mode' => 1, // Existing strings are kept, only new strings are added.
  866. ));
  867. // Attempt to import .po file which has no plurals and prove that this
  868. // will not overwrite the proper plural formula imported above.
  869. $this->assert(db_query("SELECT plurals FROM {languages} WHERE language = 'fr'")->fetchField() == 2, 'No plurals: plural numbers untouched.');
  870. // Try importing a .po file with overriding strings, and ensure existing
  871. // strings are overwritten.
  872. $this->importPoFile($this->getOverwritePoFile(), array(
  873. 'langcode' => 'fr',
  874. 'mode' => 0, // Strings in the uploaded file replace existing ones, new ones are added.
  875. ));
  876. // The import should have updated 2 strings.
  877. $this->assertRaw(t('The translation was successfully imported. There are %number newly created translated strings, %update strings were updated and %delete strings were removed.', array('%number' => 0, '%update' => 2, '%delete' => 0)), 'The translation file was successfully imported.');
  878. // Ensure string was overwritten.
  879. $search = array(
  880. 'string' => 'Montag',
  881. 'language' => 'fr',
  882. 'translation' => 'translated',
  883. 'group' => 'all',
  884. );
  885. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  886. $this->assertNoText(t('No strings available.'), 'String overwritten by imported string.');
  887. // This import should have changed number of plural forms.
  888. $this->assert(db_query("SELECT plurals FROM {languages} WHERE language = 'fr'")->fetchField() == 3, 'Plural numbers changed.');
  889. }
  890. /**
  891. * Test automatic import of a module's translation files when a language is
  892. * enabled.
  893. */
  894. function testAutomaticModuleTranslationImportLanguageEnable() {
  895. // Code for the language - manually set to match the test translation file.
  896. $langcode = 'xx';
  897. // The English name for the language.
  898. $name = $this->randomName(16);
  899. // The native name for the language.
  900. $native = $this->randomName(16);
  901. // The domain prefix.
  902. $prefix = $langcode;
  903. // Create a custom language.
  904. $edit = array(
  905. 'langcode' => $langcode,
  906. 'name' => $name,
  907. 'native' => $native,
  908. 'prefix' => $prefix,
  909. 'direction' => '0',
  910. );
  911. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
  912. // Ensure the translation file was automatically imported when language was
  913. // added.
  914. $this->assertText(t('One translation file imported for the enabled modules.'), 'Language file automatically imported.');
  915. // Ensure strings were successfully imported.
  916. $search = array(
  917. 'string' => 'lundi',
  918. 'language' => $langcode,
  919. 'translation' => 'translated',
  920. 'group' => 'all',
  921. );
  922. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  923. $this->assertNoText(t('No strings available.'), 'String successfully imported.');
  924. }
  925. /**
  926. * Test msgctxt context support.
  927. */
  928. function testLanguageContext() {
  929. // Try importing a .po file.
  930. $this->importPoFile($this->getPoFileWithContext(), array(
  931. 'langcode' => 'hr',
  932. ));
  933. $this->assertIdentical(t('May', array(), array('langcode' => 'hr', 'context' => 'Long month name')), 'Svibanj', 'Long month name context is working.');
  934. $this->assertIdentical(t('May', array(), array('langcode' => 'hr')), 'Svi.', 'Default context is working.');
  935. }
  936. /**
  937. * Test empty msgstr at end of .po file see #611786.
  938. */
  939. function testEmptyMsgstr() {
  940. $langcode = 'hu';
  941. // Try importing a .po file.
  942. $this->importPoFile($this->getPoFileWithMsgstr(), array(
  943. 'langcode' => $langcode,
  944. ));
  945. $this->assertRaw(t('The translation was successfully imported. There are %number newly created translated strings, %update strings were updated and %delete strings were removed.', array('%number' => 1, '%update' => 0, '%delete' => 0)), 'The translation file was successfully imported.');
  946. $this->assertIdentical(t('Operations', array(), array('langcode' => $langcode)), 'Műveletek', 'String imported and translated.');
  947. // Try importing a .po file.
  948. $this->importPoFile($this->getPoFileWithEmptyMsgstr(), array(
  949. 'langcode' => $langcode,
  950. 'mode' => 0,
  951. ));
  952. $this->assertRaw(t('The translation was successfully imported. There are %number newly created translated strings, %update strings were updated and %delete strings were removed.', array('%number' => 0, '%update' => 0, '%delete' => 1)), 'The translation file was successfully imported.');
  953. // This is the language indicator on the translation search screen for
  954. // untranslated strings. Copied straight from locale.inc.
  955. $language_indicator = "<em class=\"locale-untranslated\">$langcode</em> ";
  956. $str = "Operations";
  957. $search = array(
  958. 'string' => $str,
  959. 'language' => 'all',
  960. 'translation' => 'all',
  961. 'group' => 'all',
  962. );
  963. $this->drupalPost('admin/config/regional/translate/translate', $search, t('Filter'));
  964. // assertText() seems to remove the input field where $str always could be
  965. // found, so this is not a false assert.
  966. $this->assertText($str, 'Search found the string.');
  967. $this->assertRaw($language_indicator, 'String is untranslated again.');
  968. }
  969. /**
  970. * Helper function: import a standalone .po file in a given language.
  971. *
  972. * @param $contents
  973. * Contents of the .po file to import.
  974. * @param $options
  975. * Additional options to pass to the translation import form.
  976. */
  977. function importPoFile($contents, array $options = array()) {
  978. $name = tempnam('temporary://', "po_") . '.po';
  979. file_put_contents($name, $contents);
  980. $options['files[file]'] = $name;
  981. $this->drupalPost('admin/config/regional/translate/import', $options, t('Import'));
  982. drupal_unlink($name);
  983. }
  984. /**
  985. * Helper function that returns a proper .po file.
  986. */
  987. function getPoFile() {
  988. return <<< EOF
  989. msgid ""
  990. msgstr ""
  991. "Project-Id-Version: Drupal 7\\n"
  992. "MIME-Version: 1.0\\n"
  993. "Content-Type: text/plain; charset=UTF-8\\n"
  994. "Content-Transfer-Encoding: 8bit\\n"
  995. "Plural-Forms: nplurals=2; plural=(n > 1);\\n"
  996. msgid "One sheep"
  997. msgid_plural "@count sheep"
  998. msgstr[0] "un mouton"
  999. msgstr[1] "@count moutons"
  1000. msgid "Monday"
  1001. msgstr "lundi"
  1002. msgid "Tuesday"
  1003. msgstr "mardi"
  1004. msgid "Wednesday"
  1005. msgstr "mercredi"
  1006. msgid "Thursday"
  1007. msgstr "jeudi"
  1008. msgid "Friday"
  1009. msgstr "vendredi"
  1010. msgid "Saturday"
  1011. msgstr "samedi"
  1012. msgid "Sunday"
  1013. msgstr "dimanche"
  1014. EOF;
  1015. }
  1016. /**
  1017. * Helper function that returns a bad .po file.
  1018. */
  1019. function getBadPoFile() {
  1020. return <<< EOF
  1021. msgid ""
  1022. msgstr ""
  1023. "Project-Id-Version: Drupal 7\\n"
  1024. "MIME-Version: 1.0\\n"
  1025. "Content-Type: text/plain; charset=UTF-8\\n"
  1026. "Content-Transfer-Encoding: 8bit\\n"
  1027. "Plural-Forms: nplurals=2; plural=(n > 1);\\n"
  1028. msgid "Save configuration"
  1029. msgstr "Enregistrer la configuration"
  1030. msgid "edit"
  1031. msgstr "modifier<img SRC="javascript:alert(\'xss\');">"
  1032. msgid "delete"
  1033. msgstr "supprimer<script>alert('xss');</script>"
  1034. EOF;
  1035. }
  1036. /**
  1037. * Helper function that returns a proper .po file, for testing overwriting
  1038. * existing translations.
  1039. */
  1040. function getOverwritePoFile() {
  1041. return <<< EOF
  1042. msgid ""
  1043. msgstr ""
  1044. "Project-Id-Version: Drupal 7\\n"
  1045. "MIME-Version: 1.0\\n"
  1046. "Content-Type: text/plain; charset=UTF-8\\n"
  1047. "Content-Transfer-Encoding: 8bit\\n"
  1048. "Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\\n"
  1049. msgid "Monday"
  1050. msgstr "Montag"
  1051. msgid "Day"
  1052. msgstr "Jour"
  1053. EOF;
  1054. }
  1055. /**
  1056. * Helper function that returns a .po file with context.
  1057. */
  1058. function getPoFileWithContext() {
  1059. // Croatian (code hr) is one the the languages that have a different
  1060. // form for the full name and the abbreviated name for the month May.
  1061. return <<< EOF
  1062. msgid ""
  1063. msgstr ""
  1064. "Project-Id-Version: Drupal 7\\n"
  1065. "MIME-Version: 1.0\\n"
  1066. "Content-Type: text/plain; charset=UTF-8\\n"
  1067. "Content-Transfer-Encoding: 8bit\\n"
  1068. "Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\\n"
  1069. msgctxt "Long month name"
  1070. msgid "May"
  1071. msgstr "Svibanj"
  1072. msgid "May"
  1073. msgstr "Svi."
  1074. EOF;
  1075. }
  1076. /**
  1077. * Helper function that returns a .po file with an empty last item.
  1078. */
  1079. function getPoFileWithEmptyMsgstr() {
  1080. return <<< EOF
  1081. msgid ""
  1082. msgstr ""
  1083. "Project-Id-Version: Drupal 7\\n"
  1084. "MIME-Version: 1.0\\n"
  1085. "Content-Type: text/plain; charset=UTF-8\\n"
  1086. "Content-Transfer-Encoding: 8bit\\n"
  1087. "Plural-Forms: nplurals=2; plural=(n > 1);\\n"
  1088. msgid "Operations"
  1089. msgstr ""
  1090. EOF;
  1091. }
  1092. /**
  1093. * Helper function that returns a .po file with an empty last item.
  1094. */
  1095. function getPoFileWithMsgstr() {
  1096. return <<< EOF
  1097. msgid ""
  1098. msgstr ""
  1099. "Project-Id-Version: Drupal 7\\n"
  1100. "MIME-Version: 1.0\\n"
  1101. "Content-Type: text/plain; charset=UTF-8\\n"
  1102. "Content-Transfer-Encoding: 8bit\\n"
  1103. "Plural-Forms: nplurals=2; plural=(n > 1);\\n"
  1104. msgid "Operations"
  1105. msgstr "Műveletek"
  1106. msgid "Will not appear in Drupal core, so we can ensure the test passes"
  1107. msgstr ""
  1108. EOF;
  1109. }
  1110. /**
  1111. * Returns a .po file with a missing plural formula.
  1112. */
  1113. function getPoFileWithMissingPlural() {
  1114. return <<< EOF
  1115. msgid ""
  1116. msgstr ""
  1117. "Project-Id-Version: Drupal 7\\n"
  1118. "MIME-Version: 1.0\\n"
  1119. "Content-Type: text/plain; charset=UTF-8\\n"
  1120. "Content-Transfer-Encoding: 8bit\\n"
  1121. msgid "Monday"
  1122. msgstr "Ponedjeljak"
  1123. EOF;
  1124. }
  1125. /**
  1126. * Returns a .po file with a broken plural formula.
  1127. */
  1128. function getPoFileWithBrokenPlural() {
  1129. return <<< EOF
  1130. msgid ""
  1131. msgstr ""
  1132. "Project-Id-Version: Drupal 7\\n"
  1133. "MIME-Version: 1.0\\n"
  1134. "Content-Type: text/plain; charset=UTF-8\\n"
  1135. "Content-Transfer-Encoding: 8bit\\n"
  1136. "Plural-Forms: broken, will not parse\\n"
  1137. msgid "Monday"
  1138. msgstr "lundi"
  1139. EOF;
  1140. }
  1141. }
  1142. /**
  1143. * Functional tests for the export of translation files.
  1144. */
  1145. class LocaleExportFunctionalTest extends DrupalWebTestCase {
  1146. public static function getInfo() {
  1147. return array(
  1148. 'name' => 'Translation export',
  1149. 'description' => 'Tests the exportation of locale files.',
  1150. 'group' => 'Locale',
  1151. );
  1152. }
  1153. /**
  1154. * A user able to create languages and export translations.
  1155. */
  1156. protected $admin_user = NULL;
  1157. function setUp() {
  1158. parent::setUp('locale', 'locale_test');
  1159. $this->admin_user = $this->drupalCreateUser(array('administer languages', 'translate interface', 'access administration pages'));
  1160. $this->drupalLogin($this->admin_user);
  1161. }
  1162. /**
  1163. * Test exportation of translations.
  1164. */
  1165. function testExportTranslation() {
  1166. // First import some known translations.
  1167. // This will also automatically enable the 'fr' language.
  1168. $name = tempnam('temporary://', "po_") . '.po';
  1169. file_put_contents($name, $this->getPoFile());
  1170. $this->drupalPost('admin/config/regional/translate/import', array(
  1171. 'langcode' => 'fr',
  1172. 'files[file]' => $name,
  1173. ), t('Import'));
  1174. drupal_unlink($name);
  1175. // Get the French translations.
  1176. $this->drupalPost('admin/config/regional/translate/export', array(
  1177. 'langcode' => 'fr',
  1178. ), t('Export'));
  1179. // Ensure we have a translation file.
  1180. $this->assertRaw('# French translation of Drupal', 'Exported French translation file.');
  1181. // Ensure our imported translations exist in the file.
  1182. $this->assertRaw('msgstr "lundi"', 'French translations present in exported file.');
  1183. }
  1184. /**
  1185. * Test exportation of translation template file.
  1186. */
  1187. function testExportTranslationTemplateFile() {
  1188. // Get the translation template file.
  1189. // There are two 'Export' buttons on this page, but it somehow works. It'd
  1190. // be better if we could use the submit button id like documented but that
  1191. // doesn't work.
  1192. $this->drupalPost('admin/config/regional/translate/export', array(), t('Export'));
  1193. // Ensure we have a translation file.
  1194. $this->assertRaw('# LANGUAGE translation of PROJECT', 'Exported translation template file.');
  1195. }
  1196. /**
  1197. * Helper function that returns a proper .po file.
  1198. */
  1199. function getPoFile() {
  1200. return <<< EOF
  1201. msgid ""
  1202. msgstr ""
  1203. "Project-Id-Version: Drupal 6\\n"
  1204. "MIME-Version: 1.0\\n"
  1205. "Content-Type: text/plain; charset=UTF-8\\n"
  1206. "Content-Transfer-Encoding: 8bit\\n"
  1207. "Plural-Forms: nplurals=2; plural=(n > 1);\\n"
  1208. msgid "Monday"
  1209. msgstr "lundi"
  1210. EOF;
  1211. }
  1212. }
  1213. /**
  1214. * Tests for the st() function.
  1215. */
  1216. class LocaleInstallTest extends DrupalWebTestCase {
  1217. public static function getInfo() {
  1218. return array(
  1219. 'name' => 'String translation using st()',
  1220. 'description' => 'Tests that st() works like t().',
  1221. 'group' => 'Locale',
  1222. );
  1223. }
  1224. function setUp() {
  1225. parent::setUp('locale');
  1226. // st() lives in install.inc, so ensure that it is loaded for all tests.
  1227. require_once DRUPAL_ROOT . '/includes/install.inc';
  1228. }
  1229. /**
  1230. * Verify that function signatures of t() and st() are equal.
  1231. */
  1232. function testFunctionSignatures() {
  1233. $reflector_t = new ReflectionFunction('t');
  1234. $reflector_st = new ReflectionFunction('st');
  1235. $this->assertEqual($reflector_t->getParameters(), $reflector_st->getParameters(), 'Function signatures of t() and st() are equal.');
  1236. }
  1237. }
  1238. /**
  1239. * Locale uninstall with English UI functional test.
  1240. */
  1241. class LocaleUninstallFunctionalTest extends DrupalWebTestCase {
  1242. public static function getInfo() {
  1243. return array(
  1244. 'name' => 'Locale uninstall (EN)',
  1245. 'description' => 'Tests the uninstall process using the built-in UI language.',
  1246. 'group' => 'Locale',
  1247. );
  1248. }
  1249. /**
  1250. * The default language set for the UI before uninstall.
  1251. */
  1252. protected $language;
  1253. function setUp() {
  1254. parent::setUp('locale');
  1255. $this->language = 'en';
  1256. }
  1257. /**
  1258. * Check if the values of the Locale variables are correct after uninstall.
  1259. */
  1260. function testUninstallProcess() {
  1261. $locale_module = array('locale');
  1262. // Add a new language and optionally set it as default.
  1263. require_once DRUPAL_ROOT . '/includes/locale.inc';
  1264. locale_add_language('fr', 'French', 'Français', LANGUAGE_LTR, '', '', TRUE, $this->language == 'fr');
  1265. // Check the UI language.
  1266. drupal_language_initialize();
  1267. global $language;
  1268. $this->assertEqual($language->language, $this->language, format_string('Current language: %lang', array('%lang' => $language->language)));
  1269. // Enable multilingual workflow option for articles.
  1270. variable_set('language_content_type_article', 1);
  1271. // Change JavaScript translations directory.
  1272. variable_set('locale_js_directory', 'js_translations');
  1273. // Build the JavaScript translation file for French.
  1274. $user = $this->drupalCreateUser(array('translate interface', 'access administration pages'));
  1275. $this->drupalLogin($user);
  1276. $this->drupalGet('admin/config/regional/translate/translate');
  1277. $string = db_query('SELECT min(lid) AS lid FROM {locales_source} WHERE location LIKE :location AND textgroup = :textgroup', array(
  1278. ':location' => '%.js%',
  1279. ':textgroup' => 'default',
  1280. ))->fetchObject();
  1281. $edit = array('translations[fr]' => 'french translation');
  1282. $this->drupalPost('admin/config/regional/translate/edit/' . $string->lid, $edit, t('Save translations'));
  1283. _locale_rebuild_js('fr');
  1284. $file = db_query('SELECT javascript FROM {languages} WHERE language = :language', array(':language' => 'fr'))->fetchObject();
  1285. $js_file = 'public://' . variable_get('locale_js_directory', 'languages') . '/fr_' . $file->javascript . '.js';
  1286. $this->assertTrue($result = file_exists($js_file), format_string('JavaScript file created: %file', array('%file' => $result ? $js_file : 'none')));
  1287. // Disable string caching.
  1288. variable_set('locale_cache_strings', 0);
  1289. // Change language negotiation options.
  1290. drupal_load('module', 'locale');
  1291. variable_set('language_types', drupal_language_types() + array('language_custom' => TRUE));
  1292. variable_set('language_negotiation_' . LANGUAGE_TYPE_INTERFACE, locale_language_negotiation_info());
  1293. variable_set('language_negotiation_' . LANGUAGE_TYPE_CONTENT, locale_language_negotiation_info());
  1294. variable_set('language_negotiation_' . LANGUAGE_TYPE_URL, locale_language_negotiation_info());
  1295. // Change language providers settings.
  1296. variable_set('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX);
  1297. variable_set('locale_language_negotiation_session_param', TRUE);
  1298. // Uninstall Locale.
  1299. module_disable($locale_module);
  1300. drupal_uninstall_modules($locale_module);
  1301. // Visit the front page.
  1302. $this->drupalGet('');
  1303. // Check the init language logic.
  1304. drupal_language_initialize();
  1305. $this->assertEqual($language->language, 'en', format_string('Language after uninstall: %lang', array('%lang' => $language->language)));
  1306. // Check JavaScript files deletion.
  1307. $this->assertTrue($result = !file_exists($js_file), format_string('JavaScript file deleted: %file', array('%file' => $result ? $js_file : 'found')));
  1308. // Check language count.
  1309. $language_count = variable_get('language_count', 1);
  1310. $this->assertEqual($language_count, 1, format_string('Language count: %count', array('%count' => $language_count)));
  1311. // Check language negotiation.
  1312. require_once DRUPAL_ROOT . '/includes/language.inc';
  1313. $this->assertTrue(count(language_types()) == count(drupal_language_types()), 'Language types reset');
  1314. $language_negotiation = language_negotiation_get(LANGUAGE_TYPE_INTERFACE) == LANGUAGE_NEGOTIATION_DEFAULT;
  1315. $this->assertTrue($language_negotiation, format_string('Interface language negotiation: %setting', array('%setting' => $language_negotiation ? 'none' : 'set')));
  1316. $language_negotiation = language_negotiation_get(LANGUAGE_TYPE_CONTENT) == LANGUAGE_NEGOTIATION_DEFAULT;
  1317. $this->assertTrue($language_negotiation, format_string('Content language negotiation: %setting', array('%setting' => $language_negotiation ? 'none' : 'set')));
  1318. $language_negotiation = language_negotiation_get(LANGUAGE_TYPE_URL) == LANGUAGE_NEGOTIATION_DEFAULT;
  1319. $this->assertTrue($language_negotiation, format_string('URL language negotiation: %setting', array('%setting' => $language_negotiation ? 'none' : 'set')));
  1320. // Check language providers settings.
  1321. $this->assertFalse(variable_get('locale_language_negotiation_url_part', FALSE), 'URL language provider indicator settings cleared.');
  1322. $this->assertFalse(variable_get('locale_language_negotiation_session_param', FALSE), 'Visit language provider settings cleared.');
  1323. // Check JavaScript parsed.
  1324. $javascript_parsed_count = count(variable_get('javascript_parsed', array()));
  1325. $this->assertEqual($javascript_parsed_count, 0, format_string('JavaScript parsed count: %count', array('%count' => $javascript_parsed_count)));
  1326. // Check multilingual workflow option for articles.
  1327. $multilingual = variable_get('language_content_type_article', 0);
  1328. $this->assertEqual($multilingual, 0, format_string('Multilingual workflow option: %status', array('%status' => $multilingual ? 'enabled': 'disabled')));
  1329. // Check JavaScript translations directory.
  1330. $locale_js_directory = variable_get('locale_js_directory', 'languages');
  1331. $this->assertEqual($locale_js_directory, 'languages', format_string('JavaScript translations directory: %dir', array('%dir' => $locale_js_directory)));
  1332. // Check string caching.
  1333. $locale_cache_strings = variable_get('locale_cache_strings', 1);
  1334. $this->assertEqual($locale_cache_strings, 1, format_string('String caching: %status', array('%status' => $locale_cache_strings ? 'enabled': 'disabled')));
  1335. }
  1336. }
  1337. /**
  1338. * Locale uninstall with French UI functional test.
  1339. *
  1340. * Because this class extends LocaleUninstallFunctionalTest, it doesn't require a new
  1341. * test of its own. Rather, it switches the default UI language in setUp and then
  1342. * runs the testUninstallProcess (which it inherits from LocaleUninstallFunctionalTest)
  1343. * to test with this new language.
  1344. */
  1345. class LocaleUninstallFrenchFunctionalTest extends LocaleUninstallFunctionalTest {
  1346. public static function getInfo() {
  1347. return array(
  1348. 'name' => 'Locale uninstall (FR)',
  1349. 'description' => 'Tests the uninstall process using French as interface language.',
  1350. 'group' => 'Locale',
  1351. );
  1352. }
  1353. function setUp() {
  1354. parent::setUp();
  1355. $this->language = 'fr';
  1356. }
  1357. }
  1358. /**
  1359. * Functional tests for the language switching feature.
  1360. */
  1361. class LocaleLanguageSwitchingFunctionalTest extends DrupalWebTestCase {
  1362. public static function getInfo() {
  1363. return array(
  1364. 'name' => 'Language switching',
  1365. 'description' => 'Tests for the language switching feature.',
  1366. 'group' => 'Locale',
  1367. );
  1368. }
  1369. function setUp() {
  1370. parent::setUp('locale');
  1371. // Create and login user.
  1372. $admin_user = $this->drupalCreateUser(array('administer blocks', 'administer languages', 'translate interface', 'access administration pages'));
  1373. $this->drupalLogin($admin_user);
  1374. }
  1375. /**
  1376. * Functional tests for the language switcher block.
  1377. */
  1378. function testLanguageBlock() {
  1379. // Enable the language switching block.
  1380. $language_type = LANGUAGE_TYPE_INTERFACE;
  1381. $edit = array(
  1382. "blocks[locale_{$language_type}][region]" => 'sidebar_first',
  1383. );
  1384. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  1385. // Add language.
  1386. $edit = array(
  1387. 'langcode' => 'fr',
  1388. );
  1389. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add language'));
  1390. // Enable URL language detection and selection.
  1391. $edit = array('language[enabled][locale-url]' => '1');
  1392. $this->drupalPost('admin/config/regional/language/configure', $edit, t('Save settings'));
  1393. // Assert that the language switching block is displayed on the frontpage.
  1394. $this->drupalGet('');
  1395. $this->assertText(t('Languages'), 'Language switcher block found.');
  1396. // Assert that only the current language is marked as active.
  1397. list($language_switcher) = $this->xpath('//div[@id=:id]/div[@class="content"]', array(':id' => 'block-locale-' . $language_type));
  1398. $links = array(
  1399. 'active' => array(),
  1400. 'inactive' => array(),
  1401. );
  1402. $anchors = array(
  1403. 'active' => array(),
  1404. 'inactive' => array(),
  1405. );
  1406. foreach ($language_switcher->ul->li as $link) {
  1407. $classes = explode(" ", (string) $link['class']);
  1408. list($language) = array_intersect($classes, array('en', 'fr'));
  1409. if (in_array('active', $classes)) {
  1410. $links['active'][] = $language;
  1411. }
  1412. else {
  1413. $links['inactive'][] = $language;
  1414. }
  1415. $anchor_classes = explode(" ", (string) $link->a['class']);
  1416. if (in_array('active', $anchor_classes)) {
  1417. $anchors['active'][] = $language;
  1418. }
  1419. else {
  1420. $anchors['inactive'][] = $language;
  1421. }
  1422. }
  1423. $this->assertIdentical($links, array('active' => array('en'), 'inactive' => array('fr')), 'Only the current language list item is marked as active on the language switcher block.');
  1424. $this->assertIdentical($anchors, array('active' => array('en'), 'inactive' => array('fr')), 'Only the current language anchor is marked as active on the language switcher block.');
  1425. }
  1426. }
  1427. /**
  1428. * Test browser language detection.
  1429. */
  1430. class LocaleBrowserDetectionTest extends DrupalUnitTestCase {
  1431. public static function getInfo() {
  1432. return array(
  1433. 'name' => 'Browser language detection',
  1434. 'description' => 'Tests for the browser language detection.',
  1435. 'group' => 'Locale',
  1436. );
  1437. }
  1438. /**
  1439. * Unit tests for the locale_language_from_browser() function.
  1440. */
  1441. function testLanguageFromBrowser() {
  1442. // Load the required functions.
  1443. require_once DRUPAL_ROOT . '/includes/locale.inc';
  1444. $languages = array(
  1445. // In our test case, 'en' has priority over 'en-US'.
  1446. 'en' => (object) array(
  1447. 'language' => 'en',
  1448. ),
  1449. 'en-US' => (object) array(
  1450. 'language' => 'en-US',
  1451. ),
  1452. // But 'fr-CA' has priority over 'fr'.
  1453. 'fr-CA' => (object) array(
  1454. 'language' => 'fr-CA',
  1455. ),
  1456. 'fr' => (object) array(
  1457. 'language' => 'fr',
  1458. ),
  1459. // 'es-MX' is alone.
  1460. 'es-MX' => (object) array(
  1461. 'language' => 'es-MX',
  1462. ),
  1463. // 'pt' is alone.
  1464. 'pt' => (object) array(
  1465. 'language' => 'pt',
  1466. ),
  1467. // Language codes with more then one dash are actually valid.
  1468. // eh-oh-laa-laa is the official language code of the Teletubbies.
  1469. 'eh-oh-laa-laa' => (object) array(
  1470. 'language' => 'eh-oh-laa-laa',
  1471. ),
  1472. );
  1473. $test_cases = array(
  1474. // Equal qvalue for each language, choose the site preferred one.
  1475. 'en,en-US,fr-CA,fr,es-MX' => 'en',
  1476. 'en-US,en,fr-CA,fr,es-MX' => 'en',
  1477. 'fr,en' => 'en',
  1478. 'en,fr' => 'en',
  1479. 'en-US,fr' => 'en',
  1480. 'fr,en-US' => 'en',
  1481. 'fr,fr-CA' => 'fr-CA',
  1482. 'fr-CA,fr' => 'fr-CA',
  1483. 'fr' => 'fr-CA',
  1484. 'fr;q=1' => 'fr-CA',
  1485. 'fr,es-MX' => 'fr-CA',
  1486. 'fr,es' => 'fr-CA',
  1487. 'es,fr' => 'fr-CA',
  1488. 'es-MX,de' => 'es-MX',
  1489. 'de,es-MX' => 'es-MX',
  1490. // Different cases and whitespace.
  1491. 'en' => 'en',
  1492. 'En' => 'en',
  1493. 'EN' => 'en',
  1494. ' en' => 'en',
  1495. 'en ' => 'en',
  1496. 'en, fr' => 'en',
  1497. // A less specific language from the browser matches a more specific one
  1498. // from the website, and the other way around for compatibility with
  1499. // some versions of Internet Explorer.
  1500. 'es' => 'es-MX',
  1501. 'es-MX' => 'es-MX',
  1502. 'pt' => 'pt',
  1503. 'pt-PT' => 'pt',
  1504. 'pt-PT;q=0.5,pt-BR;q=1,en;q=0.7' => 'en',
  1505. 'pt-PT;q=1,pt-BR;q=0.5,en;q=0.7' => 'en',
  1506. 'pt-PT;q=0.4,pt-BR;q=0.1,en;q=0.7' => 'en',
  1507. 'pt-PT;q=0.1,pt-BR;q=0.4,en;q=0.7' => 'en',
  1508. // Language code with several dashes are valid. The less specific language
  1509. // from the browser matches the more specific one from the website.
  1510. 'eh-oh-laa-laa' => 'eh-oh-laa-laa',
  1511. 'eh-oh-laa' => 'eh-oh-laa-laa',
  1512. 'eh-oh' => 'eh-oh-laa-laa',
  1513. 'eh' => 'eh-oh-laa-laa',
  1514. // Different qvalues.
  1515. 'fr,en;q=0.5' => 'fr-CA',
  1516. 'fr,en;q=0.5,fr-CA;q=0.25' => 'fr',
  1517. // Silly wildcards are also valid.
  1518. '*,fr-CA;q=0.5' => 'en',
  1519. '*,en;q=0.25' => 'fr-CA',
  1520. 'en,en-US;q=0.5,fr;q=0.25' => 'en',
  1521. 'en-US,en;q=0.5,fr;q=0.25' => 'en-US',
  1522. // Unresolvable cases.
  1523. '' => FALSE,
  1524. 'de,pl' => FALSE,
  1525. 'iecRswK4eh' => FALSE,
  1526. $this->randomName(10) => FALSE,
  1527. );
  1528. foreach ($test_cases as $accept_language => $expected_result) {
  1529. $_SERVER['HTTP_ACCEPT_LANGUAGE'] = $accept_language;
  1530. $result = locale_language_from_browser($languages);
  1531. $this->assertIdentical($result, $expected_result, format_string("Language selection '@accept-language' selects '@result', result = '@actual'", array('@accept-language' => $accept_language, '@result' => $expected_result, '@actual' => isset($result) ? $result : 'none')));
  1532. }
  1533. }
  1534. }
  1535. /**
  1536. * Functional tests for a user's ability to change their default language.
  1537. */
  1538. class LocaleUserLanguageFunctionalTest extends DrupalWebTestCase {
  1539. public static function getInfo() {
  1540. return array(
  1541. 'name' => 'User language settings',
  1542. 'description' => "Tests user's ability to change their default language.",
  1543. 'group' => 'Locale',
  1544. );
  1545. }
  1546. function setUp() {
  1547. parent::setUp('locale');
  1548. }
  1549. /**
  1550. * Test if user can change their default language.
  1551. */
  1552. function testUserLanguageConfiguration() {
  1553. global $base_url;
  1554. // User to add and remove language.
  1555. $admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages'));
  1556. // User to change their default language.
  1557. $web_user = $this->drupalCreateUser();
  1558. // Add custom language.
  1559. $this->drupalLogin($admin_user);
  1560. // Code for the language.
  1561. $langcode = 'xx';
  1562. // The English name for the language.
  1563. $name = $this->randomName(16);
  1564. // The native name for the language.
  1565. $native = $this->randomName(16);
  1566. // The domain prefix.
  1567. $prefix = 'xx';
  1568. $edit = array(
  1569. 'langcode' => $langcode,
  1570. 'name' => $name,
  1571. 'native' => $native,
  1572. 'prefix' => $prefix,
  1573. 'direction' => '0',
  1574. );
  1575. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
  1576. // Add custom language and disable it.
  1577. // Code for the language.
  1578. $langcode_disabled = 'xx-yy';
  1579. // The English name for the language. This will be translated.
  1580. $name_disabled = $this->randomName(16);
  1581. // The native name for the language.
  1582. $native_disabled = $this->randomName(16);
  1583. // The domain prefix.
  1584. $prefix_disabled = $langcode_disabled;
  1585. $edit = array(
  1586. 'langcode' => $langcode_disabled,
  1587. 'name' => $name_disabled,
  1588. 'native' => $native_disabled,
  1589. 'prefix' => $prefix_disabled,
  1590. 'direction' => '0',
  1591. );
  1592. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
  1593. // Disable the language.
  1594. $edit = array(
  1595. 'enabled[' . $langcode_disabled . ']' => FALSE,
  1596. );
  1597. $this->drupalPost('admin/config/regional/language', $edit, t('Save configuration'));
  1598. $this->drupalLogout();
  1599. // Login as normal user and edit account settings.
  1600. $this->drupalLogin($web_user);
  1601. $path = 'user/' . $web_user->uid . '/edit';
  1602. $this->drupalGet($path);
  1603. // Ensure language settings fieldset is available.
  1604. $this->assertText(t('Language settings'), 'Language settings available.');
  1605. // Ensure custom language is present.
  1606. $this->assertText($name, 'Language present on form.');
  1607. // Ensure disabled language isn't present.
  1608. $this->assertNoText($name_disabled, 'Disabled language not present on form.');
  1609. // Switch to our custom language.
  1610. $edit = array(
  1611. 'language' => $langcode,
  1612. );
  1613. $this->drupalPost($path, $edit, t('Save'));
  1614. // Ensure form was submitted successfully.
  1615. $this->assertText(t('The changes have been saved.'), 'Changes were saved.');
  1616. // Check if language was changed.
  1617. $elements = $this->xpath('//input[@id=:id]', array(':id' => 'edit-language-' . $langcode));
  1618. $this->assertTrue(isset($elements[0]) && !empty($elements[0]['checked']), 'Default language successfully updated.');
  1619. $this->drupalLogout();
  1620. }
  1621. }
  1622. /**
  1623. * Functional test for language handling during user creation.
  1624. */
  1625. class LocaleUserCreationTest extends DrupalWebTestCase {
  1626. public static function getInfo() {
  1627. return array(
  1628. 'name' => 'User creation',
  1629. 'description' => 'Tests whether proper language is stored for new users and access to language selector.',
  1630. 'group' => 'Locale',
  1631. );
  1632. }
  1633. function setUp() {
  1634. parent::setUp('locale');
  1635. variable_set('user_register', USER_REGISTER_VISITORS);
  1636. }
  1637. /**
  1638. * Functional test for language handling during user creation.
  1639. */
  1640. function testLocalUserCreation() {
  1641. // User to add and remove language and create new users.
  1642. $admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages', 'administer users'));
  1643. $this->drupalLogin($admin_user);
  1644. // Add predefined language.
  1645. $langcode = 'fr';
  1646. $edit = array(
  1647. 'langcode' => 'fr',
  1648. );
  1649. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add language'));
  1650. $this->assertText($langcode, 'Language added successfully.');
  1651. $this->assertEqual($this->getUrl(), url('admin/config/regional/language', array('absolute' => TRUE)), 'Correct page redirection.');
  1652. // Set language negotiation.
  1653. $edit = array(
  1654. 'language[enabled][locale-url]' => TRUE,
  1655. );
  1656. $this->drupalPost('admin/config/regional/language/configure', $edit, t('Save settings'));
  1657. $this->assertText(t('Language negotiation configuration saved.'), 'Set language negotiation.');
  1658. // Check if the language selector is available on admin/people/create and
  1659. // set to the currently active language.
  1660. $this->drupalGet($langcode . '/admin/people/create');
  1661. $this->assertFieldChecked("edit-language-$langcode", 'Global language set in the language selector.');
  1662. // Create a user with the admin/people/create form and check if the correct
  1663. // language is set.
  1664. $username = $this->randomName(10);
  1665. $edit = array(
  1666. 'name' => $username,
  1667. 'mail' => $this->randomName(4) . '@example.com',
  1668. 'pass[pass1]' => $username,
  1669. 'pass[pass2]' => $username,
  1670. );
  1671. $this->drupalPost($langcode . '/admin/people/create', $edit, t('Create new account'));
  1672. $user = user_load_by_name($username);
  1673. $this->assertEqual($user->language, $langcode, 'New user has correct language set.');
  1674. // Register a new user and check if the language selector is hidden.
  1675. $this->drupalLogout();
  1676. $this->drupalGet($langcode . '/user/register');
  1677. $this->assertNoFieldByName('language[fr]', 'Language selector is not accessible.');
  1678. $username = $this->randomName(10);
  1679. $edit = array(
  1680. 'name' => $username,
  1681. 'mail' => $this->randomName(4) . '@example.com',
  1682. );
  1683. $this->drupalPost($langcode . '/user/register', $edit, t('Create new account'));
  1684. $user = user_load_by_name($username);
  1685. $this->assertEqual($user->language, $langcode, 'New user has correct language set.');
  1686. // Test if the admin can use the language selector and if the
  1687. // correct language is was saved.
  1688. $user_edit = $langcode . '/user/' . $user->uid . '/edit';
  1689. $this->drupalLogin($admin_user);
  1690. $this->drupalGet($user_edit);
  1691. $this->assertFieldChecked("edit-language-$langcode", 'Language selector is accessible and correct language is selected.');
  1692. // Set pass_raw so we can login the new user.
  1693. $user->pass_raw = $this->randomName(10);
  1694. $edit = array(
  1695. 'pass[pass1]' => $user->pass_raw,
  1696. 'pass[pass2]' => $user->pass_raw,
  1697. );
  1698. $this->drupalPost($user_edit, $edit, t('Save'));
  1699. $this->drupalLogin($user);
  1700. $this->drupalGet($user_edit);
  1701. $this->assertFieldChecked("edit-language-$langcode", 'Language selector is accessible and correct language is selected.');
  1702. }
  1703. }
  1704. /**
  1705. * Functional tests for configuring a different path alias per language.
  1706. */
  1707. class LocalePathFunctionalTest extends DrupalWebTestCase {
  1708. public static function getInfo() {
  1709. return array(
  1710. 'name' => 'Path language settings',
  1711. 'description' => 'Checks you can configure a language for individual URL aliases.',
  1712. 'group' => 'Locale',
  1713. );
  1714. }
  1715. function setUp() {
  1716. parent::setUp('locale', 'path');
  1717. }
  1718. /**
  1719. * Test if a language can be associated with a path alias.
  1720. */
  1721. function testPathLanguageConfiguration() {
  1722. global $base_url;
  1723. // User to add and remove language.
  1724. $admin_user = $this->drupalCreateUser(array('administer languages', 'create page content', 'administer url aliases', 'create url aliases', 'access administration pages'));
  1725. // Add custom language.
  1726. $this->drupalLogin($admin_user);
  1727. // Code for the language.
  1728. $langcode = 'xx';
  1729. // The English name for the language.
  1730. $name = $this->randomName(16);
  1731. // The native name for the language.
  1732. $native = $this->randomName(16);
  1733. // The domain prefix.
  1734. $prefix = $langcode;
  1735. $edit = array(
  1736. 'langcode' => $langcode,
  1737. 'name' => $name,
  1738. 'native' => $native,
  1739. 'prefix' => $prefix,
  1740. 'direction' => '0',
  1741. );
  1742. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
  1743. // Check that the "xx" front page is not available when path prefixes are
  1744. // not enabled yet.
  1745. $this->drupalPost('admin/config/regional/language/configure', array(), t('Save settings'));
  1746. $this->drupalGet($prefix);
  1747. $this->assertResponse(404, 'The "xx" front page is not available yet.');
  1748. // Enable URL language detection and selection.
  1749. $edit = array('language[enabled][locale-url]' => 1);
  1750. $this->drupalPost('admin/config/regional/language/configure', $edit, t('Save settings'));
  1751. // Create a node.
  1752. $node = $this->drupalCreateNode(array('type' => 'page'));
  1753. // Create a path alias in default language (English).
  1754. $path = 'admin/config/search/path/add';
  1755. $english_path = $this->randomName(8);
  1756. $edit = array(
  1757. 'source' => 'node/' . $node->nid,
  1758. 'alias' => $english_path,
  1759. 'language' => 'en',
  1760. );
  1761. $this->drupalPost($path, $edit, t('Save'));
  1762. // Create a path alias in new custom language.
  1763. $custom_language_path = $this->randomName(8);
  1764. $edit = array(
  1765. 'source' => 'node/' . $node->nid,
  1766. 'alias' => $custom_language_path,
  1767. 'language' => $langcode,
  1768. );
  1769. $this->drupalPost($path, $edit, t('Save'));
  1770. // Confirm English language path alias works.
  1771. $this->drupalGet($english_path);
  1772. $this->assertText($node->title, 'English alias works.');
  1773. // Confirm custom language path alias works.
  1774. $this->drupalGet($prefix . '/' . $custom_language_path);
  1775. $this->assertText($node->title, 'Custom language alias works.');
  1776. // Create a custom path.
  1777. $custom_path = $this->randomName(8);
  1778. // Check priority of language for alias by source path.
  1779. $edit = array(
  1780. 'source' => 'node/' . $node->nid,
  1781. 'alias' => $custom_path,
  1782. 'language' => LANGUAGE_NONE,
  1783. );
  1784. path_save($edit);
  1785. $lookup_path = drupal_lookup_path('alias', 'node/' . $node->nid, 'en');
  1786. $this->assertEqual($english_path, $lookup_path, 'English language alias has priority.');
  1787. // Same check for language 'xx'.
  1788. $lookup_path = drupal_lookup_path('alias', 'node/' . $node->nid, $prefix);
  1789. $this->assertEqual($custom_language_path, $lookup_path, 'Custom language alias has priority.');
  1790. path_delete($edit);
  1791. // Create language nodes to check priority of aliases.
  1792. $first_node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
  1793. $second_node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
  1794. // Assign a custom path alias to the first node with the English language.
  1795. $edit = array(
  1796. 'source' => 'node/' . $first_node->nid,
  1797. 'alias' => $custom_path,
  1798. 'language' => 'en',
  1799. );
  1800. path_save($edit);
  1801. // Assign a custom path alias to second node with LANGUAGE_NONE.
  1802. $edit = array(
  1803. 'source' => 'node/' . $second_node->nid,
  1804. 'alias' => $custom_path,
  1805. 'language' => LANGUAGE_NONE,
  1806. );
  1807. path_save($edit);
  1808. // Test that both node titles link to our path alias.
  1809. $this->drupalGet('<front>');
  1810. $custom_path_url = base_path() . (variable_get('clean_url', 0) ? $custom_path : '?q=' . $custom_path);
  1811. $elements = $this->xpath('//a[@href=:href and .=:title]', array(':href' => $custom_path_url, ':title' => $first_node->title));
  1812. $this->assertTrue(!empty($elements), 'First node links to the path alias.');
  1813. $elements = $this->xpath('//a[@href=:href and .=:title]', array(':href' => $custom_path_url, ':title' => $second_node->title));
  1814. $this->assertTrue(!empty($elements), 'Second node links to the path alias.');
  1815. // Confirm that the custom path leads to the first node.
  1816. $this->drupalGet($custom_path);
  1817. $this->assertText($first_node->title, 'Custom alias returns first node.');
  1818. // Confirm that the custom path with prefix leads to the second node.
  1819. $this->drupalGet($prefix . '/' . $custom_path);
  1820. $this->assertText($second_node->title, 'Custom alias with prefix returns second node.');
  1821. }
  1822. }
  1823. /**
  1824. * Functional tests for multilingual support on nodes.
  1825. */
  1826. class LocaleContentFunctionalTest extends DrupalWebTestCase {
  1827. public static function getInfo() {
  1828. return array(
  1829. 'name' => 'Content language settings',
  1830. 'description' => 'Checks you can enable multilingual support on content types and configure a language for a node.',
  1831. 'group' => 'Locale',
  1832. );
  1833. }
  1834. function setUp() {
  1835. parent::setUp('locale');
  1836. }
  1837. /**
  1838. * Verifies that machine name fields are always LTR.
  1839. */
  1840. function testMachineNameLTR() {
  1841. // User to add and remove language.
  1842. $admin_user = $this->drupalCreateUser(array('administer languages', 'administer content types', 'access administration pages'));
  1843. // Log in as admin.
  1844. $this->drupalLogin($admin_user);
  1845. // Verify that the machine name field is LTR for a new content type.
  1846. $this->drupalGet('admin/structure/types/add');
  1847. $this->assertFieldByXpath('//input[@name="type" and @dir="ltr"]', NULL, 'The machine name field is LTR when no additional language is configured.');
  1848. // Install the Arabic language (which is RTL) and configure as the default.
  1849. $edit = array();
  1850. $edit['langcode'] = 'ar';
  1851. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add language'));
  1852. $edit = array();
  1853. $edit['site_default'] = 'ar';
  1854. $this->drupalPost(NULL, $edit, t('Save configuration'));
  1855. // Verify that the machine name field is still LTR for a new content type.
  1856. $this->drupalGet('admin/structure/types/add');
  1857. $this->assertFieldByXpath('//input[@name="type" and @dir="ltr"]', NULL, 'The machine name field is LTR when the default language is RTL.');
  1858. }
  1859. /**
  1860. * Test if a content type can be set to multilingual and language setting is
  1861. * present on node add and edit forms.
  1862. */
  1863. function testContentTypeLanguageConfiguration() {
  1864. global $base_url;
  1865. // User to add and remove language.
  1866. $admin_user = $this->drupalCreateUser(array('administer languages', 'administer content types', 'access administration pages'));
  1867. // User to create a node.
  1868. $web_user = $this->drupalCreateUser(array('create article content', 'create page content', 'edit any page content'));
  1869. // Add custom language.
  1870. $this->drupalLogin($admin_user);
  1871. // Code for the language.
  1872. $langcode = 'xx';
  1873. // The English name for the language.
  1874. $name = $this->randomName(16);
  1875. // The native name for the language.
  1876. $native = $this->randomName(16);
  1877. // The domain prefix.
  1878. $prefix = $langcode;
  1879. $edit = array(
  1880. 'langcode' => $langcode,
  1881. 'name' => $name,
  1882. 'native' => $native,
  1883. 'prefix' => $prefix,
  1884. 'direction' => '0',
  1885. );
  1886. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
  1887. // Add disabled custom language.
  1888. // Code for the language.
  1889. $langcode_disabled = 'xx-yy';
  1890. // The English name for the language.
  1891. $name_disabled = $this->randomName(16);
  1892. // The native name for the language.
  1893. $native_disabled = $this->randomName(16);
  1894. // The domain prefix.
  1895. $prefix_disabled = $langcode_disabled;
  1896. $edit = array(
  1897. 'langcode' => $langcode_disabled,
  1898. 'name' => $name_disabled,
  1899. 'native' => $native_disabled,
  1900. 'prefix' => $prefix_disabled,
  1901. 'direction' => '0',
  1902. );
  1903. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add custom language'));
  1904. // Disable second custom language.
  1905. $path = 'admin/config/regional/language';
  1906. $edit = array(
  1907. 'enabled[' . $langcode_disabled . ']' => FALSE,
  1908. );
  1909. $this->drupalPost($path, $edit, t('Save configuration'));
  1910. // Set "Basic page" content type to use multilingual support.
  1911. $this->drupalGet('admin/structure/types/manage/page');
  1912. $this->assertText(t('Multilingual support'), 'Multilingual support fieldset present on content type configuration form.');
  1913. $edit = array(
  1914. 'language_content_type' => 1,
  1915. );
  1916. $this->drupalPost('admin/structure/types/manage/page', $edit, t('Save content type'));
  1917. $this->assertRaw(t('The content type %type has been updated.', array('%type' => 'Basic page')), 'Basic page content type has been updated.');
  1918. $this->drupalLogout();
  1919. // Verify language selection is not present on add article form.
  1920. $this->drupalLogin($web_user);
  1921. $this->drupalGet('node/add/article');
  1922. // Verify language select list is not present.
  1923. $this->assertNoFieldByName('language', NULL, 'Language select not present on add article form.');
  1924. // Verify language selection appears on add "Basic page" form.
  1925. $this->drupalGet('node/add/page');
  1926. // Verify language select list is present.
  1927. $this->assertFieldByName('language', NULL, 'Language select present on add Basic page form.');
  1928. // Ensure enabled language appears.
  1929. $this->assertText($name, 'Enabled language present.');
  1930. // Ensure disabled language doesn't appear.
  1931. $this->assertNoText($name_disabled, 'Disabled language not present.');
  1932. // Create "Basic page" content.
  1933. $node_title = $this->randomName();
  1934. $node_body = $this->randomName();
  1935. $edit = array(
  1936. 'type' => 'page',
  1937. 'title' => $node_title,
  1938. 'body' => array($langcode => array(array('value' => $node_body))),
  1939. 'language' => $langcode,
  1940. );
  1941. $node = $this->drupalCreateNode($edit);
  1942. // Edit the content and ensure correct language is selected.
  1943. $path = 'node/' . $node->nid . '/edit';
  1944. $this->drupalGet($path);
  1945. $this->assertRaw('<option value="' . $langcode . '" selected="selected">' . $name . '</option>', 'Correct language selected.');
  1946. // Ensure we can change the node language.
  1947. $edit = array(
  1948. 'language' => 'en',
  1949. );
  1950. $this->drupalPost($path, $edit, t('Save'));
  1951. $this->assertRaw(t('%title has been updated.', array('%title' => $node_title)), 'Basic page content updated.');
  1952. $this->drupalLogout();
  1953. }
  1954. }
  1955. /**
  1956. * Test UI language negotiation
  1957. * 1. URL (PATH) > DEFAULT
  1958. * UI Language base on URL prefix, browser language preference has no
  1959. * influence:
  1960. * admin/config
  1961. * UI in site default language
  1962. * zh-hans/admin/config
  1963. * UI in Chinese
  1964. * blah-blah/admin/config
  1965. * 404
  1966. * 2. URL (PATH) > BROWSER > DEFAULT
  1967. * admin/config
  1968. * UI in user's browser language preference if the site has that
  1969. * language enabled, if not, the default language
  1970. * zh-hans/admin/config
  1971. * UI in Chinese
  1972. * blah-blah/admin/config
  1973. * 404
  1974. * 3. URL (DOMAIN) > DEFAULT
  1975. * http://example.com/admin/config
  1976. * UI language in site default
  1977. * http://example.cn/admin/config
  1978. * UI language in Chinese
  1979. */
  1980. class LocaleUILanguageNegotiationTest extends DrupalWebTestCase {
  1981. public static function getInfo() {
  1982. return array(
  1983. 'name' => 'UI language negotiation',
  1984. 'description' => 'Test UI language switching by URL path prefix and domain.',
  1985. 'group' => 'Locale',
  1986. );
  1987. }
  1988. function setUp() {
  1989. parent::setUp('locale', 'locale_test');
  1990. require_once DRUPAL_ROOT . '/includes/language.inc';
  1991. drupal_load('module', 'locale');
  1992. $admin_user = $this->drupalCreateUser(array('administer languages', 'translate interface', 'access administration pages', 'administer blocks'));
  1993. $this->drupalLogin($admin_user);
  1994. }
  1995. /**
  1996. * Tests for language switching by URL path.
  1997. */
  1998. function testUILanguageNegotiation() {
  1999. // A few languages to switch to.
  2000. // This one is unknown, should get the default lang version.
  2001. $language_unknown = 'blah-blah';
  2002. // For testing browser lang preference.
  2003. $language_browser_fallback = 'vi';
  2004. // For testing path prefix.
  2005. $language = 'zh-hans';
  2006. // For setting browser language preference to 'vi'.
  2007. $http_header_browser_fallback = array("Accept-Language: $language_browser_fallback;q=1");
  2008. // For setting browser language preference to some unknown.
  2009. $http_header_blah = array("Accept-Language: blah;q=1");
  2010. // This domain should switch the UI to Chinese.
  2011. $language_domain = 'example.cn';
  2012. // Setup the site languages by installing two languages.
  2013. require_once DRUPAL_ROOT . '/includes/locale.inc';
  2014. locale_add_language($language_browser_fallback);
  2015. locale_add_language($language);
  2016. // We will look for this string in the admin/config screen to see if the
  2017. // corresponding translated string is shown.
  2018. $default_string = 'Configure languages for content and the user interface';
  2019. // Set the default language in order for the translated string to be registered
  2020. // into database when seen by t(). Without doing this, our target string
  2021. // is for some reason not found when doing translate search. This might
  2022. // be some bug.
  2023. drupal_static_reset('language_list');
  2024. $languages = language_list('enabled');
  2025. variable_set('language_default', $languages[1]['vi']);
  2026. // First visit this page to make sure our target string is searchable.
  2027. $this->drupalGet('admin/config');
  2028. // Now the t()'ed string is in db so switch the language back to default.
  2029. variable_del('language_default');
  2030. // Translate the string.
  2031. $language_browser_fallback_string = "In $language_browser_fallback In $language_browser_fallback In $language_browser_fallback";
  2032. $language_string = "In $language In $language In $language";
  2033. // Do a translate search of our target string.
  2034. $edit = array( 'string' => $default_string);
  2035. $this->drupalPost('admin/config/regional/translate/translate', $edit, t('Filter'));
  2036. // Should find the string and now click edit to post translated string.
  2037. $this->clickLink('edit');
  2038. $edit = array(
  2039. "translations[$language_browser_fallback]" => $language_browser_fallback_string,
  2040. "translations[$language]" => $language_string,
  2041. );
  2042. $this->drupalPost(NULL, $edit, t('Save translations'));
  2043. // Configure URL language rewrite.
  2044. variable_set('locale_language_negotiation_url_type', LANGUAGE_TYPE_INTERFACE);
  2045. $tests = array(
  2046. // Default, browser preference should have no influence.
  2047. array(
  2048. 'language_negotiation' => array(LOCALE_LANGUAGE_NEGOTIATION_URL, LANGUAGE_NEGOTIATION_DEFAULT),
  2049. 'path' => 'admin/config',
  2050. 'expect' => $default_string,
  2051. 'expected_provider' => LANGUAGE_NEGOTIATION_DEFAULT,
  2052. 'http_header' => $http_header_browser_fallback,
  2053. 'message' => 'URL (PATH) > DEFAULT: no language prefix, UI language is default and the browser language preference setting is not used.',
  2054. ),
  2055. // Language prefix.
  2056. array(
  2057. 'language_negotiation' => array(LOCALE_LANGUAGE_NEGOTIATION_URL, LANGUAGE_NEGOTIATION_DEFAULT),
  2058. 'path' => "$language/admin/config",
  2059. 'expect' => $language_string,
  2060. 'expected_provider' => LOCALE_LANGUAGE_NEGOTIATION_URL,
  2061. 'http_header' => $http_header_browser_fallback,
  2062. 'message' => 'URL (PATH) > DEFAULT: with language prefix, UI language is switched based on path prefix',
  2063. ),
  2064. // Default, go by browser preference.
  2065. array(
  2066. 'language_negotiation' => array(LOCALE_LANGUAGE_NEGOTIATION_URL, LOCALE_LANGUAGE_NEGOTIATION_BROWSER),
  2067. 'path' => 'admin/config',
  2068. 'expect' => $language_browser_fallback_string,
  2069. 'expected_provider' => LOCALE_LANGUAGE_NEGOTIATION_BROWSER,
  2070. 'http_header' => $http_header_browser_fallback,
  2071. 'message' => 'URL (PATH) > BROWSER: no language prefix, UI language is determined by browser language preference',
  2072. ),
  2073. // Prefix, switch to the language.
  2074. array(
  2075. 'language_negotiation' => array(LOCALE_LANGUAGE_NEGOTIATION_URL, LOCALE_LANGUAGE_NEGOTIATION_BROWSER),
  2076. 'path' => "$language/admin/config",
  2077. 'expect' => $language_string,
  2078. 'expected_provider' => LOCALE_LANGUAGE_NEGOTIATION_URL,
  2079. 'http_header' => $http_header_browser_fallback,
  2080. 'message' => 'URL (PATH) > BROWSER: with langage prefix, UI language is based on path prefix',
  2081. ),
  2082. // Default, browser language preference is not one of site's lang.
  2083. array(
  2084. 'language_negotiation' => array(LOCALE_LANGUAGE_NEGOTIATION_URL, LOCALE_LANGUAGE_NEGOTIATION_BROWSER, LANGUAGE_NEGOTIATION_DEFAULT),
  2085. 'path' => 'admin/config',
  2086. 'expect' => $default_string,
  2087. 'expected_provider' => LANGUAGE_NEGOTIATION_DEFAULT,
  2088. 'http_header' => $http_header_blah,
  2089. 'message' => 'URL (PATH) > BROWSER > DEFAULT: no language prefix and browser language preference set to unknown language should use default language',
  2090. ),
  2091. );
  2092. foreach ($tests as $test) {
  2093. $this->runTest($test);
  2094. }
  2095. // Unknown language prefix should return 404.
  2096. variable_set('language_negotiation_' . LANGUAGE_TYPE_INTERFACE, locale_language_negotiation_info());
  2097. $this->drupalGet("$language_unknown/admin/config", array(), $http_header_browser_fallback);
  2098. $this->assertResponse(404, "Unknown language path prefix should return 404");
  2099. // Setup for domain negotiation, first configure the language to have domain
  2100. // URL. We use HTTPS and a port to make sure that only the domain name is used.
  2101. $edit = array('prefix' => '', 'domain' => "https://$language_domain:99");
  2102. $this->drupalPost("admin/config/regional/language/edit/$language", $edit, t('Save language'));
  2103. // Set the site to use domain language negotiation.
  2104. $tests = array(
  2105. // Default domain, browser preference should have no influence.
  2106. array(
  2107. 'language_negotiation' => array(LOCALE_LANGUAGE_NEGOTIATION_URL, LANGUAGE_NEGOTIATION_DEFAULT),
  2108. 'locale_language_negotiation_url_part' => LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN,
  2109. 'path' => 'admin/config',
  2110. 'expect' => $default_string,
  2111. 'expected_provider' => LANGUAGE_NEGOTIATION_DEFAULT,
  2112. 'http_header' => $http_header_browser_fallback,
  2113. 'message' => 'URL (DOMAIN) > DEFAULT: default domain should get default language',
  2114. ),
  2115. // Language domain specific URL, we set the $_SERVER['HTTP_HOST'] in
  2116. // locale_test.module hook_boot() to simulate this.
  2117. array(
  2118. 'language_negotiation' => array(LOCALE_LANGUAGE_NEGOTIATION_URL, LANGUAGE_NEGOTIATION_DEFAULT),
  2119. 'locale_language_negotiation_url_part' => LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN,
  2120. 'locale_test_domain' => $language_domain . ':88',
  2121. 'path' => 'admin/config',
  2122. 'expect' => $language_string,
  2123. 'expected_provider' => LOCALE_LANGUAGE_NEGOTIATION_URL,
  2124. 'http_header' => $http_header_browser_fallback,
  2125. 'message' => 'URL (DOMAIN) > DEFAULT: domain example.cn should switch to Chinese',
  2126. ),
  2127. );
  2128. foreach ($tests as $test) {
  2129. $this->runTest($test);
  2130. }
  2131. }
  2132. private function runTest($test) {
  2133. if (!empty($test['language_negotiation'])) {
  2134. $negotiation = array_flip($test['language_negotiation']);
  2135. language_negotiation_set(LANGUAGE_TYPE_INTERFACE, $negotiation);
  2136. }
  2137. if (!empty($test['locale_language_negotiation_url_part'])) {
  2138. variable_set('locale_language_negotiation_url_part', $test['locale_language_negotiation_url_part']);
  2139. }
  2140. if (!empty($test['locale_test_domain'])) {
  2141. variable_set('locale_test_domain', $test['locale_test_domain']);
  2142. }
  2143. $this->drupalGet($test['path'], array(), $test['http_header']);
  2144. $this->assertText($test['expect'], $test['message']);
  2145. $this->assertText(t('Language negotiation provider: @name', array('@name' => $test['expected_provider'])));
  2146. }
  2147. /**
  2148. * Test URL language detection when the requested URL has no language.
  2149. */
  2150. function testUrlLanguageFallback() {
  2151. // Add the Italian language.
  2152. $language_browser_fallback = 'it';
  2153. locale_add_language($language_browser_fallback);
  2154. $languages = language_list();
  2155. // Enable the path prefix for the default language: this way any unprefixed
  2156. // URL must have a valid fallback value.
  2157. $edit = array('prefix' => 'en');
  2158. $this->drupalPost('admin/config/regional/language/edit/en', $edit, t('Save language'));
  2159. // Enable browser and URL language detection.
  2160. $edit = array(
  2161. 'language[enabled][locale-browser]' => TRUE,
  2162. 'language[enabled][locale-url]' => TRUE,
  2163. 'language[weight][locale-browser]' => -8,
  2164. 'language[weight][locale-url]' => -10,
  2165. );
  2166. $this->drupalPost('admin/config/regional/language/configure', $edit, t('Save settings'));
  2167. $this->drupalGet('admin/config/regional/language/configure');
  2168. // Enable the language switcher block.
  2169. $edit = array('blocks[locale_language][region]' => 'sidebar_first');
  2170. $this->drupalPost('admin/structure/block', $edit, t('Save blocks'));
  2171. // Access the front page without specifying any valid URL language prefix
  2172. // and having as browser language preference a non-default language.
  2173. $http_header = array("Accept-Language: $language_browser_fallback;q=1");
  2174. $this->drupalGet('', array(), $http_header);
  2175. // Check that the language switcher active link matches the given browser
  2176. // language.
  2177. $args = array(':url' => base_path() . (!empty($GLOBALS['conf']['clean_url']) ? $language_browser_fallback : "?q=$language_browser_fallback"));
  2178. $fields = $this->xpath('//div[@id="block-locale-language"]//a[@class="language-link active" and @href=:url]', $args);
  2179. $this->assertTrue($fields[0] == $languages[$language_browser_fallback]->native, 'The browser language is the URL active language');
  2180. // Check that URLs are rewritten using the given browser language.
  2181. $fields = $this->xpath('//div[@id="site-name"]//a[@rel="home" and @href=:url]//span', $args);
  2182. $this->assertTrue($fields[0] == 'Drupal', 'URLs are rewritten using the browser language.');
  2183. }
  2184. /**
  2185. * Tests url() when separate domains are used for multiple languages.
  2186. */
  2187. function testLanguageDomain() {
  2188. // Add the Italian language, without protocol.
  2189. $langcode = 'it';
  2190. locale_add_language($langcode, 'Italian', 'Italian', LANGUAGE_LTR, 'it.example.com', '', TRUE, FALSE);
  2191. // Add the French language, with protocol.
  2192. $langcode = 'fr';
  2193. locale_add_language($langcode, 'French', 'French', LANGUAGE_LTR, 'http://fr.example.com', '', TRUE, FALSE);
  2194. // Enable language URL detection.
  2195. $negotiation = array_flip(array(LOCALE_LANGUAGE_NEGOTIATION_URL, LANGUAGE_NEGOTIATION_DEFAULT));
  2196. language_negotiation_set(LANGUAGE_TYPE_INTERFACE, $negotiation);
  2197. variable_set('locale_language_negotiation_url_part', 1);
  2198. global $is_https;
  2199. $languages = language_list();
  2200. foreach (array('it', 'fr') as $langcode) {
  2201. // Build the link we're going to test based on the clean URL setting.
  2202. $link = (!empty($GLOBALS['conf']['clean_url'])) ? $langcode . '.example.com/admin' : $langcode . '.example.com/?q=admin';
  2203. // Test URL in another language.
  2204. // Base path gives problems on the testbot, so $correct_link is hard-coded.
  2205. // @see UrlAlterFunctionalTest::assertUrlOutboundAlter (path.test).
  2206. $url = url('admin', array('language' => $languages[$langcode]));
  2207. $url_scheme = ($is_https) ? 'https://' : 'http://';
  2208. $correct_link = $url_scheme . $link;
  2209. $this->assertTrue($url == $correct_link, format_string('The url() function returns the right url (@url) in accordance with the chosen language', array('@url' => $url . " == " . $correct_link)));
  2210. // Test HTTPS via options.
  2211. variable_set('https', TRUE);
  2212. $url = url('admin', array('https' => TRUE, 'language' => $languages[$langcode]));
  2213. $correct_link = 'https://' . $link;
  2214. $this->assertTrue($url == $correct_link, format_string('The url() function returns the right https url (via options) (@url) in accordance with the chosen language', array('@url' => $url . " == " . $correct_link)));
  2215. variable_set('https', FALSE);
  2216. // Test HTTPS via current URL scheme.
  2217. $temp_https = $is_https;
  2218. $is_https = TRUE;
  2219. $url = url('admin', array('language' => $languages[$langcode]));
  2220. $correct_link = 'https://' . $link;
  2221. $this->assertTrue($url == $correct_link, format_string('The url() function returns the right url (via current url scheme) (@url) in accordance with the chosen language', array('@url' => $url . " == " . $correct_link)));
  2222. $is_https = $temp_https;
  2223. }
  2224. }
  2225. }
  2226. /**
  2227. * Test that URL rewriting works as expected.
  2228. */
  2229. class LocaleUrlRewritingTest extends DrupalWebTestCase {
  2230. public static function getInfo() {
  2231. return array(
  2232. 'name' => 'URL rewriting',
  2233. 'description' => 'Test that URL rewriting works as expected.',
  2234. 'group' => 'Locale',
  2235. );
  2236. }
  2237. function setUp() {
  2238. parent::setUp('locale');
  2239. // Create and login user.
  2240. $this->web_user = $this->drupalCreateUser(array('administer languages', 'access administration pages'));
  2241. $this->drupalLogin($this->web_user);
  2242. // Install French language.
  2243. $edit = array();
  2244. $edit['langcode'] = 'fr';
  2245. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add language'));
  2246. // Install Italian language.
  2247. $edit = array();
  2248. $edit['langcode'] = 'it';
  2249. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add language'));
  2250. // Disable Italian language.
  2251. $edit = array('enabled[it]' => FALSE);
  2252. $this->drupalPost('admin/config/regional/language', $edit, t('Save configuration'));
  2253. // Enable URL language detection and selection.
  2254. $edit = array('language[enabled][locale-url]' => 1);
  2255. $this->drupalPost('admin/config/regional/language/configure', $edit, t('Save settings'));
  2256. // Reset static caching.
  2257. drupal_static_reset('language_list');
  2258. drupal_static_reset('locale_url_outbound_alter');
  2259. drupal_static_reset('locale_language_url_rewrite_url');
  2260. }
  2261. /**
  2262. * Check that disabled or non-installed languages are not considered.
  2263. */
  2264. function testUrlRewritingEdgeCases() {
  2265. // Check URL rewriting with a disabled language.
  2266. $languages = language_list();
  2267. $this->checkUrl($languages['it'], 'Path language is ignored if language is disabled.', 'URL language negotiation does not work with disabled languages');
  2268. // Check URL rewriting with a non-installed language.
  2269. $non_existing = language_default();
  2270. $non_existing->language = $this->randomName();
  2271. $non_existing->prefix = $this->randomName();
  2272. $this->checkUrl($non_existing, 'Path language is ignored if language is not installed.', 'URL language negotiation does not work with non-installed languages');
  2273. }
  2274. /**
  2275. * Check URL rewriting for the given language.
  2276. *
  2277. * The test is performed with a fixed URL (the default front page) to simply
  2278. * check that language prefixes are not added to it and that the prefixed URL
  2279. * is actually not working.
  2280. *
  2281. * @param string $language
  2282. * The language prefix, e.g. 'es'.
  2283. * @param string $message1
  2284. * Message to display in assertion that language prefixes are not added.
  2285. * @param string $message2
  2286. * The message to display confirming prefixed URL is not working.
  2287. */
  2288. private function checkUrl($language, $message1, $message2) {
  2289. $options = array('language' => $language);
  2290. $base_path = trim(base_path(), '/');
  2291. $rewritten_path = trim(str_replace(array('?q=', $base_path), '', url('node', $options)), '/');
  2292. $segments = explode('/', $rewritten_path, 2);
  2293. $prefix = $segments[0];
  2294. $path = isset($segments[1]) ? $segments[1] : $prefix;
  2295. // If the rewritten URL has not a language prefix we pick the right one from
  2296. // the language object so we can always check the prefixed URL.
  2297. if ($this->assertNotEqual($language->prefix, $prefix, $message1)) {
  2298. $prefix = $language->prefix;
  2299. }
  2300. $this->drupalGet("$prefix/$path");
  2301. $this->assertResponse(404, $message2);
  2302. }
  2303. }
  2304. /**
  2305. * Functional test for multilingual fields.
  2306. */
  2307. class LocaleMultilingualFieldsFunctionalTest extends DrupalWebTestCase {
  2308. public static function getInfo() {
  2309. return array(
  2310. 'name' => 'Multilingual fields',
  2311. 'description' => 'Test multilingual support for fields.',
  2312. 'group' => 'Locale',
  2313. );
  2314. }
  2315. function setUp() {
  2316. parent::setUp('locale');
  2317. // Setup users.
  2318. $admin_user = $this->drupalCreateUser(array('administer languages', 'administer content types', 'access administration pages', 'create page content', 'edit own page content'));
  2319. $this->drupalLogin($admin_user);
  2320. // Add a new language.
  2321. require_once DRUPAL_ROOT . '/includes/locale.inc';
  2322. locale_add_language('it', 'Italian', 'Italiano', LANGUAGE_LTR, '', '', TRUE, FALSE);
  2323. // Enable URL language detection and selection.
  2324. $edit = array('language[enabled][locale-url]' => '1');
  2325. $this->drupalPost('admin/config/regional/language/configure', $edit, t('Save settings'));
  2326. // Set "Basic page" content type to use multilingual support.
  2327. $edit = array(
  2328. 'language_content_type' => 1,
  2329. );
  2330. $this->drupalPost('admin/structure/types/manage/page', $edit, t('Save content type'));
  2331. $this->assertRaw(t('The content type %type has been updated.', array('%type' => 'Basic page')), 'Basic page content type has been updated.');
  2332. // Make node body translatable.
  2333. $field = field_info_field('body');
  2334. $field['translatable'] = TRUE;
  2335. field_update_field($field);
  2336. }
  2337. /**
  2338. * Test if field languages are correctly set through the node form.
  2339. */
  2340. function testMultilingualNodeForm() {
  2341. // Create "Basic page" content.
  2342. $langcode = LANGUAGE_NONE;
  2343. $title_key = "title";
  2344. $title_value = $this->randomName(8);
  2345. $body_key = "body[$langcode][0][value]";
  2346. $body_value = $this->randomName(16);
  2347. // Create node to edit.
  2348. $edit = array();
  2349. $edit[$title_key] = $title_value;
  2350. $edit[$body_key] = $body_value;
  2351. $edit['language'] = 'en';
  2352. $this->drupalPost('node/add/page', $edit, t('Save'));
  2353. // Check that the node exists in the database.
  2354. $node = $this->drupalGetNodeByTitle($edit[$title_key]);
  2355. $this->assertTrue($node, 'Node found in database.');
  2356. $assert = isset($node->body['en']) && !isset($node->body[LANGUAGE_NONE]) && $node->body['en'][0]['value'] == $body_value;
  2357. $this->assertTrue($assert, 'Field language correctly set.');
  2358. // Change node language.
  2359. $this->drupalGet("node/$node->nid/edit");
  2360. $edit = array(
  2361. $title_key => $this->randomName(8),
  2362. 'language' => 'it'
  2363. );
  2364. $this->drupalPost(NULL, $edit, t('Save'));
  2365. $node = $this->drupalGetNodeByTitle($edit[$title_key]);
  2366. $this->assertTrue($node, 'Node found in database.');
  2367. $assert = isset($node->body['it']) && !isset($node->body['en']) && $node->body['it'][0]['value'] == $body_value;
  2368. $this->assertTrue($assert, 'Field language correctly changed.');
  2369. // Enable content language URL detection.
  2370. language_negotiation_set(LANGUAGE_TYPE_CONTENT, array(LOCALE_LANGUAGE_NEGOTIATION_URL => 0));
  2371. // Test multilingual field language fallback logic.
  2372. $this->drupalGet("it/node/$node->nid");
  2373. $this->assertRaw($body_value, 'Body correctly displayed using Italian as requested language');
  2374. $this->drupalGet("node/$node->nid");
  2375. $this->assertRaw($body_value, 'Body correctly displayed using English as requested language');
  2376. }
  2377. /*
  2378. * Test multilingual field display settings.
  2379. */
  2380. function testMultilingualDisplaySettings() {
  2381. // Create "Basic page" content.
  2382. $langcode = LANGUAGE_NONE;
  2383. $title_key = "title";
  2384. $title_value = $this->randomName(8);
  2385. $body_key = "body[$langcode][0][value]";
  2386. $body_value = $this->randomName(16);
  2387. // Create node to edit.
  2388. $edit = array();
  2389. $edit[$title_key] = $title_value;
  2390. $edit[$body_key] = $body_value;
  2391. $edit['language'] = 'en';
  2392. $this->drupalPost('node/add/page', $edit, t('Save'));
  2393. // Check that the node exists in the database.
  2394. $node = $this->drupalGetNodeByTitle($edit[$title_key]);
  2395. $this->assertTrue($node, 'Node found in database.');
  2396. // Check if node body is showed.
  2397. $this->drupalGet("node/$node->nid");
  2398. $body = $this->xpath('//div[@id=:id]//div[@property="content:encoded"]/p', array(':id' => 'node-' . $node->nid));
  2399. $this->assertEqual(current($body), $node->body['en'][0]['value'], 'Node body is correctly showed.');
  2400. }
  2401. }
  2402. /**
  2403. * Functional tests for comment language.
  2404. */
  2405. class LocaleCommentLanguageFunctionalTest extends DrupalWebTestCase {
  2406. public static function getInfo() {
  2407. return array(
  2408. 'name' => 'Comment language',
  2409. 'description' => 'Tests for comment language.',
  2410. 'group' => 'Locale',
  2411. );
  2412. }
  2413. function setUp() {
  2414. parent::setUp('locale', 'locale_test');
  2415. // Create and login user.
  2416. $admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer languages', 'access administration pages', 'administer content types', 'administer comments', 'create article content'));
  2417. $this->drupalLogin($admin_user);
  2418. // Add language.
  2419. $edit = array('langcode' => 'fr');
  2420. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add language'));
  2421. // Set "Article" content type to use multilingual support.
  2422. $edit = array('language_content_type' => 1);
  2423. $this->drupalPost('admin/structure/types/manage/article', $edit, t('Save content type'));
  2424. // Enable content language negotiation UI.
  2425. variable_set('locale_test_content_language_type', TRUE);
  2426. // Set interface language detection to user and content language detection
  2427. // to URL. Disable inheritance from interface language to ensure content
  2428. // language will fall back to the default language if no URL language can be
  2429. // detected.
  2430. $edit = array(
  2431. 'language[enabled][locale-user]' => TRUE,
  2432. 'language_content[enabled][locale-url]' => TRUE,
  2433. 'language_content[enabled][locale-interface]' => FALSE,
  2434. );
  2435. $this->drupalPost('admin/config/regional/language/configure', $edit, t('Save settings'));
  2436. // Change user language preference, this way interface language is always
  2437. // French no matter what path prefix the URLs have.
  2438. $edit = array('language' => 'fr');
  2439. $this->drupalPost("user/{$admin_user->uid}/edit", $edit, t('Save'));
  2440. // Make comment body translatable.
  2441. $field = field_info_field('comment_body');
  2442. $field['translatable'] = TRUE;
  2443. field_update_field($field);
  2444. $this->assertTrue(field_is_translatable('comment', $field), 'Comment body is translatable.');
  2445. }
  2446. /**
  2447. * Test that comment language is properly set.
  2448. */
  2449. function testCommentLanguage() {
  2450. drupal_static_reset('language_list');
  2451. // Create two nodes, one for english and one for french, and comment each
  2452. // node using both english and french as content language by changing URL
  2453. // language prefixes. Meanwhile interface language is always French, which
  2454. // is the user language preference. This way we can ensure that node
  2455. // language and interface language do not influence comment language, as
  2456. // only content language has to.
  2457. foreach (language_list() as $node_langcode => $node_language) {
  2458. $language_none = LANGUAGE_NONE;
  2459. // Create "Article" content.
  2460. $title = $this->randomName();
  2461. $edit = array(
  2462. "title" => $title,
  2463. "body[$language_none][0][value]" => $this->randomName(),
  2464. "language" => $node_langcode,
  2465. );
  2466. $this->drupalPost("node/add/article", $edit, t('Save'));
  2467. $node = $this->drupalGetNodeByTitle($title);
  2468. foreach (language_list() as $langcode => $language) {
  2469. // Post a comment with content language $langcode.
  2470. $prefix = empty($language->prefix) ? '' : $language->prefix . '/';
  2471. $comment_values[$node_langcode][$langcode] = $this->randomName();
  2472. // Initially field form widgets have no language.
  2473. $edit = array(
  2474. 'subject' => $this->randomName(),
  2475. "comment_body[$language_none][0][value]" => $comment_values[$node_langcode][$langcode],
  2476. );
  2477. $this->drupalPost("{$prefix}node/{$node->nid}", $edit, t('Preview'));
  2478. // After the first submit the submitted entity language is taken into
  2479. // account.
  2480. $edit = array(
  2481. 'subject' => $edit['subject'],
  2482. "comment_body[$langcode][0][value]" => $comment_values[$node_langcode][$langcode],
  2483. );
  2484. $this->drupalPost(NULL, $edit, t('Save'));
  2485. // Check that comment language matches the current content language.
  2486. $cid = db_select('comment', 'c')
  2487. ->fields('c', array('cid'))
  2488. ->condition('nid', $node->nid)
  2489. ->orderBy('cid', 'DESC')
  2490. ->range(0, 1)
  2491. ->execute()
  2492. ->fetchField();
  2493. $comment = comment_load($cid);
  2494. $comment_langcode = entity_language('comment', $comment);
  2495. $args = array('%node_language' => $node_langcode, '%comment_language' => $comment_langcode, '%langcode' => $langcode);
  2496. $this->assertEqual($comment_langcode, $langcode, format_string('The comment posted with content language %langcode and belonging to the node with language %node_language has language %comment_language', $args));
  2497. $this->assertEqual($comment->comment_body[$langcode][0]['value'], $comment_values[$node_langcode][$langcode], 'Comment body correctly stored.');
  2498. }
  2499. }
  2500. // Check that comment bodies appear in the administration UI.
  2501. $this->drupalGet('admin/content/comment');
  2502. foreach ($comment_values as $node_values) {
  2503. foreach ($node_values as $value) {
  2504. $this->assertRaw($value);
  2505. }
  2506. }
  2507. }
  2508. }
  2509. /**
  2510. * Functional tests for localizing date formats.
  2511. */
  2512. class LocaleDateFormatsFunctionalTest extends DrupalWebTestCase {
  2513. public static function getInfo() {
  2514. return array(
  2515. 'name' => 'Localize date formats',
  2516. 'description' => 'Tests for the localization of date formats.',
  2517. 'group' => 'Locale',
  2518. );
  2519. }
  2520. function setUp() {
  2521. parent::setUp('locale');
  2522. // Create and login user.
  2523. $admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer languages', 'access administration pages', 'create article content'));
  2524. $this->drupalLogin($admin_user);
  2525. }
  2526. /**
  2527. * Functional tests for localizing date formats.
  2528. */
  2529. function testLocalizeDateFormats() {
  2530. // Add language.
  2531. $edit = array(
  2532. 'langcode' => 'fr',
  2533. );
  2534. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add language'));
  2535. // Set language negotiation.
  2536. $language_type = LANGUAGE_TYPE_INTERFACE;
  2537. $edit = array(
  2538. "{$language_type}[enabled][locale-url]" => TRUE,
  2539. );
  2540. $this->drupalPost('admin/config/regional/language/configure', $edit, t('Save settings'));
  2541. // Configure date formats.
  2542. $this->drupalGet('admin/config/regional/date-time/locale');
  2543. $this->assertText('Français', 'Configured languages appear.');
  2544. $edit = array(
  2545. 'date_format_long' => 'd.m.Y - H:i',
  2546. 'date_format_medium' => 'd.m.Y - H:i',
  2547. 'date_format_short' => 'd.m.Y - H:i',
  2548. );
  2549. $this->drupalPost('admin/config/regional/date-time/locale/fr/edit', $edit, t('Save configuration'));
  2550. $this->assertText(t('Configuration saved.'), 'French date formats updated.');
  2551. $edit = array(
  2552. 'date_format_long' => 'j M Y - g:ia',
  2553. 'date_format_medium' => 'j M Y - g:ia',
  2554. 'date_format_short' => 'j M Y - g:ia',
  2555. );
  2556. $this->drupalPost('admin/config/regional/date-time/locale/en/edit', $edit, t('Save configuration'));
  2557. $this->assertText(t('Configuration saved.'), 'English date formats updated.');
  2558. // Create node content.
  2559. $node = $this->drupalCreateNode(array('type' => 'article'));
  2560. // Configure format for the node posted date changes with the language.
  2561. $this->drupalGet('node/' . $node->nid);
  2562. $english_date = format_date($node->created, 'custom', 'j M Y');
  2563. $this->assertText($english_date, 'English date format appears');
  2564. $this->drupalGet('fr/node/' . $node->nid);
  2565. $french_date = format_date($node->created, 'custom', 'd.m.Y');
  2566. $this->assertText($french_date, 'French date format appears');
  2567. }
  2568. }
  2569. /**
  2570. * Functional test for language types/negotiation info.
  2571. */
  2572. class LocaleLanguageNegotiationInfoFunctionalTest extends DrupalWebTestCase {
  2573. public static function getInfo() {
  2574. return array(
  2575. 'name' => 'Language negotiation info',
  2576. 'description' => 'Tests alterations to language types/negotiation info.',
  2577. 'group' => 'Locale',
  2578. );
  2579. }
  2580. function setUp() {
  2581. parent::setUp('locale');
  2582. require_once DRUPAL_ROOT .'/includes/language.inc';
  2583. $admin_user = $this->drupalCreateUser(array('administer languages', 'access administration pages', 'view the administration theme'));
  2584. $this->drupalLogin($admin_user);
  2585. $this->drupalPost('admin/config/regional/language/add', array('langcode' => 'it'), t('Add language'));
  2586. }
  2587. /**
  2588. * Tests alterations to language types/negotiation info.
  2589. */
  2590. function testInfoAlterations() {
  2591. // Enable language type/negotiation info alterations.
  2592. variable_set('locale_test_language_types', TRUE);
  2593. variable_set('locale_test_language_negotiation_info', TRUE);
  2594. $this->languageNegotiationUpdate();
  2595. // Check that fixed language types are properly configured without the need
  2596. // of saving the language negotiation settings.
  2597. $this->checkFixedLanguageTypes();
  2598. // Make the content language type configurable by updating the language
  2599. // negotiation settings with the proper flag enabled.
  2600. variable_set('locale_test_content_language_type', TRUE);
  2601. $this->languageNegotiationUpdate();
  2602. $type = LANGUAGE_TYPE_CONTENT;
  2603. $language_types = variable_get('language_types', drupal_language_types());
  2604. $this->assertTrue($language_types[$type], 'Content language type is configurable.');
  2605. // Enable some core and custom language providers. The test language type is
  2606. // supposed to be configurable.
  2607. $test_type = 'test_language_type';
  2608. $provider = LOCALE_LANGUAGE_NEGOTIATION_INTERFACE;
  2609. $test_provider = 'test_language_provider';
  2610. $form_field = $type . '[enabled]['. $provider .']';
  2611. $edit = array(
  2612. $form_field => TRUE,
  2613. $type . '[enabled][' . $test_provider . ']' => TRUE,
  2614. $test_type . '[enabled][' . $test_provider . ']' => TRUE,
  2615. );
  2616. $this->drupalPost('admin/config/regional/language/configure', $edit, t('Save settings'));
  2617. // Remove the interface language provider by updating the language
  2618. // negotiation settings with the proper flag enabled.
  2619. variable_set('locale_test_language_negotiation_info_alter', TRUE);
  2620. $this->languageNegotiationUpdate();
  2621. $negotiation = variable_get("language_negotiation_$type", array());
  2622. $this->assertFalse(isset($negotiation[$provider]), 'Interface language provider removed from the stored settings.');
  2623. $this->assertNoFieldByXPath("//input[@name=\"$form_field\"]", NULL, 'Interface language provider unavailable.');
  2624. // Check that type-specific language providers can be assigned only to the
  2625. // corresponding language types.
  2626. foreach (language_types_configurable() as $type) {
  2627. $form_field = $type . '[enabled][test_language_provider_ts]';
  2628. if ($type == $test_type) {
  2629. $this->assertFieldByXPath("//input[@name=\"$form_field\"]", NULL, format_string('Type-specific test language provider available for %type.', array('%type' => $type)));
  2630. }
  2631. else {
  2632. $this->assertNoFieldByXPath("//input[@name=\"$form_field\"]", NULL, format_string('Type-specific test language provider unavailable for %type.', array('%type' => $type)));
  2633. }
  2634. }
  2635. // Check language negotiation results.
  2636. $this->drupalGet('');
  2637. $last = variable_get('locale_test_language_negotiation_last', array());
  2638. foreach (language_types() as $type) {
  2639. $langcode = $last[$type];
  2640. $value = $type == LANGUAGE_TYPE_CONTENT || strpos($type, 'test') !== FALSE ? 'it' : 'en';
  2641. $this->assertEqual($langcode, $value, format_string('The negotiated language for %type is %language', array('%type' => $type, '%language' => $langcode)));
  2642. }
  2643. // Disable locale_test and check that everything is set back to the original
  2644. // status.
  2645. $this->languageNegotiationUpdate('disable');
  2646. // Check that only the core language types are available.
  2647. foreach (language_types() as $type) {
  2648. $this->assertTrue(strpos($type, 'test') === FALSE, format_string('The %type language is still available', array('%type' => $type)));
  2649. }
  2650. // Check that fixed language types are properly configured, even those
  2651. // previously set to configurable.
  2652. $this->checkFixedLanguageTypes();
  2653. // Check that unavailable language providers are not present in the
  2654. // negotiation settings.
  2655. $negotiation = variable_get("language_negotiation_$type", array());
  2656. $this->assertFalse(isset($negotiation[$test_provider]), 'The disabled test language provider is not part of the content language negotiation settings.');
  2657. // Check that configuration page presents the correct options and settings.
  2658. $this->assertNoRaw(t('Test language detection'), 'No test language type configuration available.');
  2659. $this->assertNoRaw(t('This is a test language provider'), 'No test language provider available.');
  2660. }
  2661. /**
  2662. * Update language types/negotiation information.
  2663. *
  2664. * Manually invoke locale_modules_enabled()/locale_modules_disabled() since
  2665. * they would not be invoked after enabling/disabling locale_test the first
  2666. * time.
  2667. */
  2668. private function languageNegotiationUpdate($op = 'enable') {
  2669. static $last_op = NULL;
  2670. $modules = array('locale_test');
  2671. // Enable/disable locale_test only if we did not already before.
  2672. if ($last_op != $op) {
  2673. $function = "module_{$op}";
  2674. $function($modules);
  2675. // Reset hook implementation cache.
  2676. module_implements(NULL, FALSE, TRUE);
  2677. }
  2678. drupal_static_reset('language_types_info');
  2679. drupal_static_reset('language_negotiation_info');
  2680. $function = "locale_modules_{$op}d";
  2681. if (function_exists($function)) {
  2682. $function($modules);
  2683. }
  2684. $this->drupalGet('admin/config/regional/language/configure');
  2685. }
  2686. /**
  2687. * Check that language negotiation for fixed types matches the stored one.
  2688. */
  2689. private function checkFixedLanguageTypes() {
  2690. drupal_static_reset('language_types_info');
  2691. foreach (language_types_info() as $type => $info) {
  2692. if (isset($info['fixed'])) {
  2693. $negotiation = variable_get("language_negotiation_$type", array());
  2694. $equal = count($info['fixed']) == count($negotiation);
  2695. while ($equal && list($id) = each($negotiation)) {
  2696. list(, $info_id) = each($info['fixed']);
  2697. $equal = $info_id == $id;
  2698. }
  2699. $this->assertTrue($equal, format_string('language negotiation for %type is properly set up', array('%type' => $type)));
  2700. }
  2701. }
  2702. }
  2703. }
  2704. /**
  2705. * Functional tests for CSS alter functions.
  2706. */
  2707. class LocaleCSSAlterTest extends DrupalWebTestCase {
  2708. public static function getInfo() {
  2709. return array(
  2710. 'name' => 'CSS altering',
  2711. 'description' => 'Test CSS alter functions.',
  2712. 'group' => 'Locale',
  2713. );
  2714. }
  2715. function setUp() {
  2716. parent::setUp('locale');
  2717. }
  2718. /**
  2719. * Verifies that -rtl.css file is added directly after LTR .css file.
  2720. */
  2721. function testCSSFilesOrderInRTLMode() {
  2722. global $base_url;
  2723. // User to add and remove language.
  2724. $admin_user = $this->drupalCreateUser(array('administer languages', 'administer content types', 'access administration pages'));
  2725. // Log in as admin.
  2726. $this->drupalLogin($admin_user);
  2727. // Install the Arabic language (which is RTL) and configure as the default.
  2728. $edit = array();
  2729. $edit['langcode'] = 'ar';
  2730. $this->drupalPost('admin/config/regional/language/add', $edit, t('Add language'));
  2731. $edit = array();
  2732. $edit['site_default'] = 'ar';
  2733. $this->drupalPost(NULL, $edit, t('Save configuration'));
  2734. // Verify that the -rtl.css file is added directly after LTR file.
  2735. $this->drupalGet('');
  2736. $query_string = '?' . variable_get('css_js_query_string', '0');
  2737. $this->assertRaw('@import url("' . $base_url . '/modules/system/system.base.css' . $query_string . '");' . "\n" . '@import url("' . $base_url . '/modules/system/system.base-rtl.css' . $query_string . '");' . "\n", 'CSS: system.base-rtl.css is added directly after system.base.css.');
  2738. $this->assertRaw('@import url("' . $base_url . '/modules/system/system.menus.css' . $query_string . '");' . "\n" . '@import url("' . $base_url . '/modules/system/system.menus-rtl.css' . $query_string . '");' . "\n", 'CSS: system.menus-rtl.css is added directly after system.menus.css.');
  2739. $this->assertRaw('@import url("' . $base_url . '/modules/system/system.messages.css' . $query_string . '");' . "\n" . '@import url("' . $base_url . '/modules/system/system.messages-rtl.css' . $query_string . '");' . "\n", 'CSS: system.messages-rtl.css is added directly after system.messages.css.');
  2740. }
  2741. }