PageRenderTime 35ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/drupal-7.14/includes/locale.inc

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