PageRenderTime 64ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/locale.inc

http://github.com/drupal/drupal
Pascal | 1917 lines | 863 code | 132 blank | 922 comment | 128 complexity | 64d76f30c6003d5693ea1a48abbcc4cd MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1

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. $options['absolute'] = TRUE;
  383. $options['base_url'] = $options['language']->domain;
  384. }
  385. break;
  386. case LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX:
  387. if (!empty($options['language']->prefix)) {
  388. $options['prefix'] = $options['language']->prefix . '/';
  389. }
  390. break;
  391. }
  392. }
  393. }
  394. /**
  395. * Rewrite URLs for the Session language provider.
  396. */
  397. function locale_language_url_rewrite_session(&$path, &$options) {
  398. static $query_rewrite, $query_param, $query_value;
  399. // The following values are not supposed to change during a single page
  400. // request processing.
  401. if (!isset($query_rewrite)) {
  402. global $user;
  403. if (!$user->uid) {
  404. $languages = language_list('enabled');
  405. $languages = $languages[1];
  406. $query_param = check_plain(variable_get('locale_language_negotiation_session_param', 'language'));
  407. $query_value = isset($_GET[$query_param]) ? check_plain($_GET[$query_param]) : NULL;
  408. $query_rewrite = isset($languages[$query_value]) && language_negotiation_get_any(LOCALE_LANGUAGE_NEGOTIATION_SESSION);
  409. }
  410. else {
  411. $query_rewrite = FALSE;
  412. }
  413. }
  414. // If the user is anonymous, the user language provider is enabled, and the
  415. // corresponding option has been set, we must preserve any explicit user
  416. // language preference even with cookies disabled.
  417. if ($query_rewrite) {
  418. if (is_string($options['query'])) {
  419. $options['query'] = drupal_get_query_array($options['query']);
  420. }
  421. if (!isset($options['query'][$query_param])) {
  422. $options['query'][$query_param] = $query_value;
  423. }
  424. }
  425. }
  426. /**
  427. * @} End of "locale-languages-negotiation"
  428. */
  429. /**
  430. * Check that a string is safe to be added or imported as a translation.
  431. *
  432. * This test can be used to detect possibly bad translation strings. It should
  433. * not have any false positives. But it is only a test, not a transformation,
  434. * as it destroys valid HTML. We cannot reliably filter translation strings
  435. * on import because some strings are irreversibly corrupted. For example,
  436. * a &amp; in the translation would get encoded to &amp;amp; by filter_xss()
  437. * before being put in the database, and thus would be displayed incorrectly.
  438. *
  439. * The allowed tag list is like filter_xss_admin(), but omitting div and img as
  440. * not needed for translation and likely to cause layout issues (div) or a
  441. * possible attack vector (img).
  442. */
  443. function locale_string_is_safe($string) {
  444. 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')));
  445. }
  446. /**
  447. * @defgroup locale-api-add Language addition API
  448. * @{
  449. * Add a language.
  450. *
  451. * The language addition API is used to create languages and store them.
  452. */
  453. /**
  454. * API function to add a language.
  455. *
  456. * @param $langcode
  457. * Language code.
  458. * @param $name
  459. * English name of the language
  460. * @param $native
  461. * Native name of the language
  462. * @param $direction
  463. * LANGUAGE_LTR or LANGUAGE_RTL
  464. * @param $domain
  465. * Optional custom domain name with protocol, without
  466. * trailing slash (eg. http://de.example.com).
  467. * @param $prefix
  468. * Optional path prefix for the language. Defaults to the
  469. * language code if omitted.
  470. * @param $enabled
  471. * Optionally TRUE to enable the language when created or FALSE to disable.
  472. * @param $default
  473. * Optionally set this language to be the default.
  474. */
  475. function locale_add_language($langcode, $name = NULL, $native = NULL, $direction = LANGUAGE_LTR, $domain = '', $prefix = '', $enabled = TRUE, $default = FALSE) {
  476. // Default prefix on language code.
  477. if (empty($prefix)) {
  478. $prefix = $langcode;
  479. }
  480. // If name was not set, we add a predefined language.
  481. if (!isset($name)) {
  482. include_once DRUPAL_ROOT . '/includes/iso.inc';
  483. $predefined = _locale_get_predefined_list();
  484. $name = $predefined[$langcode][0];
  485. $native = isset($predefined[$langcode][1]) ? $predefined[$langcode][1] : $predefined[$langcode][0];
  486. $direction = isset($predefined[$langcode][2]) ? $predefined[$langcode][2] : LANGUAGE_LTR;
  487. }
  488. db_insert('languages')
  489. ->fields(array(
  490. 'language' => $langcode,
  491. 'name' => $name,
  492. 'native' => $native,
  493. 'direction' => $direction,
  494. 'domain' => $domain,
  495. 'prefix' => $prefix,
  496. 'enabled' => $enabled,
  497. ))
  498. ->execute();
  499. // Only set it as default if enabled.
  500. if ($enabled && $default) {
  501. 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' => ''));
  502. }
  503. if ($enabled) {
  504. // Increment enabled language count if we are adding an enabled language.
  505. variable_set('language_count', variable_get('language_count', 1) + 1);
  506. }
  507. // Kill the static cache in language_list().
  508. drupal_static_reset('language_list');
  509. // Force JavaScript translation file creation for the newly added language.
  510. _locale_invalidate_js($langcode);
  511. watchdog('locale', 'The %language language (%code) has been created.', array('%language' => $name, '%code' => $langcode));
  512. module_invoke_all('multilingual_settings_changed');
  513. }
  514. /**
  515. * @} End of "locale-api-add"
  516. */
  517. /**
  518. * @defgroup locale-api-import-export Translation import/export API.
  519. * @{
  520. * Functions to import and export translations.
  521. *
  522. * These functions provide the ability to import translations from
  523. * external files and to export translations and translation templates.
  524. */
  525. /**
  526. * Parses Gettext Portable Object file information and inserts into database
  527. *
  528. * @param $file
  529. * Drupal file object corresponding to the PO file to import.
  530. * @param $langcode
  531. * Language code.
  532. * @param $mode
  533. * Should existing translations be replaced LOCALE_IMPORT_KEEP or
  534. * LOCALE_IMPORT_OVERWRITE.
  535. * @param $group
  536. * Text group to import PO file into (eg. 'default' for interface
  537. * translations).
  538. */
  539. function _locale_import_po($file, $langcode, $mode, $group = NULL) {
  540. // Try to allocate enough time to parse and import the data.
  541. drupal_set_time_limit(240);
  542. // Check if we have the language already in the database.
  543. if (!db_query("SELECT COUNT(language) FROM {languages} WHERE language = :language", array(':language' => $langcode))->fetchField()) {
  544. drupal_set_message(t('The language selected for import is not supported.'), 'error');
  545. return FALSE;
  546. }
  547. // Get strings from file (returns on failure after a partial import, or on success)
  548. $status = _locale_import_read_po('db-store', $file, $mode, $langcode, $group);
  549. if ($status === FALSE) {
  550. // Error messages are set in _locale_import_read_po().
  551. return FALSE;
  552. }
  553. // Get status information on import process.
  554. list($header_done, $additions, $updates, $deletes, $skips) = _locale_import_one_string('db-report');
  555. if (!$header_done) {
  556. drupal_set_message(t('The translation file %filename appears to have a missing or malformed header.', array('%filename' => $file->filename)), 'error');
  557. }
  558. // Clear cache and force refresh of JavaScript translations.
  559. _locale_invalidate_js($langcode);
  560. cache_clear_all('locale:', 'cache', TRUE);
  561. // Rebuild the menu, strings may have changed.
  562. menu_rebuild();
  563. 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)));
  564. 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));
  565. if ($skips) {
  566. $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.');
  567. drupal_set_message($skip_message);
  568. watchdog('locale', '@count disallowed HTML string(s) in %file', array('@count' => $skips, '%file' => $file->uri), WATCHDOG_WARNING);
  569. }
  570. return TRUE;
  571. }
  572. /**
  573. * Parses Gettext Portable Object file into an array
  574. *
  575. * @param $op
  576. * Storage operation type: db-store or mem-store.
  577. * @param $file
  578. * Drupal file object corresponding to the PO file to import.
  579. * @param $mode
  580. * Should existing translations be replaced LOCALE_IMPORT_KEEP or
  581. * LOCALE_IMPORT_OVERWRITE.
  582. * @param $lang
  583. * Language code.
  584. * @param $group
  585. * Text group to import PO file into (eg. 'default' for interface
  586. * translations).
  587. */
  588. function _locale_import_read_po($op, $file, $mode = NULL, $lang = NULL, $group = 'default') {
  589. // The file will get closed by PHP on returning from this function.
  590. $fd = fopen($file->uri, 'rb');
  591. if (!$fd) {
  592. _locale_import_message('The translation import failed, because the file %filename could not be read.', $file);
  593. return FALSE;
  594. }
  595. /*
  596. * The parser context. Can be:
  597. * - 'COMMENT' (#)
  598. * - 'MSGID' (msgid)
  599. * - 'MSGID_PLURAL' (msgid_plural)
  600. * - 'MSGCTXT' (msgctxt)
  601. * - 'MSGSTR' (msgstr or msgstr[])
  602. * - 'MSGSTR_ARR' (msgstr_arg)
  603. */
  604. $context = 'COMMENT';
  605. // Current entry being read.
  606. $current = array();
  607. // Current plurality for 'msgstr[]'.
  608. $plural = 0;
  609. // Current line.
  610. $lineno = 0;
  611. while (!feof($fd)) {
  612. // A line should not be longer than 10 * 1024.
  613. $line = fgets($fd, 10 * 1024);
  614. if ($lineno == 0) {
  615. // The first line might come with a UTF-8 BOM, which should be removed.
  616. $line = str_replace("\xEF\xBB\xBF", '', $line);
  617. }
  618. $lineno++;
  619. // Trim away the linefeed.
  620. $line = trim(strtr($line, array("\\\n" => "")));
  621. if (!strncmp('#', $line, 1)) {
  622. // Lines starting with '#' are comments.
  623. if ($context == 'COMMENT') {
  624. // Already in comment token, insert the comment.
  625. $current['#'][] = substr($line, 1);
  626. }
  627. elseif (($context == 'MSGSTR') || ($context == 'MSGSTR_ARR')) {
  628. // We are currently in string token, close it out.
  629. _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
  630. // Start a new entry for the comment.
  631. $current = array();
  632. $current['#'][] = substr($line, 1);
  633. $context = 'COMMENT';
  634. }
  635. else {
  636. // A comment following any other token is a syntax error.
  637. _locale_import_message('The translation file %filename contains an error: "msgstr" was expected but not found on line %line.', $file, $lineno);
  638. return FALSE;
  639. }
  640. }
  641. elseif (!strncmp('msgid_plural', $line, 12)) {
  642. // A plural form for the current message.
  643. if ($context != 'MSGID') {
  644. // A plural form cannot be added to anything else but the id directly.
  645. _locale_import_message('The translation file %filename contains an error: "msgid_plural" was expected but not found on line %line.', $file, $lineno);
  646. return FALSE;
  647. }
  648. // Remove 'msgid_plural' and trim away whitespace.
  649. $line = trim(substr($line, 12));
  650. // At this point, $line should now contain only the plural form.
  651. $quoted = _locale_import_parse_quoted($line);
  652. if ($quoted === FALSE) {
  653. // The plural form must be wrapped in quotes.
  654. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  655. return FALSE;
  656. }
  657. // Append the plural form to the current entry.
  658. $current['msgid'] .= "\0" . $quoted;
  659. $context = 'MSGID_PLURAL';
  660. }
  661. elseif (!strncmp('msgid', $line, 5)) {
  662. // Starting a new message.
  663. if (($context == 'MSGSTR') || ($context == 'MSGSTR_ARR')) {
  664. // We are currently in a message string, close it out.
  665. _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
  666. // Start a new context for the id.
  667. $current = array();
  668. }
  669. elseif ($context == 'MSGID') {
  670. // We are currently already in the context, meaning we passed an id with no data.
  671. _locale_import_message('The translation file %filename contains an error: "msgid" is unexpected on line %line.', $file, $lineno);
  672. return FALSE;
  673. }
  674. // Remove 'msgid' and trim away whitespace.
  675. $line = trim(substr($line, 5));
  676. // At this point, $line should now contain only the message id.
  677. $quoted = _locale_import_parse_quoted($line);
  678. if ($quoted === FALSE) {
  679. // The message id must be wrapped in quotes.
  680. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  681. return FALSE;
  682. }
  683. $current['msgid'] = $quoted;
  684. $context = 'MSGID';
  685. }
  686. elseif (!strncmp('msgctxt', $line, 7)) {
  687. // Starting a new context.
  688. if (($context == 'MSGSTR') || ($context == 'MSGSTR_ARR')) {
  689. // We are currently in a message, start a new one.
  690. _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
  691. $current = array();
  692. }
  693. elseif (!empty($current['msgctxt'])) {
  694. // A context cannot apply to another context.
  695. _locale_import_message('The translation file %filename contains an error: "msgctxt" is unexpected on line %line.', $file, $lineno);
  696. return FALSE;
  697. }
  698. // Remove 'msgctxt' and trim away whitespaces.
  699. $line = trim(substr($line, 7));
  700. // At this point, $line should now contain the context.
  701. $quoted = _locale_import_parse_quoted($line);
  702. if ($quoted === FALSE) {
  703. // The context string must be quoted.
  704. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  705. return FALSE;
  706. }
  707. $current['msgctxt'] = $quoted;
  708. $context = 'MSGCTXT';
  709. }
  710. elseif (!strncmp('msgstr[', $line, 7)) {
  711. // A message string for a specific plurality.
  712. if (($context != 'MSGID') && ($context != 'MSGCTXT') && ($context != 'MSGID_PLURAL') && ($context != 'MSGSTR_ARR')) {
  713. // Message strings must come after msgid, msgxtxt, msgid_plural, or other msgstr[] entries.
  714. _locale_import_message('The translation file %filename contains an error: "msgstr[]" is unexpected on line %line.', $file, $lineno);
  715. return FALSE;
  716. }
  717. // Ensure the plurality is terminated.
  718. if (strpos($line, ']') === FALSE) {
  719. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  720. return FALSE;
  721. }
  722. // Extract the plurality.
  723. $frombracket = strstr($line, '[');
  724. $plural = substr($frombracket, 1, strpos($frombracket, ']') - 1);
  725. // Skip to the next whitespace and trim away any further whitespace, bringing $line to the message data.
  726. $line = trim(strstr($line, " "));
  727. $quoted = _locale_import_parse_quoted($line);
  728. if ($quoted === FALSE) {
  729. // The string must be quoted.
  730. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  731. return FALSE;
  732. }
  733. $current['msgstr'][$plural] = $quoted;
  734. $context = 'MSGSTR_ARR';
  735. }
  736. elseif (!strncmp("msgstr", $line, 6)) {
  737. // A string for the an id or context.
  738. if (($context != 'MSGID') && ($context != 'MSGCTXT')) {
  739. // Strings are only valid within an id or context scope.
  740. _locale_import_message('The translation file %filename contains an error: "msgstr" is unexpected on line %line.', $file, $lineno);
  741. return FALSE;
  742. }
  743. // Remove 'msgstr' and trim away away whitespaces.
  744. $line = trim(substr($line, 6));
  745. // At this point, $line should now contain the message.
  746. $quoted = _locale_import_parse_quoted($line);
  747. if ($quoted === FALSE) {
  748. // The string must be quoted.
  749. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  750. return FALSE;
  751. }
  752. $current['msgstr'] = $quoted;
  753. $context = 'MSGSTR';
  754. }
  755. elseif ($line != '') {
  756. // Anything that is not a token may be a continuation of a previous token.
  757. $quoted = _locale_import_parse_quoted($line);
  758. if ($quoted === FALSE) {
  759. // The string must be quoted.
  760. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  761. return FALSE;
  762. }
  763. // Append the string to the current context.
  764. if (($context == 'MSGID') || ($context == 'MSGID_PLURAL')) {
  765. $current['msgid'] .= $quoted;
  766. }
  767. elseif ($context == 'MSGCTXT') {
  768. $current['msgctxt'] .= $quoted;
  769. }
  770. elseif ($context == 'MSGSTR') {
  771. $current['msgstr'] .= $quoted;
  772. }
  773. elseif ($context == 'MSGSTR_ARR') {
  774. $current['msgstr'][$plural] .= $quoted;
  775. }
  776. else {
  777. // No valid context to append to.
  778. _locale_import_message('The translation file %filename contains an error: there is an unexpected string on line %line.', $file, $lineno);
  779. return FALSE;
  780. }
  781. }
  782. }
  783. // End of PO file, closed out the last entry.
  784. if (($context == 'MSGSTR') || ($context == 'MSGSTR_ARR')) {
  785. _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
  786. }
  787. elseif ($context != 'COMMENT') {
  788. _locale_import_message('The translation file %filename ended unexpectedly at line %line.', $file, $lineno);
  789. return FALSE;
  790. }
  791. }
  792. /**
  793. * Sets an error message occurred during locale file parsing.
  794. *
  795. * @param $message
  796. * The message to be translated.
  797. * @param $file
  798. * Drupal file object corresponding to the PO file to import.
  799. * @param $lineno
  800. * An optional line number argument.
  801. */
  802. function _locale_import_message($message, $file, $lineno = NULL) {
  803. $vars = array('%filename' => $file->filename);
  804. if (isset($lineno)) {
  805. $vars['%line'] = $lineno;
  806. }
  807. $t = get_t();
  808. drupal_set_message($t($message, $vars), 'error');
  809. }
  810. /**
  811. * Imports a string into the database
  812. *
  813. * @param $op
  814. * Operation to perform: 'db-store', 'db-report', 'mem-store' or 'mem-report'.
  815. * @param $value
  816. * Details of the string stored.
  817. * @param $mode
  818. * Should existing translations be replaced LOCALE_IMPORT_KEEP or
  819. * LOCALE_IMPORT_OVERWRITE.
  820. * @param $lang
  821. * Language to store the string in.
  822. * @param $file
  823. * Object representation of file being imported, only required when op is
  824. * 'db-store'.
  825. * @param $group
  826. * Text group to import PO file into (eg. 'default' for interface
  827. * translations).
  828. */
  829. function _locale_import_one_string($op, $value = NULL, $mode = NULL, $lang = NULL, $file = NULL, $group = 'default') {
  830. $report = &drupal_static(__FUNCTION__, array('additions' => 0, 'updates' => 0, 'deletes' => 0, 'skips' => 0));
  831. $header_done = &drupal_static(__FUNCTION__ . ':header_done', FALSE);
  832. $strings = &drupal_static(__FUNCTION__ . ':strings', array());
  833. switch ($op) {
  834. // Return stored strings
  835. case 'mem-report':
  836. return $strings;
  837. // Store string in memory (only supports single strings)
  838. case 'mem-store':
  839. $strings[isset($value['msgctxt']) ? $value['msgctxt'] : ''][$value['msgid']] = $value['msgstr'];
  840. return;
  841. // Called at end of import to inform the user
  842. case 'db-report':
  843. return array($header_done, $report['additions'], $report['updates'], $report['deletes'], $report['skips']);
  844. // Store the string we got in the database.
  845. case 'db-store':
  846. // We got header information.
  847. if ($value['msgid'] == '') {
  848. $languages = language_list();
  849. if (($mode != LOCALE_IMPORT_KEEP) || empty($languages[$lang]->plurals)) {
  850. // Since we only need to parse the header if we ought to update the
  851. // plural formula, only run this if we don't need to keep existing
  852. // data untouched or if we don't have an existing plural formula.
  853. $header = _locale_import_parse_header($value['msgstr']);
  854. // Get the plural formula and update in database.
  855. if (isset($header["Plural-Forms"]) && $p = _locale_import_parse_plural_forms($header["Plural-Forms"], $file->uri)) {
  856. list($nplurals, $plural) = $p;
  857. db_update('languages')
  858. ->fields(array(
  859. 'plurals' => $nplurals,
  860. 'formula' => $plural,
  861. ))
  862. ->condition('language', $lang)
  863. ->execute();
  864. }
  865. else {
  866. db_update('languages')
  867. ->fields(array(
  868. 'plurals' => 0,
  869. 'formula' => '',
  870. ))
  871. ->condition('language', $lang)
  872. ->execute();
  873. }
  874. }
  875. $header_done = TRUE;
  876. }
  877. else {
  878. // Some real string to import.
  879. $comments = _locale_import_shorten_comments(empty($value['#']) ? array() : $value['#']);
  880. if (strpos($value['msgid'], "\0")) {
  881. // This string has plural versions.
  882. $english = explode("\0", $value['msgid'], 2);
  883. $entries = array_keys($value['msgstr']);
  884. for ($i = 3; $i <= count($entries); $i++) {
  885. $english[] = $english[1];
  886. }
  887. $translation = array_map('_locale_import_append_plural', $value['msgstr'], $entries);
  888. $english = array_map('_locale_import_append_plural', $english, $entries);
  889. foreach ($translation as $key => $trans) {
  890. if ($key == 0) {
  891. $plid = 0;
  892. }
  893. $plid = _locale_import_one_string_db($report, $lang, isset($value['msgctxt']) ? $value['msgctxt'] : '', $english[$key], $trans, $group, $comments, $mode, $plid, $key);
  894. }
  895. }
  896. else {
  897. // A simple string to import.
  898. $english = $value['msgid'];
  899. $translation = $value['msgstr'];
  900. _locale_import_one_string_db($report, $lang, isset($value['msgctxt']) ? $value['msgctxt'] : '', $english, $translation, $group, $comments, $mode);
  901. }
  902. }
  903. } // end of db-store operation
  904. }
  905. /**
  906. * Import one string into the database.
  907. *
  908. * @param $report
  909. * Report array summarizing the number of changes done in the form:
  910. * array(inserts, updates, deletes).
  911. * @param $langcode
  912. * Language code to import string into.
  913. * @param $context
  914. * The context of this string.
  915. * @param $source
  916. * Source string.
  917. * @param $translation
  918. * Translation to language specified in $langcode.
  919. * @param $textgroup
  920. * Name of textgroup to store translation in.
  921. * @param $location
  922. * Location value to save with source string.
  923. * @param $mode
  924. * Import mode to use, LOCALE_IMPORT_KEEP or LOCALE_IMPORT_OVERWRITE.
  925. * @param $plid
  926. * Optional plural ID to use.
  927. * @param $plural
  928. * Optional plural value to use.
  929. *
  930. * @return
  931. * The string ID of the existing string modified or the new string added.
  932. */
  933. function _locale_import_one_string_db(&$report, $langcode, $context, $source, $translation, $textgroup, $location, $mode, $plid = 0, $plural = 0) {
  934. $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();
  935. if (!empty($translation)) {
  936. // Skip this string unless it passes a check for dangerous code.
  937. // Text groups other than default still can contain HTML tags
  938. // (i.e. translatable blocks).
  939. if ($textgroup == "default" && !locale_string_is_safe($translation)) {
  940. $report['skips']++;
  941. $lid = 0;
  942. }
  943. elseif ($lid) {
  944. // We have this source string saved already.
  945. db_update('locales_source')
  946. ->fields(array(
  947. 'location' => $location,
  948. ))
  949. ->condition('lid', $lid)
  950. ->execute();
  951. $exists = db_query("SELECT COUNT(lid) FROM {locales_target} WHERE lid = :lid AND language = :language", array(':lid' => $lid, ':language' => $langcode))->fetchField();
  952. if (!$exists) {
  953. // No translation in this language.
  954. db_insert('locales_target')
  955. ->fields(array(
  956. 'lid' => $lid,
  957. 'language' => $langcode,
  958. 'translation' => $translation,
  959. 'plid' => $plid,
  960. 'plural' => $plural,
  961. ))
  962. ->execute();
  963. $report['additions']++;
  964. }
  965. elseif ($mode == LOCALE_IMPORT_OVERWRITE) {
  966. // Translation exists, only overwrite if instructed.
  967. db_update('locales_target')
  968. ->fields(array(
  969. 'translation' => $translation,
  970. 'plid' => $plid,
  971. 'plural' => $plural,
  972. ))
  973. ->condition('language', $langcode)
  974. ->condition('lid', $lid)
  975. ->execute();
  976. $report['updates']++;
  977. }
  978. }
  979. else {
  980. // No such source string in the database yet.
  981. $lid = db_insert('locales_source')
  982. ->fields(array(
  983. 'location' => $location,
  984. 'source' => $source,
  985. 'context' => (string) $context,
  986. 'textgroup' => $textgroup,
  987. ))
  988. ->execute();
  989. db_insert('locales_target')
  990. ->fields(array(
  991. 'lid' => $lid,
  992. 'language' => $langcode,
  993. 'translation' => $translation,
  994. 'plid' => $plid,
  995. 'plural' => $plural
  996. ))
  997. ->execute();
  998. $report['additions']++;
  999. }
  1000. }
  1001. elseif ($mode == LOCALE_IMPORT_OVERWRITE) {
  1002. // Empty translation, remove existing if instructed.
  1003. db_delete('locales_target')
  1004. ->condition('language', $langcode)
  1005. ->condition('lid', $lid)
  1006. ->condition('plid', $plid)
  1007. ->condition('plural', $plural)
  1008. ->execute();
  1009. $report['deletes']++;
  1010. }
  1011. return $lid;
  1012. }
  1013. /**
  1014. * Parses a Gettext Portable Object file header
  1015. *
  1016. * @param $header
  1017. * A string containing the complete header.
  1018. *
  1019. * @return
  1020. * An associative array of key-value pairs.
  1021. */
  1022. function _locale_import_parse_header($header) {
  1023. $header_parsed = array();
  1024. $lines = array_map('trim', explode("\n", $header));
  1025. foreach ($lines as $line) {
  1026. if ($line) {
  1027. list($tag, $contents) = explode(":", $line, 2);
  1028. $header_parsed[trim($tag)] = trim($contents);
  1029. }
  1030. }
  1031. return $header_parsed;
  1032. }
  1033. /**
  1034. * Parses a Plural-Forms entry from a Gettext Portable Object file header
  1035. *
  1036. * @param $pluralforms
  1037. * A string containing the Plural-Forms entry.
  1038. * @param $filepath
  1039. * A string containing the filepath.
  1040. *
  1041. * @return
  1042. * An array containing the number of plurals and a
  1043. * formula in PHP for computing the plural form.
  1044. */
  1045. function _locale_import_parse_plural_forms($pluralforms, $filepath) {
  1046. // First, delete all whitespace
  1047. $pluralforms = strtr($pluralforms, array(" " => "", "\t" => ""));
  1048. // Select the parts that define nplurals and plural
  1049. $nplurals = strstr($pluralforms, "nplurals=");
  1050. if (strpos($nplurals, ";")) {
  1051. $nplurals = substr($nplurals, 9, strpos($nplurals, ";") - 9);
  1052. }
  1053. else {
  1054. return FALSE;
  1055. }
  1056. $plural = strstr($pluralforms, "plural=");
  1057. if (strpos($plural, ";")) {
  1058. $plural = substr($plural, 7, strpos($plural, ";") - 7);
  1059. }
  1060. else {
  1061. return FALSE;
  1062. }
  1063. // Get PHP version of the plural formula
  1064. $plural = _locale_import_parse_arithmetic($plural);
  1065. if ($plural !== FALSE) {
  1066. return array($nplurals, $plural);
  1067. }
  1068. else {
  1069. drupal_set_message(t('The translation file %filepath contains an error: the plural formula could not be parsed.', array('%filepath' => $filepath)), 'error');
  1070. return FALSE;
  1071. }
  1072. }
  1073. /**
  1074. * Parses and sanitizes an arithmetic formula into a PHP expression
  1075. *
  1076. * While parsing, we ensure, that the operators have the right
  1077. * precedence and associativity.
  1078. *
  1079. * @param $string
  1080. * A string containing the arithmetic formula.
  1081. *
  1082. * @return
  1083. * The PHP version of the formula.
  1084. */
  1085. function _locale_import_parse_arithmetic($string) {
  1086. // Operator precedence table
  1087. $precedence = array("(" => -1, ")" => -1, "?" => 1, ":" => 1, "||" => 3, "&&" => 4, "==" => 5, "!=" => 5, "<" => 6, ">" => 6, "<=" => 6, ">=" => 6, "+" => 7, "-" => 7, "*" => 8, "/" => 8, "%" => 8);
  1088. // Right associativity
  1089. $right_associativity = array("?" => 1, ":" => 1);
  1090. $tokens = _locale_import_tokenize_formula($string);
  1091. // Parse by converting into infix notation then back into postfix
  1092. // Operator stack - holds math operators and symbols
  1093. $operator_stack = array();
  1094. // Element Stack - holds data to be operated on
  1095. $element_stack = array();
  1096. foreach ($tokens as $token) {
  1097. $current_token = $token;
  1098. // Numbers and the $n variable are simply pushed into $element_stack
  1099. if (is_numeric($token)) {
  1100. $element_stack[] = $current_token;
  1101. }
  1102. elseif ($current_token == "n") {
  1103. $element_stack[] = '$n';
  1104. }
  1105. elseif ($current_token == "(") {
  1106. $operator_stack[] = $current_token;
  1107. }
  1108. elseif ($current_token == ")") {
  1109. $topop = array_pop($operator_stack);
  1110. while (isset($topop) && ($topop != "(")) {
  1111. $element_stack[] = $topop;
  1112. $topop = array_pop($operator_stack);
  1113. }
  1114. }
  1115. elseif (!empty($precedence[$current_token])) {
  1116. // If it's an operator, then pop from $operator_stack into $element_stack until the
  1117. // precedence in $operator_stack is less than current, then push into $operator_stack
  1118. $topop = array_pop($operator_stack);
  1119. while (isset($topop) && ($precedence[$topop] >= $precedence[$current_token]) && !(($precedence[$topop] == $precedence[$current_token]) && !empty($right_associativity[$topop]) && !empty($right_associativity[$current_token]))) {
  1120. $element_stack[] = $topop;
  1121. $topop = array_pop($operator_stack);
  1122. }
  1123. if ($topop) {
  1124. $operator_stack[] = $topop; // Return element to top
  1125. }
  1126. $operator_stack[] = $current_token; // Parentheses are not needed
  1127. }
  1128. else {
  1129. return FALSE;
  1130. }
  1131. }
  1132. // Flush operator stack
  1133. $topop = array_pop($operator_stack);
  1134. while ($topop != NULL) {
  1135. $element_stack[] = $topop;
  1136. $topop = array_pop($operator_stack);
  1137. }
  1138. // Now extract formula from stack
  1139. $previous_size = count($element_stack) + 1;
  1140. while (count($element_stack) < $previous_size) {
  1141. $previous_size = count($element_stack);
  1142. for ($i = 2; $i < count($element_stack); $i++) {
  1143. $op = $element_stack[$i];
  1144. if (!empty($precedence[$op])) {
  1145. $f = "";
  1146. if ($op == ":") {
  1147. $f = $element_stack[$i - 2] . "):" . $element_stack[$i - 1] . ")";
  1148. }
  1149. elseif ($op == "?") {
  1150. $f = "(" . $element_stack[$i - 2] . "?(" . $element_stack[$i - 1];
  1151. }
  1152. else {
  1153. $f = "(" . $element_stack[$i - 2] . $op . $element_stack[$i - 1] . ")";
  1154. }
  1155. array_splice($element_stack, $i - 2, 3, $f);
  1156. break;
  1157. }
  1158. }
  1159. }
  1160. // If only one element is left, the number of operators is appropriate
  1161. if (count($element_stack) == 1) {
  1162. return $element_stack[0];
  1163. }
  1164. else {
  1165. return FALSE;
  1166. }
  1167. }
  1168. /**
  1169. * Backward compatible implementation of token_get_all() for formula parsing
  1170. *
  1171. * @param $string
  1172. * A string containing the arithmetic formula.
  1173. *
  1174. * @return
  1175. * The PHP version of the formula.
  1176. */
  1177. function _locale_import_tokenize_formula($formula) {
  1178. $formula = str_replace(" ", "", $formula);
  1179. $tokens = array();
  1180. for ($i = 0; $i < strlen($formula); $i++) {
  1181. if (is_numeric($formula[$i])) {
  1182. $num = $formula[$i];
  1183. $j = $i + 1;
  1184. while ($j < strlen($formula) && is_numeric($formula[$j])) {
  1185. $num .= $formula[$j];
  1186. $j++;
  1187. }
  1188. $i = $j - 1;
  1189. $tokens[] = $num;
  1190. }
  1191. elseif ($pos = strpos(" =<>!&|", $formula[$i])) { // We won't have a space
  1192. $next = $formula[$i + 1];
  1193. switch ($pos) {
  1194. case 1:
  1195. case 2:
  1196. case 3:
  1197. case 4:
  1198. if ($next == '=') {
  1199. $tokens[] = $formula[$i] . '=';
  1200. $i++;
  1201. }
  1202. else {
  1203. $tokens[] = $formula[$i];
  1204. }
  1205. break;
  1206. case 5:
  1207. if ($next == '&') {
  1208. $tokens[] = '&&';
  1209. $i++;
  1210. }
  1211. else {
  1212. $tokens[] = $formula[$i];
  1213. }
  1214. break;
  1215. case 6:
  1216. if ($next == '|') {
  1217. $tokens[] = '||';
  1218. $i++;
  1219. }
  1220. else {
  1221. $tokens[] = $formula[$i];
  1222. }
  1223. break;
  1224. }
  1225. }
  1226. else {
  1227. $tokens[] = $formula[$i];
  1228. }
  1229. }
  1230. return $tokens;
  1231. }
  1232. /**
  1233. * Modify a string to contain proper count indices
  1234. *
  1235. * This is a callback function used via array_map()
  1236. *
  1237. * @param $entry
  1238. * An array element.
  1239. * @param $key
  1240. * Index of the array element.
  1241. */
  1242. function _locale_import_append_plural($entry, $key) {
  1243. // No modifications for 0, 1
  1244. if ($key == 0 || $key == 1) {
  1245. return $entry;
  1246. }
  1247. // First remove any possibly false indices, then add new ones
  1248. $entry = preg_replace('/(@count)\[[0-9]\]/', '\\1', $entry);
  1249. return preg_replace('/(@count)/', "\\1[$key]", $entry);
  1250. }
  1251. /**
  1252. * Generate a short, one string version of the passed comment array
  1253. *
  1254. * @param $comment
  1255. * An array of strings containing a comment.
  1256. *
  1257. * @return
  1258. * Short one string version of the comment.
  1259. */
  1260. function _locale_import_shorten_comments($comment) {
  1261. $comm = '';
  1262. while (count($comment)) {
  1263. $test = $comm . substr(array_shift($comment), 1) . ', ';
  1264. if (strlen($comm) < 130) {
  1265. $comm = $test;
  1266. }
  1267. else {
  1268. break;
  1269. }
  1270. }
  1271. return trim(substr($comm, 0, -2));
  1272. }
  1273. /**
  1274. * Parses a string in quotes
  1275. *
  1276. * @param $string
  1277. * A string specified with enclosing quotes.
  1278. *
  1279. * @return
  1280. * The string parsed from inside the quotes.
  1281. */
  1282. function _locale_import_parse_quoted($string) {
  1283. if (substr($string, 0, 1) != substr($string, -1, 1)) {
  1284. return FALSE; // Start and end quotes must be the same
  1285. }
  1286. $quote = substr($string, 0, 1);
  1287. $string = substr($string, 1, -1);
  1288. if ($quote == '"') { // Double quotes: strip slashes
  1289. return stripcslashes($string);
  1290. }
  1291. elseif ($quote == "'") { // Simple quote: return as-is
  1292. return $string;
  1293. }
  1294. else {
  1295. return FALSE; // Unrecognized quote
  1296. }
  1297. }
  1298. /**
  1299. * @} End of "locale-api-import-export"
  1300. */
  1301. /**
  1302. * Parses a JavaScript file, extracts strings wrapped in Drupal.t() and
  1303. * Drupal.formatPlural() and inserts them into the database.
  1304. */
  1305. function _locale_parse_js_file($filepath) {
  1306. global $language;
  1307. // The file path might contain a query string, so make sure we only use the
  1308. // actual file.
  1309. $parsed_url = drupal_parse_url($filepath);
  1310. $filepath = $parsed_url['path'];
  1311. // Load the JavaScript file.
  1312. $file = file_get_contents($filepath);
  1313. // Match all calls to Drupal.t() in an array.
  1314. // Note: \s also matches newlines with the 's' modifier.
  1315. preg_match_all('~
  1316. [^\w]Drupal\s*\.\s*t\s* # match "Drupal.t" with whitespace
  1317. \(\s* # match "(" argument list start
  1318. (' . LOCALE_JS_STRING . ')\s* # capture string argument
  1319. (?:,\s*' . LOCALE_JS_OBJECT . '\s* # optionally capture str args
  1320. (?:,\s*' . LOCALE_JS_OBJECT_CONTEXT . '\s*) # optionally capture context
  1321. ?)? # close optional args
  1322. [,\)] # match ")" or "," to finish
  1323. ~sx', $file, $t_matches);
  1324. /

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