locale.inc

  1. cis7 includes/locale.inc
  2. cle7 includes/locale.inc
  3. ecd7 includes/locale.inc
  4. elmsmedia7 includes/locale.inc
  5. harmony7 includes/locale.inc
  6. icor7 includes/locale.inc
  7. meedjum_blog7 includes/locale.inc
  8. mooc7 includes/locale.inc

Administration functions for locale.module.

Functions

Namesort descending Description
country_get_list Get list of all predefined and custom countries.
locale_add_language API function to add a language.
locale_batch_by_component Prepare a batch to run when installing modules or enabling themes.
locale_batch_by_language Prepare a batch to import translations for all enabled modules in a given language.
locale_date_format_save Save locale specific date formats to the database.
locale_get_localized_date_format Select locale date format details from database.
locale_language_from_browser Identify language from the Accept-language HTTP header we got.
locale_language_from_interface Identifies the language from the current interface language.
locale_language_from_session Identify language from a request/session parameter.
locale_language_from_url Identify language via URL prefix or domain.
locale_language_from_user Identify language from the user preferences.
locale_language_switcher_session Return the session language switcher block.
locale_language_switcher_url Return the URL language switcher block. Translation links may be provided by other modules.
locale_language_url_fallback Determines the language to be assigned to URLs when none is detected.
locale_language_url_rewrite_session Rewrite URLs for the Session language provider.
locale_language_url_rewrite_url Rewrite URLs for the URL language provider.
locale_string_is_safe Check that a string is safe to be added or imported as a translation.
_locale_batch_build Build a locale batch from an array of files.
_locale_batch_import Perform interface translation import as a batch step.
_locale_batch_language_finished Finished callback of language addition locale import batch. Inform the user of translation files imported.
_locale_batch_system_finished Finished callback of system page locale import batch. Inform the user of translation files imported.
_locale_export_get_strings Generates a structured array of all strings with translations in $language, if given. This array can be used to generate an export of the string in the database.
_locale_export_po Write a generated PO or POT file to the output.
_locale_export_po_generate Generates the PO(T) file contents for given strings.
_locale_export_remove_plural Removes plural index information from a string
_locale_export_string Print out a string on multiple lines
_locale_export_wrap Custom word wrapping for Portable Object (Template) files.
_locale_import_append_plural Modify a string to contain proper count indices
_locale_import_message Sets an error message occurred during locale file parsing.
_locale_import_one_string Imports a string into the database
_locale_import_one_string_db Import one string into the database.
_locale_import_parse_arithmetic Parses and sanitizes an arithmetic formula into a PHP expression
_locale_import_parse_header Parses a Gettext Portable Object file header
_locale_import_parse_plural_forms Parses a Plural-Forms entry from a Gettext Portable Object file header
_locale_import_parse_quoted Parses a string in quotes
_locale_import_po Parses Gettext Portable Object file information and inserts into database
_locale_import_read_po Parses Gettext Portable Object file into an array
_locale_import_shorten_comments Generate a short, one string version of the passed comment array
_locale_import_tokenize_formula Backward compatible implementation of token_get_all() for formula parsing
_locale_invalidate_js Force the JavaScript translation file(s) to be refreshed.
_locale_parse_js_file Parses a JavaScript file, extracts strings wrapped in Drupal.t() and Drupal.formatPlural() and inserts them into the database.
_locale_prepare_predefined_list Prepares the language code list for a select form item with only the unsupported ones
_locale_rebuild_js (Re-)Creates the JavaScript translation file for a language.
_locale_translate_language_list List languages in search result table
_locale_translate_seek Perform a string search and display results in a table
_locale_translate_seek_query Build array out of search criteria specified in request variables

Constants

Namesort descending Description
LOCALE_IMPORT_KEEP Translation import mode keeping existing translations and only inserting new strings.
LOCALE_IMPORT_OVERWRITE Translation import mode overwriting all existing translations if new translated version available.
LOCALE_JS_OBJECT Regular expression pattern used to match simple JS object literal.
LOCALE_JS_OBJECT_CONTEXT Regular expression to match an object containing a key 'context'.
LOCALE_JS_STRING Regular expression pattern used to localize JavaScript strings.
LOCALE_LANGUAGE_NEGOTIATION_BROWSER The language is set based on the browser language settings.
LOCALE_LANGUAGE_NEGOTIATION_INTERFACE The language is determined using the current interface language.
LOCALE_LANGUAGE_NEGOTIATION_SESSION The language is set based on the request/session parameters.
LOCALE_LANGUAGE_NEGOTIATION_URL The language is determined using a URL language indicator: path prefix or domain according to the configuration.
LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN URL language negotiation: use the domain as URL language indicator.
LOCALE_LANGUAGE_NEGOTIATION_URL_FALLBACK If no URL language is available language is determined using an already detected one.
LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX URL language negotiation: use the path prefix as URL language indicator.
LOCALE_LANGUAGE_NEGOTIATION_USER The language is set based on the user language settings.

File

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