locale.inc 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500
  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 ? 1 : 0,
  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(additions, deletes, skips, updates).
  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*~', (string) $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. // Include custom string overrides.
  1850. $custom_strings = variable_get('locale_custom_strings_' . $language->language, array());
  1851. foreach ($custom_strings as $context => $strings) {
  1852. foreach ($strings as $source => $translation) {
  1853. $translations[$context][$source] = $translation;
  1854. }
  1855. }
  1856. // Construct the JavaScript file, if there are translations.
  1857. $data_hash = NULL;
  1858. $data = $status = '';
  1859. if (!empty($translations)) {
  1860. $data = "Drupal.locale = { ";
  1861. if (!empty($language->formula)) {
  1862. $data .= "'pluralFormula': function (\$n) { return Number({$language->formula}); }, ";
  1863. }
  1864. $data .= "'strings': " . drupal_json_encode($translations) . " };";
  1865. $data_hash = drupal_hash_base64($data);
  1866. }
  1867. // Construct the filepath where JS translation files are stored.
  1868. // There is (on purpose) no front end to edit that variable.
  1869. $dir = 'public://' . variable_get('locale_js_directory', 'languages');
  1870. // Delete old file, if we have no translations anymore, or a different file to be saved.
  1871. $changed_hash = $language->javascript != $data_hash;
  1872. if (!empty($language->javascript) && (!$data || $changed_hash)) {
  1873. file_unmanaged_delete($dir . '/' . $language->language . '_' . $language->javascript . '.js');
  1874. $language->javascript = '';
  1875. $status = 'deleted';
  1876. }
  1877. // Only create a new file if the content has changed or the original file got
  1878. // lost.
  1879. $dest = $dir . '/' . $language->language . '_' . $data_hash . '.js';
  1880. if ($data && ($changed_hash || !file_exists($dest))) {
  1881. // Ensure that the directory exists and is writable, if possible.
  1882. file_prepare_directory($dir, FILE_CREATE_DIRECTORY);
  1883. // Save the file.
  1884. if (file_unmanaged_save_data($data, $dest)) {
  1885. $language->javascript = $data_hash;
  1886. // If we deleted a previous version of the file and we replace it with a
  1887. // new one we have an update.
  1888. if ($status == 'deleted') {
  1889. $status = 'updated';
  1890. }
  1891. // If the file did not exist previously and the data has changed we have
  1892. // a fresh creation.
  1893. elseif ($changed_hash) {
  1894. $status = 'created';
  1895. }
  1896. // If the data hash is unchanged the translation was lost and has to be
  1897. // rebuilt.
  1898. else {
  1899. $status = 'rebuilt';
  1900. }
  1901. }
  1902. else {
  1903. $language->javascript = '';
  1904. $status = 'error';
  1905. }
  1906. }
  1907. // Save the new JavaScript hash (or an empty value if the file just got
  1908. // deleted). Act only if some operation was executed that changed the hash
  1909. // code.
  1910. if ($status && $changed_hash) {
  1911. db_update('languages')
  1912. ->fields(array(
  1913. 'javascript' => $language->javascript,
  1914. ))
  1915. ->condition('language', $language->language)
  1916. ->execute();
  1917. // Update the default language variable if the default language has been altered.
  1918. // This is necessary to keep the variable consistent with the database
  1919. // version of the language and to prevent checking against an outdated hash.
  1920. $default_langcode = language_default('language');
  1921. if ($default_langcode == $language->language) {
  1922. $default = db_query("SELECT * FROM {languages} WHERE language = :language", array(':language' => $default_langcode))->fetchObject();
  1923. variable_set('language_default', $default);
  1924. }
  1925. }
  1926. // Log the operation and return success flag.
  1927. switch ($status) {
  1928. case 'updated':
  1929. watchdog('locale', 'Updated JavaScript translation file for the language %language.', array('%language' => t($language->name)));
  1930. return TRUE;
  1931. case 'rebuilt':
  1932. watchdog('locale', 'JavaScript translation file %file.js was lost.', array('%file' => $language->javascript), WATCHDOG_WARNING);
  1933. // Proceed to the 'created' case as the JavaScript translation file has
  1934. // been created again.
  1935. case 'created':
  1936. watchdog('locale', 'Created JavaScript translation file for the language %language.', array('%language' => t($language->name)));
  1937. return TRUE;
  1938. case 'deleted':
  1939. watchdog('locale', 'Removed JavaScript translation file for the language %language, because no translations currently exist for that language.', array('%language' => t($language->name)));
  1940. return TRUE;
  1941. case 'error':
  1942. watchdog('locale', 'An error occurred during creation of the JavaScript translation file for the language %language.', array('%language' => t($language->name)), WATCHDOG_ERROR);
  1943. return FALSE;
  1944. default:
  1945. // No operation needed.
  1946. return TRUE;
  1947. }
  1948. }
  1949. /**
  1950. * List languages in search result table
  1951. */
  1952. function _locale_translate_language_list($string, $limit_language) {
  1953. // Add CSS.
  1954. drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
  1955. // Include both translated and not yet translated target languages in the
  1956. // list. The source language is English for built-in strings and the default
  1957. // language for other strings.
  1958. $languages = language_list();
  1959. $default = language_default();
  1960. $omit = $string['group'] == 'default' ? 'en' : $default->language;
  1961. unset($languages[$omit]);
  1962. $output = '';
  1963. foreach ($languages as $langcode => $language) {
  1964. if (!$limit_language || $limit_language == $langcode) {
  1965. $output .= (!empty($string['languages'][$langcode])) ? $langcode . ' ' : "<em class=\"locale-untranslated\">$langcode</em> ";
  1966. }
  1967. }
  1968. return $output;
  1969. }
  1970. /**
  1971. * @} End of "locale-api-seek"
  1972. */
  1973. /**
  1974. * @defgroup locale-api-predefined List of predefined languages
  1975. * @{
  1976. * API to provide a list of predefined languages.
  1977. */
  1978. /**
  1979. * Prepares the language code list for a select form item with only the unsupported ones
  1980. */
  1981. function _locale_prepare_predefined_list() {
  1982. include_once DRUPAL_ROOT . '/includes/iso.inc';
  1983. $languages = language_list();
  1984. $predefined = _locale_get_predefined_list();
  1985. foreach ($predefined as $key => $value) {
  1986. if (isset($languages[$key])) {
  1987. unset($predefined[$key]);
  1988. continue;
  1989. }
  1990. // Include native name in output, if possible
  1991. if (count($value) > 1) {
  1992. $tname = t($value[0]);
  1993. $predefined[$key] = ($tname == $value[1]) ? $tname : "$tname ($value[1])";
  1994. }
  1995. else {
  1996. $predefined[$key] = t($value[0]);
  1997. }
  1998. }
  1999. asort($predefined);
  2000. return $predefined;
  2001. }
  2002. /**
  2003. * @} End of "locale-api-languages-predefined"
  2004. */
  2005. /**
  2006. * @defgroup locale-autoimport Automatic interface translation import
  2007. * @{
  2008. * Functions to create batches for importing translations.
  2009. *
  2010. * These functions can be used to import translations for installed
  2011. * modules.
  2012. */
  2013. /**
  2014. * Prepare a batch to import translations for all enabled
  2015. * modules in a given language.
  2016. *
  2017. * @param $langcode
  2018. * Language code to import translations for.
  2019. * @param $finished
  2020. * Optional finished callback for the batch.
  2021. * @param $skip
  2022. * Array of component names to skip. Used in the installer for the
  2023. * second pass import, when most components are already imported.
  2024. *
  2025. * @return
  2026. * A batch structure or FALSE if no files found.
  2027. */
  2028. function locale_batch_by_language($langcode, $finished = NULL, $skip = array()) {
  2029. // Collect all files to import for all enabled modules and themes.
  2030. $files = array();
  2031. $components = array();
  2032. $query = db_select('system', 's');
  2033. $query->fields('s', array('name', 'filename'));
  2034. $query->condition('s.status', 1);
  2035. if (count($skip)) {
  2036. $query->condition('name', $skip, 'NOT IN');
  2037. }
  2038. $result = $query->execute();
  2039. foreach ($result as $component) {
  2040. // Collect all files for all components, names as $langcode.po or
  2041. // with names ending with $langcode.po. This allows for filenames
  2042. // like node-module.de.po to let translators use small files and
  2043. // be able to import in smaller chunks.
  2044. $files = array_merge($files, file_scan_directory(dirname($component->filename) . '/translations', '/(^|\.)' . $langcode . '\.po$/', array('recurse' => FALSE)));
  2045. $components[] = $component->name;
  2046. }
  2047. return _locale_batch_build($files, $finished, $components);
  2048. }
  2049. /**
  2050. * Prepare a batch to run when installing modules or enabling themes.
  2051. *
  2052. * This batch will import translations for the newly added components
  2053. * in all the languages already set up on the site.
  2054. *
  2055. * @param $components
  2056. * An array of component (theme and/or module) names to import
  2057. * translations for.
  2058. * @param $finished
  2059. * Optional finished callback for the batch.
  2060. */
  2061. function locale_batch_by_component($components, $finished = '_locale_batch_system_finished') {
  2062. $files = array();
  2063. $languages = language_list('enabled');
  2064. unset($languages[1]['en']);
  2065. if (count($languages[1])) {
  2066. $language_list = join('|', array_keys($languages[1]));
  2067. // Collect all files to import for all $components.
  2068. $result = db_query("SELECT name, filename FROM {system} WHERE status = 1");
  2069. foreach ($result as $component) {
  2070. if (in_array($component->name, $components)) {
  2071. // Collect all files for this component in all enabled languages, named
  2072. // as $langcode.po or with names ending with $langcode.po. This allows
  2073. // for filenames like node-module.de.po to let translators use small
  2074. // files and be able to import in smaller chunks.
  2075. $files = array_merge($files, file_scan_directory(dirname($component->filename) . '/translations', '/(^|\.)(' . $language_list . ')\.po$/', array('recurse' => FALSE)));
  2076. }
  2077. }
  2078. return _locale_batch_build($files, $finished);
  2079. }
  2080. return FALSE;
  2081. }
  2082. /**
  2083. * Build a locale batch from an array of files.
  2084. *
  2085. * @param $files
  2086. * Array of files to import.
  2087. * @param $finished
  2088. * Optional finished callback for the batch.
  2089. * @param $components
  2090. * Optional list of component names the batch covers. Used in the installer.
  2091. *
  2092. * @return
  2093. * A batch structure.
  2094. */
  2095. function _locale_batch_build($files, $finished = NULL, $components = array()) {
  2096. $t = get_t();
  2097. if (count($files)) {
  2098. $operations = array();
  2099. foreach ($files as $file) {
  2100. // We call _locale_batch_import for every batch operation.
  2101. $operations[] = array('_locale_batch_import', array($file->uri));
  2102. }
  2103. $batch = array(
  2104. 'operations' => $operations,
  2105. 'title' => $t('Importing interface translations'),
  2106. 'init_message' => $t('Starting import'),
  2107. 'error_message' => $t('Error importing interface translations'),
  2108. 'file' => 'includes/locale.inc',
  2109. // This is not a batch API construct, but data passed along to the
  2110. // installer, so we know what did we import already.
  2111. '#components' => $components,
  2112. );
  2113. if (isset($finished)) {
  2114. $batch['finished'] = $finished;
  2115. }
  2116. return $batch;
  2117. }
  2118. return FALSE;
  2119. }
  2120. /**
  2121. * Implements callback_batch_operation().
  2122. *
  2123. * Perform interface translation import as a batch step.
  2124. *
  2125. * @param $filepath
  2126. * Path to a file to import.
  2127. * @param $results
  2128. * Contains a list of files imported.
  2129. */
  2130. function _locale_batch_import($filepath, &$context) {
  2131. // The filename is either {langcode}.po or {prefix}.{langcode}.po, so
  2132. // we can extract the language code to use for the import from the end.
  2133. if (preg_match('!(/|\.)([^\./]+)\.po$!', $filepath, $langcode)) {
  2134. $file = (object) array('filename' => drupal_basename($filepath), 'uri' => $filepath);
  2135. _locale_import_read_po('db-store', $file, LOCALE_IMPORT_KEEP, $langcode[2]);
  2136. $context['results'][] = $filepath;
  2137. }
  2138. }
  2139. /**
  2140. * Implements callback_batch_finished().
  2141. *
  2142. * Finished callback of system page locale import batch.
  2143. * Inform the user of translation files imported.
  2144. */
  2145. function _locale_batch_system_finished($success, $results) {
  2146. if ($success) {
  2147. 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.'));
  2148. }
  2149. }
  2150. /**
  2151. * Implements callback_batch_finished().
  2152. *
  2153. * Finished callback of language addition locale import batch.
  2154. * Inform the user of translation files imported.
  2155. */
  2156. function _locale_batch_language_finished($success, $results) {
  2157. if ($success) {
  2158. drupal_set_message(format_plural(count($results), 'One translation file imported for the enabled modules.', '@count translation files imported for the enabled modules.'));
  2159. }
  2160. }
  2161. /**
  2162. * @} End of "locale-autoimport"
  2163. */
  2164. /**
  2165. * Get list of all predefined and custom countries.
  2166. *
  2167. * @return
  2168. * An array of all country code => country name pairs.
  2169. */
  2170. function country_get_list() {
  2171. include_once DRUPAL_ROOT . '/includes/iso.inc';
  2172. $countries = _country_get_predefined_list();
  2173. // Allow other modules to modify the country list.
  2174. drupal_alter('countries', $countries);
  2175. return $countries;
  2176. }
  2177. /**
  2178. * Save locale specific date formats to the database.
  2179. *
  2180. * @param $langcode
  2181. * Language code, can be 2 characters, e.g. 'en' or 5 characters, e.g.
  2182. * 'en-CA'.
  2183. * @param $type
  2184. * Date format type, e.g. 'short', 'medium'.
  2185. * @param $format
  2186. * The date format string.
  2187. */
  2188. function locale_date_format_save($langcode, $type, $format) {
  2189. $locale_format = array();
  2190. $locale_format['language'] = $langcode;
  2191. $locale_format['type'] = $type;
  2192. $locale_format['format'] = $format;
  2193. $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();
  2194. if ($is_existing) {
  2195. $keys = array('type', 'language');
  2196. drupal_write_record('date_format_locale', $locale_format, $keys);
  2197. }
  2198. else {
  2199. drupal_write_record('date_format_locale', $locale_format);
  2200. }
  2201. }
  2202. /**
  2203. * Select locale date format details from database.
  2204. *
  2205. * @param $languages
  2206. * An array of language codes.
  2207. *
  2208. * @return
  2209. * An array of date formats.
  2210. */
  2211. function locale_get_localized_date_format($languages) {
  2212. $formats = array();
  2213. // Get list of different format types.
  2214. $format_types = system_get_date_types();
  2215. $short_default = variable_get('date_format_short', 'm/d/Y - H:i');
  2216. // Loop through each language until we find one with some date formats
  2217. // configured.
  2218. foreach ($languages as $language) {
  2219. $date_formats = system_date_format_locale($language);
  2220. if (!empty($date_formats)) {
  2221. // We have locale-specific date formats, so check for their types. If
  2222. // we're missing a type, use the default setting instead.
  2223. foreach ($format_types as $type => $type_info) {
  2224. // If format exists for this language, use it.
  2225. if (!empty($date_formats[$type])) {
  2226. $formats['date_format_' . $type] = $date_formats[$type];
  2227. }
  2228. // Otherwise get default variable setting. If this is not set, default
  2229. // to the short format.
  2230. else {
  2231. $formats['date_format_' . $type] = variable_get('date_format_' . $type, $short_default);
  2232. }
  2233. }
  2234. // Return on the first match.
  2235. return $formats;
  2236. }
  2237. }
  2238. // No locale specific formats found, so use defaults.
  2239. $system_types = array('short', 'medium', 'long');
  2240. // Handle system types separately as they have defaults if no variable exists.
  2241. $formats['date_format_short'] = $short_default;
  2242. $formats['date_format_medium'] = variable_get('date_format_medium', 'D, m/d/Y - H:i');
  2243. $formats['date_format_long'] = variable_get('date_format_long', 'l, F j, Y - H:i');
  2244. // For non-system types, get the default setting, otherwise use the short
  2245. // format.
  2246. foreach ($format_types as $type => $type_info) {
  2247. if (!in_array($type, $system_types)) {
  2248. $formats['date_format_' . $type] = variable_get('date_format_' . $type, $short_default);
  2249. }
  2250. }
  2251. return $formats;
  2252. }