home *** CD-ROM | disk | FTP | other *** search
/ Cricao de Sites - 650 Layouts Prontos / WebMasters.iso / CMS / drupal-6.0.exe / drupal-6.0 / includes / locale.inc < prev    next >
Encoding:
Text File  |  2008-01-09  |  91.3 KB  |  2,571 lines

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