PageRenderTime 49ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/drupal-7.14/includes/locale.inc

#
Pascal | 2433 lines | 1102 code | 165 blank | 1166 comment | 154 complexity | cc06586633d9fad11969703a09c80f2f MD5 | raw file
Possible License(s): GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * @file
  4. * Administration functions for locale.module.
  5. */
  6. /**
  7. * The language is determined using a URL language indicator:
  8. * path prefix or domain according to the configuration.
  9. */
  10. define('LOCALE_LANGUAGE_NEGOTIATION_URL', 'locale-url');
  11. /**
  12. * The language is set based on the browser language settings.
  13. */
  14. define('LOCALE_LANGUAGE_NEGOTIATION_BROWSER', 'locale-browser');
  15. /**
  16. * The language is determined using the current interface language.
  17. */
  18. define('LOCALE_LANGUAGE_NEGOTIATION_INTERFACE', 'locale-interface');
  19. /**
  20. * If no URL language is available language is determined using an already
  21. * detected one.
  22. */
  23. define('LOCALE_LANGUAGE_NEGOTIATION_URL_FALLBACK', 'locale-url-fallback');
  24. /**
  25. * The language is set based on the user language settings.
  26. */
  27. define('LOCALE_LANGUAGE_NEGOTIATION_USER', 'locale-user');
  28. /**
  29. * The language is set based on the request/session parameters.
  30. */
  31. define('LOCALE_LANGUAGE_NEGOTIATION_SESSION', 'locale-session');
  32. /**
  33. * Regular expression pattern used to localize JavaScript strings.
  34. */
  35. define('LOCALE_JS_STRING', '(?:(?:\'(?:\\\\\'|[^\'])*\'|"(?:\\\\"|[^"])*")(?:\s*\+\s*)?)+');
  36. /**
  37. * Regular expression pattern used to match simple JS object literal.
  38. *
  39. * This pattern matches a basic JS object, but will fail on an object with
  40. * nested objects. Used in JS file parsing for string arg processing.
  41. */
  42. define('LOCALE_JS_OBJECT', '\{.*?\}');
  43. /**
  44. * Regular expression to match an object containing a key 'context'.
  45. *
  46. * Pattern to match a JS object containing a 'context key' with a string value,
  47. * which is captured. Will fail if there are nested objects.
  48. */
  49. define('LOCALE_JS_OBJECT_CONTEXT', '
  50. \{ # match object literal start
  51. .*? # match anything, non-greedy
  52. (?: # match a form of "context"
  53. \'context\'
  54. |
  55. "context"
  56. |
  57. context
  58. )
  59. \s*:\s* # match key-value separator ":"
  60. (' . LOCALE_JS_STRING . ') # match context string
  61. .*? # match anything, non-greedy
  62. \} # match end of object literal
  63. ');
  64. /**
  65. * Translation import mode overwriting all existing translations
  66. * if new translated version available.
  67. */
  68. define('LOCALE_IMPORT_OVERWRITE', 0);
  69. /**
  70. * Translation import mode keeping existing translations and only
  71. * inserting new strings.
  72. */
  73. define('LOCALE_IMPORT_KEEP', 1);
  74. /**
  75. * URL language negotiation: use the path prefix as URL language
  76. * indicator.
  77. */
  78. define('LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX', 0);
  79. /**
  80. * URL language negotiation: use the domain as URL language
  81. * indicator.
  82. */
  83. define('LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN', 1);
  84. /**
  85. * @defgroup locale-languages-negotiation Language negotiation options
  86. * @{
  87. * Functions for language negotiation.
  88. *
  89. * There are functions that provide the ability to identify the
  90. * language. This behavior can be controlled by various options.
  91. */
  92. /**
  93. * Identifies the language from the current interface language.
  94. *
  95. * @return
  96. * The current interface language code.
  97. */
  98. function locale_language_from_interface() {
  99. global $language;
  100. return isset($language->language) ? $language->language : FALSE;
  101. }
  102. /**
  103. * Identify language from the Accept-language HTTP header we got.
  104. *
  105. * We perform browser accept-language parsing only if page cache is disabled,
  106. * otherwise we would cache a user-specific preference.
  107. *
  108. * @param $languages
  109. * An array of language objects for enabled languages ordered by weight.
  110. *
  111. * @return
  112. * A valid language code on success, FALSE otherwise.
  113. */
  114. function locale_language_from_browser($languages) {
  115. if (empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  116. return FALSE;
  117. }
  118. // The Accept-Language header contains information about the language
  119. // preferences configured in the user's browser / operating system.
  120. // RFC 2616 (section 14.4) defines the Accept-Language header as follows:
  121. // Accept-Language = "Accept-Language" ":"
  122. // 1#( language-range [ ";" "q" "=" qvalue ] )
  123. // language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )
  124. // Samples: "hu, en-us;q=0.66, en;q=0.33", "hu,en-us;q=0.5"
  125. $browser_langcodes = array();
  126. if (preg_match_all('@(?<=[, ]|^)([a-zA-Z-]+|\*)(?:;q=([0-9.]+))?(?:$|\s*,\s*)@', trim($_SERVER['HTTP_ACCEPT_LANGUAGE']), $matches, PREG_SET_ORDER)) {
  127. foreach ($matches as $match) {
  128. // We can safely use strtolower() here, tags are ASCII.
  129. // RFC2616 mandates that the decimal part is no more than three digits,
  130. // so we multiply the qvalue by 1000 to avoid floating point comparisons.
  131. $langcode = strtolower($match[1]);
  132. $qvalue = isset($match[2]) ? (float) $match[2] : 1;
  133. $browser_langcodes[$langcode] = (int) ($qvalue * 1000);
  134. }
  135. }
  136. // We should take pristine values from the HTTP headers, but Internet Explorer
  137. // from version 7 sends only specific language tags (eg. fr-CA) without the
  138. // corresponding generic tag (fr) unless explicitly configured. In that case,
  139. // we assume that the lowest value of the specific tags is the value of the
  140. // generic language to be as close to the HTTP 1.1 spec as possible.
  141. // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 and
  142. // http://blogs.msdn.com/b/ie/archive/2006/10/17/accept-language-header-for-internet-explorer-7.aspx
  143. asort($browser_langcodes);
  144. foreach ($browser_langcodes as $langcode => $qvalue) {
  145. $generic_tag = strtok($langcode, '-');
  146. if (!isset($browser_langcodes[$generic_tag])) {
  147. $browser_langcodes[$generic_tag] = $qvalue;
  148. }
  149. }
  150. // Find the enabled language with the greatest qvalue, following the rules
  151. // of RFC 2616 (section 14.4). If several languages have the same qvalue,
  152. // prefer the one with the greatest weight.
  153. $best_match_langcode = FALSE;
  154. $max_qvalue = 0;
  155. foreach ($languages as $langcode => $language) {
  156. // Language tags are case insensitive (RFC2616, sec 3.10).
  157. $langcode = strtolower($langcode);
  158. // If nothing matches below, the default qvalue is the one of the wildcard
  159. // language, if set, or is 0 (which will never match).
  160. $qvalue = isset($browser_langcodes['*']) ? $browser_langcodes['*'] : 0;
  161. // Find the longest possible prefix of the browser-supplied language
  162. // ('the language-range') that matches this site language ('the language tag').
  163. $prefix = $langcode;
  164. do {
  165. if (isset($browser_langcodes[$prefix])) {
  166. $qvalue = $browser_langcodes[$prefix];
  167. break;
  168. }
  169. }
  170. while ($prefix = substr($prefix, 0, strrpos($prefix, '-')));
  171. // Find the best match.
  172. if ($qvalue > $max_qvalue) {
  173. $best_match_langcode = $language->language;
  174. $max_qvalue = $qvalue;
  175. }
  176. }
  177. return $best_match_langcode;
  178. }
  179. /**
  180. * Identify language from the user preferences.
  181. *
  182. * @param $languages
  183. * An array of valid language objects.
  184. *
  185. * @return
  186. * A valid language code on success, FALSE otherwise.
  187. */
  188. function locale_language_from_user($languages) {
  189. // User preference (only for logged users).
  190. global $user;
  191. if ($user->uid) {
  192. return $user->language;
  193. }
  194. // No language preference from the user.
  195. return FALSE;
  196. }
  197. /**
  198. * Identify language from a request/session parameter.
  199. *
  200. * @param $languages
  201. * An array of valid language objects.
  202. *
  203. * @return
  204. * A valid language code on success, FALSE otherwise.
  205. */
  206. function locale_language_from_session($languages) {
  207. $param = variable_get('locale_language_negotiation_session_param', 'language');
  208. // Request parameter: we need to update the session parameter only if we have
  209. // an authenticated user.
  210. if (isset($_GET[$param]) && isset($languages[$langcode = $_GET[$param]])) {
  211. global $user;
  212. if ($user->uid) {
  213. $_SESSION[$param] = $langcode;
  214. }
  215. return $langcode;
  216. }
  217. // Session parameter.
  218. if (isset($_SESSION[$param])) {
  219. return $_SESSION[$param];
  220. }
  221. return FALSE;
  222. }
  223. /**
  224. * Identify language via URL prefix or domain.
  225. *
  226. * @param $languages
  227. * An array of valid language objects.
  228. *
  229. * @return
  230. * A valid language code on success, FALSE otherwise.
  231. */
  232. function locale_language_from_url($languages) {
  233. $language_url = FALSE;
  234. if (!language_negotiation_get_any(LOCALE_LANGUAGE_NEGOTIATION_URL)) {
  235. return $language_url;
  236. }
  237. switch (variable_get('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX)) {
  238. case LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX:
  239. // $_GET['q'] might not be available at this time, because
  240. // path initialization runs after the language bootstrap phase.
  241. list($language, $_GET['q']) = language_url_split_prefix(isset($_GET['q']) ? $_GET['q'] : NULL, $languages);
  242. if ($language !== FALSE) {
  243. $language_url = $language->language;
  244. }
  245. break;
  246. case LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN:
  247. foreach ($languages as $language) {
  248. // Skip check if the language doesn't have a domain.
  249. if ($language->domain) {
  250. // Only compare the domains not the protocols or ports.
  251. // Remove protocol and add http:// so parse_url works
  252. $host = 'http://' . str_replace(array('http://', 'https://'), '', $language->domain);
  253. $host = parse_url($host, PHP_URL_HOST);
  254. if ($_SERVER['HTTP_HOST'] == $host) {
  255. $language_url = $language->language;
  256. break;
  257. }
  258. }
  259. }
  260. break;
  261. }
  262. return $language_url;
  263. }
  264. /**
  265. * Determines the language to be assigned to URLs when none is detected.
  266. *
  267. * The language negotiation process has a fallback chain that ends with the
  268. * default language provider. Each built-in language type has a separate
  269. * initialization:
  270. * - Interface language, which is the only configurable one, always gets a valid
  271. * value. If no request-specific language is detected, the default language
  272. * will be used.
  273. * - Content language merely inherits the interface language by default.
  274. * - URL language is detected from the requested URL and will be used to rewrite
  275. * URLs appearing in the page being rendered. If no language can be detected,
  276. * there are two possibilities:
  277. * - If the default language has no configured path prefix or domain, then the
  278. * default language is used. This guarantees that (missing) URL prefixes are
  279. * preserved when navigating through the site.
  280. * - If the default language has a configured path prefix or domain, a
  281. * requested URL having an empty prefix or domain is an anomaly that must be
  282. * fixed. This is done by introducing a prefix or domain in the rendered
  283. * page matching the detected interface language.
  284. *
  285. * @param $languages
  286. * (optional) An array of valid language objects. This is passed by
  287. * language_provider_invoke() to every language provider callback, but it is
  288. * not actually needed here. Defaults to NULL.
  289. * @param $language_type
  290. * (optional) The language type to fall back to. Defaults to the interface
  291. * language.
  292. *
  293. * @return
  294. * A valid language code.
  295. */
  296. function locale_language_url_fallback($language = NULL, $language_type = LANGUAGE_TYPE_INTERFACE) {
  297. $default = language_default();
  298. $prefix = (variable_get('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX);
  299. // If the default language is not configured to convey language information,
  300. // a missing URL language information indicates that URL language should be
  301. // the default one, otherwise we fall back to an already detected language.
  302. if (($prefix && empty($default->prefix)) || (!$prefix && empty($default->domain))) {
  303. return $default->language;
  304. }
  305. else {
  306. return $GLOBALS[$language_type]->language;
  307. }
  308. }
  309. /**
  310. * Return the URL language switcher block. Translation links may be provided by
  311. * other modules.
  312. */
  313. function locale_language_switcher_url($type, $path) {
  314. $languages = language_list('enabled');
  315. $links = array();
  316. foreach ($languages[1] as $language) {
  317. $links[$language->language] = array(
  318. 'href' => $path,
  319. 'title' => $language->native,
  320. 'language' => $language,
  321. 'attributes' => array('class' => array('language-link')),
  322. );
  323. }
  324. return $links;
  325. }
  326. /**
  327. * Return the session language switcher block.
  328. */
  329. function locale_language_switcher_session($type, $path) {
  330. drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');
  331. $param = variable_get('locale_language_negotiation_session_param', 'language');
  332. $language_query = isset($_SESSION[$param]) ? $_SESSION[$param] : $GLOBALS[$type]->language;
  333. $languages = language_list('enabled');
  334. $links = array();
  335. $query = $_GET;
  336. unset($query['q']);
  337. foreach ($languages[1] as $language) {
  338. $langcode = $language->language;
  339. $links[$langcode] = array(
  340. 'href' => $path,
  341. 'title' => $language->native,
  342. 'attributes' => array('class' => array('language-link')),
  343. 'query' => $query,
  344. );
  345. if ($language_query != $langcode) {
  346. $links[$langcode]['query'][$param] = $langcode;
  347. }
  348. else {
  349. $links[$langcode]['attributes']['class'][] = ' session-active';
  350. }
  351. }
  352. return $links;
  353. }
  354. /**
  355. * Rewrite URLs for the URL language provider.
  356. */
  357. function locale_language_url_rewrite_url(&$path, &$options) {
  358. static $drupal_static_fast;
  359. if (!isset($drupal_static_fast)) {
  360. $drupal_static_fast['languages'] = &drupal_static(__FUNCTION__);
  361. }
  362. $languages = &$drupal_static_fast['languages'];
  363. if (!isset($languages)) {
  364. $languages = language_list('enabled');
  365. $languages = array_flip(array_keys($languages[1]));
  366. }
  367. // Language can be passed as an option, or we go for current URL language.
  368. if (!isset($options['language'])) {
  369. global $language_url;
  370. $options['language'] = $language_url;
  371. }
  372. // We allow only enabled languages here.
  373. elseif (!isset($languages[$options['language']->language])) {
  374. unset($options['language']);
  375. return;
  376. }
  377. if (isset($options['language'])) {
  378. switch (variable_get('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX)) {
  379. case LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN:
  380. if ($options['language']->domain) {
  381. // Ask for an absolute URL with our modified base_url.
  382. global $is_https;
  383. $url_scheme = ($is_https) ? 'https://' : 'http://';
  384. $options['absolute'] = TRUE;
  385. // Take the domain without ports or protocols so we can apply the
  386. // protocol needed. The setting might include a protocol.
  387. // This is changed in Drupal 8 but we need to keep backwards
  388. // compatibility for Drupal 7.
  389. $host = 'http://' . str_replace(array('http://', 'https://'), '', $options['language']->domain);
  390. $host = parse_url($host, PHP_URL_HOST);
  391. // Apply the appropriate protocol to the URL.
  392. $options['base_url'] = $url_scheme . $host;
  393. if (isset($options['https']) && variable_get('https', FALSE)) {
  394. if ($options['https'] === TRUE) {
  395. $options['base_url'] = str_replace('http://', 'https://', $options['base_url']);
  396. }
  397. elseif ($options['https'] === FALSE) {
  398. $options['base_url'] = str_replace('https://', 'http://', $options['base_url']);
  399. }
  400. }
  401. }
  402. break;
  403. case LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX:
  404. if (!empty($options['language']->prefix)) {
  405. $options['prefix'] = $options['language']->prefix . '/';
  406. }
  407. break;
  408. }
  409. }
  410. }
  411. /**
  412. * Rewrite URLs for the Session language provider.
  413. */
  414. function locale_language_url_rewrite_session(&$path, &$options) {
  415. static $query_rewrite, $query_param, $query_value;
  416. // The following values are not supposed to change during a single page
  417. // request processing.
  418. if (!isset($query_rewrite)) {
  419. global $user;
  420. if (!$user->uid) {
  421. $languages = language_list('enabled');
  422. $languages = $languages[1];
  423. $query_param = check_plain(variable_get('locale_language_negotiation_session_param', 'language'));
  424. $query_value = isset($_GET[$query_param]) ? check_plain($_GET[$query_param]) : NULL;
  425. $query_rewrite = isset($languages[$query_value]) && language_negotiation_get_any(LOCALE_LANGUAGE_NEGOTIATION_SESSION);
  426. }
  427. else {
  428. $query_rewrite = FALSE;
  429. }
  430. }
  431. // If the user is anonymous, the user language provider is enabled, and the
  432. // corresponding option has been set, we must preserve any explicit user
  433. // language preference even with cookies disabled.
  434. if ($query_rewrite) {
  435. if (is_string($options['query'])) {
  436. $options['query'] = drupal_get_query_array($options['query']);
  437. }
  438. if (!isset($options['query'][$query_param])) {
  439. $options['query'][$query_param] = $query_value;
  440. }
  441. }
  442. }
  443. /**
  444. * @} End of "locale-languages-negotiation"
  445. */
  446. /**
  447. * Check that a string is safe to be added or imported as a translation.
  448. *
  449. * This test can be used to detect possibly bad translation strings. It should
  450. * not have any false positives. But it is only a test, not a transformation,
  451. * as it destroys valid HTML. We cannot reliably filter translation strings
  452. * on import because some strings are irreversibly corrupted. For example,
  453. * a &amp; in the translation would get encoded to &amp;amp; by filter_xss()
  454. * before being put in the database, and thus would be displayed incorrectly.
  455. *
  456. * The allowed tag list is like filter_xss_admin(), but omitting div and img as
  457. * not needed for translation and likely to cause layout issues (div) or a
  458. * possible attack vector (img).
  459. */
  460. function locale_string_is_safe($string) {
  461. return decode_entities($string) == decode_entities(filter_xss($string, array('a', 'abbr', 'acronym', 'address', 'b', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dl', 'dt', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'ins', 'kbd', 'li', 'ol', 'p', 'pre', 'q', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'tt', 'ul', 'var')));
  462. }
  463. /**
  464. * @defgroup locale-api-add Language addition API
  465. * @{
  466. * Add a language.
  467. *
  468. * The language addition API is used to create languages and store them.
  469. */
  470. /**
  471. * API function to add a language.
  472. *
  473. * @param $langcode
  474. * Language code.
  475. * @param $name
  476. * English name of the language
  477. * @param $native
  478. * Native name of the language
  479. * @param $direction
  480. * LANGUAGE_LTR or LANGUAGE_RTL
  481. * @param $domain
  482. * Optional custom domain name with protocol, without
  483. * trailing slash (eg. http://de.example.com).
  484. * @param $prefix
  485. * Optional path prefix for the language. Defaults to the
  486. * language code if omitted.
  487. * @param $enabled
  488. * Optionally TRUE to enable the language when created or FALSE to disable.
  489. * @param $default
  490. * Optionally set this language to be the default.
  491. */
  492. function locale_add_language($langcode, $name = NULL, $native = NULL, $direction = LANGUAGE_LTR, $domain = '', $prefix = '', $enabled = TRUE, $default = FALSE) {
  493. // Default prefix on language code.
  494. if (empty($prefix)) {
  495. $prefix = $langcode;
  496. }
  497. // If name was not set, we add a predefined language.
  498. if (!isset($name)) {
  499. include_once DRUPAL_ROOT . '/includes/iso.inc';
  500. $predefined = _locale_get_predefined_list();
  501. $name = $predefined[$langcode][0];
  502. $native = isset($predefined[$langcode][1]) ? $predefined[$langcode][1] : $predefined[$langcode][0];
  503. $direction = isset($predefined[$langcode][2]) ? $predefined[$langcode][2] : LANGUAGE_LTR;
  504. }
  505. db_insert('languages')
  506. ->fields(array(
  507. 'language' => $langcode,
  508. 'name' => $name,
  509. 'native' => $native,
  510. 'direction' => $direction,
  511. 'domain' => $domain,
  512. 'prefix' => $prefix,
  513. 'enabled' => $enabled,
  514. ))
  515. ->execute();
  516. // Only set it as default if enabled.
  517. if ($enabled && $default) {
  518. variable_set('language_default', (object) array('language' => $langcode, 'name' => $name, 'native' => $native, 'direction' => $direction, 'enabled' => (int) $enabled, 'plurals' => 0, 'formula' => '', 'domain' => '', 'prefix' => $prefix, 'weight' => 0, 'javascript' => ''));
  519. }
  520. if ($enabled) {
  521. // Increment enabled language count if we are adding an enabled language.
  522. variable_set('language_count', variable_get('language_count', 1) + 1);
  523. }
  524. // Kill the static cache in language_list().
  525. drupal_static_reset('language_list');
  526. // Force JavaScript translation file creation for the newly added language.
  527. _locale_invalidate_js($langcode);
  528. watchdog('locale', 'The %language language (%code) has been created.', array('%language' => $name, '%code' => $langcode));
  529. module_invoke_all('multilingual_settings_changed');
  530. }
  531. /**
  532. * @} End of "locale-api-add"
  533. */
  534. /**
  535. * @defgroup locale-api-import-export Translation import/export API.
  536. * @{
  537. * Functions to import and export translations.
  538. *
  539. * These functions provide the ability to import translations from
  540. * external files and to export translations and translation templates.
  541. */
  542. /**
  543. * Parses Gettext Portable Object file information and inserts into database
  544. *
  545. * @param $file
  546. * Drupal file object corresponding to the PO file to import.
  547. * @param $langcode
  548. * Language code.
  549. * @param $mode
  550. * Should existing translations be replaced LOCALE_IMPORT_KEEP or
  551. * LOCALE_IMPORT_OVERWRITE.
  552. * @param $group
  553. * Text group to import PO file into (eg. 'default' for interface
  554. * translations).
  555. */
  556. function _locale_import_po($file, $langcode, $mode, $group = NULL) {
  557. // Try to allocate enough time to parse and import the data.
  558. drupal_set_time_limit(240);
  559. // Check if we have the language already in the database.
  560. if (!db_query("SELECT COUNT(language) FROM {languages} WHERE language = :language", array(':language' => $langcode))->fetchField()) {
  561. drupal_set_message(t('The language selected for import is not supported.'), 'error');
  562. return FALSE;
  563. }
  564. // Get strings from file (returns on failure after a partial import, or on success)
  565. $status = _locale_import_read_po('db-store', $file, $mode, $langcode, $group);
  566. if ($status === FALSE) {
  567. // Error messages are set in _locale_import_read_po().
  568. return FALSE;
  569. }
  570. // Get status information on import process.
  571. list($header_done, $additions, $updates, $deletes, $skips) = _locale_import_one_string('db-report');
  572. if (!$header_done) {
  573. drupal_set_message(t('The translation file %filename appears to have a missing or malformed header.', array('%filename' => $file->filename)), 'error');
  574. }
  575. // Clear cache and force refresh of JavaScript translations.
  576. _locale_invalidate_js($langcode);
  577. cache_clear_all('locale:', 'cache', TRUE);
  578. // Rebuild the menu, strings may have changed.
  579. menu_rebuild();
  580. drupal_set_message(t('The translation was successfully imported. There are %number newly created translated strings, %update strings were updated and %delete strings were removed.', array('%number' => $additions, '%update' => $updates, '%delete' => $deletes)));
  581. watchdog('locale', 'Imported %file into %locale: %number new strings added, %update updated and %delete removed.', array('%file' => $file->filename, '%locale' => $langcode, '%number' => $additions, '%update' => $updates, '%delete' => $deletes));
  582. if ($skips) {
  583. $skip_message = format_plural($skips, 'One translation string was skipped because it contains disallowed HTML.', '@count translation strings were skipped because they contain disallowed HTML.');
  584. drupal_set_message($skip_message);
  585. watchdog('locale', '@count disallowed HTML string(s) in %file', array('@count' => $skips, '%file' => $file->uri), WATCHDOG_WARNING);
  586. }
  587. return TRUE;
  588. }
  589. /**
  590. * Parses Gettext Portable Object file into an array
  591. *
  592. * @param $op
  593. * Storage operation type: db-store or mem-store.
  594. * @param $file
  595. * Drupal file object corresponding to the PO file to import.
  596. * @param $mode
  597. * Should existing translations be replaced LOCALE_IMPORT_KEEP or
  598. * LOCALE_IMPORT_OVERWRITE.
  599. * @param $lang
  600. * Language code.
  601. * @param $group
  602. * Text group to import PO file into (eg. 'default' for interface
  603. * translations).
  604. */
  605. function _locale_import_read_po($op, $file, $mode = NULL, $lang = NULL, $group = 'default') {
  606. // The file will get closed by PHP on returning from this function.
  607. $fd = fopen($file->uri, 'rb');
  608. if (!$fd) {
  609. _locale_import_message('The translation import failed, because the file %filename could not be read.', $file);
  610. return FALSE;
  611. }
  612. /*
  613. * The parser context. Can be:
  614. * - 'COMMENT' (#)
  615. * - 'MSGID' (msgid)
  616. * - 'MSGID_PLURAL' (msgid_plural)
  617. * - 'MSGCTXT' (msgctxt)
  618. * - 'MSGSTR' (msgstr or msgstr[])
  619. * - 'MSGSTR_ARR' (msgstr_arg)
  620. */
  621. $context = 'COMMENT';
  622. // Current entry being read.
  623. $current = array();
  624. // Current plurality for 'msgstr[]'.
  625. $plural = 0;
  626. // Current line.
  627. $lineno = 0;
  628. while (!feof($fd)) {
  629. // A line should not be longer than 10 * 1024.
  630. $line = fgets($fd, 10 * 1024);
  631. if ($lineno == 0) {
  632. // The first line might come with a UTF-8 BOM, which should be removed.
  633. $line = str_replace("\xEF\xBB\xBF", '', $line);
  634. }
  635. $lineno++;
  636. // Trim away the linefeed.
  637. $line = trim(strtr($line, array("\\\n" => "")));
  638. if (!strncmp('#', $line, 1)) {
  639. // Lines starting with '#' are comments.
  640. if ($context == 'COMMENT') {
  641. // Already in comment token, insert the comment.
  642. $current['#'][] = substr($line, 1);
  643. }
  644. elseif (($context == 'MSGSTR') || ($context == 'MSGSTR_ARR')) {
  645. // We are currently in string token, close it out.
  646. _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
  647. // Start a new entry for the comment.
  648. $current = array();
  649. $current['#'][] = substr($line, 1);
  650. $context = 'COMMENT';
  651. }
  652. else {
  653. // A comment following any other token is a syntax error.
  654. _locale_import_message('The translation file %filename contains an error: "msgstr" was expected but not found on line %line.', $file, $lineno);
  655. return FALSE;
  656. }
  657. }
  658. elseif (!strncmp('msgid_plural', $line, 12)) {
  659. // A plural form for the current message.
  660. if ($context != 'MSGID') {
  661. // A plural form cannot be added to anything else but the id directly.
  662. _locale_import_message('The translation file %filename contains an error: "msgid_plural" was expected but not found on line %line.', $file, $lineno);
  663. return FALSE;
  664. }
  665. // Remove 'msgid_plural' and trim away whitespace.
  666. $line = trim(substr($line, 12));
  667. // At this point, $line should now contain only the plural form.
  668. $quoted = _locale_import_parse_quoted($line);
  669. if ($quoted === FALSE) {
  670. // The plural form must be wrapped in quotes.
  671. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  672. return FALSE;
  673. }
  674. // Append the plural form to the current entry.
  675. $current['msgid'] .= "\0" . $quoted;
  676. $context = 'MSGID_PLURAL';
  677. }
  678. elseif (!strncmp('msgid', $line, 5)) {
  679. // Starting a new message.
  680. if (($context == 'MSGSTR') || ($context == 'MSGSTR_ARR')) {
  681. // We are currently in a message string, close it out.
  682. _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
  683. // Start a new context for the id.
  684. $current = array();
  685. }
  686. elseif ($context == 'MSGID') {
  687. // We are currently already in the context, meaning we passed an id with no data.
  688. _locale_import_message('The translation file %filename contains an error: "msgid" is unexpected on line %line.', $file, $lineno);
  689. return FALSE;
  690. }
  691. // Remove 'msgid' and trim away whitespace.
  692. $line = trim(substr($line, 5));
  693. // At this point, $line should now contain only the message id.
  694. $quoted = _locale_import_parse_quoted($line);
  695. if ($quoted === FALSE) {
  696. // The message id must be wrapped in quotes.
  697. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  698. return FALSE;
  699. }
  700. $current['msgid'] = $quoted;
  701. $context = 'MSGID';
  702. }
  703. elseif (!strncmp('msgctxt', $line, 7)) {
  704. // Starting a new context.
  705. if (($context == 'MSGSTR') || ($context == 'MSGSTR_ARR')) {
  706. // We are currently in a message, start a new one.
  707. _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
  708. $current = array();
  709. }
  710. elseif (!empty($current['msgctxt'])) {
  711. // A context cannot apply to another context.
  712. _locale_import_message('The translation file %filename contains an error: "msgctxt" is unexpected on line %line.', $file, $lineno);
  713. return FALSE;
  714. }
  715. // Remove 'msgctxt' and trim away whitespaces.
  716. $line = trim(substr($line, 7));
  717. // At this point, $line should now contain the context.
  718. $quoted = _locale_import_parse_quoted($line);
  719. if ($quoted === FALSE) {
  720. // The context string must be quoted.
  721. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  722. return FALSE;
  723. }
  724. $current['msgctxt'] = $quoted;
  725. $context = 'MSGCTXT';
  726. }
  727. elseif (!strncmp('msgstr[', $line, 7)) {
  728. // A message string for a specific plurality.
  729. if (($context != 'MSGID') && ($context != 'MSGCTXT') && ($context != 'MSGID_PLURAL') && ($context != 'MSGSTR_ARR')) {
  730. // Message strings must come after msgid, msgxtxt, msgid_plural, or other msgstr[] entries.
  731. _locale_import_message('The translation file %filename contains an error: "msgstr[]" is unexpected on line %line.', $file, $lineno);
  732. return FALSE;
  733. }
  734. // Ensure the plurality is terminated.
  735. if (strpos($line, ']') === FALSE) {
  736. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  737. return FALSE;
  738. }
  739. // Extract the plurality.
  740. $frombracket = strstr($line, '[');
  741. $plural = substr($frombracket, 1, strpos($frombracket, ']') - 1);
  742. // Skip to the next whitespace and trim away any further whitespace, bringing $line to the message data.
  743. $line = trim(strstr($line, " "));
  744. $quoted = _locale_import_parse_quoted($line);
  745. if ($quoted === FALSE) {
  746. // The string must be quoted.
  747. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  748. return FALSE;
  749. }
  750. $current['msgstr'][$plural] = $quoted;
  751. $context = 'MSGSTR_ARR';
  752. }
  753. elseif (!strncmp("msgstr", $line, 6)) {
  754. // A string for the an id or context.
  755. if (($context != 'MSGID') && ($context != 'MSGCTXT')) {
  756. // Strings are only valid within an id or context scope.
  757. _locale_import_message('The translation file %filename contains an error: "msgstr" is unexpected on line %line.', $file, $lineno);
  758. return FALSE;
  759. }
  760. // Remove 'msgstr' and trim away away whitespaces.
  761. $line = trim(substr($line, 6));
  762. // At this point, $line should now contain the message.
  763. $quoted = _locale_import_parse_quoted($line);
  764. if ($quoted === FALSE) {
  765. // The string must be quoted.
  766. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  767. return FALSE;
  768. }
  769. $current['msgstr'] = $quoted;
  770. $context = 'MSGSTR';
  771. }
  772. elseif ($line != '') {
  773. // Anything that is not a token may be a continuation of a previous token.
  774. $quoted = _locale_import_parse_quoted($line);
  775. if ($quoted === FALSE) {
  776. // The string must be quoted.
  777. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  778. return FALSE;
  779. }
  780. // Append the string to the current context.
  781. if (($context == 'MSGID') || ($context == 'MSGID_PLURAL')) {
  782. $current['msgid'] .= $quoted;
  783. }
  784. elseif ($context == 'MSGCTXT') {
  785. $current['msgctxt'] .= $quoted;
  786. }
  787. elseif ($context == 'MSGSTR') {
  788. $current['msgstr'] .= $quoted;
  789. }
  790. elseif ($context == 'MSGSTR_ARR') {
  791. $current['msgstr'][$plural] .= $quoted;
  792. }
  793. else {
  794. // No valid context to append to.
  795. _locale_import_message('The translation file %filename contains an error: there is an unexpected string on line %line.', $file, $lineno);
  796. return FALSE;
  797. }
  798. }
  799. }
  800. // End of PO file, closed out the last entry.
  801. if (($context == 'MSGSTR') || ($context == 'MSGSTR_ARR')) {
  802. _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
  803. }
  804. elseif ($context != 'COMMENT') {
  805. _locale_import_message('The translation file %filename ended unexpectedly at line %line.', $file, $lineno);
  806. return FALSE;
  807. }
  808. }
  809. /**
  810. * Sets an error message occurred during locale file parsing.
  811. *
  812. * @param $message
  813. * The message to be translated.
  814. * @param $file
  815. * Drupal file object corresponding to the PO file to import.
  816. * @param $lineno
  817. * An optional line number argument.
  818. */
  819. function _locale_import_message($message, $file, $lineno = NULL) {
  820. $vars = array('%filename' => $file->filename);
  821. if (isset($lineno)) {
  822. $vars['%line'] = $lineno;
  823. }
  824. $t = get_t();
  825. drupal_set_message($t($message, $vars), 'error');
  826. }
  827. /**
  828. * Imports a string into the database
  829. *
  830. * @param $op
  831. * Operation to perform: 'db-store', 'db-report', 'mem-store' or 'mem-report'.
  832. * @param $value
  833. * Details of the string stored.
  834. * @param $mode
  835. * Should existing translations be replaced LOCALE_IMPORT_KEEP or
  836. * LOCALE_IMPORT_OVERWRITE.
  837. * @param $lang
  838. * Language to store the string in.
  839. * @param $file
  840. * Object representation of file being imported, only required when op is
  841. * 'db-store'.
  842. * @param $group
  843. * Text group to import PO file into (eg. 'default' for interface
  844. * translations).
  845. */
  846. function _locale_import_one_string($op, $value = NULL, $mode = NULL, $lang = NULL, $file = NULL, $group = 'default') {
  847. $report = &drupal_static(__FUNCTION__, array('additions' => 0, 'updates' => 0, 'deletes' => 0, 'skips' => 0));
  848. $header_done = &drupal_static(__FUNCTION__ . ':header_done', FALSE);
  849. $strings = &drupal_static(__FUNCTION__ . ':strings', array());
  850. switch ($op) {
  851. // Return stored strings
  852. case 'mem-report':
  853. return $strings;
  854. // Store string in memory (only supports single strings)
  855. case 'mem-store':
  856. $strings[isset($value['msgctxt']) ? $value['msgctxt'] : ''][$value['msgid']] = $value['msgstr'];
  857. return;
  858. // Called at end of import to inform the user
  859. case 'db-report':
  860. return array($header_done, $report['additions'], $report['updates'], $report['deletes'], $report['skips']);
  861. // Store the string we got in the database.
  862. case 'db-store':
  863. // We got header information.
  864. if ($value['msgid'] == '') {
  865. $languages = language_list();
  866. if (($mode != LOCALE_IMPORT_KEEP) || empty($languages[$lang]->plurals)) {
  867. // Since we only need to parse the header if we ought to update the
  868. // plural formula, only run this if we don't need to keep existing
  869. // data untouched or if we don't have an existing plural formula.
  870. $header = _locale_import_parse_header($value['msgstr']);
  871. // Get and store the plural formula if available.
  872. if (isset($header["Plural-Forms"]) && $p = _locale_import_parse_plural_forms($header["Plural-Forms"], $file->uri)) {
  873. list($nplurals, $plural) = $p;
  874. db_update('languages')
  875. ->fields(array(
  876. 'plurals' => $nplurals,
  877. 'formula' => $plural,
  878. ))
  879. ->condition('language', $lang)
  880. ->execute();
  881. }
  882. }
  883. $header_done = TRUE;
  884. }
  885. else {
  886. // Some real string to import.
  887. $comments = _locale_import_shorten_comments(empty($value['#']) ? array() : $value['#']);
  888. if (strpos($value['msgid'], "\0")) {
  889. // This string has plural versions.
  890. $english = explode("\0", $value['msgid'], 2);
  891. $entries = array_keys($value['msgstr']);
  892. for ($i = 3; $i <= count($entries); $i++) {
  893. $english[] = $english[1];
  894. }
  895. $translation = array_map('_locale_import_append_plural', $value['msgstr'], $entries);
  896. $english = array_map('_locale_import_append_plural', $english, $entries);
  897. foreach ($translation as $key => $trans) {
  898. if ($key == 0) {
  899. $plid = 0;
  900. }
  901. $plid = _locale_import_one_string_db($report, $lang, isset($value['msgctxt']) ? $value['msgctxt'] : '', $english[$key], $trans, $group, $comments, $mode, $plid, $key);
  902. }
  903. }
  904. else {
  905. // A simple string to import.
  906. $english = $value['msgid'];
  907. $translation = $value['msgstr'];
  908. _locale_import_one_string_db($report, $lang, isset($value['msgctxt']) ? $value['msgctxt'] : '', $english, $translation, $group, $comments, $mode);
  909. }
  910. }
  911. } // end of db-store operation
  912. }
  913. /**
  914. * Import one string into the database.
  915. *
  916. * @param $report
  917. * Report array summarizing the number of changes done in the form:
  918. * array(inserts, updates, deletes).
  919. * @param $langcode
  920. * Language code to import string into.
  921. * @param $context
  922. * The context of this string.
  923. * @param $source
  924. * Source string.
  925. * @param $translation
  926. * Translation to language specified in $langcode.
  927. * @param $textgroup
  928. * Name of textgroup to store translation in.
  929. * @param $location
  930. * Location value to save with source string.
  931. * @param $mode
  932. * Import mode to use, LOCALE_IMPORT_KEEP or LOCALE_IMPORT_OVERWRITE.
  933. * @param $plid
  934. * Optional plural ID to use.
  935. * @param $plural
  936. * Optional plural value to use.
  937. *
  938. * @return
  939. * The string ID of the existing string modified or the new string added.
  940. */
  941. function _locale_import_one_string_db(&$report, $langcode, $context, $source, $translation, $textgroup, $location, $mode, $plid = 0, $plural = 0) {
  942. $lid = db_query("SELECT lid FROM {locales_source} WHERE source = :source AND context = :context AND textgroup = :textgroup", array(':source' => $source, ':context' => $context, ':textgroup' => $textgroup))->fetchField();
  943. if (!empty($translation)) {
  944. // Skip this string unless it passes a check for dangerous code.
  945. // Text groups other than default still can contain HTML tags
  946. // (i.e. translatable blocks).
  947. if ($textgroup == "default" && !locale_string_is_safe($translation)) {
  948. $report['skips']++;
  949. $lid = 0;
  950. }
  951. elseif ($lid) {
  952. // We have this source string saved already.
  953. db_update('locales_source')
  954. ->fields(array(
  955. 'location' => $location,
  956. ))
  957. ->condition('lid', $lid)
  958. ->execute();
  959. $exists = db_query("SELECT COUNT(lid) FROM {locales_target} WHERE lid = :lid AND language = :language", array(':lid' => $lid, ':language' => $langcode))->fetchField();
  960. if (!$exists) {
  961. // No translation in this language.
  962. db_insert('locales_target')
  963. ->fields(array(
  964. 'lid' => $lid,
  965. 'language' => $langcode,
  966. 'translation' => $translation,
  967. 'plid' => $plid,
  968. 'plural' => $plural,
  969. ))
  970. ->execute();
  971. $report['additions']++;
  972. }
  973. elseif ($mode == LOCALE_IMPORT_OVERWRITE) {
  974. // Translation exists, only overwrite if instructed.
  975. db_update('locales_target')
  976. ->fields(array(
  977. 'translation' => $translation,
  978. 'plid' => $plid,
  979. 'plural' => $plural,
  980. ))
  981. ->condition('language', $langcode)
  982. ->condition('lid', $lid)
  983. ->execute();
  984. $report['updates']++;
  985. }
  986. }
  987. else {
  988. // No such source string in the database yet.
  989. $lid = db_insert('locales_source')
  990. ->fields(array(
  991. 'location' => $location,
  992. 'source' => $source,
  993. 'context' => (string) $context,
  994. 'textgroup' => $textgroup,
  995. ))
  996. ->execute();
  997. db_insert('locales_target')
  998. ->fields(array(
  999. 'lid' => $lid,
  1000. 'language' => $langcode,
  1001. 'translation' => $translation,
  1002. 'plid' => $plid,
  1003. 'plural' => $plural
  1004. ))
  1005. ->execute();
  1006. $report['additions']++;
  1007. }
  1008. }
  1009. elseif ($mode == LOCALE_IMPORT_OVERWRITE) {
  1010. // Empty translation, remove existing if instructed.
  1011. db_delete('locales_target')
  1012. ->condition('language', $langcode)
  1013. ->condition('lid', $lid)
  1014. ->condition('plid', $plid)
  1015. ->condition('plural', $plural)
  1016. ->execute();
  1017. $report['deletes']++;
  1018. }
  1019. return $lid;
  1020. }
  1021. /**
  1022. * Parses a Gettext Portable Object file header
  1023. *
  1024. * @param $header
  1025. * A string containing the complete header.
  1026. *
  1027. * @return
  1028. * An associative array of key-value pairs.
  1029. */
  1030. function _locale_import_parse_header($header) {
  1031. $header_parsed = array();
  1032. $lines = array_map('trim', explode("\n", $header));
  1033. foreach ($lines as $line) {
  1034. if ($line) {
  1035. list($tag, $contents) = explode(":", $line, 2);
  1036. $header_parsed[trim($tag)] = trim($contents);
  1037. }
  1038. }
  1039. return $header_parsed;
  1040. }
  1041. /**
  1042. * Parses a Plural-Forms entry from a Gettext Portable Object file header
  1043. *
  1044. * @param $pluralforms
  1045. * A string containing the Plural-Forms entry.
  1046. * @param $filepath
  1047. * A string containing the filepath.
  1048. *
  1049. * @return
  1050. * An array containing the number of plurals and a
  1051. * formula in PHP for computing the plural form.
  1052. */
  1053. function _locale_import_parse_plural_forms($pluralforms, $filepath) {
  1054. // First, delete all whitespace
  1055. $pluralforms = strtr($pluralforms, array(" " => "", "\t" => ""));
  1056. // Select the parts that define nplurals and plural
  1057. $nplurals = strstr($pluralforms, "nplurals=");
  1058. if (strpos($nplurals, ";")) {
  1059. $nplurals = substr($nplurals, 9, strpos($nplurals, ";") - 9);
  1060. }
  1061. else {
  1062. return FALSE;
  1063. }
  1064. $plural = strstr($pluralforms, "plural=");
  1065. if (strpos($plural, ";")) {
  1066. $plural = substr($plural, 7, strpos($plural, ";") - 7);
  1067. }
  1068. else {
  1069. return FALSE;
  1070. }
  1071. // Get PHP version of the plural formula
  1072. $plural = _locale_import_parse_arithmetic($plural);
  1073. if ($plural !== FALSE) {
  1074. return array($nplurals, $plural);
  1075. }
  1076. else {
  1077. drupal_set_message(t('The translation file %filepath contains an error: the plural formula could not be parsed.', array('%filepath' => $filepath)), 'error');
  1078. return FALSE;
  1079. }
  1080. }
  1081. /**
  1082. * Parses and sanitizes an arithmetic formula into a PHP expression
  1083. *
  1084. * While parsing, we ensure, that the operators have the right
  1085. * precedence and associativity.
  1086. *
  1087. * @param $string
  1088. * A string containing the arithmetic formula.
  1089. *
  1090. * @return
  1091. * The PHP version of the formula.
  1092. */
  1093. function _locale_import_parse_arithmetic($string) {
  1094. // Operator precedence table
  1095. $precedence = array("(" => -1, ")" => -1, "?" => 1, ":" => 1, "||" => 3, "&&" => 4, "==" => 5, "!=" => 5, "<" => 6, ">" => 6, "<=" => 6, ">=" => 6, "+" => 7, "-" => 7, "*" => 8, "/" => 8, "%" => 8);
  1096. // Right associativity
  1097. $right_associativity = array("?" => 1, ":" => 1);
  1098. $tokens = _locale_import_tokenize_formula($string);
  1099. // Parse by converting into infix notation then back into postfix
  1100. // Operator stack - holds math operators and symbols
  1101. $operator_stack = array();
  1102. // Element Stack - holds data to be operated on
  1103. $element_stack = array();
  1104. foreach ($tokens as $token) {
  1105. $current_token = $token;
  1106. // Numbers and the $n variable are simply pushed into $element_stack
  1107. if (is_numeric($token)) {
  1108. $element_stack[] = $current_token;
  1109. }
  1110. elseif ($current_token == "n") {
  1111. $element_stack[] = '$n';
  1112. }
  1113. elseif ($current_token == "(") {
  1114. $operator_stack[] = $current_token;
  1115. }
  1116. elseif ($current_token == ")") {
  1117. $topop = array_pop($operator_stack);
  1118. while (isset($topop) && ($topop != "(")) {
  1119. $element_stack[] = $topop;
  1120. $topop = array_pop($operator_stack);
  1121. }
  1122. }
  1123. elseif (!empty($precedence[$current_token])) {
  1124. // If it's an operator, then pop from $operator_stack into $element_stack until the
  1125. // precedence in $operator_stack is less than current, then push into $operator_stack
  1126. $topop = array_pop($operator_stack);
  1127. while (isset($topop) && ($precedence[$topop] >= $precedence[$current_token]) && !(($precedence[$topop] == $precedence[$current_token]) && !empty($right_associativity[$topop]) && !empty($right_associativity[$current_token]))) {
  1128. $element_stack[] = $topop;
  1129. $topop = array_pop($operator_stack);
  1130. }
  1131. if ($topop) {
  1132. $operator_stack[] = $topop; // Return element to top
  1133. }
  1134. $operator_stack[] = $current_token; // Parentheses are not needed
  1135. }
  1136. else {
  1137. return FALSE;
  1138. }
  1139. }
  1140. // Flush operator stack
  1141. $topop = array_pop($operator_stack);
  1142. while ($topop != NULL) {
  1143. $element_stack[] = $topop;
  1144. $topop = array_pop($operator_stack);
  1145. }
  1146. // Now extract formula from stack
  1147. $previous_size = count($element_stack) + 1;
  1148. while (count($element_stack) < $previous_size) {
  1149. $previous_size = count($element_stack);
  1150. for ($i = 2; $i < count($element_stack); $i++) {
  1151. $op = $element_stack[$i];
  1152. if (!empty($precedence[$op])) {
  1153. $f = "";
  1154. if ($op == ":") {
  1155. $f = $element_stack[$i - 2] . "):" . $element_stack[$i - 1] . ")";
  1156. }
  1157. elseif ($op == "?") {
  1158. $f = "(" . $element_stack[$i - 2] . "?(" . $element_stack[$i - 1];
  1159. }
  1160. else {
  1161. $f = "(" . $element_stack[$i - 2] . $op . $element_stack[$i - 1] . ")";
  1162. }
  1163. array_splice($element_stack, $i - 2, 3, $f);
  1164. break;
  1165. }
  1166. }
  1167. }
  1168. // If only one element is left, the number of operators is appropriate
  1169. if (count($element_stack) == 1) {
  1170. return $element_stack[0];
  1171. }
  1172. else {
  1173. return FALSE;
  1174. }
  1175. }
  1176. /**
  1177. * Backward compatible implementation of token_get_all() for formula parsing
  1178. *
  1179. * @param $string
  1180. * A string containing the arithmetic formula.
  1181. *
  1182. * @return
  1183. * The PHP version of the formula.
  1184. */
  1185. function _locale_import_tokenize_formula($formula) {
  1186. $formula = str_replace(" ", "", $formula);
  1187. $tokens = array();
  1188. for ($i = 0; $i < strlen($formula); $i++) {
  1189. if (is_numeric($formula[$i])) {
  1190. $num = $formula[$i];
  1191. $j = $i + 1;
  1192. while ($j < strlen($formula) && is_numeric($formula[$j])) {
  1193. $num .= $formula[$j];
  1194. $j++;
  1195. }
  1196. $i = $j - 1;
  1197. $tokens[] = $num;
  1198. }
  1199. elseif ($pos = strpos(" =<>!&|", $formula[$i])) { // We won't have a space
  1200. $next = $formula[$i + 1];
  1201. switch ($pos) {
  1202. case 1:
  1203. case 2:
  1204. case 3:
  1205. case 4:
  1206. if ($next == '=') {
  1207. $tokens[] = $formula[$i] . '=';
  1208. $i++;
  1209. }
  1210. else {
  1211. $tokens[] = $formula[$i];
  1212. }
  1213. break;
  1214. case 5:
  1215. if ($next == '&') {
  1216. $tokens[] = '&&';
  1217. $i++;
  1218. }
  1219. else {
  1220. $tokens[] = $formula[$i];
  1221. }
  1222. break;
  1223. case 6:
  1224. if ($next == '|') {
  1225. $tokens[] = '||';
  1226. $i++;
  1227. }
  1228. else {
  1229. $tokens[] = $formula[$i];
  1230. }
  1231. break;
  1232. }
  1233. }
  1234. else {
  1235. $tokens[] = $formula[$i];
  1236. }
  1237. }
  1238. return $tokens;
  1239. }
  1240. /**
  1241. * Modify a string to contain proper count indices
  1242. *
  1243. * This is a callback function used via array_map()
  1244. *
  1245. * @param $entry
  1246. * An array element.
  1247. * @param $key
  1248. * Index of the array element.
  1249. */
  1250. function _locale_import_append_plural($entry, $key) {
  1251. // No modifications for 0, 1
  1252. if ($key == 0 || $key == 1) {
  1253. return $entry;
  1254. }
  1255. // First remove any possibly false indices, then add new ones
  1256. $entry = preg_replace('/(@count)\[[0-9]\]/', '\\1', $entry);
  1257. return preg_replace('/(@count)/', "\\1[$key]", $entry);
  1258. }
  1259. /**
  1260. * Generate a short, one string version of the passed comment array
  1261. *
  1262. * @param $comment
  1263. * An array of strings containing a comment.
  1264. *
  1265. * @return
  1266. * Short one string version of the comment.
  1267. */
  1268. function _locale_import_shorten_comments($comment) {
  1269. $comm = '';
  1270. while (count($comment)) {
  1271. $test = $comm . substr(array_shift($comment), 1) . ', ';
  1272. if (strlen($comm) < 130) {
  1273. $comm = $test;
  1274. }
  1275. else {
  1276. break;
  1277. }
  1278. }
  1279. return trim(substr($comm, 0, -2));
  1280. }
  1281. /**
  1282. * Parses a string in quotes
  1283. *
  1284. * @param $string
  1285. * A string specified with enclosing quotes.
  1286. *
  1287. * @return
  1288. * The string parsed from inside the quotes.
  1289. */
  1290. function _locale_import_parse_quoted($string) {
  1291. if (substr($string, 0, 1) != substr($string, -1, 1)) {
  1292. return FALSE; // Start and end quotes must be the same
  1293. }
  1294. $quote = substr($string, 0, 1);
  1295. $string = substr($string, 1, -1);
  1296. if ($quote == '"') { // Double quotes: strip slashes
  1297. return stripcslashes($string);
  1298. }
  1299. elseif ($quote == "'") { // Simple quote: return as-is
  1300. return $string;
  1301. }
  1302. else {
  1303. return FALSE; // Unrecognized quote
  1304. }
  1305. }
  1306. /**
  1307. * @} End of "locale-api-import-export"
  1308. */
  1309. /**
  1310. * Parses a JavaScript file, extracts strings wrapped in Drupal.t() and
  1311. * Drupal.formatPlural() and inserts them into the database.
  1312. */
  1313. function _locale_parse_js_file($filepath) {
  1314. global $language;
  1315. // The file path might contain a query string, so make sure we only use the
  1316. // actual file.
  1317. $parsed_url = drupal_parse_url($filepath);
  1318. $filepath = $parsed_url['path'];
  1319. // Load the JavaScript file.
  1320. $file = file_get_contents($filepath);

Large files files are truncated, but you can click here to view the full file