locale.inc 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492
  1. <?php
  2. /**
  3. * @file
  4. * Administration functions for locale.module.
  5. */
  6. /**
  7. * The language is determined using a URL language indicator:
  8. * path prefix or domain according to the configuration.
  9. */
  10. define('LOCALE_LANGUAGE_NEGOTIATION_URL', 'locale-url');
  11. /**
  12. * The language is set based on the browser language settings.
  13. */
  14. define('LOCALE_LANGUAGE_NEGOTIATION_BROWSER', 'locale-browser');
  15. /**
  16. * The language is determined using the current interface language.
  17. */
  18. define('LOCALE_LANGUAGE_NEGOTIATION_INTERFACE', 'locale-interface');
  19. /**
  20. * If no URL language is available language is determined using an already
  21. * detected one.
  22. */
  23. define('LOCALE_LANGUAGE_NEGOTIATION_URL_FALLBACK', 'locale-url-fallback');
  24. /**
  25. * The language is set based on the user language settings.
  26. */
  27. define('LOCALE_LANGUAGE_NEGOTIATION_USER', 'locale-user');
  28. /**
  29. * The language is set based on the request/session parameters.
  30. */
  31. define('LOCALE_LANGUAGE_NEGOTIATION_SESSION', 'locale-session');
  32. /**
  33. * Regular expression pattern used to localize JavaScript strings.
  34. */
  35. define('LOCALE_JS_STRING', '(?:(?:\'(?:\\\\\'|[^\'])*\'|"(?:\\\\"|[^"])*")(?:\s*\+\s*)?)+');
  36. /**
  37. * Regular expression pattern used to match simple JS object literal.
  38. *
  39. * This pattern matches a basic JS object, but will fail on an object with
  40. * nested objects. Used in JS file parsing for string arg processing.
  41. */
  42. define('LOCALE_JS_OBJECT', '\{.*?\}');
  43. /**
  44. * Regular expression to match an object containing a key 'context'.
  45. *
  46. * Pattern to match a JS object containing a 'context key' with a string value,
  47. * which is captured. Will fail if there are nested objects.
  48. */
  49. define('LOCALE_JS_OBJECT_CONTEXT', '
  50. \{ # match object literal start
  51. .*? # match anything, non-greedy
  52. (?: # match a form of "context"
  53. \'context\'
  54. |
  55. "context"
  56. |
  57. context
  58. )
  59. \s*:\s* # match key-value separator ":"
  60. (' . LOCALE_JS_STRING . ') # match context string
  61. .*? # match anything, non-greedy
  62. \} # match end of object literal
  63. ');
  64. /**
  65. * Translation import mode overwriting all existing translations
  66. * if new translated version available.
  67. */
  68. define('LOCALE_IMPORT_OVERWRITE', 0);
  69. /**
  70. * Translation import mode keeping existing translations and only
  71. * inserting new strings.
  72. */
  73. define('LOCALE_IMPORT_KEEP', 1);
  74. /**
  75. * URL language negotiation: use the path prefix as URL language
  76. * indicator.
  77. */
  78. define('LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX', 0);
  79. /**
  80. * URL language negotiation: use the domain as URL language
  81. * indicator.
  82. */
  83. define('LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN', 1);
  84. /**
  85. * @defgroup locale-languages-negotiation Language negotiation options
  86. * @{
  87. * Functions for language negotiation.
  88. *
  89. * There are functions that provide the ability to identify the
  90. * language. This behavior can be controlled by various options.
  91. */
  92. /**
  93. * Identifies the language from the current interface language.
  94. *
  95. * @return
  96. * The current interface language code.
  97. */
  98. function locale_language_from_interface() {
  99. global $language;
  100. return isset($language->language) ? $language->language : FALSE;
  101. }
  102. /**
  103. * Identify language from the Accept-language HTTP header we got.
  104. *
  105. * We perform browser accept-language parsing only if page cache is disabled,
  106. * otherwise we would cache a user-specific preference.
  107. *
  108. * @param $languages
  109. * An array of language objects for enabled languages ordered by weight.
  110. *
  111. * @return
  112. * A valid language code on success, FALSE otherwise.
  113. */
  114. function locale_language_from_browser($languages) {
  115. if (empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  116. return FALSE;
  117. }
  118. // The Accept-Language header contains information about the language
  119. // preferences configured in the user's browser / operating system.
  120. // RFC 2616 (section 14.4) defines the Accept-Language header as follows:
  121. // Accept-Language = "Accept-Language" ":"
  122. // 1#( language-range [ ";" "q" "=" qvalue ] )
  123. // language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )
  124. // Samples: "hu, en-us;q=0.66, en;q=0.33", "hu,en-us;q=0.5"
  125. $browser_langcodes = array();
  126. if (preg_match_all('@(?<=[, ]|^)([a-zA-Z-]+|\*)(?:;q=([0-9.]+))?(?:$|\s*,\s*)@', trim($_SERVER['HTTP_ACCEPT_LANGUAGE']), $matches, PREG_SET_ORDER)) {
  127. foreach ($matches as $match) {
  128. // We can safely use strtolower() here, tags are ASCII.
  129. // RFC2616 mandates that the decimal part is no more than three digits,
  130. // so we multiply the qvalue by 1000 to avoid floating point comparisons.
  131. $langcode = strtolower($match[1]);
  132. $qvalue = isset($match[2]) ? (float) $match[2] : 1;
  133. $browser_langcodes[$langcode] = (int) ($qvalue * 1000);
  134. }
  135. }
  136. // We should take pristine values from the HTTP headers, but Internet Explorer
  137. // from version 7 sends only specific language tags (eg. fr-CA) without the
  138. // corresponding generic tag (fr) unless explicitly configured. In that case,
  139. // we assume that the lowest value of the specific tags is the value of the
  140. // generic language to be as close to the HTTP 1.1 spec as possible.
  141. // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 and
  142. // http://blogs.msdn.com/b/ie/archive/2006/10/17/accept-language-header-for-internet-explorer-7.aspx
  143. asort($browser_langcodes);
  144. foreach ($browser_langcodes as $langcode => $qvalue) {
  145. $generic_tag = strtok($langcode, '-');
  146. if (!isset($browser_langcodes[$generic_tag])) {
  147. $browser_langcodes[$generic_tag] = $qvalue;
  148. }
  149. }
  150. // Find the enabled language with the greatest qvalue, following the rules
  151. // of RFC 2616 (section 14.4). If several languages have the same qvalue,
  152. // prefer the one with the greatest weight.
  153. $best_match_langcode = FALSE;
  154. $max_qvalue = 0;
  155. foreach ($languages as $langcode => $language) {
  156. // Language tags are case insensitive (RFC2616, sec 3.10).
  157. $langcode = strtolower($langcode);
  158. // If nothing matches below, the default qvalue is the one of the wildcard
  159. // language, if set, or is 0 (which will never match).
  160. $qvalue = isset($browser_langcodes['*']) ? $browser_langcodes['*'] : 0;
  161. // Find the longest possible prefix of the browser-supplied language
  162. // ('the language-range') that matches this site language ('the language tag').
  163. $prefix = $langcode;
  164. do {
  165. if (isset($browser_langcodes[$prefix])) {
  166. $qvalue = $browser_langcodes[$prefix];
  167. break;
  168. }
  169. }
  170. while ($prefix = substr($prefix, 0, strrpos($prefix, '-')));
  171. // Find the best match.
  172. if ($qvalue > $max_qvalue) {
  173. $best_match_langcode = $language->language;
  174. $max_qvalue = $qvalue;
  175. }
  176. }
  177. return $best_match_langcode;
  178. }
  179. /**
  180. * Identify language from the user preferences.
  181. *
  182. * @param $languages
  183. * An array of valid language objects.
  184. *
  185. * @return
  186. * A valid language code on success, FALSE otherwise.
  187. */
  188. function locale_language_from_user($languages) {
  189. // User preference (only for logged users).
  190. global $user;
  191. if ($user->uid) {
  192. return $user->language;
  193. }
  194. // No language preference from the user.
  195. return FALSE;
  196. }
  197. /**
  198. * Identify language from a request/session parameter.
  199. *
  200. * @param $languages
  201. * An array of valid language objects.
  202. *
  203. * @return
  204. * A valid language code on success, FALSE otherwise.
  205. */
  206. function locale_language_from_session($languages) {
  207. $param = variable_get('locale_language_negotiation_session_param', 'language');
  208. // Request parameter: we need to update the session parameter only if we have
  209. // an authenticated user.
  210. if (isset($_GET[$param]) && isset($languages[$langcode = $_GET[$param]])) {
  211. global $user;
  212. if ($user->uid) {
  213. $_SESSION[$param] = $langcode;
  214. }
  215. return $langcode;
  216. }
  217. // Session parameter.
  218. if (isset($_SESSION[$param])) {
  219. return $_SESSION[$param];
  220. }
  221. return FALSE;
  222. }
  223. /**
  224. * Identify language via URL prefix or domain.
  225. *
  226. * @param $languages
  227. * An array of valid language objects.
  228. *
  229. * @return
  230. * A valid language code on success, FALSE otherwise.
  231. */
  232. function locale_language_from_url($languages) {
  233. $language_url = FALSE;
  234. if (!language_negotiation_get_any(LOCALE_LANGUAGE_NEGOTIATION_URL)) {
  235. return $language_url;
  236. }
  237. switch (variable_get('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX)) {
  238. case LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX:
  239. // $_GET['q'] might not be available at this time, because
  240. // path initialization runs after the language bootstrap phase.
  241. list($language, $_GET['q']) = language_url_split_prefix(isset($_GET['q']) ? $_GET['q'] : NULL, $languages);
  242. if ($language !== FALSE) {
  243. $language_url = $language->language;
  244. }
  245. break;
  246. case LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN:
  247. // Get only the host, not the port.
  248. $http_host= $_SERVER['HTTP_HOST'];
  249. if (strpos($http_host, ':') !== FALSE) {
  250. $http_host_tmp = explode(':', $http_host);
  251. $http_host = current($http_host_tmp);
  252. }
  253. foreach ($languages as $language) {
  254. // Skip check if the language doesn't have a domain.
  255. if ($language->domain) {
  256. // Only compare the domains not the protocols or ports.
  257. // Remove protocol and add http:// so parse_url works
  258. $host = 'http://' . str_replace(array('http://', 'https://'), '', $language->domain);
  259. $host = parse_url($host, PHP_URL_HOST);
  260. if ($http_host == $host) {
  261. $language_url = $language->language;
  262. break;
  263. }
  264. }
  265. }
  266. break;
  267. }
  268. return $language_url;
  269. }
  270. /**
  271. * Determines the language to be assigned to URLs when none is detected.
  272. *
  273. * The language negotiation process has a fallback chain that ends with the
  274. * default language provider. Each built-in language type has a separate
  275. * initialization:
  276. * - Interface language, which is the only configurable one, always gets a valid
  277. * value. If no request-specific language is detected, the default language
  278. * will be used.
  279. * - Content language merely inherits the interface language by default.
  280. * - URL language is detected from the requested URL and will be used to rewrite
  281. * URLs appearing in the page being rendered. If no language can be detected,
  282. * there are two possibilities:
  283. * - If the default language has no configured path prefix or domain, then the
  284. * default language is used. This guarantees that (missing) URL prefixes are
  285. * preserved when navigating through the site.
  286. * - If the default language has a configured path prefix or domain, a
  287. * requested URL having an empty prefix or domain is an anomaly that must be
  288. * fixed. This is done by introducing a prefix or domain in the rendered
  289. * page matching the detected interface language.
  290. *
  291. * @param $languages
  292. * (optional) An array of valid language objects. This is passed by
  293. * language_provider_invoke() to every language provider callback, but it is
  294. * not actually needed here. Defaults to NULL.
  295. * @param $language_type
  296. * (optional) The language type to fall back to. Defaults to the interface
  297. * language.
  298. *
  299. * @return
  300. * A valid language code.
  301. */
  302. function locale_language_url_fallback($language = NULL, $language_type = LANGUAGE_TYPE_INTERFACE) {
  303. $default = language_default();
  304. $prefix = (variable_get('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX);
  305. // If the default language is not configured to convey language information,
  306. // a missing URL language information indicates that URL language should be
  307. // the default one, otherwise we fall back to an already detected language.
  308. if (($prefix && empty($default->prefix)) || (!$prefix && empty($default->domain))) {
  309. return $default->language;
  310. }
  311. else {
  312. return $GLOBALS[$language_type]->language;
  313. }
  314. }
  315. /**
  316. * Return the URL language switcher block. Translation links may be provided by
  317. * other modules.
  318. */
  319. function locale_language_switcher_url($type, $path) {
  320. $languages = language_list('enabled');
  321. $links = array();
  322. foreach ($languages[1] as $language) {
  323. $links[$language->language] = array(
  324. 'href' => $path,
  325. 'title' => $language->native,
  326. 'language' => $language,
  327. 'attributes' => array('class' => array('language-link')),
  328. );
  329. }
  330. return $links;
  331. }
  332. /**
  333. * Return the session language switcher block.
  334. */
  335. function locale_language_switcher_session($type, $path) {
  336. drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
  337. $param = variable_get('locale_language_negotiation_session_param', 'language');
  338. $language_query = isset($_SESSION[$param]) ? $_SESSION[$param] : $GLOBALS[$type]->language;
  339. $languages = language_list('enabled');
  340. $links = array();
  341. $query = $_GET;
  342. unset($query['q']);
  343. foreach ($languages[1] as $language) {
  344. $langcode = $language->language;
  345. $links[$langcode] = array(
  346. 'href' => $path,
  347. 'title' => $language->native,
  348. 'attributes' => array('class' => array('language-link')),
  349. 'query' => $query,
  350. );
  351. if ($language_query != $langcode) {
  352. $links[$langcode]['query'][$param] = $langcode;
  353. }
  354. else {
  355. $links[$langcode]['attributes']['class'][] = 'session-active';
  356. }
  357. }
  358. return $links;
  359. }
  360. /**
  361. * Rewrite URLs for the URL language provider.
  362. */
  363. function locale_language_url_rewrite_url(&$path, &$options) {
  364. static $drupal_static_fast;
  365. if (!isset($drupal_static_fast)) {
  366. $drupal_static_fast['languages'] = &drupal_static(__FUNCTION__);
  367. }
  368. $languages = &$drupal_static_fast['languages'];
  369. if (!isset($languages)) {
  370. $languages = language_list('enabled');
  371. $languages = array_flip(array_keys($languages[1]));
  372. }
  373. // Language can be passed as an option, or we go for current URL language.
  374. if (!isset($options['language'])) {
  375. global $language_url;
  376. $options['language'] = $language_url;
  377. }
  378. // We allow only enabled languages here.
  379. elseif (!isset($languages[$options['language']->language])) {
  380. unset($options['language']);
  381. return;
  382. }
  383. if (isset($options['language'])) {
  384. switch (variable_get('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX)) {
  385. case LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN:
  386. if ($options['language']->domain) {
  387. // Save the original base URL. If it contains a port, we need to
  388. // retain it below.
  389. if (!empty($options['base_url'])) {
  390. // The colon in the URL scheme messes up the port checking below.
  391. $normalized_base_url = str_replace(array('https://', 'http://'), '', $options['base_url']);
  392. }
  393. // Ask for an absolute URL with our modified base_url.
  394. global $is_https;
  395. $url_scheme = ($is_https) ? 'https://' : 'http://';
  396. $options['absolute'] = TRUE;
  397. // Take the domain without ports or protocols so we can apply the
  398. // protocol needed. The setting might include a protocol.
  399. // This is changed in Drupal 8 but we need to keep backwards
  400. // compatibility for Drupal 7.
  401. $host = 'http://' . str_replace(array('http://', 'https://'), '', $options['language']->domain);
  402. $host = parse_url($host, PHP_URL_HOST);
  403. // Apply the appropriate protocol to the URL.
  404. $options['base_url'] = $url_scheme . $host;
  405. // In case either the original base URL or the HTTP host contains a
  406. // port, retain it.
  407. $http_host = $_SERVER['HTTP_HOST'];
  408. if (isset($normalized_base_url) && strpos($normalized_base_url, ':') !== FALSE) {
  409. list($host, $port) = explode(':', $normalized_base_url);
  410. $options['base_url'] .= ':' . $port;
  411. }
  412. elseif (strpos($http_host, ':') !== FALSE) {
  413. list($host, $port) = explode(':', $http_host);
  414. $options['base_url'] .= ':' . $port;
  415. }
  416. if (isset($options['https']) && variable_get('https', FALSE)) {
  417. if ($options['https'] === TRUE) {
  418. $options['base_url'] = str_replace('http://', 'https://', $options['base_url']);
  419. }
  420. elseif ($options['https'] === FALSE) {
  421. $options['base_url'] = str_replace('https://', 'http://', $options['base_url']);
  422. }
  423. }
  424. }
  425. break;
  426. case LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX:
  427. if (!empty($options['language']->prefix)) {
  428. $options['prefix'] = $options['language']->prefix . '/';
  429. }
  430. break;
  431. }
  432. }
  433. }
  434. /**
  435. * Rewrite URLs for the Session language provider.
  436. */
  437. function locale_language_url_rewrite_session(&$path, &$options) {
  438. static $query_rewrite, $query_param, $query_value;
  439. // The following values are not supposed to change during a single page
  440. // request processing.
  441. if (!isset($query_rewrite)) {
  442. global $user;
  443. if (!$user->uid) {
  444. $languages = language_list('enabled');
  445. $languages = $languages[1];
  446. $query_param = check_plain(variable_get('locale_language_negotiation_session_param', 'language'));
  447. $query_value = isset($_GET[$query_param]) ? check_plain($_GET[$query_param]) : NULL;
  448. $query_rewrite = isset($languages[$query_value]) && language_negotiation_get_any(LOCALE_LANGUAGE_NEGOTIATION_SESSION);
  449. }
  450. else {
  451. $query_rewrite = FALSE;
  452. }
  453. }
  454. // If the user is anonymous, the user language provider is enabled, and the
  455. // corresponding option has been set, we must preserve any explicit user
  456. // language preference even with cookies disabled.
  457. if ($query_rewrite) {
  458. if (is_string($options['query'])) {
  459. $options['query'] = drupal_get_query_array($options['query']);
  460. }
  461. if (!isset($options['query'][$query_param])) {
  462. $options['query'][$query_param] = $query_value;
  463. }
  464. }
  465. }
  466. /**
  467. * @} End of "locale-languages-negotiation"
  468. */
  469. /**
  470. * Check that a string is safe to be added or imported as a translation.
  471. *
  472. * This test can be used to detect possibly bad translation strings. It should
  473. * not have any false positives. But it is only a test, not a transformation,
  474. * as it destroys valid HTML. We cannot reliably filter translation strings
  475. * on import because some strings are irreversibly corrupted. For example,
  476. * a &amp; in the translation would get encoded to &amp;amp; by filter_xss()
  477. * before being put in the database, and thus would be displayed incorrectly.
  478. *
  479. * The allowed tag list is like filter_xss_admin(), but omitting div and img as
  480. * not needed for translation and likely to cause layout issues (div) or a
  481. * possible attack vector (img).
  482. */
  483. function locale_string_is_safe($string) {
  484. // Some strings have tokens in them. For tokens in the first part of href or
  485. // src HTML attributes, filter_xss() removes part of the token, the part
  486. // before the first colon. filter_xss() assumes it could be an attempt to
  487. // inject javascript. When filter_xss() removes part of tokens, it causes the
  488. // string to not be translatable when it should be translatable. See
  489. // LocaleStringIsSafeTest::testLocaleStringIsSafe().
  490. //
  491. // We can recognize tokens since they are wrapped with brackets and are only
  492. // composed of alphanumeric characters, colon, underscore, and dashes. We can
  493. // be sure these strings are safe to strip out before the string is checked in
  494. // filter_xss() because no dangerous javascript will match that pattern.
  495. //
  496. // @todo Do not strip out the token. Fix filter_xss() to not incorrectly
  497. // alter the string. https://www.drupal.org/node/2372127
  498. $string = preg_replace('/\[[a-z0-9_-]+(:[a-z0-9_-]+)+\]/i', '', $string);
  499. return decode_entities($string) == decode_entities(filter_xss($string, array('a', 'abbr', 'acronym', 'address', 'b', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dl', 'dt', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'ins', 'kbd', 'li', 'ol', 'p', 'pre', 'q', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'tt', 'ul', 'var')));
  500. }
  501. /**
  502. * @defgroup locale-api-add Language addition API
  503. * @{
  504. * Add a language.
  505. *
  506. * The language addition API is used to create languages and store them.
  507. */
  508. /**
  509. * API function to add a language.
  510. *
  511. * @param $langcode
  512. * Language code.
  513. * @param $name
  514. * English name of the language
  515. * @param $native
  516. * Native name of the language
  517. * @param $direction
  518. * LANGUAGE_LTR or LANGUAGE_RTL
  519. * @param $domain
  520. * Optional custom domain name with protocol, without
  521. * trailing slash (eg. http://de.example.com).
  522. * @param $prefix
  523. * Optional path prefix for the language. Defaults to the
  524. * language code if omitted.
  525. * @param $enabled
  526. * Optionally TRUE to enable the language when created or FALSE to disable.
  527. * @param $default
  528. * Optionally set this language to be the default.
  529. */
  530. function locale_add_language($langcode, $name = NULL, $native = NULL, $direction = LANGUAGE_LTR, $domain = '', $prefix = '', $enabled = TRUE, $default = FALSE) {
  531. // Default prefix on language code.
  532. if (empty($prefix)) {
  533. $prefix = $langcode;
  534. }
  535. // If name was not set, we add a predefined language.
  536. if (!isset($name)) {
  537. include_once DRUPAL_ROOT . '/includes/iso.inc';
  538. $predefined = _locale_get_predefined_list();
  539. $name = $predefined[$langcode][0];
  540. $native = isset($predefined[$langcode][1]) ? $predefined[$langcode][1] : $predefined[$langcode][0];
  541. $direction = isset($predefined[$langcode][2]) ? $predefined[$langcode][2] : LANGUAGE_LTR;
  542. }
  543. db_insert('languages')
  544. ->fields(array(
  545. 'language' => $langcode,
  546. 'name' => $name,
  547. 'native' => $native,
  548. 'direction' => $direction,
  549. 'domain' => $domain,
  550. 'prefix' => $prefix,
  551. 'enabled' => $enabled,
  552. ))
  553. ->execute();
  554. // Only set it as default if enabled.
  555. if ($enabled && $default) {
  556. variable_set('language_default', (object) array('language' => $langcode, 'name' => $name, 'native' => $native, 'direction' => $direction, 'enabled' => (int) $enabled, 'plurals' => 0, 'formula' => '', 'domain' => '', 'prefix' => $prefix, 'weight' => 0, 'javascript' => ''));
  557. }
  558. if ($enabled) {
  559. // Increment enabled language count if we are adding an enabled language.
  560. variable_set('language_count', variable_get('language_count', 1) + 1);
  561. }
  562. // Kill the static cache in language_list().
  563. drupal_static_reset('language_list');
  564. // Force JavaScript translation file creation for the newly added language.
  565. _locale_invalidate_js($langcode);
  566. watchdog('locale', 'The %language language (%code) has been created.', array('%language' => $name, '%code' => $langcode));
  567. module_invoke_all('multilingual_settings_changed');
  568. }
  569. /**
  570. * @} End of "locale-api-add"
  571. */
  572. /**
  573. * @defgroup locale-api-import-export Translation import/export API.
  574. * @{
  575. * Functions to import and export translations.
  576. *
  577. * These functions provide the ability to import translations from
  578. * external files and to export translations and translation templates.
  579. */
  580. /**
  581. * Parses Gettext Portable Object file information and inserts into database
  582. *
  583. * @param $file
  584. * Drupal file object corresponding to the PO file to import.
  585. * @param $langcode
  586. * Language code.
  587. * @param $mode
  588. * Should existing translations be replaced LOCALE_IMPORT_KEEP or
  589. * LOCALE_IMPORT_OVERWRITE.
  590. * @param $group
  591. * Text group to import PO file into (eg. 'default' for interface
  592. * translations).
  593. */
  594. function _locale_import_po($file, $langcode, $mode, $group = NULL) {
  595. // Check if we have the language already in the database.
  596. if (!db_query("SELECT COUNT(language) FROM {languages} WHERE language = :language", array(':language' => $langcode))->fetchField()) {
  597. drupal_set_message(t('The language selected for import is not supported.'), 'error');
  598. return FALSE;
  599. }
  600. // Get strings from file (returns on failure after a partial import, or on success)
  601. $status = _locale_import_read_po('db-store', $file, $mode, $langcode, $group);
  602. if ($status === FALSE) {
  603. // Error messages are set in _locale_import_read_po().
  604. return FALSE;
  605. }
  606. // Get status information on import process.
  607. list($header_done, $additions, $updates, $deletes, $skips) = _locale_import_one_string('db-report');
  608. if (!$header_done) {
  609. drupal_set_message(t('The translation file %filename appears to have a missing or malformed header.', array('%filename' => $file->filename)), 'error');
  610. }
  611. // Clear cache and force refresh of JavaScript translations.
  612. _locale_invalidate_js($langcode);
  613. cache_clear_all('locale:', 'cache', TRUE);
  614. // Rebuild the menu, strings may have changed.
  615. menu_rebuild();
  616. drupal_set_message(t('The translation was successfully imported. There are %number newly created translated strings, %update strings were updated and %delete strings were removed.', array('%number' => $additions, '%update' => $updates, '%delete' => $deletes)));
  617. watchdog('locale', 'Imported %file into %locale: %number new strings added, %update updated and %delete removed.', array('%file' => $file->filename, '%locale' => $langcode, '%number' => $additions, '%update' => $updates, '%delete' => $deletes));
  618. if ($skips) {
  619. $skip_message = format_plural($skips, 'One translation string was skipped because it contains disallowed HTML.', '@count translation strings were skipped because they contain disallowed HTML.');
  620. drupal_set_message($skip_message);
  621. watchdog('locale', '@count disallowed HTML string(s) in %file', array('@count' => $skips, '%file' => $file->uri), WATCHDOG_WARNING);
  622. }
  623. return TRUE;
  624. }
  625. /**
  626. * Parses Gettext Portable Object file into an array
  627. *
  628. * @param $op
  629. * Storage operation type: db-store or mem-store.
  630. * @param $file
  631. * Drupal file object corresponding to the PO file to import.
  632. * @param $mode
  633. * Should existing translations be replaced LOCALE_IMPORT_KEEP or
  634. * LOCALE_IMPORT_OVERWRITE.
  635. * @param $lang
  636. * Language code.
  637. * @param $group
  638. * Text group to import PO file into (eg. 'default' for interface
  639. * translations).
  640. */
  641. function _locale_import_read_po($op, $file, $mode = NULL, $lang = NULL, $group = 'default') {
  642. // The file will get closed by PHP on returning from this function.
  643. $fd = fopen($file->uri, 'rb');
  644. if (!$fd) {
  645. _locale_import_message('The translation import failed, because the file %filename could not be read.', $file);
  646. return FALSE;
  647. }
  648. /*
  649. * The parser context. Can be:
  650. * - 'COMMENT' (#)
  651. * - 'MSGID' (msgid)
  652. * - 'MSGID_PLURAL' (msgid_plural)
  653. * - 'MSGCTXT' (msgctxt)
  654. * - 'MSGSTR' (msgstr or msgstr[])
  655. * - 'MSGSTR_ARR' (msgstr_arg)
  656. */
  657. $context = 'COMMENT';
  658. // Current entry being read.
  659. $current = array();
  660. // Current plurality for 'msgstr[]'.
  661. $plural = 0;
  662. // Current line.
  663. $lineno = 0;
  664. while (!feof($fd)) {
  665. // Refresh the time limit every 10 parsed rows to ensure there is always
  666. // enough time to import the data for large PO files.
  667. if (!($lineno % 10)) {
  668. drupal_set_time_limit(30);
  669. }
  670. // A line should not be longer than 10 * 1024.
  671. $line = fgets($fd, 10 * 1024);
  672. if ($lineno == 0) {
  673. // The first line might come with a UTF-8 BOM, which should be removed.
  674. $line = str_replace("\xEF\xBB\xBF", '', $line);
  675. }
  676. $lineno++;
  677. // Trim away the linefeed.
  678. $line = trim(strtr($line, array("\\\n" => "")));
  679. if (!strncmp('#', $line, 1)) {
  680. // Lines starting with '#' are comments.
  681. if ($context == 'COMMENT') {
  682. // Already in comment token, insert the comment.
  683. $current['#'][] = substr($line, 1);
  684. }
  685. elseif (($context == 'MSGSTR') || ($context == 'MSGSTR_ARR')) {
  686. // We are currently in string token, close it out.
  687. _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
  688. // Start a new entry for the comment.
  689. $current = array();
  690. $current['#'][] = substr($line, 1);
  691. $context = 'COMMENT';
  692. }
  693. else {
  694. // A comment following any other token is a syntax error.
  695. _locale_import_message('The translation file %filename contains an error: "msgstr" was expected but not found on line %line.', $file, $lineno);
  696. return FALSE;
  697. }
  698. }
  699. elseif (!strncmp('msgid_plural', $line, 12)) {
  700. // A plural form for the current message.
  701. if ($context != 'MSGID') {
  702. // A plural form cannot be added to anything else but the id directly.
  703. _locale_import_message('The translation file %filename contains an error: "msgid_plural" was expected but not found on line %line.', $file, $lineno);
  704. return FALSE;
  705. }
  706. // Remove 'msgid_plural' and trim away whitespace.
  707. $line = trim(substr($line, 12));
  708. // At this point, $line should now contain only the plural form.
  709. $quoted = _locale_import_parse_quoted($line);
  710. if ($quoted === FALSE) {
  711. // The plural form must be wrapped in quotes.
  712. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  713. return FALSE;
  714. }
  715. // Append the plural form to the current entry.
  716. $current['msgid'] .= "\0" . $quoted;
  717. $context = 'MSGID_PLURAL';
  718. }
  719. elseif (!strncmp('msgid', $line, 5)) {
  720. // Starting a new message.
  721. if (($context == 'MSGSTR') || ($context == 'MSGSTR_ARR')) {
  722. // We are currently in a message string, close it out.
  723. _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
  724. // Start a new context for the id.
  725. $current = array();
  726. }
  727. elseif ($context == 'MSGID') {
  728. // We are currently already in the context, meaning we passed an id with no data.
  729. _locale_import_message('The translation file %filename contains an error: "msgid" is unexpected on line %line.', $file, $lineno);
  730. return FALSE;
  731. }
  732. // Remove 'msgid' and trim away whitespace.
  733. $line = trim(substr($line, 5));
  734. // At this point, $line should now contain only the message id.
  735. $quoted = _locale_import_parse_quoted($line);
  736. if ($quoted === FALSE) {
  737. // The message id must be wrapped in quotes.
  738. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  739. return FALSE;
  740. }
  741. $current['msgid'] = $quoted;
  742. $context = 'MSGID';
  743. }
  744. elseif (!strncmp('msgctxt', $line, 7)) {
  745. // Starting a new context.
  746. if (($context == 'MSGSTR') || ($context == 'MSGSTR_ARR')) {
  747. // We are currently in a message, start a new one.
  748. _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
  749. $current = array();
  750. }
  751. elseif (!empty($current['msgctxt'])) {
  752. // A context cannot apply to another context.
  753. _locale_import_message('The translation file %filename contains an error: "msgctxt" is unexpected on line %line.', $file, $lineno);
  754. return FALSE;
  755. }
  756. // Remove 'msgctxt' and trim away whitespaces.
  757. $line = trim(substr($line, 7));
  758. // At this point, $line should now contain the context.
  759. $quoted = _locale_import_parse_quoted($line);
  760. if ($quoted === FALSE) {
  761. // The context string must be quoted.
  762. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  763. return FALSE;
  764. }
  765. $current['msgctxt'] = $quoted;
  766. $context = 'MSGCTXT';
  767. }
  768. elseif (!strncmp('msgstr[', $line, 7)) {
  769. // A message string for a specific plurality.
  770. if (($context != 'MSGID') && ($context != 'MSGCTXT') && ($context != 'MSGID_PLURAL') && ($context != 'MSGSTR_ARR')) {
  771. // Message strings must come after msgid, msgxtxt, msgid_plural, or other msgstr[] entries.
  772. _locale_import_message('The translation file %filename contains an error: "msgstr[]" is unexpected on line %line.', $file, $lineno);
  773. return FALSE;
  774. }
  775. // Ensure the plurality is terminated.
  776. if (strpos($line, ']') === FALSE) {
  777. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  778. return FALSE;
  779. }
  780. // Extract the plurality.
  781. $frombracket = strstr($line, '[');
  782. $plural = substr($frombracket, 1, strpos($frombracket, ']') - 1);
  783. // Skip to the next whitespace and trim away any further whitespace, bringing $line to the message data.
  784. $line = trim(strstr($line, " "));
  785. $quoted = _locale_import_parse_quoted($line);
  786. if ($quoted === FALSE) {
  787. // The string must be quoted.
  788. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  789. return FALSE;
  790. }
  791. $current['msgstr'][$plural] = $quoted;
  792. $context = 'MSGSTR_ARR';
  793. }
  794. elseif (!strncmp("msgstr", $line, 6)) {
  795. // A string for the an id or context.
  796. if (($context != 'MSGID') && ($context != 'MSGCTXT')) {
  797. // Strings are only valid within an id or context scope.
  798. _locale_import_message('The translation file %filename contains an error: "msgstr" is unexpected on line %line.', $file, $lineno);
  799. return FALSE;
  800. }
  801. // Remove 'msgstr' and trim away away whitespaces.
  802. $line = trim(substr($line, 6));
  803. // At this point, $line should now contain the message.
  804. $quoted = _locale_import_parse_quoted($line);
  805. if ($quoted === FALSE) {
  806. // The string must be quoted.
  807. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  808. return FALSE;
  809. }
  810. $current['msgstr'] = $quoted;
  811. $context = 'MSGSTR';
  812. }
  813. elseif ($line != '') {
  814. // Anything that is not a token may be a continuation of a previous token.
  815. $quoted = _locale_import_parse_quoted($line);
  816. if ($quoted === FALSE) {
  817. // The string must be quoted.
  818. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  819. return FALSE;
  820. }
  821. // Append the string to the current context.
  822. if (($context == 'MSGID') || ($context == 'MSGID_PLURAL')) {
  823. $current['msgid'] .= $quoted;
  824. }
  825. elseif ($context == 'MSGCTXT') {
  826. $current['msgctxt'] .= $quoted;
  827. }
  828. elseif ($context == 'MSGSTR') {
  829. $current['msgstr'] .= $quoted;
  830. }
  831. elseif ($context == 'MSGSTR_ARR') {
  832. $current['msgstr'][$plural] .= $quoted;
  833. }
  834. else {
  835. // No valid context to append to.
  836. _locale_import_message('The translation file %filename contains an error: there is an unexpected string on line %line.', $file, $lineno);
  837. return FALSE;
  838. }
  839. }
  840. }
  841. // End of PO file, closed out the last entry.
  842. if (($context == 'MSGSTR') || ($context == 'MSGSTR_ARR')) {
  843. _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
  844. }
  845. elseif ($context != 'COMMENT') {
  846. _locale_import_message('The translation file %filename ended unexpectedly at line %line.', $file, $lineno);
  847. return FALSE;
  848. }
  849. }
  850. /**
  851. * Sets an error message occurred during locale file parsing.
  852. *
  853. * @param $message
  854. * The message to be translated.
  855. * @param $file
  856. * Drupal file object corresponding to the PO file to import.
  857. * @param $lineno
  858. * An optional line number argument.
  859. */
  860. function _locale_import_message($message, $file, $lineno = NULL) {
  861. $vars = array('%filename' => $file->filename);
  862. if (isset($lineno)) {
  863. $vars['%line'] = $lineno;
  864. }
  865. $t = get_t();
  866. drupal_set_message($t($message, $vars), 'error');
  867. }
  868. /**
  869. * Imports a string into the database
  870. *
  871. * @param $op
  872. * Operation to perform: 'db-store', 'db-report', 'mem-store' or 'mem-report'.
  873. * @param $value
  874. * Details of the string stored.
  875. * @param $mode
  876. * Should existing translations be replaced LOCALE_IMPORT_KEEP or
  877. * LOCALE_IMPORT_OVERWRITE.
  878. * @param $lang
  879. * Language to store the string in.
  880. * @param $file
  881. * Object representation of file being imported, only required when op is
  882. * 'db-store'.
  883. * @param $group
  884. * Text group to import PO file into (eg. 'default' for interface
  885. * translations).
  886. */
  887. function _locale_import_one_string($op, $value = NULL, $mode = NULL, $lang = NULL, $file = NULL, $group = 'default') {
  888. $report = &drupal_static(__FUNCTION__, array('additions' => 0, 'updates' => 0, 'deletes' => 0, 'skips' => 0));
  889. $header_done = &drupal_static(__FUNCTION__ . ':header_done', FALSE);
  890. $strings = &drupal_static(__FUNCTION__ . ':strings', array());
  891. switch ($op) {
  892. // Return stored strings
  893. case 'mem-report':
  894. return $strings;
  895. // Store string in memory (only supports single strings)
  896. case 'mem-store':
  897. $strings[isset($value['msgctxt']) ? $value['msgctxt'] : ''][$value['msgid']] = $value['msgstr'];
  898. return;
  899. // Called at end of import to inform the user
  900. case 'db-report':
  901. return array($header_done, $report['additions'], $report['updates'], $report['deletes'], $report['skips']);
  902. // Store the string we got in the database.
  903. case 'db-store':
  904. // We got header information.
  905. if ($value['msgid'] == '') {
  906. $languages = language_list();
  907. if (($mode != LOCALE_IMPORT_KEEP) || empty($languages[$lang]->plurals)) {
  908. // Since we only need to parse the header if we ought to update the
  909. // plural formula, only run this if we don't need to keep existing
  910. // data untouched or if we don't have an existing plural formula.
  911. $header = _locale_import_parse_header($value['msgstr']);
  912. // Get and store the plural formula if available.
  913. if (isset($header["Plural-Forms"]) && $p = _locale_import_parse_plural_forms($header["Plural-Forms"], $file->uri)) {
  914. list($nplurals, $plural) = $p;
  915. db_update('languages')
  916. ->fields(array(
  917. 'plurals' => $nplurals,
  918. 'formula' => $plural,
  919. ))
  920. ->condition('language', $lang)
  921. ->execute();
  922. }
  923. }
  924. $header_done = TRUE;
  925. }
  926. else {
  927. // Some real string to import.
  928. $comments = _locale_import_shorten_comments(empty($value['#']) ? array() : $value['#']);
  929. if (strpos($value['msgid'], "\0")) {
  930. // This string has plural versions.
  931. $english = explode("\0", $value['msgid'], 2);
  932. $entries = array_keys($value['msgstr']);
  933. for ($i = 3; $i <= count($entries); $i++) {
  934. $english[] = $english[1];
  935. }
  936. $translation = array_map('_locale_import_append_plural', $value['msgstr'], $entries);
  937. $english = array_map('_locale_import_append_plural', $english, $entries);
  938. foreach ($translation as $key => $trans) {
  939. if ($key == 0) {
  940. $plid = 0;
  941. }
  942. $plid = _locale_import_one_string_db($report, $lang, isset($value['msgctxt']) ? $value['msgctxt'] : '', $english[$key], $trans, $group, $comments, $mode, $plid, $key);
  943. }
  944. }
  945. else {
  946. // A simple string to import.
  947. $english = $value['msgid'];
  948. $translation = $value['msgstr'];
  949. _locale_import_one_string_db($report, $lang, isset($value['msgctxt']) ? $value['msgctxt'] : '', $english, $translation, $group, $comments, $mode);
  950. }
  951. }
  952. } // end of db-store operation
  953. }
  954. /**
  955. * Import one string into the database.
  956. *
  957. * @param $report
  958. * Report array summarizing the number of changes done in the form:
  959. * array(inserts, updates, deletes).
  960. * @param $langcode
  961. * Language code to import string into.
  962. * @param $context
  963. * The context of this string.
  964. * @param $source
  965. * Source string.
  966. * @param $translation
  967. * Translation to language specified in $langcode.
  968. * @param $textgroup
  969. * Name of textgroup to store translation in.
  970. * @param $location
  971. * Location value to save with source string.
  972. * @param $mode
  973. * Import mode to use, LOCALE_IMPORT_KEEP or LOCALE_IMPORT_OVERWRITE.
  974. * @param $plid
  975. * Optional plural ID to use.
  976. * @param $plural
  977. * Optional plural value to use.
  978. *
  979. * @return
  980. * The string ID of the existing string modified or the new string added.
  981. */
  982. function _locale_import_one_string_db(&$report, $langcode, $context, $source, $translation, $textgroup, $location, $mode, $plid = 0, $plural = 0) {
  983. $lid = db_query("SELECT lid FROM {locales_source} WHERE source = :source AND context = :context AND textgroup = :textgroup", array(':source' => $source, ':context' => $context, ':textgroup' => $textgroup))->fetchField();
  984. if (!empty($translation)) {
  985. // Skip this string unless it passes a check for dangerous code.
  986. // Text groups other than default still can contain HTML tags
  987. // (i.e. translatable blocks).
  988. if ($textgroup == "default" && !locale_string_is_safe($translation)) {
  989. $report['skips']++;
  990. $lid = 0;
  991. }
  992. elseif ($lid) {
  993. // We have this source string saved already.
  994. db_update('locales_source')
  995. ->fields(array(
  996. 'location' => $location,
  997. ))
  998. ->condition('lid', $lid)
  999. ->execute();
  1000. $exists = db_query("SELECT COUNT(lid) FROM {locales_target} WHERE lid = :lid AND language = :language", array(':lid' => $lid, ':language' => $langcode))->fetchField();
  1001. if (!$exists) {
  1002. // No translation in this language.
  1003. db_insert('locales_target')
  1004. ->fields(array(
  1005. 'lid' => $lid,
  1006. 'language' => $langcode,
  1007. 'translation' => $translation,
  1008. 'plid' => $plid,
  1009. 'plural' => $plural,
  1010. ))
  1011. ->execute();
  1012. $report['additions']++;
  1013. }
  1014. elseif ($mode == LOCALE_IMPORT_OVERWRITE) {
  1015. // Translation exists, only overwrite if instructed.
  1016. db_update('locales_target')
  1017. ->fields(array(
  1018. 'translation' => $translation,
  1019. 'plid' => $plid,
  1020. 'plural' => $plural,
  1021. ))
  1022. ->condition('language', $langcode)
  1023. ->condition('lid', $lid)
  1024. ->execute();
  1025. $report['updates']++;
  1026. }
  1027. }
  1028. else {
  1029. // No such source string in the database yet.
  1030. $lid = db_insert('locales_source')
  1031. ->fields(array(
  1032. 'location' => $location,
  1033. 'source' => $source,
  1034. 'context' => (string) $context,
  1035. 'textgroup' => $textgroup,
  1036. ))
  1037. ->execute();
  1038. db_insert('locales_target')
  1039. ->fields(array(
  1040. 'lid' => $lid,
  1041. 'language' => $langcode,
  1042. 'translation' => $translation,
  1043. 'plid' => $plid,
  1044. 'plural' => $plural
  1045. ))
  1046. ->execute();
  1047. $report['additions']++;
  1048. }
  1049. }
  1050. elseif ($mode == LOCALE_IMPORT_OVERWRITE) {
  1051. // Empty translation, remove existing if instructed.
  1052. db_delete('locales_target')
  1053. ->condition('language', $langcode)
  1054. ->condition('lid', $lid)
  1055. ->condition('plid', $plid)
  1056. ->condition('plural', $plural)
  1057. ->execute();
  1058. $report['deletes']++;
  1059. }
  1060. return $lid;
  1061. }
  1062. /**
  1063. * Parses a Gettext Portable Object file header
  1064. *
  1065. * @param $header
  1066. * A string containing the complete header.
  1067. *
  1068. * @return
  1069. * An associative array of key-value pairs.
  1070. */
  1071. function _locale_import_parse_header($header) {
  1072. $header_parsed = array();
  1073. $lines = array_map('trim', explode("\n", $header));
  1074. foreach ($lines as $line) {
  1075. if ($line) {
  1076. list($tag, $contents) = explode(":", $line, 2);
  1077. $header_parsed[trim($tag)] = trim($contents);
  1078. }
  1079. }
  1080. return $header_parsed;
  1081. }
  1082. /**
  1083. * Parses a Plural-Forms entry from a Gettext Portable Object file header
  1084. *
  1085. * @param $pluralforms
  1086. * A string containing the Plural-Forms entry.
  1087. * @param $filepath
  1088. * A string containing the filepath.
  1089. *
  1090. * @return
  1091. * An array containing the number of plurals and a
  1092. * formula in PHP for computing the plural form.
  1093. */
  1094. function _locale_import_parse_plural_forms($pluralforms, $filepath) {
  1095. // First, delete all whitespace
  1096. $pluralforms = strtr($pluralforms, array(" " => "", "\t" => ""));
  1097. // Select the parts that define nplurals and plural
  1098. $nplurals = strstr($pluralforms, "nplurals=");
  1099. if (strpos($nplurals, ";")) {
  1100. $nplurals = substr($nplurals, 9, strpos($nplurals, ";") - 9);
  1101. }
  1102. else {
  1103. return FALSE;
  1104. }
  1105. $plural = strstr($pluralforms, "plural=");
  1106. if (strpos($plural, ";")) {
  1107. $plural = substr($plural, 7, strpos($plural, ";") - 7);
  1108. }
  1109. else {
  1110. return FALSE;
  1111. }
  1112. // Get PHP version of the plural formula
  1113. $plural = _locale_import_parse_arithmetic($plural);
  1114. if ($plural !== FALSE) {
  1115. return array($nplurals, $plural);
  1116. }
  1117. else {
  1118. drupal_set_message(t('The translation file %filepath contains an error: the plural formula could not be parsed.', array('%filepath' => $filepath)), 'error');
  1119. return FALSE;
  1120. }
  1121. }
  1122. /**
  1123. * Parses and sanitizes an arithmetic formula into a PHP expression
  1124. *
  1125. * While parsing, we ensure, that the operators have the right
  1126. * precedence and associativity.
  1127. *
  1128. * @param $string
  1129. * A string containing the arithmetic formula.
  1130. *
  1131. * @return
  1132. * The PHP version of the formula.
  1133. */
  1134. function _locale_import_parse_arithmetic($string) {
  1135. // Operator precedence table
  1136. $precedence = array("(" => -1, ")" => -1, "?" => 1, ":" => 1, "||" => 3, "&&" => 4, "==" => 5, "!=" => 5, "<" => 6, ">" => 6, "<=" => 6, ">=" => 6, "+" => 7, "-" => 7, "*" => 8, "/" => 8, "%" => 8);
  1137. // Right associativity
  1138. $right_associativity = array("?" => 1, ":" => 1);
  1139. $tokens = _locale_import_tokenize_formula($string);
  1140. // Parse by converting into infix notation then back into postfix
  1141. // Operator stack - holds math operators and symbols
  1142. $operator_stack = array();
  1143. // Element Stack - holds data to be operated on
  1144. $element_stack = array();
  1145. foreach ($tokens as $token) {
  1146. $current_token = $token;
  1147. // Numbers and the $n variable are simply pushed into $element_stack
  1148. if (is_numeric($token)) {
  1149. $element_stack[] = $current_token;
  1150. }
  1151. elseif ($current_token == "n") {
  1152. $element_stack[] = '$n';
  1153. }
  1154. elseif ($current_token == "(") {
  1155. $operator_stack[] = $current_token;
  1156. }
  1157. elseif ($current_token == ")") {
  1158. $topop = array_pop($operator_stack);
  1159. while (isset($topop) && ($topop != "(")) {
  1160. $element_stack[] = $topop;
  1161. $topop = array_pop($operator_stack);
  1162. }
  1163. }
  1164. elseif (!empty($precedence[$current_token])) {
  1165. // If it's an operator, then pop from $operator_stack into $element_stack until the
  1166. // precedence in $operator_stack is less than current, then push into $operator_stack
  1167. $topop = array_pop($operator_stack);
  1168. while (isset($topop) && ($precedence[$topop] >= $precedence[$current_token]) && !(($precedence[$topop] == $precedence[$current_token]) && !empty($right_associativity[$topop]) && !empty($right_associativity[$current_token]))) {
  1169. $element_stack[] = $topop;
  1170. $topop = array_pop($operator_stack);
  1171. }
  1172. if ($topop) {
  1173. $operator_stack[] = $topop; // Return element to top
  1174. }
  1175. $operator_stack[] = $current_token; // Parentheses are not needed
  1176. }
  1177. else {
  1178. return FALSE;
  1179. }
  1180. }
  1181. // Flush operator stack
  1182. $topop = array_pop($operator_stack);
  1183. while ($topop != NULL) {
  1184. $element_stack[] = $topop;
  1185. $topop = array_pop($operator_stack);
  1186. }
  1187. // Now extract formula from stack
  1188. $previous_size = count($element_stack) + 1;
  1189. while (count($element_stack) < $previous_size) {
  1190. $previous_size = count($element_stack);
  1191. for ($i = 2; $i < count($element_stack); $i++) {
  1192. $op = $element_stack[$i];
  1193. if (!empty($precedence[$op])) {
  1194. $f = "";
  1195. if ($op == ":") {
  1196. $f = $element_stack[$i - 2] . "):" . $element_stack[$i - 1] . ")";
  1197. }
  1198. elseif ($op == "?") {
  1199. $f = "(" . $element_stack[$i - 2] . "?(" . $element_stack[$i - 1];
  1200. }
  1201. else {
  1202. $f = "(" . $element_stack[$i - 2] . $op . $element_stack[$i - 1] . ")";
  1203. }
  1204. array_splice($element_stack, $i - 2, 3, $f);
  1205. break;
  1206. }
  1207. }
  1208. }
  1209. // If only one element is left, the number of operators is appropriate
  1210. if (count($element_stack) == 1) {
  1211. return $element_stack[0];
  1212. }
  1213. else {
  1214. return FALSE;
  1215. }
  1216. }
  1217. /**
  1218. * Backward compatible implementation of token_get_all() for formula parsing
  1219. *
  1220. * @param $string
  1221. * A string containing the arithmetic formula.
  1222. *
  1223. * @return
  1224. * The PHP version of the formula.
  1225. */
  1226. function _locale_import_tokenize_formula($formula) {
  1227. $formula = str_replace(" ", "", $formula);
  1228. $tokens = array();
  1229. for ($i = 0; $i < strlen($formula); $i++) {
  1230. if (is_numeric($formula[$i])) {
  1231. $num = $formula[$i];
  1232. $j = $i + 1;
  1233. while ($j < strlen($formula) && is_numeric($formula[$j])) {
  1234. $num .= $formula[$j];
  1235. $j++;
  1236. }
  1237. $i = $j - 1;
  1238. $tokens[] = $num;
  1239. }
  1240. elseif ($pos = strpos(" =<>!&|", $formula[$i])) { // We won't have a space
  1241. $next = $formula[$i + 1];
  1242. switch ($pos) {
  1243. case 1:
  1244. case 2:
  1245. case 3:
  1246. case 4:
  1247. if ($next == '=') {
  1248. $tokens[] = $formula[$i] . '=';
  1249. $i++;
  1250. }
  1251. else {
  1252. $tokens[] = $formula[$i];
  1253. }
  1254. break;
  1255. case 5:
  1256. if ($next == '&') {
  1257. $tokens[] = '&&';
  1258. $i++;
  1259. }
  1260. else {
  1261. $tokens[] = $formula[$i];
  1262. }
  1263. break;
  1264. case 6:
  1265. if ($next == '|') {
  1266. $tokens[] = '||';
  1267. $i++;
  1268. }
  1269. else {
  1270. $tokens[] = $formula[$i];
  1271. }
  1272. break;
  1273. }
  1274. }
  1275. else {
  1276. $tokens[] = $formula[$i];
  1277. }
  1278. }
  1279. return $tokens;
  1280. }
  1281. /**
  1282. * Modify a string to contain proper count indices
  1283. *
  1284. * This is a callback function used via array_map()
  1285. *
  1286. * @param $entry
  1287. * An array element.
  1288. * @param $key
  1289. * Index of the array element.
  1290. */
  1291. function _locale_import_append_plural($entry, $key) {
  1292. // No modifications for 0, 1
  1293. if ($key == 0 || $key == 1) {
  1294. return $entry;
  1295. }
  1296. // First remove any possibly false indices, then add new ones
  1297. $entry = preg_replace('/(@count)\[[0-9]\]/', '\\1', $entry);
  1298. return preg_replace('/(@count)/', "\\1[$key]", $entry);
  1299. }
  1300. /**
  1301. * Generate a short, one string version of the passed comment array
  1302. *
  1303. * @param $comment
  1304. * An array of strings containing a comment.
  1305. *
  1306. * @return
  1307. * Short one string version of the comment.
  1308. */
  1309. function _locale_import_shorten_comments($comment) {
  1310. $comm = '';
  1311. while (count($comment)) {
  1312. $test = $comm . substr(array_shift($comment), 1) . ', ';
  1313. if (strlen($comm) < 130) {
  1314. $comm = $test;
  1315. }
  1316. else {
  1317. break;
  1318. }
  1319. }
  1320. return trim(substr($comm, 0, -2));
  1321. }
  1322. /**
  1323. * Parses a string in quotes
  1324. *
  1325. * @param $string
  1326. * A string specified with enclosing quotes.
  1327. *
  1328. * @return
  1329. * The string parsed from inside the quotes.
  1330. */
  1331. function _locale_import_parse_quoted($string) {
  1332. if (substr($string, 0, 1) != substr($string, -1, 1)) {
  1333. return FALSE; // Start and end quotes must be the same
  1334. }
  1335. $quote = substr($string, 0, 1);
  1336. $string = substr($string, 1, -1);
  1337. if ($quote == '"') { // Double quotes: strip slashes
  1338. return stripcslashes($string);
  1339. }
  1340. elseif ($quote == "'") { // Simple quote: return as-is
  1341. return $string;
  1342. }
  1343. else {
  1344. return FALSE; // Unrecognized quote
  1345. }
  1346. }
  1347. /**
  1348. * @} End of "locale-api-import-export"
  1349. */
  1350. /**
  1351. * Parses a JavaScript file, extracts strings wrapped in Drupal.t() and
  1352. * Drupal.formatPlural() and inserts them into the database.
  1353. */
  1354. function _locale_parse_js_file($filepath) {
  1355. global $language;
  1356. // The file path might contain a query string, so make sure we only use the
  1357. // actual file.
  1358. $parsed_url = drupal_parse_url($filepath);
  1359. $filepath = $parsed_url['path'];
  1360. // Load the JavaScript file.
  1361. $file = file_get_contents($filepath);
  1362. // Match all calls to Drupal.t() in an array.
  1363. // Note: \s also matches newlines with the 's' modifier.
  1364. preg_match_all('~
  1365. [^\w]Drupal\s*\.\s*t\s* # match "Drupal.t" with whitespace
  1366. \(\s* # match "(" argument list start
  1367. (' . LOCALE_JS_STRING . ')\s* # capture string argument
  1368. (?:,\s*' . LOCALE_JS_OBJECT . '\s* # optionally capture str args
  1369. (?:,\s*' . LOCALE_JS_OBJECT_CONTEXT . '\s*) # optionally capture context
  1370. ?)? # close optional args
  1371. [,\)] # match ")" or "," to finish
  1372. ~sx', $file, $t_matches);
  1373. // Match all Drupal.formatPlural() calls in another array.
  1374. preg_match_all('~
  1375. [^\w]Drupal\s*\.\s*formatPlural\s* # match "Drupal.formatPlural" with whitespace
  1376. \( # match "(" argument list start
  1377. \s*.+?\s*,\s* # match count argument
  1378. (' . LOCALE_JS_STRING . ')\s*,\s* # match singular string argument
  1379. ( # capture plural string argument
  1380. (?: # non-capturing group to repeat string pieces
  1381. (?:
  1382. \' # match start of single-quoted string
  1383. (?:\\\\\'|[^\'])* # match any character except unescaped single-quote
  1384. @count # match "@count"
  1385. (?:\\\\\'|[^\'])* # match any character except unescaped single-quote
  1386. \' # match end of single-quoted string
  1387. |
  1388. " # match start of double-quoted string
  1389. (?:\\\\"|[^"])* # match any character except unescaped double-quote
  1390. @count # match "@count"
  1391. (?:\\\\"|[^"])* # match any character except unescaped double-quote
  1392. " # match end of double-quoted string
  1393. )
  1394. (?:\s*\+\s*)? # match "+" with possible whitespace, for str concat
  1395. )+ # match multiple because we supports concatenating strs
  1396. )\s* # end capturing of plural string argument
  1397. (?:,\s*' . LOCALE_JS_OBJECT . '\s* # optionally capture string args
  1398. (?:,\s*' . LOCALE_JS_OBJECT_CONTEXT . '\s*)? # optionally capture context
  1399. )?
  1400. [,\)]
  1401. ~sx', $file, $plural_matches);
  1402. $matches = array();
  1403. // Add strings from Drupal.t().
  1404. foreach ($t_matches[1] as $key => $string) {
  1405. $matches[] = array(
  1406. 'string' => $string,
  1407. 'context' => $t_matches[2][$key],
  1408. );
  1409. }
  1410. // Add string from Drupal.formatPlural().
  1411. foreach ($plural_matches[1] as $key => $string) {
  1412. $matches[] = array(
  1413. 'string' => $string,
  1414. 'context' => $plural_matches[3][$key],
  1415. );
  1416. // If there is also a plural version of this string, add it to the strings array.
  1417. if (isset($plural_matches[2][$key])) {
  1418. $matches[] = array(
  1419. 'string' => $plural_matches[2][$key],
  1420. 'context' => $plural_matches[3][$key],
  1421. );
  1422. }
  1423. }
  1424. foreach ($matches as $key => $match) {
  1425. // Remove the quotes and string concatenations from the string.
  1426. $string = implode('', preg_split('~(?<!\\\\)[\'"]\s*\+\s*[\'"]~s', substr($match['string'], 1, -1)));
  1427. $context = implode('', preg_split('~(?<!\\\\)[\'"]\s*\+\s*[\'"]~s', substr($match['context'], 1, -1)));
  1428. $source = db_query("SELECT lid, location FROM {locales_source} WHERE source = :source AND context = :context AND textgroup = 'default'", array(':source' => $string, ':context' => $context))->fetchObject();
  1429. if ($source) {
  1430. // We already have this source string and now have to add the location
  1431. // to the location column, if this file is not yet present in there.
  1432. $locations = preg_split('~\s*;\s*~', $source->location);
  1433. if (!in_array($filepath, $locations)) {
  1434. $locations[] = $filepath;
  1435. $locations = implode('; ', $locations);
  1436. // Save the new locations string to the database.
  1437. db_update('locales_source')
  1438. ->fields(array(
  1439. 'location' => $locations,
  1440. ))
  1441. ->condition('lid', $source->lid)
  1442. ->execute();
  1443. }
  1444. }
  1445. else {
  1446. // We don't have the source string yet, thus we insert it into the database.
  1447. db_insert('locales_source')
  1448. ->fields(array(
  1449. 'location' => $filepath,
  1450. 'source' => $string,
  1451. 'context' => $context,
  1452. 'textgroup' => 'default',
  1453. ))
  1454. ->execute();
  1455. }
  1456. }
  1457. }
  1458. /**
  1459. * @addtogroup locale-api-import-export
  1460. * @{
  1461. */
  1462. /**
  1463. * Generates a structured array of all strings with translations in
  1464. * $language, if given. This array can be used to generate an export
  1465. * of the string in the database.
  1466. *
  1467. * @param $language
  1468. * Language object to generate the output for, or NULL if generating
  1469. * translation template.
  1470. * @param $group
  1471. * Text group to export PO file from (eg. 'default' for interface
  1472. * translations).
  1473. */
  1474. function _locale_export_get_strings($language = NULL, $group = 'default') {
  1475. if (isset($language)) {
  1476. $result = db_query("SELECT s.lid, s.source, s.context, s.location, t.translation, t.plid, t.plural FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.textgroup = :textgroup ORDER BY t.plid, t.plural", array(':language' => $language->language, ':textgroup' => $group));
  1477. }
  1478. else {
  1479. $result = db_query("SELECT s.lid, s.source, s.context, s.location, t.plid, t.plural FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid WHERE s.textgroup = :textgroup ORDER BY t.plid, t.plural", array(':textgroup' => $group));
  1480. }
  1481. $strings = array();
  1482. foreach ($result as $child) {
  1483. $string = array(
  1484. 'comment' => $child->location,
  1485. 'source' => $child->source,
  1486. 'context' => $child->context,
  1487. 'translation' => isset($child->translation) ? $child->translation : '',
  1488. );
  1489. if ($child->plid) {
  1490. // Has a parent lid. Since we process in the order of plids,
  1491. // we already have the parent in the array, so we can add the
  1492. // lid to the next plural version to it. This builds a linked
  1493. // list of plurals.
  1494. $string['child'] = TRUE;
  1495. $strings[$child->plid]['plural'] = $child->lid;
  1496. }
  1497. $strings[$child->lid] = $string;
  1498. }
  1499. return $strings;
  1500. }
  1501. /**
  1502. * Generates the PO(T) file contents for given strings.
  1503. *
  1504. * @param $language
  1505. * Language object to generate the output for, or NULL if generating
  1506. * translation template.
  1507. * @param $strings
  1508. * Array of strings to export. See _locale_export_get_strings()
  1509. * on how it should be formatted.
  1510. * @param $header
  1511. * The header portion to use for the output file. Defaults
  1512. * are provided for PO and POT files.
  1513. */
  1514. function _locale_export_po_generate($language = NULL, $strings = array(), $header = NULL) {
  1515. global $user;
  1516. if (!isset($header)) {
  1517. if (isset($language)) {
  1518. $header = '# ' . $language->name . ' translation of ' . variable_get('site_name', 'Drupal') . "\n";
  1519. $header .= '# Generated by ' . $user->name . ' <' . $user->mail . ">\n";
  1520. $header .= "#\n";
  1521. $header .= "msgid \"\"\n";
  1522. $header .= "msgstr \"\"\n";
  1523. $header .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
  1524. $header .= "\"POT-Creation-Date: " . date("Y-m-d H:iO") . "\\n\"\n";
  1525. $header .= "\"PO-Revision-Date: " . date("Y-m-d H:iO") . "\\n\"\n";
  1526. $header .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
  1527. $header .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
  1528. $header .= "\"MIME-Version: 1.0\\n\"\n";
  1529. $header .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
  1530. $header .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
  1531. if ($language->formula && $language->plurals) {
  1532. $header .= "\"Plural-Forms: nplurals=" . $language->plurals . "; plural=" . strtr($language->formula, array('$' => '')) . ";\\n\"\n";
  1533. }
  1534. }
  1535. else {
  1536. $header = "# LANGUAGE translation of PROJECT\n";
  1537. $header .= "# Copyright (c) YEAR NAME <EMAIL@ADDRESS>\n";
  1538. $header .= "#\n";
  1539. $header .= "msgid \"\"\n";
  1540. $header .= "msgstr \"\"\n";
  1541. $header .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
  1542. $header .= "\"POT-Creation-Date: " . date("Y-m-d H:iO") . "\\n\"\n";
  1543. $header .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
  1544. $header .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
  1545. $header .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
  1546. $header .= "\"MIME-Version: 1.0\\n\"\n";
  1547. $header .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
  1548. $header .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
  1549. $header .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n";
  1550. }
  1551. }
  1552. $output = $header . "\n";
  1553. foreach ($strings as $lid => $string) {
  1554. // Only process non-children, children are output below their parent.
  1555. if (!isset($string['child'])) {
  1556. if ($string['comment']) {
  1557. $output .= '#: ' . $string['comment'] . "\n";
  1558. }
  1559. if (!empty($string['context'])) {
  1560. $output .= 'msgctxt ' . _locale_export_string($string['context']);
  1561. }
  1562. $output .= 'msgid ' . _locale_export_string($string['source']);
  1563. if (!empty($string['plural'])) {
  1564. $plural = $string['plural'];
  1565. $output .= 'msgid_plural ' . _locale_export_string($strings[$plural]['source']);
  1566. if (isset($language)) {
  1567. $translation = $string['translation'];
  1568. for ($i = 0; $i < $language->plurals; $i++) {
  1569. $output .= 'msgstr[' . $i . '] ' . _locale_export_string($translation);
  1570. if ($plural) {
  1571. $translation = _locale_export_remove_plural($strings[$plural]['translation']);
  1572. $plural = isset($strings[$plural]['plural']) ? $strings[$plural]['plural'] : 0;
  1573. }
  1574. else {
  1575. $translation = '';
  1576. }
  1577. }
  1578. }
  1579. else {
  1580. $output .= 'msgstr[0] ""' . "\n";
  1581. $output .= 'msgstr[1] ""' . "\n";
  1582. }
  1583. }
  1584. else {
  1585. $output .= 'msgstr ' . _locale_export_string($string['translation']);
  1586. }
  1587. $output .= "\n";
  1588. }
  1589. }
  1590. return $output;
  1591. }
  1592. /**
  1593. * Write a generated PO or POT file to the output.
  1594. *
  1595. * @param $language
  1596. * Language object to generate the output for, or NULL if generating
  1597. * translation template.
  1598. * @param $output
  1599. * The PO(T) file to output as a string. See _locale_export_generate_po()
  1600. * on how it can be generated.
  1601. */
  1602. function _locale_export_po($language = NULL, $output = NULL) {
  1603. // Log the export event.
  1604. if (isset($language)) {
  1605. $filename = $language->language . '.po';
  1606. watchdog('locale', 'Exported %locale translation file: %filename.', array('%locale' => $language->name, '%filename' => $filename));
  1607. }
  1608. else {
  1609. $filename = 'drupal.pot';
  1610. watchdog('locale', 'Exported translation file: %filename.', array('%filename' => $filename));
  1611. }
  1612. // Download the file for the client.
  1613. header("Content-Disposition: attachment; filename=$filename");
  1614. header("Content-Type: text/plain; charset=utf-8");
  1615. print $output;
  1616. drupal_exit();
  1617. }
  1618. /**
  1619. * Print out a string on multiple lines
  1620. */
  1621. function _locale_export_string($str) {
  1622. $stri = addcslashes($str, "\0..\37\\\"");
  1623. $parts = array();
  1624. // Cut text into several lines
  1625. while ($stri != "") {
  1626. $i = strpos($stri, "\\n");
  1627. if ($i === FALSE) {
  1628. $curstr = $stri;
  1629. $stri = "";
  1630. }
  1631. else {
  1632. $curstr = substr($stri, 0, $i + 2);
  1633. $stri = substr($stri, $i + 2);
  1634. }
  1635. $curparts = explode("\n", _locale_export_wrap($curstr, 70));
  1636. $parts = array_merge($parts, $curparts);
  1637. }
  1638. // Multiline string
  1639. if (count($parts) > 1) {
  1640. return "\"\"\n\"" . implode("\"\n\"", $parts) . "\"\n";
  1641. }
  1642. // Single line string
  1643. elseif (count($parts) == 1) {
  1644. return "\"$parts[0]\"\n";
  1645. }
  1646. // No translation
  1647. else {
  1648. return "\"\"\n";
  1649. }
  1650. }
  1651. /**
  1652. * Custom word wrapping for Portable Object (Template) files.
  1653. */
  1654. function _locale_export_wrap($str, $len) {
  1655. $words = explode(' ', $str);
  1656. $return = array();
  1657. $cur = "";
  1658. $nstr = 1;
  1659. while (count($words)) {
  1660. $word = array_shift($words);
  1661. if ($nstr) {
  1662. $cur = $word;
  1663. $nstr = 0;
  1664. }
  1665. elseif (strlen("$cur $word") > $len) {
  1666. $return[] = $cur . " ";
  1667. $cur = $word;
  1668. }
  1669. else {
  1670. $cur = "$cur $word";
  1671. }
  1672. }
  1673. $return[] = $cur;
  1674. return implode("\n", $return);
  1675. }
  1676. /**
  1677. * Removes plural index information from a string
  1678. */
  1679. function _locale_export_remove_plural($entry) {
  1680. return preg_replace('/(@count)\[[0-9]\]/', '\\1', $entry);
  1681. }
  1682. /**
  1683. * @} End of "locale-api-import-export"
  1684. */
  1685. /**
  1686. * @defgroup locale-api-seek Translation search API
  1687. * @{
  1688. * Functions to search in translation files.
  1689. *
  1690. * These functions provide the functionality to search for specific
  1691. * translations.
  1692. */
  1693. /**
  1694. * Perform a string search and display results in a table
  1695. */
  1696. function _locale_translate_seek() {
  1697. $output = '';
  1698. // We have at least one criterion to match
  1699. if (!($query = _locale_translate_seek_query())) {
  1700. $query = array(
  1701. 'translation' => 'all',
  1702. 'group' => 'all',
  1703. 'language' => 'all',
  1704. 'string' => '',
  1705. );
  1706. }
  1707. $sql_query = db_select('locales_source', 's');
  1708. $limit_language = NULL;
  1709. if ($query['language'] != 'en' && $query['language'] != 'all') {
  1710. $sql_query->leftJoin('locales_target', 't', "t.lid = s.lid AND t.language = :langcode", array(':langcode' => $query['language']));
  1711. $limit_language = $query['language'];
  1712. }
  1713. else {
  1714. $sql_query->leftJoin('locales_target', 't', 't.lid = s.lid');
  1715. }
  1716. $sql_query->fields('s', array('source', 'location', 'context', 'lid', 'textgroup'));
  1717. $sql_query->fields('t', array('translation', 'language'));
  1718. // Compute LIKE section.
  1719. switch ($query['translation']) {
  1720. case 'translated':
  1721. $sql_query->condition('t.translation', '%' . db_like($query['string']) . '%', 'LIKE');
  1722. $sql_query->orderBy('t.translation', 'DESC');
  1723. break;
  1724. case 'untranslated':
  1725. $sql_query->condition(db_and()
  1726. ->condition('s.source', '%' . db_like($query['string']) . '%', 'LIKE')
  1727. ->isNull('t.translation')
  1728. );
  1729. $sql_query->orderBy('s.source');
  1730. break;
  1731. case 'all' :
  1732. default:
  1733. $condition = db_or()
  1734. ->condition('s.source', '%' . db_like($query['string']) . '%', 'LIKE');
  1735. if ($query['language'] != 'en') {
  1736. // Only search in translations if the language is not forced to English.
  1737. $condition->condition('t.translation', '%' . db_like($query['string']) . '%', 'LIKE');
  1738. }
  1739. $sql_query->condition($condition);
  1740. break;
  1741. }
  1742. // Add a condition on the text group.
  1743. if (!empty($query['group']) && $query['group'] != 'all') {
  1744. $sql_query->condition('s.textgroup', $query['group']);
  1745. }
  1746. $sql_query = $sql_query->extend('PagerDefault')->limit(50);
  1747. $locales = $sql_query->execute();
  1748. $groups = module_invoke_all('locale', 'groups');
  1749. $header = array(t('Text group'), t('String'), t('Context'), ($limit_language) ? t('Language') : t('Languages'), array('data' => t('Operations'), 'colspan' => '2'));
  1750. $strings = array();
  1751. foreach ($locales as $locale) {
  1752. if (!isset($strings[$locale->lid])) {
  1753. $strings[$locale->lid] = array(
  1754. 'group' => $locale->textgroup,
  1755. 'languages' => array(),
  1756. 'location' => $locale->location,
  1757. 'source' => $locale->source,
  1758. 'context' => $locale->context,
  1759. );
  1760. }
  1761. if (isset($locale->language)) {
  1762. $strings[$locale->lid]['languages'][$locale->language] = $locale->translation;
  1763. }
  1764. }
  1765. $rows = array();
  1766. foreach ($strings as $lid => $string) {
  1767. $rows[] = array(
  1768. $groups[$string['group']],
  1769. array('data' => check_plain(truncate_utf8($string['source'], 150, FALSE, TRUE)) . '<br /><small>' . $string['location'] . '</small>'),
  1770. $string['context'],
  1771. array('data' => _locale_translate_language_list($string, $limit_language), 'align' => 'center'),
  1772. array('data' => l(t('edit'), "admin/config/regional/translate/edit/$lid", array('query' => drupal_get_destination())), 'class' => array('nowrap')),
  1773. array('data' => l(t('delete'), "admin/config/regional/translate/delete/$lid", array('query' => drupal_get_destination())), 'class' => array('nowrap')),
  1774. );
  1775. }
  1776. $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('No strings available.')));
  1777. $output .= theme('pager');
  1778. return $output;
  1779. }
  1780. /**
  1781. * Build array out of search criteria specified in request variables
  1782. */
  1783. function _locale_translate_seek_query() {
  1784. $query = &drupal_static(__FUNCTION__);
  1785. if (!isset($query)) {
  1786. $query = array();
  1787. $fields = array('string', 'language', 'translation', 'group');
  1788. foreach ($fields as $field) {
  1789. if (isset($_SESSION['locale_translation_filter'][$field])) {
  1790. $query[$field] = $_SESSION['locale_translation_filter'][$field];
  1791. }
  1792. }
  1793. }
  1794. return $query;
  1795. }
  1796. /**
  1797. * Force the JavaScript translation file(s) to be refreshed.
  1798. *
  1799. * This function sets a refresh flag for a specified language, or all
  1800. * languages except English, if none specified. JavaScript translation
  1801. * files are rebuilt (with locale_update_js_files()) the next time a
  1802. * request is served in that language.
  1803. *
  1804. * @param $langcode
  1805. * The language code for which the file needs to be refreshed.
  1806. *
  1807. * @return
  1808. * New content of the 'javascript_parsed' variable.
  1809. */
  1810. function _locale_invalidate_js($langcode = NULL) {
  1811. $parsed = variable_get('javascript_parsed', array());
  1812. if (empty($langcode)) {
  1813. // Invalidate all languages.
  1814. $languages = language_list();
  1815. unset($languages['en']);
  1816. foreach ($languages as $lcode => $data) {
  1817. $parsed['refresh:' . $lcode] = 'waiting';
  1818. }
  1819. }
  1820. else {
  1821. // Invalidate single language.
  1822. $parsed['refresh:' . $langcode] = 'waiting';
  1823. }
  1824. variable_set('javascript_parsed', $parsed);
  1825. return $parsed;
  1826. }
  1827. /**
  1828. * (Re-)Creates the JavaScript translation file for a language.
  1829. *
  1830. * @param $language
  1831. * The language, the translation file should be (re)created for.
  1832. */
  1833. function _locale_rebuild_js($langcode = NULL) {
  1834. if (!isset($langcode)) {
  1835. global $language;
  1836. }
  1837. else {
  1838. // Get information about the locale.
  1839. $languages = language_list();
  1840. $language = $languages[$langcode];
  1841. }
  1842. // Construct the array for JavaScript translations.
  1843. // Only add strings with a translation to the translations array.
  1844. $result = db_query("SELECT s.lid, s.source, s.context, t.translation FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.location LIKE '%.js%' AND s.textgroup = :textgroup", array(':language' => $language->language, ':textgroup' => 'default'));
  1845. $translations = array();
  1846. foreach ($result as $data) {
  1847. $translations[$data->context][$data->source] = $data->translation;
  1848. }
  1849. // Construct the JavaScript file, if there are translations.
  1850. $data_hash = NULL;
  1851. $data = $status = '';
  1852. if (!empty($translations)) {
  1853. $data = "Drupal.locale = { ";
  1854. if (!empty($language->formula)) {
  1855. $data .= "'pluralFormula': function (\$n) { return Number({$language->formula}); }, ";
  1856. }
  1857. $data .= "'strings': " . drupal_json_encode($translations) . " };";
  1858. $data_hash = drupal_hash_base64($data);
  1859. }
  1860. // Construct the filepath where JS translation files are stored.
  1861. // There is (on purpose) no front end to edit that variable.
  1862. $dir = 'public://' . variable_get('locale_js_directory', 'languages');
  1863. // Delete old file, if we have no translations anymore, or a different file to be saved.
  1864. $changed_hash = $language->javascript != $data_hash;
  1865. if (!empty($language->javascript) && (!$data || $changed_hash)) {
  1866. file_unmanaged_delete($dir . '/' . $language->language . '_' . $language->javascript . '.js');
  1867. $language->javascript = '';
  1868. $status = 'deleted';
  1869. }
  1870. // Only create a new file if the content has changed or the original file got
  1871. // lost.
  1872. $dest = $dir . '/' . $language->language . '_' . $data_hash . '.js';
  1873. if ($data && ($changed_hash || !file_exists($dest))) {
  1874. // Ensure that the directory exists and is writable, if possible.
  1875. file_prepare_directory($dir, FILE_CREATE_DIRECTORY);
  1876. // Save the file.
  1877. if (file_unmanaged_save_data($data, $dest)) {
  1878. $language->javascript = $data_hash;
  1879. // If we deleted a previous version of the file and we replace it with a
  1880. // new one we have an update.
  1881. if ($status == 'deleted') {
  1882. $status = 'updated';
  1883. }
  1884. // If the file did not exist previously and the data has changed we have
  1885. // a fresh creation.
  1886. elseif ($changed_hash) {
  1887. $status = 'created';
  1888. }
  1889. // If the data hash is unchanged the translation was lost and has to be
  1890. // rebuilt.
  1891. else {
  1892. $status = 'rebuilt';
  1893. }
  1894. }
  1895. else {
  1896. $language->javascript = '';
  1897. $status = 'error';
  1898. }
  1899. }
  1900. // Save the new JavaScript hash (or an empty value if the file just got
  1901. // deleted). Act only if some operation was executed that changed the hash
  1902. // code.
  1903. if ($status && $changed_hash) {
  1904. db_update('languages')
  1905. ->fields(array(
  1906. 'javascript' => $language->javascript,
  1907. ))
  1908. ->condition('language', $language->language)
  1909. ->execute();
  1910. // Update the default language variable if the default language has been altered.
  1911. // This is necessary to keep the variable consistent with the database
  1912. // version of the language and to prevent checking against an outdated hash.
  1913. $default_langcode = language_default('language');
  1914. if ($default_langcode == $language->language) {
  1915. $default = db_query("SELECT * FROM {languages} WHERE language = :language", array(':language' => $default_langcode))->fetchObject();
  1916. variable_set('language_default', $default);
  1917. }
  1918. }
  1919. // Log the operation and return success flag.
  1920. switch ($status) {
  1921. case 'updated':
  1922. watchdog('locale', 'Updated JavaScript translation file for the language %language.', array('%language' => t($language->name)));
  1923. return TRUE;
  1924. case 'rebuilt':
  1925. watchdog('locale', 'JavaScript translation file %file.js was lost.', array('%file' => $language->javascript), WATCHDOG_WARNING);
  1926. // Proceed to the 'created' case as the JavaScript translation file has
  1927. // been created again.
  1928. case 'created':
  1929. watchdog('locale', 'Created JavaScript translation file for the language %language.', array('%language' => t($language->name)));
  1930. return TRUE;
  1931. case 'deleted':
  1932. watchdog('locale', 'Removed JavaScript translation file for the language %language, because no translations currently exist for that language.', array('%language' => t($language->name)));
  1933. return TRUE;
  1934. case 'error':
  1935. watchdog('locale', 'An error occurred during creation of the JavaScript translation file for the language %language.', array('%language' => t($language->name)), WATCHDOG_ERROR);
  1936. return FALSE;
  1937. default:
  1938. // No operation needed.
  1939. return TRUE;
  1940. }
  1941. }
  1942. /**
  1943. * List languages in search result table
  1944. */
  1945. function _locale_translate_language_list($string, $limit_language) {
  1946. // Add CSS.
  1947. drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
  1948. // Include both translated and not yet translated target languages in the
  1949. // list. The source language is English for built-in strings and the default
  1950. // language for other strings.
  1951. $languages = language_list();
  1952. $default = language_default();
  1953. $omit = $string['group'] == 'default' ? 'en' : $default->language;
  1954. unset($languages[$omit]);
  1955. $output = '';
  1956. foreach ($languages as $langcode => $language) {
  1957. if (!$limit_language || $limit_language == $langcode) {
  1958. $output .= (!empty($string['languages'][$langcode])) ? $langcode . ' ' : "<em class=\"locale-untranslated\">$langcode</em> ";
  1959. }
  1960. }
  1961. return $output;
  1962. }
  1963. /**
  1964. * @} End of "locale-api-seek"
  1965. */
  1966. /**
  1967. * @defgroup locale-api-predefined List of predefined languages
  1968. * @{
  1969. * API to provide a list of predefined languages.
  1970. */
  1971. /**
  1972. * Prepares the language code list for a select form item with only the unsupported ones
  1973. */
  1974. function _locale_prepare_predefined_list() {
  1975. include_once DRUPAL_ROOT . '/includes/iso.inc';
  1976. $languages = language_list();
  1977. $predefined = _locale_get_predefined_list();
  1978. foreach ($predefined as $key => $value) {
  1979. if (isset($languages[$key])) {
  1980. unset($predefined[$key]);
  1981. continue;
  1982. }
  1983. // Include native name in output, if possible
  1984. if (count($value) > 1) {
  1985. $tname = t($value[0]);
  1986. $predefined[$key] = ($tname == $value[1]) ? $tname : "$tname ($value[1])";
  1987. }
  1988. else {
  1989. $predefined[$key] = t($value[0]);
  1990. }
  1991. }
  1992. asort($predefined);
  1993. return $predefined;
  1994. }
  1995. /**
  1996. * @} End of "locale-api-languages-predefined"
  1997. */
  1998. /**
  1999. * @defgroup locale-autoimport Automatic interface translation import
  2000. * @{
  2001. * Functions to create batches for importing translations.
  2002. *
  2003. * These functions can be used to import translations for installed
  2004. * modules.
  2005. */
  2006. /**
  2007. * Prepare a batch to import translations for all enabled
  2008. * modules in a given language.
  2009. *
  2010. * @param $langcode
  2011. * Language code to import translations for.
  2012. * @param $finished
  2013. * Optional finished callback for the batch.
  2014. * @param $skip
  2015. * Array of component names to skip. Used in the installer for the
  2016. * second pass import, when most components are already imported.
  2017. *
  2018. * @return
  2019. * A batch structure or FALSE if no files found.
  2020. */
  2021. function locale_batch_by_language($langcode, $finished = NULL, $skip = array()) {
  2022. // Collect all files to import for all enabled modules and themes.
  2023. $files = array();
  2024. $components = array();
  2025. $query = db_select('system', 's');
  2026. $query->fields('s', array('name', 'filename'));
  2027. $query->condition('s.status', 1);
  2028. if (count($skip)) {
  2029. $query->condition('name', $skip, 'NOT IN');
  2030. }
  2031. $result = $query->execute();
  2032. foreach ($result as $component) {
  2033. // Collect all files for all components, names as $langcode.po or
  2034. // with names ending with $langcode.po. This allows for filenames
  2035. // like node-module.de.po to let translators use small files and
  2036. // be able to import in smaller chunks.
  2037. $files = array_merge($files, file_scan_directory(dirname($component->filename) . '/translations', '/(^|\.)' . $langcode . '\.po$/', array('recurse' => FALSE)));
  2038. $components[] = $component->name;
  2039. }
  2040. return _locale_batch_build($files, $finished, $components);
  2041. }
  2042. /**
  2043. * Prepare a batch to run when installing modules or enabling themes.
  2044. *
  2045. * This batch will import translations for the newly added components
  2046. * in all the languages already set up on the site.
  2047. *
  2048. * @param $components
  2049. * An array of component (theme and/or module) names to import
  2050. * translations for.
  2051. * @param $finished
  2052. * Optional finished callback for the batch.
  2053. */
  2054. function locale_batch_by_component($components, $finished = '_locale_batch_system_finished') {
  2055. $files = array();
  2056. $languages = language_list('enabled');
  2057. unset($languages[1]['en']);
  2058. if (count($languages[1])) {
  2059. $language_list = join('|', array_keys($languages[1]));
  2060. // Collect all files to import for all $components.
  2061. $result = db_query("SELECT name, filename FROM {system} WHERE status = 1");
  2062. foreach ($result as $component) {
  2063. if (in_array($component->name, $components)) {
  2064. // Collect all files for this component in all enabled languages, named
  2065. // as $langcode.po or with names ending with $langcode.po. This allows
  2066. // for filenames like node-module.de.po to let translators use small
  2067. // files and be able to import in smaller chunks.
  2068. $files = array_merge($files, file_scan_directory(dirname($component->filename) . '/translations', '/(^|\.)(' . $language_list . ')\.po$/', array('recurse' => FALSE)));
  2069. }
  2070. }
  2071. return _locale_batch_build($files, $finished);
  2072. }
  2073. return FALSE;
  2074. }
  2075. /**
  2076. * Build a locale batch from an array of files.
  2077. *
  2078. * @param $files
  2079. * Array of files to import.
  2080. * @param $finished
  2081. * Optional finished callback for the batch.
  2082. * @param $components
  2083. * Optional list of component names the batch covers. Used in the installer.
  2084. *
  2085. * @return
  2086. * A batch structure.
  2087. */
  2088. function _locale_batch_build($files, $finished = NULL, $components = array()) {
  2089. $t = get_t();
  2090. if (count($files)) {
  2091. $operations = array();
  2092. foreach ($files as $file) {
  2093. // We call _locale_batch_import for every batch operation.
  2094. $operations[] = array('_locale_batch_import', array($file->uri));
  2095. }
  2096. $batch = array(
  2097. 'operations' => $operations,
  2098. 'title' => $t('Importing interface translations'),
  2099. 'init_message' => $t('Starting import'),
  2100. 'error_message' => $t('Error importing interface translations'),
  2101. 'file' => 'includes/locale.inc',
  2102. // This is not a batch API construct, but data passed along to the
  2103. // installer, so we know what did we import already.
  2104. '#components' => $components,
  2105. );
  2106. if (isset($finished)) {
  2107. $batch['finished'] = $finished;
  2108. }
  2109. return $batch;
  2110. }
  2111. return FALSE;
  2112. }
  2113. /**
  2114. * Implements callback_batch_operation().
  2115. *
  2116. * Perform interface translation import as a batch step.
  2117. *
  2118. * @param $filepath
  2119. * Path to a file to import.
  2120. * @param $results
  2121. * Contains a list of files imported.
  2122. */
  2123. function _locale_batch_import($filepath, &$context) {
  2124. // The filename is either {langcode}.po or {prefix}.{langcode}.po, so
  2125. // we can extract the language code to use for the import from the end.
  2126. if (preg_match('!(/|\.)([^\./]+)\.po$!', $filepath, $langcode)) {
  2127. $file = (object) array('filename' => drupal_basename($filepath), 'uri' => $filepath);
  2128. _locale_import_read_po('db-store', $file, LOCALE_IMPORT_KEEP, $langcode[2]);
  2129. $context['results'][] = $filepath;
  2130. }
  2131. }
  2132. /**
  2133. * Implements callback_batch_finished().
  2134. *
  2135. * Finished callback of system page locale import batch.
  2136. * Inform the user of translation files imported.
  2137. */
  2138. function _locale_batch_system_finished($success, $results) {
  2139. if ($success) {
  2140. drupal_set_message(format_plural(count($results), 'One translation file imported for the newly installed modules.', '@count translation files imported for the newly installed modules.'));
  2141. }
  2142. }
  2143. /**
  2144. * Implements callback_batch_finished().
  2145. *
  2146. * Finished callback of language addition locale import batch.
  2147. * Inform the user of translation files imported.
  2148. */
  2149. function _locale_batch_language_finished($success, $results) {
  2150. if ($success) {
  2151. drupal_set_message(format_plural(count($results), 'One translation file imported for the enabled modules.', '@count translation files imported for the enabled modules.'));
  2152. }
  2153. }
  2154. /**
  2155. * @} End of "locale-autoimport"
  2156. */
  2157. /**
  2158. * Get list of all predefined and custom countries.
  2159. *
  2160. * @return
  2161. * An array of all country code => country name pairs.
  2162. */
  2163. function country_get_list() {
  2164. include_once DRUPAL_ROOT . '/includes/iso.inc';
  2165. $countries = _country_get_predefined_list();
  2166. // Allow other modules to modify the country list.
  2167. drupal_alter('countries', $countries);
  2168. return $countries;
  2169. }
  2170. /**
  2171. * Save locale specific date formats to the database.
  2172. *
  2173. * @param $langcode
  2174. * Language code, can be 2 characters, e.g. 'en' or 5 characters, e.g.
  2175. * 'en-CA'.
  2176. * @param $type
  2177. * Date format type, e.g. 'short', 'medium'.
  2178. * @param $format
  2179. * The date format string.
  2180. */
  2181. function locale_date_format_save($langcode, $type, $format) {
  2182. $locale_format = array();
  2183. $locale_format['language'] = $langcode;
  2184. $locale_format['type'] = $type;
  2185. $locale_format['format'] = $format;
  2186. $is_existing = (bool) db_query_range('SELECT 1 FROM {date_format_locale} WHERE language = :langcode AND type = :type', 0, 1, array(':langcode' => $langcode, ':type' => $type))->fetchField();
  2187. if ($is_existing) {
  2188. $keys = array('type', 'language');
  2189. drupal_write_record('date_format_locale', $locale_format, $keys);
  2190. }
  2191. else {
  2192. drupal_write_record('date_format_locale', $locale_format);
  2193. }
  2194. }
  2195. /**
  2196. * Select locale date format details from database.
  2197. *
  2198. * @param $languages
  2199. * An array of language codes.
  2200. *
  2201. * @return
  2202. * An array of date formats.
  2203. */
  2204. function locale_get_localized_date_format($languages) {
  2205. $formats = array();
  2206. // Get list of different format types.
  2207. $format_types = system_get_date_types();
  2208. $short_default = variable_get('date_format_short', 'm/d/Y - H:i');
  2209. // Loop through each language until we find one with some date formats
  2210. // configured.
  2211. foreach ($languages as $language) {
  2212. $date_formats = system_date_format_locale($language);
  2213. if (!empty($date_formats)) {
  2214. // We have locale-specific date formats, so check for their types. If
  2215. // we're missing a type, use the default setting instead.
  2216. foreach ($format_types as $type => $type_info) {
  2217. // If format exists for this language, use it.
  2218. if (!empty($date_formats[$type])) {
  2219. $formats['date_format_' . $type] = $date_formats[$type];
  2220. }
  2221. // Otherwise get default variable setting. If this is not set, default
  2222. // to the short format.
  2223. else {
  2224. $formats['date_format_' . $type] = variable_get('date_format_' . $type, $short_default);
  2225. }
  2226. }
  2227. // Return on the first match.
  2228. return $formats;
  2229. }
  2230. }
  2231. // No locale specific formats found, so use defaults.
  2232. $system_types = array('short', 'medium', 'long');
  2233. // Handle system types separately as they have defaults if no variable exists.
  2234. $formats['date_format_short'] = $short_default;
  2235. $formats['date_format_medium'] = variable_get('date_format_medium', 'D, m/d/Y - H:i');
  2236. $formats['date_format_long'] = variable_get('date_format_long', 'l, F j, Y - H:i');
  2237. // For non-system types, get the default setting, otherwise use the short
  2238. // format.
  2239. foreach ($format_types as $type => $type_info) {
  2240. if (!in_array($type, $system_types)) {
  2241. $formats['date_format_' . $type] = variable_get('date_format_' . $type, $short_default);
  2242. }
  2243. }
  2244. return $formats;
  2245. }