locale.inc

Administration functions for locale.module.

Archivo

drupal-6.x/includes/locale.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Administration functions for locale.module.
  5. */
  6. define('LOCALE_JS_STRING', '(?:(?:\'(?:\\\\\'|[^\'])*\'|"(?:\\\\"|[^"])*")(?:\s*\+\s*)?)+');
  7. /**
  8. * Translation import mode overwriting all existing translations
  9. * if new translated version available.
  10. */
  11. define('LOCALE_IMPORT_OVERWRITE', 0);
  12. /**
  13. * Translation import mode keeping existing translations and only
  14. * inserting new strings.
  15. */
  16. define('LOCALE_IMPORT_KEEP', 1);
  17. /**
  18. * @defgroup locale-language-overview Language overview functionality
  19. * @{
  20. */
  21. /**
  22. * User interface for the language overview screen.
  23. */
  24. function locale_languages_overview_form() {
  25. $languages = language_list('language', TRUE);
  26. $options = array();
  27. $form['weight'] = array('#tree' => TRUE);
  28. foreach ($languages as $langcode => $language) {
  29. // Language code should contain no markup, but is emitted
  30. // by radio and checkbox options.
  31. $langcode = check_plain($langcode);
  32. $options[$langcode] = '';
  33. if ($language->enabled) {
  34. $enabled[] = $langcode;
  35. }
  36. $form['weight'][$langcode] = array(
  37. '#type' => 'weight',
  38. '#default_value' => $language->weight
  39. );
  40. $form['name'][$langcode] = array('#value' => check_plain($language->name));
  41. $form['native'][$langcode] = array('#value' => check_plain($language->native));
  42. $form['direction'][$langcode] = array('#value' => ($language->direction == LANGUAGE_RTL ? t('Right to left') : t('Left to right')));
  43. }
  44. $form['enabled'] = array('#type' => 'checkboxes',
  45. '#options' => $options,
  46. '#default_value' => $enabled,
  47. );
  48. $form['site_default'] = array('#type' => 'radios',
  49. '#options' => $options,
  50. '#default_value' => language_default('language'),
  51. );
  52. $form['submit'] = array('#type' => 'submit', '#value' => t('Save configuration'));
  53. $form['#theme'] = 'locale_languages_overview_form';
  54. return $form;
  55. }
  56. /**
  57. * Theme the language overview form.
  58. *
  59. * @ingroup themeable
  60. */
  61. function theme_locale_languages_overview_form($form) {
  62. $default = language_default();
  63. foreach ($form['name'] as $key => $element) {
  64. // Do not take form control structures.
  65. if (is_array($element) && element_child($key)) {
  66. // Disable checkbox for the default language, because it cannot be disabled.
  67. if ($key == $default->language) {
  68. $form['enabled'][$key]['#attributes']['disabled'] = 'disabled';
  69. }
  70. $rows[] = array(
  71. array('data' => drupal_render($form['enabled'][$key]), 'align' => 'center'),
  72. check_plain($key),
  73. '<strong>'. drupal_render($form['name'][$key]) .'</strong>',
  74. drupal_render($form['native'][$key]),
  75. drupal_render($form['direction'][$key]),
  76. drupal_render($form['site_default'][$key]),
  77. drupal_render($form['weight'][$key]),
  78. l(t('edit'), 'admin/settings/language/edit/'. $key) . (($key != 'en' && $key != $default->language) ? ' '. l(t('delete'), 'admin/settings/language/delete/'. $key) : '')
  79. );
  80. }
  81. }
  82. $header = array(array('data' => t('Enabled')), array('data' => t('Code')), array('data' => t('English name')), array('data' => t('Native name')), array('data' => t('Direction')), array('data' => t('Default')), array('data' => t('Weight')), array('data' => t('Operations')));
  83. $output = theme('table', $header, $rows);
  84. $output .= drupal_render($form);
  85. return $output;
  86. }
  87. /**
  88. * Process language overview form submissions, updating existing languages.
  89. */
  90. function locale_languages_overview_form_submit($form, &$form_state) {
  91. $languages = language_list();
  92. $default = language_default();
  93. $enabled_count = 0;
  94. foreach ($languages as $langcode => $language) {
  95. if ($form_state['values']['site_default'] == $langcode || $default->language == $langcode) {
  96. // Automatically enable the default language and the language
  97. // which was default previously (because we will not get the
  98. // value from that disabled checkox).
  99. $form_state['values']['enabled'][$langcode] = 1;
  100. }
  101. if ($form_state['values']['enabled'][$langcode]) {
  102. $enabled_count++;
  103. $language->enabled = 1;
  104. }
  105. else {
  106. $language->enabled = 0;
  107. }
  108. $language->weight = $form_state['values']['weight'][$langcode];
  109. db_query("UPDATE {languages} SET enabled = %d, weight = %d WHERE language = '%s'", $language->enabled, $language->weight, $langcode);
  110. $languages[$langcode] = $language;
  111. }
  112. drupal_set_message(t('Configuration saved.'));
  113. variable_set('language_default', $languages[$form_state['values']['site_default']]);
  114. variable_set('language_count', $enabled_count);
  115. // Changing the language settings impacts the interface.
  116. cache_clear_all('*', 'cache_page', TRUE);
  117. $form_state['redirect'] = 'admin/settings/language';
  118. return;
  119. }
  120. /**
  121. * @} End of "locale-language-overview"
  122. */
  123. /**
  124. * @defgroup locale-language-add-edit Language addition and editing functionality
  125. * @{
  126. */
  127. /**
  128. * User interface for the language addition screen.
  129. */
  130. function locale_languages_add_screen() {
  131. $output = drupal_get_form('locale_languages_predefined_form');
  132. $output .= drupal_get_form('locale_languages_custom_form');
  133. return $output;
  134. }
  135. /**
  136. * Predefined language setup form.
  137. */
  138. function locale_languages_predefined_form() {
  139. $predefined = _locale_prepare_predefined_list();
  140. $form = array();
  141. $form['language list'] = array('#type' => 'fieldset',
  142. '#title' => t('Predefined language'),
  143. '#collapsible' => TRUE,
  144. );
  145. $form['language list']['langcode'] = array('#type' => 'select',
  146. '#title' => t('Language name'),
  147. '#default_value' => key($predefined),
  148. '#options' => $predefined,
  149. '#description' => t('Select the desired language and click the <em>Add language</em> button. (Use the <em>Custom language</em> options if your desired language does not appear in this list.)'),
  150. );
  151. $form['language list']['submit'] = array('#type' => 'submit', '#value' => t('Add language'));
  152. return $form;
  153. }
  154. /**
  155. * Custom language addition form.
  156. */
  157. function locale_languages_custom_form() {
  158. $form = array();
  159. $form['custom language'] = array('#type' => 'fieldset',
  160. '#title' => t('Custom language'),
  161. '#collapsible' => TRUE,
  162. '#collapsed' => TRUE,
  163. );
  164. _locale_languages_common_controls($form['custom language']);
  165. $form['custom language']['submit'] = array(
  166. '#type' => 'submit',
  167. '#value' => t('Add custom language')
  168. );
  169. // Reuse the validation and submit functions of the predefined language setup form.
  170. $form['#submit'][] = 'locale_languages_predefined_form_submit';
  171. $form['#validate'][] = 'locale_languages_predefined_form_validate';
  172. return $form;
  173. }
  174. /**
  175. * Editing screen for a particular language.
  176. *
  177. * @param $langcode
  178. * Language code of the language to edit.
  179. */
  180. function locale_languages_edit_form(&$form_state, $langcode) {
  181. if ($language = db_fetch_object(db_query("SELECT * FROM {languages} WHERE language = '%s'", $langcode))) {
  182. $form = array();
  183. _locale_languages_common_controls($form, $language);
  184. $form['submit'] = array(
  185. '#type' => 'submit',
  186. '#value' => t('Save language')
  187. );
  188. $form['#submit'][] = 'locale_languages_edit_form_submit';
  189. $form['#validate'][] = 'locale_languages_edit_form_validate';
  190. return $form;
  191. }
  192. else {
  193. drupal_not_found();
  194. }
  195. }
  196. /**
  197. * Common elements of the language addition and editing form.
  198. *
  199. * @param $form
  200. * A parent form item (or empty array) to add items below.
  201. * @param $language
  202. * Language object to edit.
  203. */
  204. function _locale_languages_common_controls(&$form, $language = NULL) {
  205. if (!is_object($language)) {
  206. $language = new stdClass();
  207. }
  208. if (isset($language->language)) {
  209. $form['langcode_view'] = array(
  210. '#type' => 'item',
  211. '#title' => t('Language code'),
  212. '#value' => $language->language
  213. );
  214. $form['langcode'] = array(
  215. '#type' => 'value',
  216. '#value' => $language->language
  217. );
  218. }
  219. else {
  220. $form['langcode'] = array('#type' => 'textfield',
  221. '#title' => t('Language code'),
  222. '#size' => 12,
  223. '#maxlength' => 60,
  224. '#required' => TRUE,
  225. '#default_value' => @$language->language,
  226. '#disabled' => (isset($language->language)),
  227. '#description' => t('<a href="@rfc4646">RFC 4646</a> compliant language identifier. Language codes typically use a country code, and optionally, a script or regional variant name. <em>Examples: "en", "en-US" and "zh-Hant".</em>', array('@rfc4646' => 'http://www.ietf.org/rfc/rfc4646.txt')),
  228. );
  229. }
  230. $form['name'] = array('#type' => 'textfield',
  231. '#title' => t('Language name in English'),
  232. '#maxlength' => 64,
  233. '#default_value' => @$language->name,
  234. '#required' => TRUE,
  235. '#description' => t('Name of the language in English. Will be available for translation in all languages.'),
  236. );
  237. $form['native'] = array('#type' => 'textfield',
  238. '#title' => t('Native language name'),
  239. '#maxlength' => 64,
  240. '#default_value' => @$language->native,
  241. '#required' => TRUE,
  242. '#description' => t('Name of the language in the language being added.'),
  243. );
  244. $form['prefix'] = array('#type' => 'textfield',
  245. '#title' => t('Path prefix'),
  246. '#maxlength' => 64,
  247. '#default_value' => @$language->prefix,
  248. '#description' => t('Language code or other custom string for pattern matching within the path. With language negotiation set to <em>Path prefix only</em> or <em>Path prefix with language fallback</em>, this site is presented in this language when the Path prefix value matches an element in the path. For the default language, this value may be left blank. <strong>Modifying this value will break existing URLs and should be used with caution in a production environment.</strong> <em>Example: Specifying "deutsch" as the path prefix for German results in URLs in the form "www.example.com/deutsch/node".</em>')
  249. );
  250. $form['domain'] = array('#type' => 'textfield',
  251. '#title' => t('Language domain'),
  252. '#maxlength' => 128,
  253. '#default_value' => @$language->domain,
  254. '#description' => t('Language-specific URL, with protocol. With language negotiation set to <em>Domain name only</em>, the site is presented in this language when the URL accessing the site references this domain. For the default language, this value may be left blank. <strong>This value must include a protocol as part of the string.</strong> <em>Example: Specifying "http://example.de" or "http://de.example.com" as language domains for German results in URLs in the forms "http://example.de/node" and "http://de.example.com/node", respectively.</em>'),
  255. );
  256. $form['direction'] = array('#type' => 'radios',
  257. '#title' => t('Direction'),
  258. '#required' => TRUE,
  259. '#description' => t('Direction that text in this language is presented.'),
  260. '#default_value' => @$language->direction,
  261. '#options' => array(LANGUAGE_LTR => t('Left to right'), LANGUAGE_RTL => t('Right to left'))
  262. );
  263. return $form;
  264. }
  265. /**
  266. * Validate the language addition form.
  267. */
  268. function locale_languages_predefined_form_validate($form, &$form_state) {
  269. $langcode = $form_state['values']['langcode'];
  270. if ($duplicate = db_result(db_query("SELECT COUNT(*) FROM {languages} WHERE language = '%s'", $langcode)) != 0) {
  271. form_set_error('langcode', t('The language %language (%code) already exists.', array('%language' => $form_state['values']['name'], '%code' => $langcode)));
  272. }
  273. if (!isset($form_state['values']['name'])) {
  274. // Predefined language selection.
  275. $predefined = _locale_get_predefined_list();
  276. if (!isset($predefined[$langcode])) {
  277. form_set_error('langcode', t('Invalid language code.'));
  278. }
  279. }
  280. else {
  281. // Reuse the editing form validation routine if we add a custom language.
  282. locale_languages_edit_form_validate($form, $form_state);
  283. }
  284. }
  285. /**
  286. * Process the language addition form submission.
  287. */
  288. function locale_languages_predefined_form_submit($form, &$form_state) {
  289. $langcode = $form_state['values']['langcode'];
  290. if (isset($form_state['values']['name'])) {
  291. // Custom language form.
  292. locale_add_language($langcode, $form_state['values']['name'], $form_state['values']['native'], $form_state['values']['direction'], $form_state['values']['domain'], $form_state['values']['prefix']);
  293. drupal_set_message(t('The language %language has been created and can now be used. More information is available on the <a href="@locale-help">help screen</a>.', array('%language' => t($form_state['values']['name']), '@locale-help' => url('admin/help/locale'))));
  294. }
  295. else {
  296. // Predefined language selection.
  297. $predefined = _locale_get_predefined_list();
  298. locale_add_language($langcode);
  299. drupal_set_message(t('The language %language has been created and can now be used. More information is available on the <a href="@locale-help">help screen</a>.', array('%language' => t($predefined[$langcode][0]), '@locale-help' => url('admin/help/locale'))));
  300. }
  301. // See if we have language files to import for the newly added
  302. // language, collect and import them.
  303. if ($batch = locale_batch_by_language($langcode, '_locale_batch_language_finished')) {
  304. batch_set($batch);
  305. }
  306. $form_state['redirect'] = 'admin/settings/language';
  307. return;
  308. }
  309. /**
  310. * Validate the language editing form. Reused for custom language addition too.
  311. */
  312. function locale_languages_edit_form_validate($form, &$form_state) {
  313. // Validate that the name, native, and langcode variables are safe.
  314. if (preg_match('/["<>\']/', $form_state['values']['langcode'])) {
  315. form_set_error('langcode', t('The characters &lt;, &gt;, " and \' are not allowed in the language code field.'));
  316. }
  317. if (preg_match('/["<>\']/', $form_state['values']['name'])) {
  318. form_set_error('name', t('The characters &lt;, &gt;, " and \' are not allowed in the language name in English field.'));
  319. }
  320. if (preg_match('/["<>\']/', $form_state['values']['native'])) {
  321. form_set_error('native', t('The characters &lt;, &gt;, " and \' are not allowed in the native language name field.'));
  322. }
  323. if (!empty($form_state['values']['domain']) && !empty($form_state['values']['prefix'])) {
  324. form_set_error('prefix', t('Domain and path prefix values should not be set at the same time.'));
  325. }
  326. if (!empty($form_state['values']['domain']) && $duplicate = db_fetch_object(db_query("SELECT language FROM {languages} WHERE domain = '%s' AND language != '%s'", $form_state['values']['domain'], $form_state['values']['langcode']))) {
  327. form_set_error('domain', t('The domain (%domain) is already tied to a language (%language).', array('%domain' => $form_state['values']['domain'], '%language' => $duplicate->language)));
  328. }
  329. if (empty($form_state['values']['prefix']) && language_default('language') != $form_state['values']['langcode'] && empty($form_state['values']['domain'])) {
  330. form_set_error('prefix', t('Only the default language can have both the domain and prefix empty.'));
  331. }
  332. if (!empty($form_state['values']['prefix']) && $duplicate = db_fetch_object(db_query("SELECT language FROM {languages} WHERE prefix = '%s' AND language != '%s'", $form_state['values']['prefix'], $form_state['values']['langcode']))) {
  333. form_set_error('prefix', t('The prefix (%prefix) is already tied to a language (%language).', array('%prefix' => $form_state['values']['prefix'], '%language' => $duplicate->language)));
  334. }
  335. }
  336. /**
  337. * Process the language editing form submission.
  338. */
  339. function locale_languages_edit_form_submit($form, &$form_state) {
  340. db_query("UPDATE {languages} SET name = '%s', native = '%s', domain = '%s', prefix = '%s', direction = %d WHERE language = '%s'", $form_state['values']['name'], $form_state['values']['native'], $form_state['values']['domain'], $form_state['values']['prefix'], $form_state['values']['direction'], $form_state['values']['langcode']);
  341. $default = language_default();
  342. if ($default->language == $form_state['values']['langcode']) {
  343. $properties = array('name', 'native', 'direction', 'enabled', 'plurals', 'formula', 'domain', 'prefix', 'weight');
  344. foreach ($properties as $keyname) {
  345. if (isset($form_state['values'][$keyname])) {
  346. $default->$keyname = $form_state['values'][$keyname];
  347. }
  348. }
  349. variable_set('language_default', $default);
  350. }
  351. $form_state['redirect'] = 'admin/settings/language';
  352. return;
  353. }
  354. /**
  355. * @} End of "locale-language-add-edit"
  356. */
  357. /**
  358. * @defgroup locale-language-delete Language deletion functionality
  359. * @{
  360. */
  361. /**
  362. * User interface for the language deletion confirmation screen.
  363. */
  364. function locale_languages_delete_form(&$form_state, $langcode) {
  365. // Do not allow deletion of English locale.
  366. if ($langcode == 'en') {
  367. drupal_set_message(t('The English language cannot be deleted.'));
  368. drupal_goto('admin/settings/language');
  369. }
  370. if (language_default('language') == $langcode) {
  371. drupal_set_message(t('The default language cannot be deleted.'));
  372. drupal_goto('admin/settings/language');
  373. }
  374. // For other languages, warn user that data loss is ahead.
  375. $languages = language_list();
  376. if (!isset($languages[$langcode])) {
  377. drupal_not_found();
  378. }
  379. else {
  380. $form['langcode'] = array('#type' => 'value', '#value' => $langcode);
  381. return confirm_form($form, t('Are you sure you want to delete the language %name?', array('%name' => t($languages[$langcode]->name))), 'admin/settings/language', t('Deleting a language will remove all interface translations associated with it, and posts in this language will be set to be language neutral. This action cannot be undone.'), t('Delete'), t('Cancel'));
  382. }
  383. }
  384. /**
  385. * Process language deletion submissions.
  386. */
  387. function locale_languages_delete_form_submit($form, &$form_state) {
  388. $languages = language_list();
  389. if (isset($languages[$form_state['values']['langcode']])) {
  390. // Remove translations first.
  391. db_query("DELETE FROM {locales_target} WHERE language = '%s'", $form_state['values']['langcode']);
  392. cache_clear_all('locale:'. $form_state['values']['langcode'], 'cache');
  393. // With no translations, this removes existing JavaScript translations file.
  394. _locale_rebuild_js($form_state['values']['langcode']);
  395. // Remove the language.
  396. db_query("DELETE FROM {languages} WHERE language = '%s'", $form_state['values']['langcode']);
  397. db_query("UPDATE {node} SET language = '' WHERE language = '%s'", $form_state['values']['langcode']);
  398. $variables = array('%locale' => $languages[$form_state['values']['langcode']]->name);
  399. drupal_set_message(t('The language %locale has been removed.', $variables));
  400. watchdog('locale', 'The language %locale has been removed.', $variables);
  401. }
  402. // Changing the language settings impacts the interface:
  403. cache_clear_all('*', 'cache_page', TRUE);
  404. $form_state['redirect'] = 'admin/settings/language';
  405. return;
  406. }
  407. /**
  408. * @} End of "locale-language-add-edit"
  409. */
  410. /**
  411. * @defgroup locale-languages-negotiation Language negotiation options screen
  412. * @{
  413. */
  414. /**
  415. * Setting for language negotiation options
  416. */
  417. function locale_languages_configure_form() {
  418. $form['language_negotiation'] = array(
  419. '#title' => t('Language negotiation'),
  420. '#type' => 'radios',
  421. '#options' => array(
  422. LANGUAGE_NEGOTIATION_NONE => t('None.'),
  423. LANGUAGE_NEGOTIATION_PATH_DEFAULT => t('Path prefix only.'),
  424. LANGUAGE_NEGOTIATION_PATH => t('Path prefix with language fallback.'),
  425. LANGUAGE_NEGOTIATION_DOMAIN => t('Domain name only.')),
  426. '#default_value' => variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE),
  427. '#description' => t("Select the mechanism used to determine your site's presentation language. <strong>Modifying this setting may break all incoming URLs and should be used with caution in a production environment.</strong>")
  428. );
  429. $form['submit'] = array(
  430. '#type' => 'submit',
  431. '#value' => t('Save settings')
  432. );
  433. return $form;
  434. }
  435. /**
  436. * Submit function for language negotiation settings.
  437. */
  438. function locale_languages_configure_form_submit($form, &$form_state) {
  439. variable_set('language_negotiation', $form_state['values']['language_negotiation']);
  440. drupal_set_message(t('Language negotiation configuration saved.'));
  441. $form_state['redirect'] = 'admin/settings/language';
  442. return;
  443. }
  444. /**
  445. * @} End of "locale-languages-negotiation"
  446. */
  447. /**
  448. * @defgroup locale-translate-overview Translation overview screen.
  449. * @{
  450. */
  451. /**
  452. * Overview screen for translations.
  453. */
  454. function locale_translate_overview_screen() {
  455. $languages = language_list('language', TRUE);
  456. $groups = module_invoke_all('locale', 'groups');
  457. // Build headers with all groups in order.
  458. $headers = array_merge(array(t('Language')), array_values($groups));
  459. // Collect summaries of all source strings in all groups.
  460. $sums = db_query("SELECT COUNT(*) AS strings, textgroup FROM {locales_source} GROUP BY textgroup");
  461. $groupsums = array();
  462. while ($group = db_fetch_object($sums)) {
  463. $groupsums[$group->textgroup] = $group->strings;
  464. }
  465. // Set up overview table with default values, ensuring common order for values.
  466. $rows = array();
  467. foreach ($languages as $langcode => $language) {
  468. $rows[$langcode] = array('name' => ($langcode == 'en' ? t('English (built-in)') : t($language->name)));
  469. foreach ($groups as $group => $name) {
  470. $rows[$langcode][$group] = ($langcode == 'en' ? t('n/a') : '0/'. (isset($groupsums[$group]) ? $groupsums[$group] : 0) .' (0%)');
  471. }
  472. }
  473. // Languages with at least one record in the locale table.
  474. $translations = db_query("SELECT COUNT(*) AS translation, t.language, s.textgroup FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid GROUP BY textgroup, language");
  475. while ($data = db_fetch_object($translations)) {
  476. $ratio = (!empty($groupsums[$data->textgroup]) && $data->translation > 0) ? round(($data->translation/$groupsums[$data->textgroup])*100., 2) : 0;
  477. $rows[$data->language][$data->textgroup] = $data->translation .'/'. $groupsums[$data->textgroup] ." ($ratio%)";
  478. }
  479. return theme('table', $headers, $rows);
  480. }
  481. /**
  482. * @} End of "locale-translate-overview"
  483. */
  484. /**
  485. * @defgroup locale-translate-seek Translation search screen.
  486. * @{
  487. */
  488. /**
  489. * String search screen.
  490. */
  491. function locale_translate_seek_screen() {
  492. $output = _locale_translate_seek();
  493. $output .= drupal_get_form('locale_translate_seek_form');
  494. return $output;
  495. }
  496. /**
  497. * User interface for the string search screen.
  498. */
  499. function locale_translate_seek_form() {
  500. // Get all languages, except English
  501. $raw_languages = locale_language_list('name', TRUE);
  502. unset($raw_languages['en']);
  503. // Sanitize the values to be used in radios.
  504. $languages = array();
  505. foreach ($raw_languages as $key => $value) {
  506. $languages[check_plain($key)] = check_plain($value);
  507. }
  508. // Present edit form preserving previous user settings
  509. $query = _locale_translate_seek_query();
  510. $form = array();
  511. $form['search'] = array('#type' => 'fieldset',
  512. '#title' => t('Search'),
  513. );
  514. $form['search']['string'] = array('#type' => 'textfield',
  515. '#title' => t('String contains'),
  516. '#default_value' => @$query['string'],
  517. '#description' => t('Leave blank to show all strings. The search is case sensitive.'),
  518. );
  519. $form['search']['language'] = array(
  520. // Change type of form widget if more the 5 options will
  521. // be present (2 of the options are added below).
  522. '#type' => (count($languages) <= 3 ? 'radios' : 'select'),
  523. '#title' => t('Language'),
  524. '#default_value' => (!empty($query['language']) ? $query['language'] : 'all'),
  525. '#options' => array_merge(array('all' => t('All languages'), 'en' => t('English (provided by Drupal)')), $languages),
  526. );
  527. $form['search']['translation'] = array('#type' => 'radios',
  528. '#title' => t('Search in'),
  529. '#default_value' => (!empty($query['translation']) ? $query['translation'] : 'all'),
  530. '#options' => array('all' => t('Both translated and untranslated strings'), 'translated' => t('Only translated strings'), 'untranslated' => t('Only untranslated strings')),
  531. );
  532. $groups = module_invoke_all('locale', 'groups');
  533. $form['search']['group'] = array('#type' => 'radios',
  534. '#title' => t('Limit search to'),
  535. '#default_value' => (!empty($query['group']) ? $query['group'] : 'all'),
  536. '#options' => array_merge(array('all' => t('All text groups')), $groups),
  537. );
  538. $form['search']['submit'] = array('#type' => 'submit', '#value' => t('Search'));
  539. $form['#redirect'] = FALSE;
  540. return $form;
  541. }
  542. /**
  543. * @} End of "locale-translate-seek"
  544. */
  545. /**
  546. * @defgroup locale-translate-import Translation import screen.
  547. * @{
  548. */
  549. /**
  550. * User interface for the translation import screen.
  551. */
  552. function locale_translate_import_form() {
  553. // Get all languages, except English
  554. $names = locale_language_list('name', TRUE);
  555. unset($names['en']);
  556. if (!count($names)) {
  557. $languages = _locale_prepare_predefined_list();
  558. $default = array_shift(array_keys($languages));
  559. }
  560. else {
  561. $languages = array(
  562. t('Already added languages') => $names,
  563. t('Languages not yet added') => _locale_prepare_predefined_list()
  564. );
  565. $default = array_shift(array_keys($names));
  566. }
  567. $form = array();
  568. $form['import'] = array('#type' => 'fieldset',
  569. '#title' => t('Import translation'),
  570. );
  571. $form['import']['file'] = array('#type' => 'file',
  572. '#title' => t('Language file'),
  573. '#size' => 50,
  574. '#description' => t('A Gettext Portable Object (<em>.po</em>) file.'),
  575. );
  576. $form['import']['langcode'] = array('#type' => 'select',
  577. '#title' => t('Import into'),
  578. '#options' => $languages,
  579. '#default_value' => $default,
  580. '#description' => t('Choose the language you want to add strings into. If you choose a language which is not yet set up, it will be added.'),
  581. );
  582. $form['import']['group'] = array('#type' => 'radios',
  583. '#title' => t('Text group'),
  584. '#default_value' => 'default',
  585. '#options' => module_invoke_all('locale', 'groups'),
  586. '#description' => t('Imported translations will be added to this text group.'),
  587. );
  588. $form['import']['mode'] = array('#type' => 'radios',
  589. '#title' => t('Mode'),
  590. '#default_value' => LOCALE_IMPORT_KEEP,
  591. '#options' => array(
  592. LOCALE_IMPORT_OVERWRITE => t('Strings in the uploaded file replace existing ones, new ones are added'),
  593. LOCALE_IMPORT_KEEP => t('Existing strings are kept, only new strings are added')
  594. ),
  595. );
  596. $form['import']['submit'] = array('#type' => 'submit', '#value' => t('Import'));
  597. $form['#attributes']['enctype'] = 'multipart/form-data';
  598. return $form;
  599. }
  600. /**
  601. * Process the locale import form submission.
  602. */
  603. function locale_translate_import_form_submit($form, &$form_state) {
  604. // Ensure we have the file uploaded
  605. if ($file = file_save_upload('file')) {
  606. // Add language, if not yet supported
  607. $languages = language_list('language', TRUE);
  608. $langcode = $form_state['values']['langcode'];
  609. if (!isset($languages[$langcode])) {
  610. $predefined = _locale_get_predefined_list();
  611. locale_add_language($langcode);
  612. drupal_set_message(t('The language %language has been created.', array('%language' => t($predefined[$langcode][0]))));
  613. }
  614. // Now import strings into the language
  615. if ($ret = _locale_import_po($file, $langcode, $form_state['values']['mode'], $form_state['values']['group']) == FALSE) {
  616. $variables = array('%filename' => $file->filename);
  617. drupal_set_message(t('The translation import of %filename failed.', $variables), 'error');
  618. watchdog('locale', 'The translation import of %filename failed.', $variables, WATCHDOG_ERROR);
  619. }
  620. }
  621. else {
  622. drupal_set_message(t('File to import not found.'), 'error');
  623. $form_state['redirect'] = 'admin/build/translate/import';
  624. return;
  625. }
  626. $form_state['redirect'] = 'admin/build/translate';
  627. return;
  628. }
  629. /**
  630. * @} End of "locale-translate-import"
  631. */
  632. /**
  633. * @defgroup locale-translate-export Translation export screen.
  634. * @{
  635. */
  636. /**
  637. * User interface for the translation export screen.
  638. */
  639. function locale_translate_export_screen() {
  640. // Get all languages, except English
  641. $names = locale_language_list('name', TRUE);
  642. unset($names['en']);
  643. $output = '';
  644. // Offer translation export if any language is set up.
  645. if (count($names)) {
  646. $output = drupal_get_form('locale_translate_export_po_form', $names);
  647. }
  648. $output .= drupal_get_form('locale_translate_export_pot_form');
  649. return $output;
  650. }
  651. /**
  652. * Form to export PO files for the languages provided.
  653. *
  654. * @param $names
  655. * An associate array with localized language names
  656. */
  657. function locale_translate_export_po_form(&$form_state, $names) {
  658. $form['export'] = array('#type' => 'fieldset',
  659. '#title' => t('Export translation'),
  660. '#collapsible' => TRUE,
  661. );
  662. $form['export']['langcode'] = array('#type' => 'select',
  663. '#title' => t('Language name'),
  664. '#options' => $names,
  665. '#description' => t('Select the language to export in Gettext Portable Object (<em>.po</em>) format.'),
  666. );
  667. $form['export']['group'] = array('#type' => 'radios',
  668. '#title' => t('Text group'),
  669. '#default_value' => 'default',
  670. '#options' => module_invoke_all('locale', 'groups'),
  671. );
  672. $form['export']['submit'] = array('#type' => 'submit', '#value' => t('Export'));
  673. return $form;
  674. }
  675. /**
  676. * Translation template export form.
  677. */
  678. function locale_translate_export_pot_form() {
  679. // Complete template export of the strings
  680. $form['export'] = array('#type' => 'fieldset',
  681. '#title' => t('Export template'),
  682. '#collapsible' => TRUE,
  683. '#description' => t('Generate a Gettext Portable Object Template (<em>.pot</em>) file with all strings from the Drupal locale database.'),
  684. );
  685. $form['export']['group'] = array('#type' => 'radios',
  686. '#title' => t('Text group'),
  687. '#default_value' => 'default',
  688. '#options' => module_invoke_all('locale', 'groups'),
  689. );
  690. $form['export']['submit'] = array('#type' => 'submit', '#value' => t('Export'));
  691. // Reuse PO export submission callback.
  692. $form['#submit'][] = 'locale_translate_export_po_form_submit';
  693. $form['#validate'][] = 'locale_translate_export_po_form_validate';
  694. return $form;
  695. }
  696. /**
  697. * Process a translation (or template) export form submission.
  698. */
  699. function locale_translate_export_po_form_submit($form, &$form_state) {
  700. // If template is required, language code is not given.
  701. $language = NULL;
  702. if (isset($form_state['values']['langcode'])) {
  703. $languages = language_list();
  704. $language = $languages[$form_state['values']['langcode']];
  705. }
  706. _locale_export_po($language, _locale_export_po_generate($language, _locale_export_get_strings($language, $form_state['values']['group'])));
  707. }
  708. /**
  709. * @} End of "locale-translate-export"
  710. */
  711. /**
  712. * @defgroup locale-translate-edit Translation text editing
  713. * @{
  714. */
  715. /**
  716. * User interface for string editing.
  717. */
  718. function locale_translate_edit_form(&$form_state, $lid) {
  719. // Fetch source string, if possible.
  720. $source = db_fetch_object(db_query('SELECT source, textgroup, location FROM {locales_source} WHERE lid = %d', $lid));
  721. if (!$source) {
  722. drupal_set_message(t('String not found.'), 'error');
  723. drupal_goto('admin/build/translate/search');
  724. }
  725. // Add original text to the top and some values for form altering.
  726. $form = array(
  727. 'original' => array(
  728. '#type' => 'item',
  729. '#title' => t('Original text'),
  730. '#value' => check_plain(wordwrap($source->source, 0)),
  731. ),
  732. 'lid' => array(
  733. '#type' => 'value',
  734. '#value' => $lid
  735. ),
  736. 'textgroup' => array(
  737. '#type' => 'value',
  738. '#value' => $source->textgroup,
  739. ),
  740. 'location' => array(
  741. '#type' => 'value',
  742. '#value' => $source->location
  743. ),
  744. );
  745. // Include default form controls with empty values for all languages.
  746. // This ensures that the languages are always in the same order in forms.
  747. $languages = language_list();
  748. $default = language_default();
  749. // We don't need the default language value, that value is in $source.
  750. $omit = $source->textgroup == 'default' ? 'en' : $default->language;
  751. unset($languages[($omit)]);
  752. $form['translations'] = array('#tree' => TRUE);
  753. // Approximate the number of rows to use in the default textarea.
  754. $rows = min(ceil(str_word_count($source->source) / 12), 10);
  755. foreach ($languages as $langcode => $language) {
  756. $form['translations'][$langcode] = array(
  757. '#type' => 'textarea',
  758. '#title' => t($language->name),
  759. '#rows' => $rows,
  760. '#default_value' => '',
  761. );
  762. }
  763. // Fetch translations and fill in default values in the form.
  764. $result = db_query("SELECT DISTINCT translation, language FROM {locales_target} WHERE lid = %d AND language != '%s'", $lid, $omit);
  765. while ($translation = db_fetch_object($result)) {
  766. $form['translations'][$translation->language]['#default_value'] = $translation->translation;
  767. }
  768. $form['submit'] = array('#type' => 'submit', '#value' => t('Save translations'));
  769. return $form;
  770. }
  771. /**
  772. * Check that a string is safe to be added or imported as a translation.
  773. *
  774. * This test can be used to detect possibly bad translation strings. It should
  775. * not have any false positives. But it is only a test, not a transformation,
  776. * as it destroys valid HTML. We cannot reliably filter translation strings
  777. * on inport becuase some strings are irreversibly corrupted. For example,
  778. * a &amp; in the translation would get encoded to &amp;amp; by filter_xss()
  779. * before being put in the database, and thus would be displayed incorrectly.
  780. *
  781. * The allowed tag list is like filter_xss_admin(), but omitting div and img as
  782. * not needed for translation and likely to cause layout issues (div) or a
  783. * possible attack vector (img).
  784. */
  785. function locale_string_is_safe($string) {
  786. 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')));
  787. }
  788. /**
  789. * Validate string editing form submissions.
  790. */
  791. function locale_translate_edit_form_validate($form, &$form_state) {
  792. // Locale string check is needed for default textgroup only.
  793. $safe_check_needed = $form_state['values']['textgroup'] == 'default';
  794. foreach ($form_state['values']['translations'] as $key => $value) {
  795. if ($safe_check_needed && !locale_string_is_safe($value)) {
  796. form_set_error('translations', t('The submitted string contains disallowed HTML: %string', array('%string' => $value)));
  797. watchdog('locale', 'Attempted submission of a translation string with disallowed HTML: %string', array('%string' => $value), WATCHDOG_WARNING);
  798. }
  799. }
  800. }
  801. /**
  802. * Process string editing form submissions.
  803. *
  804. * Saves all translations of one string submitted from a form.
  805. */
  806. function locale_translate_edit_form_submit($form, &$form_state) {
  807. $lid = $form_state['values']['lid'];
  808. foreach ($form_state['values']['translations'] as $key => $value) {
  809. $translation = db_result(db_query("SELECT translation FROM {locales_target} WHERE lid = %d AND language = '%s'", $lid, $key));
  810. if (!empty($value)) {
  811. // Only update or insert if we have a value to use.
  812. if (!empty($translation)) {
  813. db_query("UPDATE {locales_target} SET translation = '%s' WHERE lid = %d AND language = '%s'", $value, $lid, $key);
  814. }
  815. else {
  816. db_query("INSERT INTO {locales_target} (lid, translation, language) VALUES (%d, '%s', '%s')", $lid, $value, $key);
  817. }
  818. }
  819. elseif (!empty($translation)) {
  820. // Empty translation entered: remove existing entry from database.
  821. db_query("DELETE FROM {locales_target} WHERE lid = %d AND language = '%s'", $lid, $key);
  822. }
  823. // Force JavaScript translation file recreation for this language.
  824. _locale_invalidate_js($key);
  825. }
  826. drupal_set_message(t('The string has been saved.'));
  827. // Clear locale cache.
  828. _locale_invalidate_js();
  829. cache_clear_all('locale:', 'cache', TRUE);
  830. $form_state['redirect'] = 'admin/build/translate/search';
  831. return;
  832. }
  833. /**
  834. * @} End of "locale-translate-edit"
  835. */
  836. /**
  837. * @defgroup locale-translate-delete Translation delete interface.
  838. * @{
  839. */
  840. /**
  841. * String deletion confirmation page.
  842. */
  843. function locale_translate_delete_page($lid) {
  844. if ($source = db_fetch_object(db_query('SELECT * FROM {locales_source} WHERE lid = %d', $lid))) {
  845. return drupal_get_form('locale_translate_delete_form', $source);
  846. }
  847. else {
  848. return drupal_not_found();
  849. }
  850. }
  851. /**
  852. * User interface for the string deletion confirmation screen.
  853. */
  854. function locale_translate_delete_form(&$form_state, $source) {
  855. $form['lid'] = array('#type' => 'value', '#value' => $source->lid);
  856. return confirm_form($form, t('Are you sure you want to delete the string "%source"?', array('%source' => $source->source)), 'admin/build/translate/search', t('Deleting the string will remove all translations of this string in all languages. This action cannot be undone.'), t('Delete'), t('Cancel'));
  857. }
  858. /**
  859. * Process string deletion submissions.
  860. */
  861. function locale_translate_delete_form_submit($form, &$form_state) {
  862. db_query('DELETE FROM {locales_source} WHERE lid = %d', $form_state['values']['lid']);
  863. db_query('DELETE FROM {locales_target} WHERE lid = %d', $form_state['values']['lid']);
  864. // Force JavaScript translation file recreation for all languages.
  865. _locale_invalidate_js();
  866. cache_clear_all('locale:', 'cache', TRUE);
  867. drupal_set_message(t('The string has been removed.'));
  868. $form_state['redirect'] = 'admin/build/translate/search';
  869. }
  870. /**
  871. * @} End of "locale-translate-delete"
  872. */
  873. /**
  874. * @defgroup locale-api-add Language addition API.
  875. * @{
  876. */
  877. /**
  878. * API function to add a language.
  879. *
  880. * @param $langcode
  881. * Language code.
  882. * @param $name
  883. * English name of the language
  884. * @param $native
  885. * Native name of the language
  886. * @param $direction
  887. * LANGUAGE_LTR or LANGUAGE_RTL
  888. * @param $domain
  889. * Optional custom domain name with protocol, without
  890. * trailing slash (eg. http://de.example.com).
  891. * @param $prefix
  892. * Optional path prefix for the language. Defaults to the
  893. * language code if omitted.
  894. * @param $enabled
  895. * Optionally TRUE to enable the language when created or FALSE to disable.
  896. * @param $default
  897. * Optionally set this language to be the default.
  898. */
  899. function locale_add_language($langcode, $name = NULL, $native = NULL, $direction = LANGUAGE_LTR, $domain = '', $prefix = '', $enabled = TRUE, $default = FALSE) {
  900. // Default prefix on language code.
  901. if (empty($prefix)) {
  902. $prefix = $langcode;
  903. }
  904. // If name was not set, we add a predefined language.
  905. if (!isset($name)) {
  906. $predefined = _locale_get_predefined_list();
  907. $name = $predefined[$langcode][0];
  908. $native = isset($predefined[$langcode][1]) ? $predefined[$langcode][1] : $predefined[$langcode][0];
  909. $direction = isset($predefined[$langcode][2]) ? $predefined[$langcode][2] : LANGUAGE_LTR;
  910. }
  911. db_query("INSERT INTO {languages} (language, name, native, direction, domain, prefix, enabled) VALUES ('%s', '%s', '%s', %d, '%s', '%s', %d)", $langcode, $name, $native, $direction, $domain, $prefix, $enabled);
  912. // Only set it as default if enabled.
  913. if ($enabled && $default) {
  914. 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' => ''));
  915. }
  916. if ($enabled) {
  917. // Increment enabled language count if we are adding an enabled language.
  918. variable_set('language_count', variable_get('language_count', 1) + 1);
  919. }
  920. // Force JavaScript translation file creation for the newly added language.
  921. _locale_invalidate_js($langcode);
  922. watchdog('locale', 'The %language language (%code) has been created.', array('%language' => $name, '%code' => $langcode));
  923. }
  924. /**
  925. * @} End of "locale-api-add"
  926. */
  927. /**
  928. * @defgroup locale-api-import Translation import API.
  929. * @{
  930. */
  931. /**
  932. * Parses Gettext Portable Object file information and inserts into database
  933. *
  934. * @param $file
  935. * Drupal file object corresponding to the PO file to import
  936. * @param $langcode
  937. * Language code
  938. * @param $mode
  939. * Should existing translations be replaced LOCALE_IMPORT_KEEP or LOCALE_IMPORT_OVERWRITE
  940. * @param $group
  941. * Text group to import PO file into (eg. 'default' for interface translations)
  942. */
  943. function _locale_import_po($file, $langcode, $mode, $group = NULL) {
  944. // Try to allocate enough time to parse and import the data.
  945. if (function_exists('set_time_limit')) {
  946. @set_time_limit(240);
  947. }
  948. // Check if we have the language already in the database.
  949. if (!db_fetch_object(db_query("SELECT language FROM {languages} WHERE language = '%s'", $langcode))) {
  950. drupal_set_message(t('The language selected for import is not supported.'), 'error');
  951. return FALSE;
  952. }
  953. // Get strings from file (returns on failure after a partial import, or on success)
  954. $status = _locale_import_read_po('db-store', $file, $mode, $langcode, $group);
  955. if ($status === FALSE) {
  956. // Error messages are set in _locale_import_read_po().
  957. return FALSE;
  958. }
  959. // Get status information on import process.
  960. list($headerdone, $additions, $updates, $deletes, $skips) = _locale_import_one_string('db-report');
  961. if (!$headerdone) {
  962. drupal_set_message(t('The translation file %filename appears to have a missing or malformed header.', array('%filename' => $file->filename)), 'error');
  963. }
  964. // Clear cache and force refresh of JavaScript translations.
  965. _locale_invalidate_js($langcode);
  966. cache_clear_all('locale:', 'cache', TRUE);
  967. // Rebuild the menu, strings may have changed.
  968. menu_rebuild();
  969. 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)));
  970. 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));
  971. if ($skips) {
  972. $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.');
  973. drupal_set_message($skip_message);
  974. watchdog('locale', $skip_message, NULL, WATCHDOG_WARNING);
  975. }
  976. return TRUE;
  977. }
  978. /**
  979. * Parses Gettext Portable Object file into an array
  980. *
  981. * @param $op
  982. * Storage operation type: db-store or mem-store
  983. * @param $file
  984. * Drupal file object corresponding to the PO file to import
  985. * @param $mode
  986. * Should existing translations be replaced LOCALE_IMPORT_KEEP or LOCALE_IMPORT_OVERWRITE
  987. * @param $lang
  988. * Language code
  989. * @param $group
  990. * Text group to import PO file into (eg. 'default' for interface translations)
  991. */
  992. function _locale_import_read_po($op, $file, $mode = NULL, $lang = NULL, $group = 'default') {
  993. $fd = fopen($file->filepath, "rb"); // File will get closed by PHP on return
  994. if (!$fd) {
  995. _locale_import_message('The translation import failed, because the file %filename could not be read.', $file);
  996. return FALSE;
  997. }
  998. $context = "COMMENT"; // Parser context: COMMENT, MSGID, MSGID_PLURAL, MSGSTR and MSGSTR_ARR
  999. $current = array(); // Current entry being read
  1000. $plural = 0; // Current plural form
  1001. $lineno = 0; // Current line
  1002. while (!feof($fd)) {
  1003. $line = fgets($fd, 10*1024); // A line should not be this long
  1004. if ($lineno == 0) {
  1005. // The first line might come with a UTF-8 BOM, which should be removed.
  1006. $line = str_replace("\xEF\xBB\xBF", '', $line);
  1007. }
  1008. $lineno++;
  1009. $line = trim(strtr($line, array("\\\n" => "")));
  1010. if (!strncmp("#", $line, 1)) { // A comment
  1011. if ($context == "COMMENT") { // Already in comment context: add
  1012. $current["#"][] = substr($line, 1);
  1013. }
  1014. elseif (($context == "MSGSTR") || ($context == "MSGSTR_ARR")) { // End current entry, start a new one
  1015. _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
  1016. $current = array();
  1017. $current["#"][] = substr($line, 1);
  1018. $context = "COMMENT";
  1019. }
  1020. else { // Parse error
  1021. _locale_import_message('The translation file %filename contains an error: "msgstr" was expected but not found on line %line.', $file, $lineno);
  1022. return FALSE;
  1023. }
  1024. }
  1025. elseif (!strncmp("msgid_plural", $line, 12)) {
  1026. if ($context != "MSGID") { // Must be plural form for current entry
  1027. _locale_import_message('The translation file %filename contains an error: "msgid_plural" was expected but not found on line %line.', $file, $lineno);
  1028. return FALSE;
  1029. }
  1030. $line = trim(substr($line, 12));
  1031. $quoted = _locale_import_parse_quoted($line);
  1032. if ($quoted === FALSE) {
  1033. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  1034. return FALSE;
  1035. }
  1036. $current["msgid"] = $current["msgid"] ."\0". $quoted;
  1037. $context = "MSGID_PLURAL";
  1038. }
  1039. elseif (!strncmp("msgid", $line, 5)) {
  1040. if (($context == "MSGSTR") || ($context == "MSGSTR_ARR")) { // End current entry, start a new one
  1041. _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
  1042. $current = array();
  1043. }
  1044. elseif ($context == "MSGID") { // Already in this context? Parse error
  1045. _locale_import_message('The translation file %filename contains an error: "msgid" is unexpected on line %line.', $file, $lineno);
  1046. return FALSE;
  1047. }
  1048. $line = trim(substr($line, 5));
  1049. $quoted = _locale_import_parse_quoted($line);
  1050. if ($quoted === FALSE) {
  1051. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  1052. return FALSE;
  1053. }
  1054. $current["msgid"] = $quoted;
  1055. $context = "MSGID";
  1056. }
  1057. elseif (!strncmp("msgstr[", $line, 7)) {
  1058. if (($context != "MSGID") && ($context != "MSGID_PLURAL") && ($context != "MSGSTR_ARR")) { // Must come after msgid, msgid_plural, or msgstr[]
  1059. _locale_import_message('The translation file %filename contains an error: "msgstr[]" is unexpected on line %line.', $file, $lineno);
  1060. return FALSE;
  1061. }
  1062. if (strpos($line, "]") === FALSE) {
  1063. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  1064. return FALSE;
  1065. }
  1066. $frombracket = strstr($line, "[");
  1067. $plural = substr($frombracket, 1, strpos($frombracket, "]") - 1);
  1068. $line = trim(strstr($line, " "));
  1069. $quoted = _locale_import_parse_quoted($line);
  1070. if ($quoted === FALSE) {
  1071. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  1072. return FALSE;
  1073. }
  1074. $current["msgstr"][$plural] = $quoted;
  1075. $context = "MSGSTR_ARR";
  1076. }
  1077. elseif (!strncmp("msgstr", $line, 6)) {
  1078. if ($context != "MSGID") { // Should come just after a msgid block
  1079. _locale_import_message('The translation file %filename contains an error: "msgstr" is unexpected on line %line.', $file, $lineno);
  1080. return FALSE;
  1081. }
  1082. $line = trim(substr($line, 6));
  1083. $quoted = _locale_import_parse_quoted($line);
  1084. if ($quoted === FALSE) {
  1085. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  1086. return FALSE;
  1087. }
  1088. $current["msgstr"] = $quoted;
  1089. $context = "MSGSTR";
  1090. }
  1091. elseif ($line != "") {
  1092. $quoted = _locale_import_parse_quoted($line);
  1093. if ($quoted === FALSE) {
  1094. _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
  1095. return FALSE;
  1096. }
  1097. if (($context == "MSGID") || ($context == "MSGID_PLURAL")) {
  1098. $current["msgid"] .= $quoted;
  1099. }
  1100. elseif ($context == "MSGSTR") {
  1101. $current["msgstr"] .= $quoted;
  1102. }
  1103. elseif ($context == "MSGSTR_ARR") {
  1104. $current["msgstr"][$plural] .= $quoted;
  1105. }
  1106. else {
  1107. _locale_import_message('The translation file %filename contains an error: there is an unexpected string on line %line.', $file, $lineno);
  1108. return FALSE;
  1109. }
  1110. }
  1111. }
  1112. // End of PO file, flush last entry
  1113. if (($context == "MSGSTR") || ($context == "MSGSTR_ARR")) {
  1114. _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
  1115. }
  1116. elseif ($context != "COMMENT") {
  1117. _locale_import_message('The translation file %filename ended unexpectedly at line %line.', $file, $lineno);
  1118. return FALSE;
  1119. }
  1120. }
  1121. /**
  1122. * Sets an error message occurred during locale file parsing.
  1123. *
  1124. * @param $message
  1125. * The message to be translated
  1126. * @param $file
  1127. * Drupal file object corresponding to the PO file to import
  1128. * @param $lineno
  1129. * An optional line number argument
  1130. */
  1131. function _locale_import_message($message, $file, $lineno = NULL) {
  1132. $vars = array('%filename' => $file->filename);
  1133. if (isset($lineno)) {
  1134. $vars['%line'] = $lineno;
  1135. }
  1136. $t = get_t();
  1137. drupal_set_message($t($message, $vars), 'error');
  1138. }
  1139. /**
  1140. * Imports a string into the database
  1141. *
  1142. * @param $op
  1143. * Operation to perform: 'db-store', 'db-report', 'mem-store' or 'mem-report'
  1144. * @param $value
  1145. * Details of the string stored
  1146. * @param $mode
  1147. * Should existing translations be replaced LOCALE_IMPORT_KEEP or LOCALE_IMPORT_OVERWRITE
  1148. * @param $lang
  1149. * Language to store the string in
  1150. * @param $file
  1151. * Object representation of file being imported, only required when op is 'db-store'
  1152. * @param $group
  1153. * Text group to import PO file into (eg. 'default' for interface translations)
  1154. */
  1155. function _locale_import_one_string($op, $value = NULL, $mode = NULL, $lang = NULL, $file = NULL, $group = 'default') {
  1156. static $report = array('additions' => 0, 'updates' => 0, 'deletes' => 0, 'skips' => 0);
  1157. static $headerdone = FALSE;
  1158. static $strings = array();
  1159. switch ($op) {
  1160. // Return stored strings
  1161. case 'mem-report':
  1162. return $strings;
  1163. // Store string in memory (only supports single strings)
  1164. case 'mem-store':
  1165. $strings[$value['msgid']] = $value['msgstr'];
  1166. return;
  1167. // Called at end of import to inform the user
  1168. case 'db-report':
  1169. return array($headerdone, $report['additions'], $report['updates'], $report['deletes'], $report['skips']);
  1170. // Store the string we got in the database.
  1171. case 'db-store':
  1172. // We got header information.
  1173. if ($value['msgid'] == '') {
  1174. $languages = language_list();
  1175. if (($mode != LOCALE_IMPORT_KEEP) || empty($languages[$lang]->plurals)) {
  1176. // Since we only need to parse the header if we ought to update the
  1177. // plural formula, only run this if we don't need to keep existing
  1178. // data untouched or if we don't have an existing plural formula.
  1179. $header = _locale_import_parse_header($value['msgstr']);
  1180. // Get and store the plural formula if available.
  1181. if (isset($header["Plural-Forms"]) && $p = _locale_import_parse_plural_forms($header["Plural-Forms"], $file->filename)) {
  1182. list($nplurals, $plural) = $p;
  1183. db_query("UPDATE {languages} SET plurals = %d, formula = '%s' WHERE language = '%s'", $nplurals, $plural, $lang);
  1184. }
  1185. }
  1186. $headerdone = TRUE;
  1187. }
  1188. else {
  1189. // Some real string to import.
  1190. $comments = _locale_import_shorten_comments(empty($value['#']) ? array() : $value['#']);
  1191. if (strpos($value['msgid'], "\0")) {
  1192. // This string has plural versions.
  1193. $english = explode("\0", $value['msgid'], 2);
  1194. $entries = array_keys($value['msgstr']);
  1195. for ($i = 3; $i <= count($entries); $i++) {
  1196. $english[] = $english[1];
  1197. }
  1198. $translation = array_map('_locale_import_append_plural', $value['msgstr'], $entries);
  1199. $english = array_map('_locale_import_append_plural', $english, $entries);
  1200. foreach ($translation as $key => $trans) {
  1201. if ($key == 0) {
  1202. $plid = 0;
  1203. }
  1204. $plid = _locale_import_one_string_db($report, $lang, $english[$key], $trans, $group, $comments, $mode, $plid, $key);
  1205. }
  1206. }
  1207. else {
  1208. // A simple string to import.
  1209. $english = $value['msgid'];
  1210. $translation = $value['msgstr'];
  1211. _locale_import_one_string_db($report, $lang, $english, $translation, $group, $comments, $mode);
  1212. }
  1213. }
  1214. } // end of db-store operation
  1215. }
  1216. /**
  1217. * Import one string into the database.
  1218. *
  1219. * @param $report
  1220. * Report array summarizing the number of changes done in the form:
  1221. * array(inserts, updates, deletes).
  1222. * @param $langcode
  1223. * Language code to import string into.
  1224. * @param $source
  1225. * Source string.
  1226. * @param $translation
  1227. * Translation to language specified in $langcode.
  1228. * @param $textgroup
  1229. * Name of textgroup to store translation in.
  1230. * @param $location
  1231. * Location value to save with source string.
  1232. * @param $mode
  1233. * Import mode to use, LOCALE_IMPORT_KEEP or LOCALE_IMPORT_OVERWRITE.
  1234. * @param $plid
  1235. * Optional plural ID to use.
  1236. * @param $plural
  1237. * Optional plural value to use.
  1238. * @return
  1239. * The string ID of the existing string modified or the new string added.
  1240. */
  1241. function _locale_import_one_string_db(&$report, $langcode, $source, $translation, $textgroup, $location, $mode, $plid = NULL, $plural = NULL) {
  1242. $lid = db_result(db_query("SELECT lid FROM {locales_source} WHERE source = '%s' AND textgroup = '%s'", $source, $textgroup));
  1243. if (!empty($translation)) {
  1244. // Skip this string unless it passes a check for dangerous code.
  1245. // Text groups other than default still can contain HTML tags
  1246. // (i.e. translatable blocks).
  1247. if ($textgroup == "default" && !locale_string_is_safe($translation)) {
  1248. $report['skips']++;
  1249. $lid = 0;
  1250. }
  1251. elseif ($lid) {
  1252. // We have this source string saved already.
  1253. db_query("UPDATE {locales_source} SET location = '%s' WHERE lid = %d", $location, $lid);
  1254. $exists = (bool) db_result(db_query("SELECT lid FROM {locales_target} WHERE lid = %d AND language = '%s'", $lid, $langcode));
  1255. if (!$exists) {
  1256. // No translation in this language.
  1257. db_query("INSERT INTO {locales_target} (lid, language, translation, plid, plural) VALUES (%d, '%s', '%s', %d, %d)", $lid, $langcode, $translation, $plid, $plural);
  1258. $report['additions']++;
  1259. }
  1260. else if ($mode == LOCALE_IMPORT_OVERWRITE) {
  1261. // Translation exists, only overwrite if instructed.
  1262. db_query("UPDATE {locales_target} SET translation = '%s', plid = %d, plural = %d WHERE language = '%s' AND lid = %d", $translation, $plid, $plural, $langcode, $lid);
  1263. $report['updates']++;
  1264. }
  1265. }
  1266. else {
  1267. // No such source string in the database yet.
  1268. db_query("INSERT INTO {locales_source} (location, source, textgroup) VALUES ('%s', '%s', '%s')", $location, $source, $textgroup);
  1269. $lid = db_result(db_query("SELECT lid FROM {locales_source} WHERE source = '%s' AND textgroup = '%s'", $source, $textgroup));
  1270. db_query("INSERT INTO {locales_target} (lid, language, translation, plid, plural) VALUES (%d, '%s', '%s', %d, %d)", $lid, $langcode, $translation, $plid, $plural);
  1271. $report['additions']++;
  1272. }
  1273. }
  1274. elseif ($mode == LOCALE_IMPORT_OVERWRITE) {
  1275. // Empty translation, remove existing if instructed.
  1276. db_query("DELETE FROM {locales_target} WHERE language = '%s' AND lid = %d AND plid = %d AND plural = %d", $langcode, $lid, $plid, $plural);
  1277. $report['deletes']++;
  1278. }
  1279. return $lid;
  1280. }
  1281. /**
  1282. * Parses a Gettext Portable Object file header
  1283. *
  1284. * @param $header
  1285. * A string containing the complete header
  1286. * @return
  1287. * An associative array of key-value pairs
  1288. */
  1289. function _locale_import_parse_header($header) {
  1290. $header_parsed = array();
  1291. $lines = array_map('trim', explode("\n", $header));
  1292. foreach ($lines as $line) {
  1293. if ($line) {
  1294. list($tag, $contents) = explode(":", $line, 2);
  1295. $header_parsed[trim($tag)] = trim($contents);
  1296. }
  1297. }
  1298. return $header_parsed;
  1299. }
  1300. /**
  1301. * Parses a Plural-Forms entry from a Gettext Portable Object file header
  1302. *
  1303. * @param $pluralforms
  1304. * A string containing the Plural-Forms entry
  1305. * @param $filename
  1306. * A string containing the filename
  1307. * @return
  1308. * An array containing the number of plurals and a
  1309. * formula in PHP for computing the plural form
  1310. */
  1311. function _locale_import_parse_plural_forms($pluralforms, $filename) {
  1312. // First, delete all whitespace
  1313. $pluralforms = strtr($pluralforms, array(" " => "", "\t" => ""));
  1314. // Select the parts that define nplurals and plural
  1315. $nplurals = strstr($pluralforms, "nplurals=");
  1316. if (strpos($nplurals, ";")) {
  1317. $nplurals = substr($nplurals, 9, strpos($nplurals, ";") - 9);
  1318. }
  1319. else {
  1320. return FALSE;
  1321. }
  1322. $plural = strstr($pluralforms, "plural=");
  1323. if (strpos($plural, ";")) {
  1324. $plural = substr($plural, 7, strpos($plural, ";") - 7);
  1325. }
  1326. else {
  1327. return FALSE;
  1328. }
  1329. // Get PHP version of the plural formula
  1330. $plural = _locale_import_parse_arithmetic($plural);
  1331. if ($plural !== FALSE) {
  1332. return array($nplurals, $plural);
  1333. }
  1334. else {
  1335. drupal_set_message(t('The translation file %filename contains an error: the plural formula could not be parsed.', array('%filename' => $filename)), 'error');
  1336. return FALSE;
  1337. }
  1338. }
  1339. /**
  1340. * Parses and sanitizes an arithmetic formula into a PHP expression
  1341. *
  1342. * While parsing, we ensure, that the operators have the right
  1343. * precedence and associativity.
  1344. *
  1345. * @param $string
  1346. * A string containing the arithmetic formula
  1347. * @return
  1348. * The PHP version of the formula
  1349. */
  1350. function _locale_import_parse_arithmetic($string) {
  1351. // Operator precedence table
  1352. $prec = array("(" => -1, ")" => -1, "?" => 1, ":" => 1, "||" => 3, "&&" => 4, "==" => 5, "!=" => 5, "<" => 6, ">" => 6, "<=" => 6, ">=" => 6, "+" => 7, "-" => 7, "*" => 8, "/" => 8, "%" => 8);
  1353. // Right associativity
  1354. $rasc = array("?" => 1, ":" => 1);
  1355. $tokens = _locale_import_tokenize_formula($string);
  1356. // Parse by converting into infix notation then back into postfix
  1357. $opstk = array();
  1358. $elstk = array();
  1359. foreach ($tokens as $token) {
  1360. $ctok = $token;
  1361. // Numbers and the $n variable are simply pushed into $elarr
  1362. if (is_numeric($token)) {
  1363. $elstk[] = $ctok;
  1364. }
  1365. elseif ($ctok == "n") {
  1366. $elstk[] = '$n';
  1367. }
  1368. elseif ($ctok == "(") {
  1369. $opstk[] = $ctok;
  1370. }
  1371. elseif ($ctok == ")") {
  1372. $topop = array_pop($opstk);
  1373. while (isset($topop) && ($topop != "(")) {
  1374. $elstk[] = $topop;
  1375. $topop = array_pop($opstk);
  1376. }
  1377. }
  1378. elseif (!empty($prec[$ctok])) {
  1379. // If it's an operator, then pop from $oparr into $elarr until the
  1380. // precedence in $oparr is less than current, then push into $oparr
  1381. $topop = array_pop($opstk);
  1382. while (isset($topop) && ($prec[$topop] >= $prec[$ctok]) && !(($prec[$topop] == $prec[$ctok]) && !empty($rasc[$topop]) && !empty($rasc[$ctok]))) {
  1383. $elstk[] = $topop;
  1384. $topop = array_pop($opstk);
  1385. }
  1386. if ($topop) {
  1387. $opstk[] = $topop; // Return element to top
  1388. }
  1389. $opstk[] = $ctok; // Parentheses are not needed
  1390. }
  1391. else {
  1392. return FALSE;
  1393. }
  1394. }
  1395. // Flush operator stack
  1396. $topop = array_pop($opstk);
  1397. while ($topop != NULL) {
  1398. $elstk[] = $topop;
  1399. $topop = array_pop($opstk);
  1400. }
  1401. // Now extract formula from stack
  1402. $prevsize = count($elstk) + 1;
  1403. while (count($elstk) < $prevsize) {
  1404. $prevsize = count($elstk);
  1405. for ($i = 2; $i < count($elstk); $i++) {
  1406. $op = $elstk[$i];
  1407. if (!empty($prec[$op])) {
  1408. $f = "";
  1409. if ($op == ":") {
  1410. $f = $elstk[$i - 2] ."):". $elstk[$i - 1] .")";
  1411. }
  1412. elseif ($op == "?") {
  1413. $f = "(". $elstk[$i - 2] ."?(". $elstk[$i - 1];
  1414. }
  1415. else {
  1416. $f = "(". $elstk[$i - 2] . $op . $elstk[$i - 1] .")";
  1417. }
  1418. array_splice($elstk, $i - 2, 3, $f);
  1419. break;
  1420. }
  1421. }
  1422. }
  1423. // If only one element is left, the number of operators is appropriate
  1424. if (count($elstk) == 1) {
  1425. return $elstk[0];
  1426. }
  1427. else {
  1428. return FALSE;
  1429. }
  1430. }
  1431. /**
  1432. * Backward compatible implementation of token_get_all() for formula parsing
  1433. *
  1434. * @param $string
  1435. * A string containing the arithmetic formula
  1436. * @return
  1437. * The PHP version of the formula
  1438. */
  1439. function _locale_import_tokenize_formula($formula) {
  1440. $formula = str_replace(" ", "", $formula);
  1441. $tokens = array();
  1442. for ($i = 0; $i < strlen($formula); $i++) {
  1443. if (is_numeric($formula[$i])) {
  1444. $num = $formula[$i];
  1445. $j = $i + 1;
  1446. while ($j < strlen($formula) && is_numeric($formula[$j])) {
  1447. $num .= $formula[$j];
  1448. $j++;
  1449. }
  1450. $i = $j - 1;
  1451. $tokens[] = $num;
  1452. }
  1453. elseif ($pos = strpos(" =<>!&|", $formula[$i])) { // We won't have a space
  1454. $next = $formula[$i + 1];
  1455. switch ($pos) {
  1456. case 1:
  1457. case 2:
  1458. case 3:
  1459. case 4:
  1460. if ($next == '=') {
  1461. $tokens[] = $formula[$i] .'=';
  1462. $i++;
  1463. }
  1464. else {
  1465. $tokens[] = $formula[$i];
  1466. }
  1467. break;
  1468. case 5:
  1469. if ($next == '&') {
  1470. $tokens[] = '&&';
  1471. $i++;
  1472. }
  1473. else {
  1474. $tokens[] = $formula[$i];
  1475. }
  1476. break;
  1477. case 6:
  1478. if ($next == '|') {
  1479. $tokens[] = '||';
  1480. $i++;
  1481. }
  1482. else {
  1483. $tokens[] = $formula[$i];
  1484. }
  1485. break;
  1486. }
  1487. }
  1488. else {
  1489. $tokens[] = $formula[$i];
  1490. }
  1491. }
  1492. return $tokens;
  1493. }
  1494. /**
  1495. * Modify a string to contain proper count indices
  1496. *
  1497. * This is a callback function used via array_map()
  1498. *
  1499. * @param $entry
  1500. * An array element
  1501. * @param $key
  1502. * Index of the array element
  1503. */
  1504. function _locale_import_append_plural($entry, $key) {
  1505. // No modifications for 0, 1
  1506. if ($key == 0 || $key == 1) {
  1507. return $entry;
  1508. }
  1509. // First remove any possibly false indices, then add new ones
  1510. $entry = preg_replace('/(@count)\[[0-9]\]/', '\\1', $entry);
  1511. return preg_replace('/(@count)/', "\\1[$key]", $entry);
  1512. }
  1513. /**
  1514. * Generate a short, one string version of the passed comment array
  1515. *
  1516. * @param $comment
  1517. * An array of strings containing a comment
  1518. * @return
  1519. * Short one string version of the comment
  1520. */
  1521. function _locale_import_shorten_comments($comment) {
  1522. $comm = '';
  1523. while (count($comment)) {
  1524. $test = $comm . substr(array_shift($comment), 1) .', ';
  1525. if (strlen($comm) < 130) {
  1526. $comm = $test;
  1527. }
  1528. else {
  1529. break;
  1530. }
  1531. }
  1532. return trim(substr($comm, 0, -2));
  1533. }
  1534. /**
  1535. * Parses a string in quotes
  1536. *
  1537. * @param $string
  1538. * A string specified with enclosing quotes
  1539. * @return
  1540. * The string parsed from inside the quotes
  1541. */
  1542. function _locale_import_parse_quoted($string) {
  1543. if (substr($string, 0, 1) != substr($string, -1, 1)) {
  1544. return FALSE; // Start and end quotes must be the same
  1545. }
  1546. $quote = substr($string, 0, 1);
  1547. $string = substr($string, 1, -1);
  1548. if ($quote == '"') { // Double quotes: strip slashes
  1549. return stripcslashes($string);
  1550. }
  1551. elseif ($quote == "'") { // Simple quote: return as-is
  1552. return $string;
  1553. }
  1554. else {
  1555. return FALSE; // Unrecognized quote
  1556. }
  1557. }
  1558. /**
  1559. * @} End of "locale-api-import"
  1560. */
  1561. /**
  1562. * Parses a JavaScript file, extracts strings wrapped in Drupal.t() and
  1563. * Drupal.formatPlural() and inserts them into the database.
  1564. */
  1565. function _locale_parse_js_file($filepath) {
  1566. global $language;
  1567. // Load the JavaScript file.
  1568. $file = file_get_contents($filepath);
  1569. // Match all calls to Drupal.t() in an array.
  1570. // Note: \s also matches newlines with the 's' modifier.
  1571. preg_match_all('~[^\w]Drupal\s*\.\s*t\s*\(\s*('. LOCALE_JS_STRING .')\s*[,\)]~s', $file, $t_matches);
  1572. // Match all Drupal.formatPlural() calls in another array.
  1573. preg_match_all('~[^\w]Drupal\s*\.\s*formatPlural\s*\(\s*.+?\s*,\s*('. LOCALE_JS_STRING .')\s*,\s*((?:(?:\'(?:\\\\\'|[^\'])*@count(?:\\\\\'|[^\'])*\'|"(?:\\\\"|[^"])*@count(?:\\\\"|[^"])*")(?:\s*\+\s*)?)+)\s*[,\)]~s', $file, $plural_matches);
  1574. // Loop through all matches and process them.
  1575. $all_matches = array_merge($plural_matches[1], $t_matches[1]);
  1576. foreach ($all_matches as $key => $string) {
  1577. $strings = array($string);
  1578. // If there is also a plural version of this string, add it to the strings array.
  1579. if (isset($plural_matches[2][$key])) {
  1580. $strings[] = $plural_matches[2][$key];
  1581. }
  1582. foreach ($strings as $key => $string) {
  1583. // Remove the quotes and string concatenations from the string.
  1584. $string = implode('', preg_split('~(?<!\\\\)[\'"]\s*\+\s*[\'"]~s', substr($string, 1, -1)));
  1585. $result = db_query("SELECT lid, location FROM {locales_source} WHERE source = '%s' AND textgroup = 'default'", $string);
  1586. if ($source = db_fetch_object($result)) {
  1587. // We already have this source string and now have to add the location
  1588. // to the location column, if this file is not yet present in there.
  1589. $locations = preg_split('~\s*;\s*~', $source->location);
  1590. if (!in_array($filepath, $locations)) {
  1591. $locations[] = $filepath;
  1592. $locations = implode('; ', $locations);
  1593. // Save the new locations string to the database.
  1594. db_query("UPDATE {locales_source} SET location = '%s' WHERE lid = %d", $locations, $source->lid);
  1595. }
  1596. }
  1597. else {
  1598. // We don't have the source string yet, thus we insert it into the database.
  1599. db_query("INSERT INTO {locales_source} (location, source, textgroup) VALUES ('%s', '%s', 'default')", $filepath, $string);
  1600. }
  1601. }
  1602. }
  1603. }
  1604. /**
  1605. * @defgroup locale-api-export Translation (template) export API.
  1606. * @{
  1607. */
  1608. /**
  1609. * Generates a structured array of all strings with translations in
  1610. * $language, if given. This array can be used to generate an export
  1611. * of the string in the database.
  1612. *
  1613. * @param $language
  1614. * Language object to generate the output for, or NULL if generating
  1615. * translation template.
  1616. * @param $group
  1617. * Text group to export PO file from (eg. 'default' for interface translations)
  1618. */
  1619. function _locale_export_get_strings($language = NULL, $group = 'default') {
  1620. if (isset($language)) {
  1621. $result = db_query("SELECT s.lid, s.source, s.location, t.translation, t.plid, t.plural FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = '%s' WHERE s.textgroup = '%s' ORDER BY t.plid, t.plural", $language->language, $group);
  1622. }
  1623. else {
  1624. $result = db_query("SELECT s.lid, s.source, s.location, t.plid, t.plural FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid WHERE s.textgroup = '%s' ORDER BY t.plid, t.plural", $group);
  1625. }
  1626. $strings = array();
  1627. while ($child = db_fetch_object($result)) {
  1628. $string = array(
  1629. 'comment' => $child->location,
  1630. 'source' => $child->source,
  1631. 'translation' => isset($child->translation) ? $child->translation : ''
  1632. );
  1633. if ($child->plid) {
  1634. // Has a parent lid. Since we process in the order of plids,
  1635. // we already have the parent in the array, so we can add the
  1636. // lid to the next plural version to it. This builds a linked
  1637. // list of plurals.
  1638. $string['child'] = TRUE;
  1639. $strings[$child->plid]['plural'] = $child->lid;
  1640. }
  1641. $strings[$child->lid] = $string;
  1642. }
  1643. return $strings;
  1644. }
  1645. /**
  1646. * Generates the PO(T) file contents for given strings.
  1647. *
  1648. * @param $language
  1649. * Language object to generate the output for, or NULL if generating
  1650. * translation template.
  1651. * @param $strings
  1652. * Array of strings to export. See _locale_export_get_strings()
  1653. * on how it should be formatted.
  1654. * @param $header
  1655. * The header portion to use for the output file. Defaults
  1656. * are provided for PO and POT files.
  1657. */
  1658. function _locale_export_po_generate($language = NULL, $strings = array(), $header = NULL) {
  1659. global $user;
  1660. if (!isset($header)) {
  1661. if (isset($language)) {
  1662. $header = '# '. $language->name .' translation of '. variable_get('site_name', 'Drupal') ."\n";
  1663. $header .= '# Generated by '. $user->name .' <'. $user->mail .">\n";
  1664. $header .= "#\n";
  1665. $header .= "msgid \"\"\n";
  1666. $header .= "msgstr \"\"\n";
  1667. $header .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
  1668. $header .= "\"POT-Creation-Date: ". date("Y-m-d H:iO") ."\\n\"\n";
  1669. $header .= "\"PO-Revision-Date: ". date("Y-m-d H:iO") ."\\n\"\n";
  1670. $header .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
  1671. $header .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
  1672. $header .= "\"MIME-Version: 1.0\\n\"\n";
  1673. $header .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
  1674. $header .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
  1675. if ($language->formula && $language->plurals) {
  1676. $header .= "\"Plural-Forms: nplurals=". $language->plurals ."; plural=". strtr($language->formula, array('$' => '')) .";\\n\"\n";
  1677. }
  1678. }
  1679. else {
  1680. $header = "# LANGUAGE translation of PROJECT\n";
  1681. $header .= "# Copyright (c) YEAR NAME <EMAIL@ADDRESS>\n";
  1682. $header .= "#\n";
  1683. $header .= "msgid \"\"\n";
  1684. $header .= "msgstr \"\"\n";
  1685. $header .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
  1686. $header .= "\"POT-Creation-Date: ". date("Y-m-d H:iO") ."\\n\"\n";
  1687. $header .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
  1688. $header .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
  1689. $header .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
  1690. $header .= "\"MIME-Version: 1.0\\n\"\n";
  1691. $header .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
  1692. $header .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
  1693. $header .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n";
  1694. }
  1695. }
  1696. $output = $header ."\n";
  1697. foreach ($strings as $lid => $string) {
  1698. // Only process non-children, children are output below their parent.
  1699. if (!isset($string['child'])) {
  1700. if ($string['comment']) {
  1701. $output .= '#: '. $string['comment'] ."\n";
  1702. }
  1703. $output .= 'msgid '. _locale_export_string($string['source']);
  1704. if (!empty($string['plural'])) {
  1705. $plural = $string['plural'];
  1706. $output .= 'msgid_plural '. _locale_export_string($strings[$plural]['source']);
  1707. if (isset($language)) {
  1708. $translation = $string['translation'];
  1709. for ($i = 0; $i < $language->plurals; $i++) {
  1710. $output .= 'msgstr['. $i .'] '. _locale_export_string($translation);
  1711. if ($plural) {
  1712. $translation = _locale_export_remove_plural($strings[$plural]['translation']);
  1713. $plural = isset($strings[$plural]['plural']) ? $strings[$plural]['plural'] : 0;
  1714. }
  1715. else {
  1716. $translation = '';
  1717. }
  1718. }
  1719. }
  1720. else {
  1721. $output .= 'msgstr[0] ""'."\n";
  1722. $output .= 'msgstr[1] ""'."\n";
  1723. }
  1724. }
  1725. else {
  1726. $output .= 'msgstr '. _locale_export_string($string['translation']);
  1727. }
  1728. $output .= "\n";
  1729. }
  1730. }
  1731. return $output;
  1732. }
  1733. /**
  1734. * Write a generated PO or POT file to the output.
  1735. *
  1736. * @param $language
  1737. * Language object to generate the output for, or NULL if generating
  1738. * translation template.
  1739. * @param $output
  1740. * The PO(T) file to output as a string. See _locale_export_generate_po()
  1741. * on how it can be generated.
  1742. */
  1743. function _locale_export_po($language = NULL, $output = NULL) {
  1744. // Log the export event.
  1745. if (isset($language)) {
  1746. $filename = $language->language .'.po';
  1747. watchdog('locale', 'Exported %locale translation file: %filename.', array('%locale' => $language->name, '%filename' => $filename));
  1748. }
  1749. else {
  1750. $filename = 'drupal.pot';
  1751. watchdog('locale', 'Exported translation file: %filename.', array('%filename' => $filename));
  1752. }
  1753. // Download the file fo the client.
  1754. header("Content-Disposition: attachment; filename=$filename");
  1755. header("Content-Type: text/plain; charset=utf-8");
  1756. print $output;
  1757. die();
  1758. }
  1759. /**
  1760. * Print out a string on multiple lines
  1761. */
  1762. function _locale_export_string($str) {
  1763. $stri = addcslashes($str, "\0..\37\\\"");
  1764. $parts = array();
  1765. // Cut text into several lines
  1766. while ($stri != "") {
  1767. $i = strpos($stri, "\\n");
  1768. if ($i === FALSE) {
  1769. $curstr = $stri;
  1770. $stri = "";
  1771. }
  1772. else {
  1773. $curstr = substr($stri, 0, $i + 2);
  1774. $stri = substr($stri, $i + 2);
  1775. }
  1776. $curparts = explode("\n", _locale_export_wrap($curstr, 70));
  1777. $parts = array_merge($parts, $curparts);
  1778. }
  1779. // Multiline string
  1780. if (count($parts) > 1) {
  1781. return "\"\"\n\"". implode("\"\n\"", $parts) ."\"\n";
  1782. }
  1783. // Single line string
  1784. elseif (count($parts) == 1) {
  1785. return "\"$parts[0]\"\n";
  1786. }
  1787. // No translation
  1788. else {
  1789. return "\"\"\n";
  1790. }
  1791. }
  1792. /**
  1793. * Custom word wrapping for Portable Object (Template) files.
  1794. */
  1795. function _locale_export_wrap($str, $len) {
  1796. $words = explode(' ', $str);
  1797. $ret = array();
  1798. $cur = "";
  1799. $nstr = 1;
  1800. while (count($words)) {
  1801. $word = array_shift($words);
  1802. if ($nstr) {
  1803. $cur = $word;
  1804. $nstr = 0;
  1805. }
  1806. elseif (strlen("$cur $word") > $len) {
  1807. $ret[] = $cur ." ";
  1808. $cur = $word;
  1809. }
  1810. else {
  1811. $cur = "$cur $word";
  1812. }
  1813. }
  1814. $ret[] = $cur;
  1815. return implode("\n", $ret);
  1816. }
  1817. /**
  1818. * Removes plural index information from a string
  1819. */
  1820. function _locale_export_remove_plural($entry) {
  1821. return preg_replace('/(@count)\[[0-9]\]/', '\\1', $entry);
  1822. }
  1823. /**
  1824. * @} End of "locale-api-export"
  1825. */
  1826. /**
  1827. * @defgroup locale-api-seek String search functions.
  1828. * @{
  1829. */
  1830. /**
  1831. * Perform a string search and display results in a table
  1832. */
  1833. function _locale_translate_seek() {
  1834. $output = '';
  1835. // We have at least one criterion to match
  1836. if ($query = _locale_translate_seek_query()) {
  1837. $join = "SELECT s.source, s.location, s.lid, s.textgroup, t.translation, t.language FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid ";
  1838. $arguments = array();
  1839. $limit_language = FALSE;
  1840. // Compute LIKE section
  1841. switch ($query['translation']) {
  1842. case 'translated':
  1843. $where = "WHERE (t.translation LIKE '%%%s%%')";
  1844. $orderby = "ORDER BY t.translation";
  1845. $arguments[] = $query['string'];
  1846. break;
  1847. case 'untranslated':
  1848. $where = "WHERE (s.source LIKE '%%%s%%' AND t.translation IS NULL)";
  1849. $orderby = "ORDER BY s.source";
  1850. $arguments[] = $query['string'];
  1851. break;
  1852. case 'all' :
  1853. default:
  1854. $where = "WHERE (s.source LIKE '%%%s%%' OR t.translation LIKE '%%%s%%')";
  1855. $orderby = '';
  1856. $arguments[] = $query['string'];
  1857. $arguments[] = $query['string'];
  1858. break;
  1859. }
  1860. $grouplimit = '';
  1861. if (!empty($query['group']) && $query['group'] != 'all') {
  1862. $grouplimit = " AND s.textgroup = '%s'";
  1863. $arguments[] = $query['group'];
  1864. }
  1865. switch ($query['language']) {
  1866. // Force search in source strings
  1867. case "en":
  1868. $sql = $join ." WHERE s.source LIKE '%%%s%%' $grouplimit ORDER BY s.source";
  1869. $arguments = array($query['string']); // $where is not used, discard its arguments
  1870. if (!empty($grouplimit)) {
  1871. $arguments[] = $query['group'];
  1872. }
  1873. break;
  1874. // Search in all languages
  1875. case "all":
  1876. $sql = "$join $where $grouplimit $orderby";
  1877. break;
  1878. // Some different language
  1879. default:
  1880. $sql = "$join AND t.language = '%s' $where $grouplimit $orderby";
  1881. array_unshift($arguments, $query['language']);
  1882. // Don't show translation flags for other languages, we can't see them with this search.
  1883. $limit_language = $query['language'];
  1884. }
  1885. $result = pager_query($sql, 50, 0, NULL, $arguments);
  1886. $groups = module_invoke_all('locale', 'groups');
  1887. $header = array(t('Text group'), t('String'), ($limit_language) ? t('Language') : t('Languages'), array('data' => t('Operations'), 'colspan' => '2'));
  1888. $arr = array();
  1889. while ($locale = db_fetch_object($result)) {
  1890. $arr[$locale->lid]['group'] = $groups[$locale->textgroup];
  1891. $arr[$locale->lid]['languages'][$locale->language] = $locale->translation;
  1892. $arr[$locale->lid]['location'] = $locale->location;
  1893. $arr[$locale->lid]['source'] = $locale->source;
  1894. }
  1895. $rows = array();
  1896. foreach ($arr as $lid => $value) {
  1897. $rows[] = array(
  1898. $value['group'],
  1899. array('data' => check_plain(truncate_utf8($value['source'], 150, FALSE, TRUE)) .'<br /><small>'. $value['location'] .'</small>'),
  1900. array('data' => _locale_translate_language_list($value['languages'], $limit_language), 'align' => 'center'),
  1901. array('data' => l(t('edit'), "admin/build/translate/edit/$lid"), 'class' => 'nowrap'),
  1902. array('data' => l(t('delete'), "admin/build/translate/delete/$lid"), 'class' => 'nowrap'),
  1903. );
  1904. }
  1905. if (count($rows)) {
  1906. $output .= theme('table', $header, $rows);
  1907. if ($pager = theme('pager', NULL, 50)) {
  1908. $output .= $pager;
  1909. }
  1910. }
  1911. else {
  1912. $output .= t('No strings found for your search.');
  1913. }
  1914. }
  1915. return $output;
  1916. }
  1917. /**
  1918. * Build array out of search criteria specified in request variables
  1919. */
  1920. function _locale_translate_seek_query() {
  1921. static $query = NULL;
  1922. if (!isset($query)) {
  1923. $query = array();
  1924. $fields = array('string', 'language', 'translation', 'group');
  1925. foreach ($fields as $field) {
  1926. if (isset($_REQUEST[$field])) {
  1927. $query[$field] = $_REQUEST[$field];
  1928. }
  1929. }
  1930. }
  1931. return $query;
  1932. }
  1933. /**
  1934. * Force the JavaScript translation file(s) to be refreshed.
  1935. *
  1936. * This function sets a refresh flag for a specified language, or all
  1937. * languages except English, if none specified. JavaScript translation
  1938. * files are rebuilt (with locale_update_js_files()) the next time a
  1939. * request is served in that language.
  1940. *
  1941. * @param $langcode
  1942. * The language code for which the file needs to be refreshed.
  1943. * @return
  1944. * New content of the 'javascript_parsed' variable.
  1945. */
  1946. function _locale_invalidate_js($langcode = NULL) {
  1947. $parsed = variable_get('javascript_parsed', array());
  1948. if (empty($langcode)) {
  1949. // Invalidate all languages.
  1950. $languages = language_list();
  1951. unset($languages['en']);
  1952. foreach ($languages as $lcode => $data) {
  1953. $parsed['refresh:'. $lcode] = 'waiting';
  1954. }
  1955. }
  1956. else {
  1957. // Invalidate single language.
  1958. $parsed['refresh:'. $langcode] = 'waiting';
  1959. }
  1960. variable_set('javascript_parsed', $parsed);
  1961. return $parsed;
  1962. }
  1963. /**
  1964. * (Re-)Creates the JavaScript translation file for a language.
  1965. *
  1966. * @param $language
  1967. * The language, the translation file should be (re)created for.
  1968. */
  1969. function _locale_rebuild_js($langcode = NULL) {
  1970. if (!isset($langcode)) {
  1971. global $language;
  1972. }
  1973. else {
  1974. // Get information about the locale.
  1975. $languages = language_list();
  1976. $language = $languages[$langcode];
  1977. }
  1978. // Construct the array for JavaScript translations.
  1979. // Only add strings with a translation to the translations array.
  1980. $result = db_query("SELECT s.lid, s.source, t.translation FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid AND t.language = '%s' WHERE s.location LIKE '%%.js%%' AND s.textgroup = 'default'", $language->language);
  1981. $translations = array();
  1982. while ($data = db_fetch_object($result)) {
  1983. $translations[$data->source] = $data->translation;
  1984. }
  1985. // Construct the JavaScript file, if there are translations.
  1986. $data_hash = NULL;
  1987. $data = $status = '';
  1988. if (!empty($translations)) {
  1989. $data = "Drupal.locale = { ";
  1990. if (!empty($language->formula)) {
  1991. $data .= "'pluralFormula': function(\$n) { return Number({$language->formula}); }, ";
  1992. }
  1993. $data .= "'strings': ". drupal_to_js($translations) ." };";
  1994. $data_hash = md5($data);
  1995. }
  1996. // Construct the filepath where JS translation files are stored.
  1997. // There is (on purpose) no front end to edit that variable.
  1998. $dir = file_create_path(variable_get('locale_js_directory', 'languages'));
  1999. // Delete old file, if we have no translations anymore, or a different file to be saved.
  2000. $changed_hash = $language->javascript != $data_hash;
  2001. if (!empty($language->javascript) && (!$data || $changed_hash)) {
  2002. file_delete(file_create_path($dir .'/'. $language->language .'_'. $language->javascript .'.js'));
  2003. $language->javascript = '';
  2004. $status = 'deleted';
  2005. }
  2006. // Only create a new file if the content has changed or the original file got
  2007. // lost.
  2008. $dest = $dir .'/'. $language->language .'_'. $data_hash .'.js';
  2009. if ($data && ($changed_hash || !file_exists($dest))) {
  2010. // Ensure that the directory exists and is writable, if possible.
  2011. file_check_directory($dir, TRUE);
  2012. // Save the file.
  2013. if (file_save_data($data, $dest)) {
  2014. $language->javascript = $data_hash;
  2015. // If we deleted a previous version of the file and we replace it with a
  2016. // new one we have an update.
  2017. if ($status == 'deleted') {
  2018. $status = 'updated';
  2019. }
  2020. // If the file did not exist previously and the data has changed we have
  2021. // a fresh creation.
  2022. elseif ($changed_hash) {
  2023. $status = 'created';
  2024. }
  2025. // If the data hash is unchanged the translation was lost and has to be
  2026. // rebuilt.
  2027. else {
  2028. $status = 'rebuilt';
  2029. }
  2030. }
  2031. else {
  2032. $language->javascript = '';
  2033. $status = 'error';
  2034. }
  2035. }
  2036. // Save the new JavaScript hash (or an empty value if the file just got
  2037. // deleted). Act only if some operation was executed that changed the hash
  2038. // code.
  2039. if ($status && $changed_hash) {
  2040. db_query("UPDATE {languages} SET javascript = '%s' WHERE language = '%s'", $language->javascript, $language->language);
  2041. // Update the default language variable if the default language has been altered.
  2042. // This is necessary to keep the variable consistent with the database
  2043. // version of the language and to prevent checking against an outdated hash.
  2044. $default_langcode = language_default('language');
  2045. if ($default_langcode == $language->language) {
  2046. $default = db_fetch_object(db_query("SELECT * FROM {languages} WHERE language = '%s'", $default_langcode));
  2047. variable_set('language_default', $default);
  2048. }
  2049. }
  2050. // Log the operation and return success flag.
  2051. switch ($status) {
  2052. case 'updated':
  2053. watchdog('locale', 'Updated JavaScript translation file for the language %language.', array('%language' => t($language->name)));
  2054. return TRUE;
  2055. case 'rebuilt':
  2056. watchdog('locale', 'JavaScript translation file %file.js was lost.', array('%file' => $language->javascript), WATCHDOG_WARNING);
  2057. // Proceed to the 'created' case as the JavaScript translation file has
  2058. // been created again.
  2059. case 'created':
  2060. watchdog('locale', 'Created JavaScript translation file for the language %language.', array('%language' => t($language->name)));
  2061. return TRUE;
  2062. case 'deleted':
  2063. watchdog('locale', 'Removed JavaScript translation file for the language %language, because no translations currently exist for that language.', array('%language' => t($language->name)));
  2064. return TRUE;
  2065. case 'error':
  2066. watchdog('locale', 'An error occurred during creation of the JavaScript translation file for the language %language.', array('%language' => t($language->name)), WATCHDOG_ERROR);
  2067. return FALSE;
  2068. default:
  2069. // No operation needed.
  2070. return TRUE;
  2071. }
  2072. }
  2073. /**
  2074. * List languages in search result table
  2075. */
  2076. function _locale_translate_language_list($translation, $limit_language) {
  2077. // Add CSS
  2078. drupal_add_css(drupal_get_path('module', 'locale') .'/locale.css', 'module', 'all', FALSE);
  2079. $languages = language_list();
  2080. unset($languages['en']);
  2081. $output = '';
  2082. foreach ($languages as $langcode => $language) {
  2083. if (!$limit_language || $limit_language == $langcode) {
  2084. $output .= (!empty($translation[$langcode])) ? $langcode .' ' : "<em class=\"locale-untranslated\">$langcode</em> ";
  2085. }
  2086. }
  2087. return $output;
  2088. }
  2089. /**
  2090. * @} End of "locale-api-seek"
  2091. */
  2092. /**
  2093. * @defgroup locale-api-predefined List of predefined languages
  2094. * @{
  2095. */
  2096. /**
  2097. * Prepares the language code list for a select form item with only the unsupported ones
  2098. */
  2099. function _locale_prepare_predefined_list() {
  2100. $languages = language_list();
  2101. $predefined = _locale_get_predefined_list();
  2102. foreach ($predefined as $key => $value) {
  2103. if (isset($languages[$key])) {
  2104. unset($predefined[$key]);
  2105. continue;
  2106. }
  2107. // Include native name in output, if possible
  2108. if (count($value) > 1) {
  2109. $tname = t($value[0]);
  2110. $predefined[$key] = ($tname == $value[1]) ? $tname : "$tname ($value[1])";
  2111. }
  2112. else {
  2113. $predefined[$key] = t($value[0]);
  2114. }
  2115. }
  2116. asort($predefined);
  2117. return $predefined;
  2118. }
  2119. /**
  2120. * Some of the common languages with their English and native names
  2121. *
  2122. * Based on ISO 639 and http://people.w3.org/rishida/names/languages.html
  2123. */
  2124. function _locale_get_predefined_list() {
  2125. return array(
  2126. "aa" => array("Afar"),
  2127. "ab" => array("Abkhazian", "аҧсуа бызшәа"),
  2128. "ae" => array("Avestan"),
  2129. "af" => array("Afrikaans"),
  2130. "ak" => array("Akan"),
  2131. "am" => array("Amharic", "አማርኛ"),
  2132. "ar" => array("Arabic", /* Left-to-right marker "‭" */ "العربية", LANGUAGE_RTL),
  2133. "as" => array("Assamese"),
  2134. "av" => array("Avar"),
  2135. "ay" => array("Aymara"),
  2136. "az" => array("Azerbaijani", "azərbaycan"),
  2137. "ba" => array("Bashkir"),
  2138. "be" => array("Belarusian", "Беларуская"),
  2139. "bg" => array("Bulgarian", "Български"),
  2140. "bh" => array("Bihari"),
  2141. "bi" => array("Bislama"),
  2142. "bm" => array("Bambara", "Bamanankan"),
  2143. "bn" => array("Bengali"),
  2144. "bo" => array("Tibetan"),
  2145. "br" => array("Breton"),
  2146. "bs" => array("Bosnian", "Bosanski"),
  2147. "ca" => array("Catalan", "Català"),
  2148. "ce" => array("Chechen"),
  2149. "ch" => array("Chamorro"),
  2150. "co" => array("Corsican"),
  2151. "cr" => array("Cree"),
  2152. "cs" => array("Czech", "Čeština"),
  2153. "cu" => array("Old Slavonic"),
  2154. "cv" => array("Chuvash"),
  2155. "cy" => array("Welsh", "Cymraeg"),
  2156. "da" => array("Danish", "Dansk"),
  2157. "de" => array("German", "Deutsch"),
  2158. "dv" => array("Maldivian"),
  2159. "dz" => array("Bhutani"),
  2160. "ee" => array("Ewe", "Ɛʋɛ"),
  2161. "el" => array("Greek", "Ελληνικά"),
  2162. "en" => array("English"),
  2163. "eo" => array("Esperanto"),
  2164. "es" => array("Spanish", "Español"),
  2165. "et" => array("Estonian", "Eesti"),
  2166. "eu" => array("Basque", "Euskera"),
  2167. "fa" => array("Persian", /* Left-to-right marker "‭" */ "فارسی", LANGUAGE_RTL),
  2168. "ff" => array("Fulah", "Fulfulde"),
  2169. "fi" => array("Finnish", "Suomi"),
  2170. "fj" => array("Fiji"),
  2171. "fo" => array("Faeroese"),
  2172. "fr" => array("French", "Français"),
  2173. "fy" => array("Frisian", "Frysk"),
  2174. "ga" => array("Irish", "Gaeilge"),
  2175. "gd" => array("Scots Gaelic"),
  2176. "gl" => array("Galician", "Galego"),
  2177. "gn" => array("Guarani"),
  2178. "gu" => array("Gujarati"),
  2179. "gv" => array("Manx"),
  2180. "ha" => array("Hausa"),
  2181. "he" => array("Hebrew", /* Left-to-right marker "‭" */ "עברית", LANGUAGE_RTL),
  2182. "hi" => array("Hindi", "हिन्दी"),
  2183. "ho" => array("Hiri Motu"),
  2184. "hr" => array("Croatian", "Hrvatski"),
  2185. "hu" => array("Hungarian", "Magyar"),
  2186. "hy" => array("Armenian", "Հայերեն"),
  2187. "hz" => array("Herero"),
  2188. "ia" => array("Interlingua"),
  2189. "id" => array("Indonesian", "Bahasa Indonesia"),
  2190. "ie" => array("Interlingue"),
  2191. "ig" => array("Igbo"),
  2192. "ik" => array("Inupiak"),
  2193. "is" => array("Icelandic", "Íslenska"),
  2194. "it" => array("Italian", "Italiano"),
  2195. "iu" => array("Inuktitut"),
  2196. "ja" => array("Japanese", "日本語"),
  2197. "jv" => array("Javanese"),
  2198. "ka" => array("Georgian"),
  2199. "kg" => array("Kongo"),
  2200. "ki" => array("Kikuyu"),
  2201. "kj" => array("Kwanyama"),
  2202. "kk" => array("Kazakh", "Қазақ"),
  2203. "kl" => array("Greenlandic"),
  2204. "km" => array("Cambodian"),
  2205. "kn" => array("Kannada", "ಕನ್ನಡ"),
  2206. "ko" => array("Korean", "한국어"),
  2207. "kr" => array("Kanuri"),
  2208. "ks" => array("Kashmiri"),
  2209. "ku" => array("Kurdish", "Kurdî"),
  2210. "kv" => array("Komi"),
  2211. "kw" => array("Cornish"),
  2212. "ky" => array("Kirghiz", "Кыргыз"),
  2213. "la" => array("Latin", "Latina"),
  2214. "lb" => array("Luxembourgish"),
  2215. "lg" => array("Luganda"),
  2216. "ln" => array("Lingala"),
  2217. "lo" => array("Laothian"),
  2218. "lt" => array("Lithuanian", "Lietuvių"),
  2219. "lv" => array("Latvian", "Latviešu"),
  2220. "mg" => array("Malagasy"),
  2221. "mh" => array("Marshallese"),
  2222. "mi" => array("Maori"),
  2223. "mk" => array("Macedonian", "Македонски"),
  2224. "ml" => array("Malayalam", "മലയാളം"),
  2225. "mn" => array("Mongolian"),
  2226. "mo" => array("Moldavian"),
  2227. "mr" => array("Marathi"),
  2228. "ms" => array("Malay", "Bahasa Melayu"),
  2229. "mt" => array("Maltese", "Malti"),
  2230. "my" => array("Burmese"),
  2231. "na" => array("Nauru"),
  2232. "nd" => array("North Ndebele"),
  2233. "ne" => array("Nepali"),
  2234. "ng" => array("Ndonga"),
  2235. "nl" => array("Dutch", "Nederlands"),
  2236. "nb" => array("Norwegian Bokmål", "Bokmål"),
  2237. "nn" => array("Norwegian Nynorsk", "Nynorsk"),
  2238. "nr" => array("South Ndebele"),
  2239. "nv" => array("Navajo"),
  2240. "ny" => array("Chichewa"),
  2241. "oc" => array("Occitan"),
  2242. "om" => array("Oromo"),
  2243. "or" => array("Oriya"),
  2244. "os" => array("Ossetian"),
  2245. "pa" => array("Punjabi"),
  2246. "pi" => array("Pali"),
  2247. "pl" => array("Polish", "Polski"),
  2248. "ps" => array("Pashto", /* Left-to-right marker "‭" */ "پښتو", LANGUAGE_RTL),
  2249. "pt-pt" => array("Portuguese, Portugal", "Português"),
  2250. "pt-br" => array("Portuguese, Brazil", "Português"),
  2251. "qu" => array("Quechua"),
  2252. "rm" => array("Rhaeto-Romance"),
  2253. "rn" => array("Kirundi"),
  2254. "ro" => array("Romanian", "Română"),
  2255. "ru" => array("Russian", "Русский"),
  2256. "rw" => array("Kinyarwanda"),
  2257. "sa" => array("Sanskrit"),
  2258. "sc" => array("Sardinian"),
  2259. "sd" => array("Sindhi"),
  2260. "se" => array("Northern Sami"),
  2261. "sg" => array("Sango"),
  2262. "sh" => array("Serbo-Croatian"),
  2263. "si" => array("Sinhala", "සිංහල"),
  2264. "sk" => array("Slovak", "Slovenčina"),
  2265. "sl" => array("Slovenian", "Slovenščina"),
  2266. "sm" => array("Samoan"),
  2267. "sn" => array("Shona"),
  2268. "so" => array("Somali"),
  2269. "sq" => array("Albanian", "Shqip"),
  2270. "sr" => array("Serbian", "Српски"),
  2271. "ss" => array("Siswati"),
  2272. "st" => array("Sesotho"),
  2273. "su" => array("Sudanese"),
  2274. "sv" => array("Swedish", "Svenska"),
  2275. "sw" => array("Swahili", "Kiswahili"),
  2276. "ta" => array("Tamil", "தமிழ்"),
  2277. "te" => array("Telugu", "తెలుగు"),
  2278. "tg" => array("Tajik"),
  2279. "th" => array("Thai", "ภาษาไทย"),
  2280. "ti" => array("Tigrinya"),
  2281. "tk" => array("Turkmen"),
  2282. "tl" => array("Tagalog"),
  2283. "tn" => array("Setswana"),
  2284. "to" => array("Tonga"),
  2285. "tr" => array("Turkish", "Türkçe"),
  2286. "ts" => array("Tsonga"),
  2287. "tt" => array("Tatar", "Tatarça"),
  2288. "tw" => array("Twi"),
  2289. "ty" => array("Tahitian"),
  2290. "ug" => array("Uighur"),
  2291. "uk" => array("Ukrainian", "Українська"),
  2292. "ur" => array("Urdu", /* Left-to-right marker "‭" */ "اردو", LANGUAGE_RTL),
  2293. "uz" => array("Uzbek", "o'zbek"),
  2294. "ve" => array("Venda"),
  2295. "vi" => array("Vietnamese", "Tiếng Việt"),
  2296. "wo" => array("Wolof"),
  2297. "xh" => array("Xhosa", "isiXhosa"),
  2298. "yi" => array("Yiddish"),
  2299. "yo" => array("Yoruba", "Yorùbá"),
  2300. "za" => array("Zhuang"),
  2301. "zh-hans" => array("Chinese, Simplified", "简体中文"),
  2302. "zh-hant" => array("Chinese, Traditional", "繁體中文"),
  2303. "zu" => array("Zulu", "isiZulu"),
  2304. );
  2305. }
  2306. /**
  2307. * @} End of "locale-api-languages-predefined"
  2308. */
  2309. /**
  2310. * @defgroup locale-autoimport Automatic interface translation import
  2311. * @{
  2312. */
  2313. /**
  2314. * Prepare a batch to import translations for all enabled
  2315. * modules in a given language.
  2316. *
  2317. * @param $langcode
  2318. * Language code to import translations for.
  2319. * @param $finished
  2320. * Optional finished callback for the batch.
  2321. * @param $skip
  2322. * Array of component names to skip. Used in the installer for the
  2323. * second pass import, when most components are already imported.
  2324. * @return
  2325. * A batch structure or FALSE if no files found.
  2326. */
  2327. function locale_batch_by_language($langcode, $finished = NULL, $skip = array()) {
  2328. // Collect all files to import for all enabled modules and themes.
  2329. $files = array();
  2330. $components = array();
  2331. $query = "SELECT name, filename FROM {system} WHERE status = 1";
  2332. if (count($skip)) {
  2333. $query .= " AND name NOT IN (". db_placeholders($skip, 'varchar') .")";
  2334. }
  2335. $result = db_query($query, $skip);
  2336. while ($component = db_fetch_object($result)) {
  2337. // Collect all files for all components, names as $langcode.po or
  2338. // with names ending with $langcode.po. This allows for filenames
  2339. // like node-module.de.po to let translators use small files and
  2340. // be able to import in smaller chunks.
  2341. $files = array_merge($files, file_scan_directory(dirname($component->filename) .'/translations', '(^|\.)'. $langcode .'\.po$', array('.', '..', 'CVS'), 0, FALSE));
  2342. $components[] = $component->name;
  2343. }
  2344. return _locale_batch_build($files, $finished, $components);
  2345. }
  2346. /**
  2347. * Prepare a batch to run when installing modules or enabling themes.
  2348. * This batch will import translations for the newly added components
  2349. * in all the languages already set up on the site.
  2350. *
  2351. * @param $components
  2352. * An array of component (theme and/or module) names to import
  2353. * translations for.
  2354. * @param $finished
  2355. * Optional finished callback for the batch.
  2356. */
  2357. function locale_batch_by_component($components, $finished = '_locale_batch_system_finished') {
  2358. $files = array();
  2359. $languages = language_list('enabled');
  2360. unset($languages[1]['en']);
  2361. if (count($languages[1])) {
  2362. $language_list = join('|', array_keys($languages[1]));
  2363. // Collect all files to import for all $components.
  2364. $result = db_query("SELECT name, filename FROM {system} WHERE status = 1");
  2365. while ($component = db_fetch_object($result)) {
  2366. if (in_array($component->name, $components)) {
  2367. // Collect all files for this component in all enabled languages, named
  2368. // as $langcode.po or with names ending with $langcode.po. This allows
  2369. // for filenames like node-module.de.po to let translators use small
  2370. // files and be able to import in smaller chunks.
  2371. $files = array_merge($files, file_scan_directory(dirname($component->filename) .'/translations', '(^|\.)('. $language_list .')\.po$', array('.', '..', 'CVS'), 0, FALSE));
  2372. }
  2373. }
  2374. return _locale_batch_build($files, $finished);
  2375. }
  2376. return FALSE;
  2377. }
  2378. /**
  2379. * Build a locale batch from an array of files.
  2380. *
  2381. * @param $files
  2382. * Array of files to import
  2383. * @param $finished
  2384. * Optional finished callback for the batch.
  2385. * @param $components
  2386. * Optional list of component names the batch covers. Used in the installer.
  2387. * @return
  2388. * A batch structure
  2389. */
  2390. function _locale_batch_build($files, $finished = NULL, $components = array()) {
  2391. $t = get_t();
  2392. if (count($files)) {
  2393. $operations = array();
  2394. foreach ($files as $file) {
  2395. // We call _locale_batch_import for every batch operation.
  2396. $operations[] = array('_locale_batch_import', array($file->filename));
  2397. }
  2398. $batch = array(
  2399. 'operations' => $operations,
  2400. 'title' => $t('Importing interface translations'),
  2401. 'init_message' => $t('Starting import'),
  2402. 'error_message' => $t('Error importing interface translations'),
  2403. 'file' => './includes/locale.inc',
  2404. // This is not a batch API construct, but data passed along to the
  2405. // installer, so we know what did we import already.
  2406. '#components' => $components,
  2407. );
  2408. if (isset($finished)) {
  2409. $batch['finished'] = $finished;
  2410. }
  2411. return $batch;
  2412. }
  2413. return FALSE;
  2414. }
  2415. /**
  2416. * Perform interface translation import as a batch step.
  2417. *
  2418. * @param $filepath
  2419. * Path to a file to import.
  2420. * @param $results
  2421. * Contains a list of files imported.
  2422. */
  2423. function _locale_batch_import($filepath, &$context) {
  2424. // The filename is either {langcode}.po or {prefix}.{langcode}.po, so
  2425. // we can extract the language code to use for the import from the end.
  2426. if (preg_match('!(/|\.)([^\./]+)\.po$!', $filepath, $langcode)) {
  2427. $file = (object) array('filename' => basename($filepath), 'filepath' => $filepath);
  2428. _locale_import_read_po('db-store', $file, LOCALE_IMPORT_KEEP, $langcode[2]);
  2429. $context['results'][] = $filepath;
  2430. }
  2431. }
  2432. /**
  2433. * Finished callback of system page locale import batch.
  2434. * Inform the user of translation files imported.
  2435. */
  2436. function _locale_batch_system_finished($success, $results) {
  2437. if ($success) {
  2438. drupal_set_message(format_plural(count($results), 'One translation file imported for the newly installed modules.', '@count translation files imported for the newly installed modules.'));
  2439. }
  2440. }
  2441. /**
  2442. * Finished callback of language addition locale import batch.
  2443. * Inform the user of translation files imported.
  2444. */
  2445. function _locale_batch_language_finished($success, $results) {
  2446. if ($success) {
  2447. drupal_set_message(format_plural(count($results), 'One translation file imported for the enabled modules.', '@count translation files imported for the enabled modules.'));
  2448. }
  2449. }
  2450. /**
  2451. * @} End of "locale-autoimport"
  2452. */

Functions

Nombreorden descendente Descripción
locale_add_language API function to add a language.
locale_batch_by_component Prepare a batch to run when installing modules or enabling themes. This batch will import translations for the newly added components in all the languages already set up on the site.
locale_batch_by_language Prepare a batch to import translations for all enabled modules in a given language.
locale_languages_add_screen User interface for the language addition screen.
locale_languages_configure_form Setting for language negotiation options
locale_languages_configure_form_submit Submit function for language negotiation settings.
locale_languages_custom_form Custom language addition form.
locale_languages_delete_form User interface for the language deletion confirmation screen.
locale_languages_delete_form_submit Process language deletion submissions.
locale_languages_edit_form Editing screen for a particular language.
locale_languages_edit_form_submit Process the language editing form submission.
locale_languages_edit_form_validate Validate the language editing form. Reused for custom language addition too.
locale_languages_overview_form User interface for the language overview screen.
locale_languages_overview_form_submit Process language overview form submissions, updating existing languages.
locale_languages_predefined_form Predefined language setup form.
locale_languages_predefined_form_submit Process the language addition form submission.
locale_languages_predefined_form_validate Validate the language addition form.
locale_string_is_safe Check that a string is safe to be added or imported as a translation.
locale_translate_delete_form User interface for the string deletion confirmation screen.
locale_translate_delete_form_submit Process string deletion submissions.
locale_translate_delete_page String deletion confirmation page.
locale_translate_edit_form User interface for string editing.
locale_translate_edit_form_submit Process string editing form submissions.
locale_translate_edit_form_validate Validate string editing form submissions.
locale_translate_export_pot_form Translation template export form.
locale_translate_export_po_form Form to export PO files for the languages provided.
locale_translate_export_po_form_submit Process a translation (or template) export form submission.
locale_translate_export_screen User interface for the translation export screen.
locale_translate_import_form User interface for the translation import screen.
locale_translate_import_form_submit Process the locale import form submission.
locale_translate_overview_screen Overview screen for translations.
locale_translate_seek_form User interface for the string search screen.
locale_translate_seek_screen String search screen.
theme_locale_languages_overview_form Theme the language overview form.
_locale_batch_build Build a locale batch from an array of files.
_locale_batch_import Perform interface translation import as a batch step.
_locale_batch_language_finished Finished callback of language addition locale import batch. Inform the user of translation files imported.
_locale_batch_system_finished Finished callback of system page locale import batch. Inform the user of translation files imported.
_locale_export_get_strings Generates a structured array of all strings with translations in $language, if given. This array can be used to generate an export of the string in the database.
_locale_export_po Write a generated PO or POT file to the output.
_locale_export_po_generate Generates the PO(T) file contents for given strings.
_locale_export_remove_plural Removes plural index information from a string
_locale_export_string Print out a string on multiple lines
_locale_export_wrap Custom word wrapping for Portable Object (Template) files.
_locale_get_predefined_list Some of the common languages with their English and native names
_locale_import_append_plural Modify a string to contain proper count indices
_locale_import_message Sets an error message occurred during locale file parsing.
_locale_import_one_string Imports a string into the database
_locale_import_one_string_db Import one string into the database.
_locale_import_parse_arithmetic Parses and sanitizes an arithmetic formula into a PHP expression
_locale_import_parse_header Parses a Gettext Portable Object file header
_locale_import_parse_plural_forms Parses a Plural-Forms entry from a Gettext Portable Object file header
_locale_import_parse_quoted Parses a string in quotes
_locale_import_po Parses Gettext Portable Object file information and inserts into database
_locale_import_read_po Parses Gettext Portable Object file into an array
_locale_import_shorten_comments Generate a short, one string version of the passed comment array
_locale_import_tokenize_formula Backward compatible implementation of token_get_all() for formula parsing
_locale_invalidate_js Force the JavaScript translation file(s) to be refreshed.
_locale_languages_common_controls Common elements of the language addition and editing form.
_locale_parse_js_file Parses a JavaScript file, extracts strings wrapped in Drupal.t() and Drupal.formatPlural() and inserts them into the database.
_locale_prepare_predefined_list Prepares the language code list for a select form item with only the unsupported ones
_locale_rebuild_js (Re-)Creates the JavaScript translation file for a language.
_locale_translate_language_list List languages in search result table
_locale_translate_seek Perform a string search and display results in a table
_locale_translate_seek_query Build array out of search criteria specified in request variables

Constants

Nombreorden descendente Descripción
LOCALE_IMPORT_KEEP Translation import mode keeping existing translations and only inserting new strings.
LOCALE_IMPORT_OVERWRITE Translation import mode overwriting all existing translations if new translated version available.
LOCALE_JS_STRING