web/drupal/includes/locale.inc
branchdrupal
changeset 74 0ff3ba646492
equal deleted inserted replaced
73:fcf75e232c5b 74:0ff3ba646492
       
     1 <?php
       
     2 // $Id: locale.inc,v 1.174.2.9 2009/06/18 12:50:33 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' => 128,
       
   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     $form_state['redirect'] = 'admin/build/translate/import';
       
   668     return;
       
   669   }
       
   670 
       
   671   $form_state['redirect'] = 'admin/build/translate';
       
   672   return;
       
   673 }
       
   674 /**
       
   675  * @} End of "locale-translate-import"
       
   676  */
       
   677 
       
   678 /**
       
   679  * @defgroup locale-translate-export Translation export screen.
       
   680  * @{
       
   681  */
       
   682 
       
   683 /**
       
   684  * User interface for the translation export screen.
       
   685  */
       
   686 function locale_translate_export_screen() {
       
   687   // Get all languages, except English
       
   688   $names = locale_language_list('name', TRUE);
       
   689   unset($names['en']);
       
   690   $output = '';
       
   691   // Offer translation export if any language is set up.
       
   692   if (count($names)) {
       
   693     $output = drupal_get_form('locale_translate_export_po_form', $names);
       
   694   }
       
   695   $output .= drupal_get_form('locale_translate_export_pot_form');
       
   696   return $output;
       
   697 }
       
   698 
       
   699 /**
       
   700  * Form to export PO files for the languages provided.
       
   701  *
       
   702  * @param $names
       
   703  *   An associate array with localized language names
       
   704  */
       
   705 function locale_translate_export_po_form(&$form_state, $names) {
       
   706   $form['export'] = array('#type' => 'fieldset',
       
   707     '#title' => t('Export translation'),
       
   708     '#collapsible' => TRUE,
       
   709   );
       
   710   $form['export']['langcode'] = array('#type' => 'select',
       
   711     '#title' => t('Language name'),
       
   712     '#options' => $names,
       
   713     '#description' => t('Select the language to export in Gettext Portable Object (<em>.po</em>) format.'),
       
   714   );
       
   715   $form['export']['group'] = array('#type' => 'radios',
       
   716     '#title' => t('Text group'),
       
   717     '#default_value' => 'default',
       
   718     '#options' => module_invoke_all('locale', 'groups'),
       
   719   );
       
   720   $form['export']['submit'] = array('#type' => 'submit', '#value' => t('Export'));
       
   721   return $form;
       
   722 }
       
   723 
       
   724 /**
       
   725  * Translation template export form.
       
   726  */
       
   727 function locale_translate_export_pot_form() {
       
   728   // Complete template export of the strings
       
   729   $form['export'] = array('#type' => 'fieldset',
       
   730     '#title' => t('Export template'),
       
   731     '#collapsible' => TRUE,
       
   732     '#description' => t('Generate a Gettext Portable Object Template (<em>.pot</em>) file with all strings from the Drupal locale database.'),
       
   733   );
       
   734   $form['export']['group'] = array('#type' => 'radios',
       
   735     '#title' => t('Text group'),
       
   736     '#default_value' => 'default',
       
   737     '#options' => module_invoke_all('locale', 'groups'),
       
   738   );
       
   739   $form['export']['submit'] = array('#type' => 'submit', '#value' => t('Export'));
       
   740   // Reuse PO export submission callback.
       
   741   $form['#submit'][] = 'locale_translate_export_po_form_submit';
       
   742   $form['#validate'][] = 'locale_translate_export_po_form_validate';
       
   743   return $form;
       
   744 }
       
   745 
       
   746 /**
       
   747  * Process a translation (or template) export form submission.
       
   748  */
       
   749 function locale_translate_export_po_form_submit($form, &$form_state) {
       
   750   // If template is required, language code is not given.
       
   751   $language = NULL;
       
   752   if (isset($form_state['values']['langcode'])) {
       
   753     $languages = language_list();
       
   754     $language = $languages[$form_state['values']['langcode']];
       
   755   }
       
   756   _locale_export_po($language, _locale_export_po_generate($language, _locale_export_get_strings($language, $form_state['values']['group'])));
       
   757 }
       
   758 /**
       
   759  * @} End of "locale-translate-export"
       
   760  */
       
   761 
       
   762 /**
       
   763  * @defgroup locale-translate-edit Translation text editing
       
   764  * @{
       
   765  */
       
   766 
       
   767 /**
       
   768  * User interface for string editing.
       
   769  */
       
   770 function locale_translate_edit_form(&$form_state, $lid) {
       
   771   // Fetch source string, if possible.
       
   772   $source = db_fetch_object(db_query('SELECT source, textgroup, location FROM {locales_source} WHERE lid = %d', $lid));
       
   773   if (!$source) {
       
   774     drupal_set_message(t('String not found.'), 'error');
       
   775     drupal_goto('admin/build/translate/search');
       
   776   }
       
   777 
       
   778   // Add original text to the top and some values for form altering.
       
   779   $form = array(
       
   780     'original' => array(
       
   781       '#type'  => 'item',
       
   782       '#title' => t('Original text'),
       
   783       '#value' => check_plain(wordwrap($source->source, 0)),
       
   784     ),
       
   785     'lid' => array(
       
   786       '#type'  => 'value',
       
   787       '#value' => $lid
       
   788     ),
       
   789     'textgroup' => array(
       
   790       '#type'  => 'value',
       
   791       '#value' => $source->textgroup,
       
   792     ),
       
   793     'location' => array(
       
   794       '#type'  => 'value',
       
   795       '#value' => $source->location
       
   796     ),
       
   797   );
       
   798 
       
   799   // Include default form controls with empty values for all languages.
       
   800   // This ensures that the languages are always in the same order in forms.
       
   801   $languages = language_list();
       
   802   $default = language_default();
       
   803   // We don't need the default language value, that value is in $source.
       
   804   $omit = $source->textgroup == 'default' ? 'en' : $default->language;
       
   805   unset($languages[($omit)]);
       
   806   $form['translations'] = array('#tree' => TRUE);
       
   807   // Approximate the number of rows to use in the default textarea.
       
   808   $rows = min(ceil(str_word_count($source->source) / 12), 10);
       
   809   foreach ($languages as $langcode => $language) {
       
   810     $form['translations'][$langcode] = array(
       
   811       '#type' => 'textarea',
       
   812       '#title' => t($language->name),
       
   813       '#rows' => $rows,
       
   814       '#default_value' => '',
       
   815     );
       
   816   }
       
   817 
       
   818   // Fetch translations and fill in default values in the form.
       
   819   $result = db_query("SELECT DISTINCT translation, language FROM {locales_target} WHERE lid = %d AND language != '%s'", $lid, $omit);
       
   820   while ($translation = db_fetch_object($result)) {
       
   821     $form['translations'][$translation->language]['#default_value'] = $translation->translation;
       
   822   }
       
   823 
       
   824   $form['submit'] = array('#type' => 'submit', '#value' => t('Save translations'));
       
   825   return $form;
       
   826 }
       
   827 
       
   828 /**
       
   829  * Check that a string is safe to be added or imported as a translation.
       
   830  *
       
   831  * This test can be used to detect possibly bad translation strings. It should
       
   832  * not have any false positives. But it is only a test, not a transformation,
       
   833  * as it destroys valid HTML. We cannot reliably filter translation strings
       
   834  * on inport becuase some strings are irreversibly corrupted. For example,
       
   835  * a &amp; in the translation would get encoded to &amp;amp; by filter_xss()
       
   836  * before being put in the database, and thus would be displayed incorrectly.
       
   837  *
       
   838  * The allowed tag list is like filter_xss_admin(), but omitting div and img as
       
   839  * not needed for translation and likely to cause layout issues (div) or a
       
   840  * possible attack vector (img).
       
   841  */
       
   842 function locale_string_is_safe($string) {
       
   843   return decode_entities($string) == decode_entities(filter_xss($string, array('a', 'abbr', 'acronym', 'address', 'b', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dl', 'dt', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'ins', 'kbd', 'li', 'ol', 'p', 'pre', 'q', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'tt', 'ul', 'var')));
       
   844 }
       
   845 
       
   846 /**
       
   847  * Validate string editing form submissions.
       
   848  */
       
   849 function locale_translate_edit_form_validate($form, &$form_state) {
       
   850   // Locale string check is needed for default textgroup only.
       
   851   $safe_check_needed = $form_state['values']['textgroup'] == 'default';
       
   852   foreach ($form_state['values']['translations'] as $key => $value) {
       
   853     if ($safe_check_needed && !locale_string_is_safe($value)) {
       
   854       form_set_error('translations', t('The submitted string contains disallowed HTML: %string', array('%string' => $value)));
       
   855       watchdog('locale', 'Attempted submission of a translation string with disallowed HTML: %string', array('%string' => $value), WATCHDOG_WARNING);
       
   856     }
       
   857   }
       
   858 }
       
   859 
       
   860 /**
       
   861  * Process string editing form submissions.
       
   862  *
       
   863  * Saves all translations of one string submitted from a form.
       
   864  */
       
   865 function locale_translate_edit_form_submit($form, &$form_state) {
       
   866   $lid = $form_state['values']['lid'];
       
   867   foreach ($form_state['values']['translations'] as $key => $value) {
       
   868     $translation = db_result(db_query("SELECT translation FROM {locales_target} WHERE lid = %d AND language = '%s'", $lid, $key));
       
   869     if (!empty($value)) {
       
   870       // Only update or insert if we have a value to use.
       
   871       if (!empty($translation)) {
       
   872         db_query("UPDATE {locales_target} SET translation = '%s' WHERE lid = %d AND language = '%s'", $value, $lid, $key);
       
   873       }
       
   874       else {
       
   875         db_query("INSERT INTO {locales_target} (lid, translation, language) VALUES (%d, '%s', '%s')", $lid, $value, $key);
       
   876       }
       
   877     }
       
   878     elseif (!empty($translation)) {
       
   879       // Empty translation entered: remove existing entry from database.
       
   880       db_query("DELETE FROM {locales_target} WHERE lid = %d AND language = '%s'", $lid, $key);
       
   881     }
       
   882 
       
   883     // Force JavaScript translation file recreation for this language.
       
   884     _locale_invalidate_js($key);
       
   885   }
       
   886 
       
   887   drupal_set_message(t('The string has been saved.'));
       
   888 
       
   889   // Clear locale cache.
       
   890   _locale_invalidate_js();
       
   891   cache_clear_all('locale:', 'cache', TRUE);
       
   892 
       
   893   $form_state['redirect'] = 'admin/build/translate/search';
       
   894   return;
       
   895 }
       
   896 /**
       
   897  * @} End of "locale-translate-edit"
       
   898  */
       
   899 
       
   900 /**
       
   901  * @defgroup locale-translate-delete Translation delete interface.
       
   902  * @{
       
   903  */
       
   904 
       
   905 /**
       
   906  * String deletion confirmation page.
       
   907  */
       
   908 function locale_translate_delete_page($lid) {
       
   909   if ($source = db_fetch_object(db_query('SELECT * FROM {locales_source} WHERE lid = %d', $lid))) {
       
   910     return drupal_get_form('locale_translate_delete_form', $source);
       
   911   }
       
   912   else {
       
   913     return drupal_not_found();
       
   914   }
       
   915 }
       
   916 
       
   917 /**
       
   918  * User interface for the string deletion confirmation screen.
       
   919  */
       
   920 function locale_translate_delete_form(&$form_state, $source) {
       
   921   $form['lid'] = array('#type' => 'value', '#value' => $source->lid);
       
   922   return confirm_form($form, t('Are you sure you want to delete the string "%source"?', array('%source' => $source->source)), 'admin/build/translate/search', t('Deleting the string will remove all translations of this string in all languages. This action cannot be undone.'), t('Delete'), t('Cancel'));
       
   923 }
       
   924 
       
   925 /**
       
   926  * Process string deletion submissions.
       
   927  */
       
   928 function locale_translate_delete_form_submit($form, &$form_state) {
       
   929   db_query('DELETE FROM {locales_source} WHERE lid = %d', $form_state['values']['lid']);
       
   930   db_query('DELETE FROM {locales_target} WHERE lid = %d', $form_state['values']['lid']);
       
   931   // Force JavaScript translation file recreation for all languages.
       
   932   _locale_invalidate_js();
       
   933   cache_clear_all('locale:', 'cache', TRUE);
       
   934   drupal_set_message(t('The string has been removed.'));
       
   935   $form_state['redirect'] = 'admin/build/translate/search';
       
   936 }
       
   937 /**
       
   938  * @} End of "locale-translate-delete"
       
   939  */
       
   940 
       
   941 /**
       
   942  * @defgroup locale-api-add Language addition API.
       
   943  * @{
       
   944  */
       
   945 
       
   946 /**
       
   947  * API function to add a language.
       
   948  *
       
   949  * @param $langcode
       
   950  *   Language code.
       
   951  * @param $name
       
   952  *   English name of the language
       
   953  * @param $native
       
   954  *   Native name of the language
       
   955  * @param $direction
       
   956  *   LANGUAGE_LTR or LANGUAGE_RTL
       
   957  * @param $domain
       
   958  *   Optional custom domain name with protocol, without
       
   959  *   trailing slash (eg. http://de.example.com).
       
   960  * @param $prefix
       
   961  *   Optional path prefix for the language. Defaults to the
       
   962  *   language code if omitted.
       
   963  * @param $enabled
       
   964  *   Optionally TRUE to enable the language when created or FALSE to disable.
       
   965  * @param $default
       
   966  *   Optionally set this language to be the default.
       
   967  */
       
   968 function locale_add_language($langcode, $name = NULL, $native = NULL, $direction = LANGUAGE_LTR, $domain = '', $prefix = '', $enabled = TRUE, $default = FALSE) {
       
   969   // Default prefix on language code.
       
   970   if (empty($prefix)) {
       
   971     $prefix = $langcode;
       
   972   }
       
   973 
       
   974   // If name was not set, we add a predefined language.
       
   975   if (!isset($name)) {
       
   976     $predefined = _locale_get_predefined_list();
       
   977     $name = $predefined[$langcode][0];
       
   978     $native = isset($predefined[$langcode][1]) ? $predefined[$langcode][1] : $predefined[$langcode][0];
       
   979     $direction = isset($predefined[$langcode][2]) ? $predefined[$langcode][2] : LANGUAGE_LTR;
       
   980   }
       
   981 
       
   982   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);
       
   983 
       
   984   // Only set it as default if enabled.
       
   985   if ($enabled && $default) {
       
   986     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' => ''));
       
   987   }
       
   988 
       
   989   if ($enabled) {
       
   990     // Increment enabled language count if we are adding an enabled language.
       
   991     variable_set('language_count', variable_get('language_count', 1) + 1);
       
   992   }
       
   993 
       
   994   // Force JavaScript translation file creation for the newly added language.
       
   995   _locale_invalidate_js($langcode);
       
   996 
       
   997   watchdog('locale', 'The %language language (%code) has been created.', array('%language' => $name, '%code' => $langcode));
       
   998 }
       
   999 /**
       
  1000  * @} End of "locale-api-add"
       
  1001  */
       
  1002 
       
  1003 /**
       
  1004  * @defgroup locale-api-import Translation import API.
       
  1005  * @{
       
  1006  */
       
  1007 
       
  1008 /**
       
  1009  * Parses Gettext Portable Object file information and inserts into database
       
  1010  *
       
  1011  * @param $file
       
  1012  *   Drupal file object corresponding to the PO file to import
       
  1013  * @param $langcode
       
  1014  *   Language code
       
  1015  * @param $mode
       
  1016  *   Should existing translations be replaced LOCALE_IMPORT_KEEP or LOCALE_IMPORT_OVERWRITE
       
  1017  * @param $group
       
  1018  *   Text group to import PO file into (eg. 'default' for interface translations)
       
  1019  */
       
  1020 function _locale_import_po($file, $langcode, $mode, $group = NULL) {
       
  1021   // If not in 'safe mode', increase the maximum execution time.
       
  1022   if (!ini_get('safe_mode')) {
       
  1023     set_time_limit(240);
       
  1024   }
       
  1025 
       
  1026   // Check if we have the language already in the database.
       
  1027   if (!db_fetch_object(db_query("SELECT language FROM {languages} WHERE language = '%s'", $langcode))) {
       
  1028     drupal_set_message(t('The language selected for import is not supported.'), 'error');
       
  1029     return FALSE;
       
  1030   }
       
  1031 
       
  1032   // Get strings from file (returns on failure after a partial import, or on success)
       
  1033   $status = _locale_import_read_po('db-store', $file, $mode, $langcode, $group);
       
  1034   if ($status === FALSE) {
       
  1035     // Error messages are set in _locale_import_read_po().
       
  1036     return FALSE;
       
  1037   }
       
  1038 
       
  1039   // Get status information on import process.
       
  1040   list($headerdone, $additions, $updates, $deletes, $skips) = _locale_import_one_string('db-report');
       
  1041 
       
  1042   if (!$headerdone) {
       
  1043     drupal_set_message(t('The translation file %filename appears to have a missing or malformed header.', array('%filename' => $file->filename)), 'error');
       
  1044   }
       
  1045 
       
  1046   // Clear cache and force refresh of JavaScript translations.
       
  1047   _locale_invalidate_js($langcode);
       
  1048   cache_clear_all('locale:', 'cache', TRUE);
       
  1049 
       
  1050   // Rebuild the menu, strings may have changed.
       
  1051   menu_rebuild();
       
  1052 
       
  1053   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)));
       
  1054   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));
       
  1055   if ($skips) {
       
  1056     $skip_message = format_plural($skips, 'One translation string was skipped because it contains disallowed HTML.', '@count translation strings were skipped because they contain disallowed HTML.');
       
  1057     drupal_set_message($skip_message);
       
  1058     watchdog('locale', $skip_message, NULL, WATCHDOG_WARNING);
       
  1059   }
       
  1060   return TRUE;
       
  1061 }
       
  1062 
       
  1063 /**
       
  1064  * Parses Gettext Portable Object file into an array
       
  1065  *
       
  1066  * @param $op
       
  1067  *   Storage operation type: db-store or mem-store
       
  1068  * @param $file
       
  1069  *   Drupal file object corresponding to the PO file to import
       
  1070  * @param $mode
       
  1071  *   Should existing translations be replaced LOCALE_IMPORT_KEEP or LOCALE_IMPORT_OVERWRITE
       
  1072  * @param $lang
       
  1073  *   Language code
       
  1074  * @param $group
       
  1075  *   Text group to import PO file into (eg. 'default' for interface translations)
       
  1076  */
       
  1077 function _locale_import_read_po($op, $file, $mode = NULL, $lang = NULL, $group = 'default') {
       
  1078 
       
  1079   $fd = fopen($file->filepath, "rb"); // File will get closed by PHP on return
       
  1080   if (!$fd) {
       
  1081     _locale_import_message('The translation import failed, because the file %filename could not be read.', $file);
       
  1082     return FALSE;
       
  1083   }
       
  1084 
       
  1085   $context = "COMMENT"; // Parser context: COMMENT, MSGID, MSGID_PLURAL, MSGSTR and MSGSTR_ARR
       
  1086   $current = array();   // Current entry being read
       
  1087   $plural = 0;          // Current plural form
       
  1088   $lineno = 0;          // Current line
       
  1089 
       
  1090   while (!feof($fd)) {
       
  1091     $line = fgets($fd, 10*1024); // A line should not be this long
       
  1092     if ($lineno == 0) {
       
  1093       // The first line might come with a UTF-8 BOM, which should be removed.
       
  1094       $line = str_replace("\xEF\xBB\xBF", '', $line);
       
  1095     }
       
  1096     $lineno++;
       
  1097     $line = trim(strtr($line, array("\\\n" => "")));
       
  1098 
       
  1099     if (!strncmp("#", $line, 1)) { // A comment
       
  1100       if ($context == "COMMENT") { // Already in comment context: add
       
  1101         $current["#"][] = substr($line, 1);
       
  1102       }
       
  1103       elseif (($context == "MSGSTR") || ($context == "MSGSTR_ARR")) { // End current entry, start a new one
       
  1104         _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
       
  1105         $current = array();
       
  1106         $current["#"][] = substr($line, 1);
       
  1107         $context = "COMMENT";
       
  1108       }
       
  1109       else { // Parse error
       
  1110         _locale_import_message('The translation file %filename contains an error: "msgstr" was expected but not found on line %line.', $file, $lineno);
       
  1111         return FALSE;
       
  1112       }
       
  1113     }
       
  1114     elseif (!strncmp("msgid_plural", $line, 12)) {
       
  1115       if ($context != "MSGID") { // Must be plural form for current entry
       
  1116         _locale_import_message('The translation file %filename contains an error: "msgid_plural" was expected but not found on line %line.', $file, $lineno);
       
  1117         return FALSE;
       
  1118       }
       
  1119       $line = trim(substr($line, 12));
       
  1120       $quoted = _locale_import_parse_quoted($line);
       
  1121       if ($quoted === FALSE) {
       
  1122         _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
       
  1123         return FALSE;
       
  1124       }
       
  1125       $current["msgid"] = $current["msgid"] ."\0". $quoted;
       
  1126       $context = "MSGID_PLURAL";
       
  1127     }
       
  1128     elseif (!strncmp("msgid", $line, 5)) {
       
  1129       if ($context == "MSGSTR") {   // End current entry, start a new one
       
  1130         _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
       
  1131         $current = array();
       
  1132       }
       
  1133       elseif ($context == "MSGID") { // Already in this context? Parse error
       
  1134         _locale_import_message('The translation file %filename contains an error: "msgid" is unexpected on line %line.', $file, $lineno);
       
  1135         return FALSE;
       
  1136       }
       
  1137       $line = trim(substr($line, 5));
       
  1138       $quoted = _locale_import_parse_quoted($line);
       
  1139       if ($quoted === FALSE) {
       
  1140         _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
       
  1141         return FALSE;
       
  1142       }
       
  1143       $current["msgid"] = $quoted;
       
  1144       $context = "MSGID";
       
  1145     }
       
  1146     elseif (!strncmp("msgstr[", $line, 7)) {
       
  1147       if (($context != "MSGID") && ($context != "MSGID_PLURAL") && ($context != "MSGSTR_ARR")) { // Must come after msgid, msgid_plural, or msgstr[]
       
  1148         _locale_import_message('The translation file %filename contains an error: "msgstr[]" is unexpected on line %line.', $file, $lineno);
       
  1149         return FALSE;
       
  1150       }
       
  1151       if (strpos($line, "]") === FALSE) {
       
  1152         _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
       
  1153         return FALSE;
       
  1154       }
       
  1155       $frombracket = strstr($line, "[");
       
  1156       $plural = substr($frombracket, 1, strpos($frombracket, "]") - 1);
       
  1157       $line = trim(strstr($line, " "));
       
  1158       $quoted = _locale_import_parse_quoted($line);
       
  1159       if ($quoted === FALSE) {
       
  1160         _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
       
  1161         return FALSE;
       
  1162       }
       
  1163       $current["msgstr"][$plural] = $quoted;
       
  1164       $context = "MSGSTR_ARR";
       
  1165     }
       
  1166     elseif (!strncmp("msgstr", $line, 6)) {
       
  1167       if ($context != "MSGID") {   // Should come just after a msgid block
       
  1168         _locale_import_message('The translation file %filename contains an error: "msgstr" is unexpected on line %line.', $file, $lineno);
       
  1169         return FALSE;
       
  1170       }
       
  1171       $line = trim(substr($line, 6));
       
  1172       $quoted = _locale_import_parse_quoted($line);
       
  1173       if ($quoted === FALSE) {
       
  1174         _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
       
  1175         return FALSE;
       
  1176       }
       
  1177       $current["msgstr"] = $quoted;
       
  1178       $context = "MSGSTR";
       
  1179     }
       
  1180     elseif ($line != "") {
       
  1181       $quoted = _locale_import_parse_quoted($line);
       
  1182       if ($quoted === FALSE) {
       
  1183         _locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
       
  1184         return FALSE;
       
  1185       }
       
  1186       if (($context == "MSGID") || ($context == "MSGID_PLURAL")) {
       
  1187         $current["msgid"] .= $quoted;
       
  1188       }
       
  1189       elseif ($context == "MSGSTR") {
       
  1190         $current["msgstr"] .= $quoted;
       
  1191       }
       
  1192       elseif ($context == "MSGSTR_ARR") {
       
  1193         $current["msgstr"][$plural] .= $quoted;
       
  1194       }
       
  1195       else {
       
  1196         _locale_import_message('The translation file %filename contains an error: there is an unexpected string on line %line.', $file, $lineno);
       
  1197         return FALSE;
       
  1198       }
       
  1199     }
       
  1200   }
       
  1201 
       
  1202   // End of PO file, flush last entry
       
  1203   if (($context == "MSGSTR") || ($context == "MSGSTR_ARR")) {
       
  1204     _locale_import_one_string($op, $current, $mode, $lang, $file, $group);
       
  1205   }
       
  1206   elseif ($context != "COMMENT") {
       
  1207     _locale_import_message('The translation file %filename ended unexpectedly at line %line.', $file, $lineno);
       
  1208     return FALSE;
       
  1209   }
       
  1210 
       
  1211 }
       
  1212 
       
  1213 /**
       
  1214  * Sets an error message occurred during locale file parsing.
       
  1215  *
       
  1216  * @param $message
       
  1217  *   The message to be translated
       
  1218  * @param $file
       
  1219  *   Drupal file object corresponding to the PO file to import
       
  1220  * @param $lineno
       
  1221  *   An optional line number argument
       
  1222  */
       
  1223 function _locale_import_message($message, $file, $lineno = NULL) {
       
  1224   $vars = array('%filename' => $file->filename);
       
  1225   if (isset($lineno)) {
       
  1226     $vars['%line'] = $lineno;
       
  1227   }
       
  1228   $t = get_t();
       
  1229   drupal_set_message($t($message, $vars), 'error');
       
  1230 }
       
  1231 
       
  1232 /**
       
  1233  * Imports a string into the database
       
  1234  *
       
  1235  * @param $op
       
  1236  *   Operation to perform: 'db-store', 'db-report', 'mem-store' or 'mem-report'
       
  1237  * @param $value
       
  1238  *   Details of the string stored
       
  1239  * @param $mode
       
  1240  *   Should existing translations be replaced LOCALE_IMPORT_KEEP or LOCALE_IMPORT_OVERWRITE
       
  1241  * @param $lang
       
  1242  *   Language to store the string in
       
  1243  * @param $file
       
  1244  *   Object representation of file being imported, only required when op is 'db-store'
       
  1245  * @param $group
       
  1246  *   Text group to import PO file into (eg. 'default' for interface translations)
       
  1247  */
       
  1248 function _locale_import_one_string($op, $value = NULL, $mode = NULL, $lang = NULL, $file = NULL, $group = 'default') {
       
  1249   static $report = array('additions' => 0, 'updates' => 0, 'deletes' => 0, 'skips' => 0);
       
  1250   static $headerdone = FALSE;
       
  1251   static $strings = array();
       
  1252 
       
  1253   switch ($op) {
       
  1254     // Return stored strings
       
  1255     case 'mem-report':
       
  1256       return $strings;
       
  1257 
       
  1258     // Store string in memory (only supports single strings)
       
  1259     case 'mem-store':
       
  1260       $strings[$value['msgid']] = $value['msgstr'];
       
  1261       return;
       
  1262 
       
  1263     // Called at end of import to inform the user
       
  1264     case 'db-report':
       
  1265       return array($headerdone, $report['additions'], $report['updates'], $report['deletes'], $report['skips']);
       
  1266 
       
  1267     // Store the string we got in the database.
       
  1268     case 'db-store':
       
  1269       // We got header information.
       
  1270       if ($value['msgid'] == '') {
       
  1271         $header = _locale_import_parse_header($value['msgstr']);
       
  1272 
       
  1273         // Get the plural formula and update in database.
       
  1274         if (isset($header["Plural-Forms"]) && $p = _locale_import_parse_plural_forms($header["Plural-Forms"], $file->filename)) {
       
  1275           list($nplurals, $plural) = $p;
       
  1276           db_query("UPDATE {languages} SET plurals = %d, formula = '%s' WHERE language = '%s'", $nplurals, $plural, $lang);
       
  1277         }
       
  1278         else {
       
  1279           db_query("UPDATE {languages} SET plurals = %d, formula = '%s' WHERE language = '%s'", 0, '', $lang);
       
  1280         }
       
  1281         $headerdone = TRUE;
       
  1282       }
       
  1283 
       
  1284       else {
       
  1285         // Some real string to import.
       
  1286         $comments = _locale_import_shorten_comments(empty($value['#']) ? array() : $value['#']);
       
  1287 
       
  1288         if (strpos($value['msgid'], "\0")) {
       
  1289           // This string has plural versions.
       
  1290           $english = explode("\0", $value['msgid'], 2);
       
  1291           $entries = array_keys($value['msgstr']);
       
  1292           for ($i = 3; $i <= count($entries); $i++) {
       
  1293             $english[] = $english[1];
       
  1294           }
       
  1295           $translation = array_map('_locale_import_append_plural', $value['msgstr'], $entries);
       
  1296           $english = array_map('_locale_import_append_plural', $english, $entries);
       
  1297           foreach ($translation as $key => $trans) {
       
  1298             if ($key == 0) {
       
  1299               $plid = 0;
       
  1300             }
       
  1301             $plid = _locale_import_one_string_db($report, $lang, $english[$key], $trans, $group, $comments, $mode, $plid, $key);
       
  1302           }
       
  1303         }
       
  1304 
       
  1305         else {
       
  1306           // A simple string to import.
       
  1307           $english = $value['msgid'];
       
  1308           $translation = $value['msgstr'];
       
  1309           _locale_import_one_string_db($report, $lang, $english, $translation, $group, $comments, $mode);
       
  1310         }
       
  1311       }
       
  1312   } // end of db-store operation
       
  1313 }
       
  1314 
       
  1315 /**
       
  1316  * Import one string into the database.
       
  1317  *
       
  1318  * @param $report
       
  1319  *   Report array summarizing the number of changes done in the form:
       
  1320  *   array(inserts, updates, deletes).
       
  1321  * @param $langcode
       
  1322  *   Language code to import string into.
       
  1323  * @param $source
       
  1324  *   Source string.
       
  1325  * @param $translation
       
  1326  *   Translation to language specified in $langcode.
       
  1327  * @param $textgroup
       
  1328  *   Name of textgroup to store translation in.
       
  1329  * @param $location
       
  1330  *   Location value to save with source string.
       
  1331  * @param $mode
       
  1332  *   Import mode to use, LOCALE_IMPORT_KEEP or LOCALE_IMPORT_OVERWRITE.
       
  1333  * @param $plid
       
  1334  *   Optional plural ID to use.
       
  1335  * @param $plural
       
  1336  *   Optional plural value to use.
       
  1337  * @return
       
  1338  *   The string ID of the existing string modified or the new string added.
       
  1339  */
       
  1340 function _locale_import_one_string_db(&$report, $langcode, $source, $translation, $textgroup, $location, $mode, $plid = NULL, $plural = NULL) {
       
  1341   $lid = db_result(db_query("SELECT lid FROM {locales_source} WHERE source = '%s' AND textgroup = '%s'", $source, $textgroup));
       
  1342 
       
  1343   if (!empty($translation)) {
       
  1344      // Skip this string unless it passes a check for dangerous code.
       
  1345      // Text groups other than default still can contain HTML tags
       
  1346      // (i.e. translatable blocks).
       
  1347      if ($textgroup == "default" && !locale_string_is_safe($translation)) {
       
  1348        $report['skips']++;
       
  1349        $lid = 0;
       
  1350      }
       
  1351      elseif ($lid) {
       
  1352       // We have this source string saved already.
       
  1353       db_query("UPDATE {locales_source} SET location = '%s' WHERE lid = %d", $location, $lid);
       
  1354       $exists = (bool) db_result(db_query("SELECT lid FROM {locales_target} WHERE lid = %d AND language = '%s'", $lid, $langcode));
       
  1355       if (!$exists) {
       
  1356         // No translation in this language.
       
  1357         db_query("INSERT INTO {locales_target} (lid, language, translation, plid, plural) VALUES (%d, '%s', '%s', %d, %d)", $lid, $langcode, $translation, $plid, $plural);
       
  1358         $report['additions']++;
       
  1359       }
       
  1360       else if ($mode == LOCALE_IMPORT_OVERWRITE) {
       
  1361         // Translation exists, only overwrite if instructed.
       
  1362         db_query("UPDATE {locales_target} SET translation = '%s', plid = %d, plural = %d WHERE language = '%s' AND lid = %d", $translation, $plid, $plural, $langcode, $lid);
       
  1363         $report['updates']++;
       
  1364       }
       
  1365     }
       
  1366     else {
       
  1367       // No such source string in the database yet.
       
  1368       db_query("INSERT INTO {locales_source} (location, source, textgroup) VALUES ('%s', '%s', '%s')", $location, $source, $textgroup);
       
  1369       $lid = db_result(db_query("SELECT lid FROM {locales_source} WHERE source = '%s' AND textgroup = '%s'", $source, $textgroup));
       
  1370       db_query("INSERT INTO {locales_target} (lid, language, translation, plid, plural) VALUES (%d, '%s', '%s', %d, %d)", $lid, $langcode, $translation, $plid, $plural);
       
  1371       $report['additions']++;
       
  1372     }
       
  1373   }
       
  1374   elseif ($mode == LOCALE_IMPORT_OVERWRITE) {
       
  1375     // Empty translation, remove existing if instructed.
       
  1376     db_query("DELETE FROM {locales_target} WHERE language = '%s' AND lid = %d AND plid = %d AND plural = %d", $langcode, $lid, $plid, $plural);
       
  1377     $report['deletes']++;
       
  1378   }
       
  1379 
       
  1380   return $lid;
       
  1381 }
       
  1382 
       
  1383 /**
       
  1384  * Parses a Gettext Portable Object file header
       
  1385  *
       
  1386  * @param $header
       
  1387  *   A string containing the complete header
       
  1388  * @return
       
  1389  *   An associative array of key-value pairs
       
  1390  */
       
  1391 function _locale_import_parse_header($header) {
       
  1392   $header_parsed = array();
       
  1393   $lines = array_map('trim', explode("\n", $header));
       
  1394   foreach ($lines as $line) {
       
  1395     if ($line) {
       
  1396       list($tag, $contents) = explode(":", $line, 2);
       
  1397       $header_parsed[trim($tag)] = trim($contents);
       
  1398     }
       
  1399   }
       
  1400   return $header_parsed;
       
  1401 }
       
  1402 
       
  1403 /**
       
  1404  * Parses a Plural-Forms entry from a Gettext Portable Object file header
       
  1405  *
       
  1406  * @param $pluralforms
       
  1407  *   A string containing the Plural-Forms entry
       
  1408  * @param $filename
       
  1409  *   A string containing the filename
       
  1410  * @return
       
  1411  *   An array containing the number of plurals and a
       
  1412  *   formula in PHP for computing the plural form
       
  1413  */
       
  1414 function _locale_import_parse_plural_forms($pluralforms, $filename) {
       
  1415   // First, delete all whitespace
       
  1416   $pluralforms = strtr($pluralforms, array(" " => "", "\t" => ""));
       
  1417 
       
  1418   // Select the parts that define nplurals and plural
       
  1419   $nplurals = strstr($pluralforms, "nplurals=");
       
  1420   if (strpos($nplurals, ";")) {
       
  1421     $nplurals = substr($nplurals, 9, strpos($nplurals, ";") - 9);
       
  1422   }
       
  1423   else {
       
  1424     return FALSE;
       
  1425   }
       
  1426   $plural = strstr($pluralforms, "plural=");
       
  1427   if (strpos($plural, ";")) {
       
  1428     $plural = substr($plural, 7, strpos($plural, ";") - 7);
       
  1429   }
       
  1430   else {
       
  1431     return FALSE;
       
  1432   }
       
  1433 
       
  1434   // Get PHP version of the plural formula
       
  1435   $plural = _locale_import_parse_arithmetic($plural);
       
  1436 
       
  1437   if ($plural !== FALSE) {
       
  1438     return array($nplurals, $plural);
       
  1439   }
       
  1440   else {
       
  1441     drupal_set_message(t('The translation file %filename contains an error: the plural formula could not be parsed.', array('%filename' => $filename)), 'error');
       
  1442     return FALSE;
       
  1443   }
       
  1444 }
       
  1445 
       
  1446 /**
       
  1447  * Parses and sanitizes an arithmetic formula into a PHP expression
       
  1448  *
       
  1449  * While parsing, we ensure, that the operators have the right
       
  1450  * precedence and associativity.
       
  1451  *
       
  1452  * @param $string
       
  1453  *   A string containing the arithmetic formula
       
  1454  * @return
       
  1455  *   The PHP version of the formula
       
  1456  */
       
  1457 function _locale_import_parse_arithmetic($string) {
       
  1458   // Operator precedence table
       
  1459   $prec = array("(" => -1, ")" => -1, "?" => 1, ":" => 1, "||" => 3, "&&" => 4, "==" => 5, "!=" => 5, "<" => 6, ">" => 6, "<=" => 6, ">=" => 6, "+" => 7, "-" => 7, "*" => 8, "/" => 8, "%" => 8);
       
  1460   // Right associativity
       
  1461   $rasc = array("?" => 1, ":" => 1);
       
  1462 
       
  1463   $tokens = _locale_import_tokenize_formula($string);
       
  1464 
       
  1465   // Parse by converting into infix notation then back into postfix
       
  1466   $opstk = array();
       
  1467   $elstk = array();
       
  1468 
       
  1469   foreach ($tokens as $token) {
       
  1470     $ctok = $token;
       
  1471 
       
  1472     // Numbers and the $n variable are simply pushed into $elarr
       
  1473     if (is_numeric($token)) {
       
  1474       $elstk[] = $ctok;
       
  1475     }
       
  1476     elseif ($ctok == "n") {
       
  1477       $elstk[] = '$n';
       
  1478     }
       
  1479     elseif ($ctok == "(") {
       
  1480       $opstk[] = $ctok;
       
  1481     }
       
  1482     elseif ($ctok == ")") {
       
  1483       $topop = array_pop($opstk);
       
  1484       while (isset($topop) && ($topop != "(")) {
       
  1485         $elstk[] = $topop;
       
  1486         $topop = array_pop($opstk);
       
  1487       }
       
  1488     }
       
  1489     elseif (!empty($prec[$ctok])) {
       
  1490       // If it's an operator, then pop from $oparr into $elarr until the
       
  1491       // precedence in $oparr is less than current, then push into $oparr
       
  1492       $topop = array_pop($opstk);
       
  1493       while (isset($topop) && ($prec[$topop] >= $prec[$ctok]) && !(($prec[$topop] == $prec[$ctok]) && !empty($rasc[$topop]) && !empty($rasc[$ctok]))) {
       
  1494         $elstk[] = $topop;
       
  1495         $topop = array_pop($opstk);
       
  1496       }
       
  1497       if ($topop) {
       
  1498         $opstk[] = $topop;   // Return element to top
       
  1499       }
       
  1500       $opstk[] = $ctok;      // Parentheses are not needed
       
  1501     }
       
  1502     else {
       
  1503       return FALSE;
       
  1504     }
       
  1505   }
       
  1506 
       
  1507   // Flush operator stack
       
  1508   $topop = array_pop($opstk);
       
  1509   while ($topop != NULL) {
       
  1510     $elstk[] = $topop;
       
  1511     $topop = array_pop($opstk);
       
  1512   }
       
  1513 
       
  1514   // Now extract formula from stack
       
  1515   $prevsize = count($elstk) + 1;
       
  1516   while (count($elstk) < $prevsize) {
       
  1517     $prevsize = count($elstk);
       
  1518     for ($i = 2; $i < count($elstk); $i++) {
       
  1519       $op = $elstk[$i];
       
  1520       if (!empty($prec[$op])) {
       
  1521         $f = "";
       
  1522         if ($op == ":") {
       
  1523           $f = $elstk[$i - 2] ."):". $elstk[$i - 1] .")";
       
  1524         }
       
  1525         elseif ($op == "?") {
       
  1526           $f = "(". $elstk[$i - 2] ."?(". $elstk[$i - 1];
       
  1527         }
       
  1528         else {
       
  1529           $f = "(". $elstk[$i - 2] . $op . $elstk[$i - 1] .")";
       
  1530         }
       
  1531         array_splice($elstk, $i - 2, 3, $f);
       
  1532         break;
       
  1533       }
       
  1534     }
       
  1535   }
       
  1536 
       
  1537   // If only one element is left, the number of operators is appropriate
       
  1538   if (count($elstk) == 1) {
       
  1539     return $elstk[0];
       
  1540   }
       
  1541   else {
       
  1542     return FALSE;
       
  1543   }
       
  1544 }
       
  1545 
       
  1546 /**
       
  1547  * Backward compatible implementation of token_get_all() for formula parsing
       
  1548  *
       
  1549  * @param $string
       
  1550  *   A string containing the arithmetic formula
       
  1551  * @return
       
  1552  *   The PHP version of the formula
       
  1553  */
       
  1554 function _locale_import_tokenize_formula($formula) {
       
  1555   $formula = str_replace(" ", "", $formula);
       
  1556   $tokens = array();
       
  1557   for ($i = 0; $i < strlen($formula); $i++) {
       
  1558     if (is_numeric($formula[$i])) {
       
  1559       $num = $formula[$i];
       
  1560       $j = $i + 1;
       
  1561       while ($j < strlen($formula) && is_numeric($formula[$j])) {
       
  1562         $num .= $formula[$j];
       
  1563         $j++;
       
  1564       }
       
  1565       $i = $j - 1;
       
  1566       $tokens[] = $num;
       
  1567     }
       
  1568     elseif ($pos = strpos(" =<>!&|", $formula[$i])) { // We won't have a space
       
  1569       $next = $formula[$i + 1];
       
  1570       switch ($pos) {
       
  1571         case 1:
       
  1572         case 2:
       
  1573         case 3:
       
  1574         case 4:
       
  1575           if ($next == '=') {
       
  1576             $tokens[] = $formula[$i] .'=';
       
  1577             $i++;
       
  1578           }
       
  1579           else {
       
  1580             $tokens[] = $formula[$i];
       
  1581           }
       
  1582           break;
       
  1583         case 5:
       
  1584           if ($next == '&') {
       
  1585             $tokens[] = '&&';
       
  1586             $i++;
       
  1587           }
       
  1588           else {
       
  1589             $tokens[] = $formula[$i];
       
  1590           }
       
  1591           break;
       
  1592         case 6:
       
  1593           if ($next == '|') {
       
  1594             $tokens[] = '||';
       
  1595             $i++;
       
  1596           }
       
  1597           else {
       
  1598             $tokens[] = $formula[$i];
       
  1599           }
       
  1600           break;
       
  1601       }
       
  1602     }
       
  1603     else {
       
  1604       $tokens[] = $formula[$i];
       
  1605     }
       
  1606   }
       
  1607   return $tokens;
       
  1608 }
       
  1609 
       
  1610 /**
       
  1611  * Modify a string to contain proper count indices
       
  1612  *
       
  1613  * This is a callback function used via array_map()
       
  1614  *
       
  1615  * @param $entry
       
  1616  *   An array element
       
  1617  * @param $key
       
  1618  *   Index of the array element
       
  1619  */
       
  1620 function _locale_import_append_plural($entry, $key) {
       
  1621   // No modifications for 0, 1
       
  1622   if ($key == 0 || $key == 1) {
       
  1623     return $entry;
       
  1624   }
       
  1625 
       
  1626   // First remove any possibly false indices, then add new ones
       
  1627   $entry = preg_replace('/(@count)\[[0-9]\]/', '\\1', $entry);
       
  1628   return preg_replace('/(@count)/', "\\1[$key]", $entry);
       
  1629 }
       
  1630 
       
  1631 /**
       
  1632  * Generate a short, one string version of the passed comment array
       
  1633  *
       
  1634  * @param $comment
       
  1635  *   An array of strings containing a comment
       
  1636  * @return
       
  1637  *   Short one string version of the comment
       
  1638  */
       
  1639 function _locale_import_shorten_comments($comment) {
       
  1640   $comm = '';
       
  1641   while (count($comment)) {
       
  1642     $test = $comm . substr(array_shift($comment), 1) .', ';
       
  1643     if (strlen($comm) < 130) {
       
  1644       $comm = $test;
       
  1645     }
       
  1646     else {
       
  1647       break;
       
  1648     }
       
  1649   }
       
  1650   return substr($comm, 0, -2);
       
  1651 }
       
  1652 
       
  1653 /**
       
  1654  * Parses a string in quotes
       
  1655  *
       
  1656  * @param $string
       
  1657  *   A string specified with enclosing quotes
       
  1658  * @return
       
  1659  *   The string parsed from inside the quotes
       
  1660  */
       
  1661 function _locale_import_parse_quoted($string) {
       
  1662   if (substr($string, 0, 1) != substr($string, -1, 1)) {
       
  1663     return FALSE;   // Start and end quotes must be the same
       
  1664   }
       
  1665   $quote = substr($string, 0, 1);
       
  1666   $string = substr($string, 1, -1);
       
  1667   if ($quote == '"') {        // Double quotes: strip slashes
       
  1668     return stripcslashes($string);
       
  1669   }
       
  1670   elseif ($quote == "'") {  // Simple quote: return as-is
       
  1671     return $string;
       
  1672   }
       
  1673   else {
       
  1674     return FALSE;             // Unrecognized quote
       
  1675   }
       
  1676 }
       
  1677 /**
       
  1678  * @} End of "locale-api-import"
       
  1679  */
       
  1680 
       
  1681 /**
       
  1682  * Parses a JavaScript file, extracts strings wrapped in Drupal.t() and
       
  1683  * Drupal.formatPlural() and inserts them into the database.
       
  1684  */
       
  1685 function _locale_parse_js_file($filepath) {
       
  1686   global $language;
       
  1687 
       
  1688   // Load the JavaScript file.
       
  1689   $file = file_get_contents($filepath);
       
  1690 
       
  1691   // Match all calls to Drupal.t() in an array.
       
  1692   // Note: \s also matches newlines with the 's' modifier.
       
  1693   preg_match_all('~[^\w]Drupal\s*\.\s*t\s*\(\s*('. LOCALE_JS_STRING .')\s*[,\)]~s', $file, $t_matches);
       
  1694 
       
  1695   // Match all Drupal.formatPlural() calls in another array.
       
  1696   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);
       
  1697 
       
  1698   // Loop through all matches and process them.
       
  1699   $all_matches = array_merge($plural_matches[1], $t_matches[1]);
       
  1700   foreach ($all_matches as $key => $string) {
       
  1701     $strings = array($string);
       
  1702 
       
  1703     // If there is also a plural version of this string, add it to the strings array.
       
  1704     if (isset($plural_matches[2][$key])) {
       
  1705       $strings[] = $plural_matches[2][$key];
       
  1706     }
       
  1707 
       
  1708     foreach ($strings as $key => $string) {
       
  1709       // Remove the quotes and string concatenations from the string.
       
  1710       $string = implode('', preg_split('~(?<!\\\\)[\'"]\s*\+\s*[\'"]~s', substr($string, 1, -1)));
       
  1711 
       
  1712       $result = db_query("SELECT lid, location FROM {locales_source} WHERE source = '%s' AND textgroup = 'default'", $string);
       
  1713       if ($source = db_fetch_object($result)) {
       
  1714         // We already have this source string and now have to add the location
       
  1715         // to the location column, if this file is not yet present in there.
       
  1716         $locations = preg_split('~\s*;\s*~', $source->location);
       
  1717 
       
  1718         if (!in_array($filepath, $locations)) {
       
  1719           $locations[] = $filepath;
       
  1720           $locations = implode('; ', $locations);
       
  1721 
       
  1722           // Save the new locations string to the database.
       
  1723           db_query("UPDATE {locales_source} SET location = '%s' WHERE lid = %d", $locations, $source->lid);
       
  1724         }
       
  1725       }
       
  1726       else {
       
  1727         // We don't have the source string yet, thus we insert it into the database.
       
  1728         db_query("INSERT INTO {locales_source} (location, source, textgroup) VALUES ('%s', '%s', 'default')", $filepath, $string);
       
  1729       }
       
  1730     }
       
  1731   }
       
  1732 }
       
  1733 
       
  1734 /**
       
  1735  * @defgroup locale-api-export Translation (template) export API.
       
  1736  * @{
       
  1737  */
       
  1738 
       
  1739 /**
       
  1740  * Generates a structured array of all strings with translations in
       
  1741  * $language, if given. This array can be used to generate an export
       
  1742  * of the string in the database.
       
  1743  *
       
  1744  * @param $language
       
  1745  *   Language object to generate the output for, or NULL if generating
       
  1746  *   translation template.
       
  1747  * @param $group
       
  1748  *   Text group to export PO file from (eg. 'default' for interface translations)
       
  1749  */
       
  1750 function _locale_export_get_strings($language = NULL, $group = 'default') {
       
  1751   if (isset($language)) {
       
  1752     $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);
       
  1753   }
       
  1754   else {
       
  1755     $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);
       
  1756   }
       
  1757   $strings = array();
       
  1758   while ($child = db_fetch_object($result)) {
       
  1759     $string = array(
       
  1760       'comment'     => $child->location,
       
  1761       'source'      => $child->source,
       
  1762       'translation' => isset($child->translation) ? $child->translation : ''
       
  1763     );
       
  1764     if ($child->plid) {
       
  1765       // Has a parent lid. Since we process in the order of plids,
       
  1766       // we already have the parent in the array, so we can add the
       
  1767       // lid to the next plural version to it. This builds a linked
       
  1768       // list of plurals.
       
  1769       $string['child'] = TRUE;
       
  1770       $strings[$child->plid]['plural'] = $child->lid;
       
  1771     }
       
  1772     $strings[$child->lid] = $string;
       
  1773   }
       
  1774   return $strings;
       
  1775 }
       
  1776 
       
  1777 /**
       
  1778  * Generates the PO(T) file contents for given strings.
       
  1779  *
       
  1780  * @param $language
       
  1781  *   Language object to generate the output for, or NULL if generating
       
  1782  *   translation template.
       
  1783  * @param $strings
       
  1784  *   Array of strings to export. See _locale_export_get_strings()
       
  1785  *   on how it should be formatted.
       
  1786  * @param $header
       
  1787  *   The header portion to use for the output file. Defaults
       
  1788  *   are provided for PO and POT files.
       
  1789  */
       
  1790 function _locale_export_po_generate($language = NULL, $strings = array(), $header = NULL) {
       
  1791   global $user;
       
  1792 
       
  1793   if (!isset($header)) {
       
  1794     if (isset($language)) {
       
  1795       $header = '# '. $language->name .' translation of '. variable_get('site_name', 'Drupal') ."\n";
       
  1796       $header .= '# Generated by '. $user->name .' <'. $user->mail .">\n";
       
  1797       $header .= "#\n";
       
  1798       $header .= "msgid \"\"\n";
       
  1799       $header .= "msgstr \"\"\n";
       
  1800       $header .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
       
  1801       $header .= "\"POT-Creation-Date: ". date("Y-m-d H:iO") ."\\n\"\n";
       
  1802       $header .= "\"PO-Revision-Date: ". date("Y-m-d H:iO") ."\\n\"\n";
       
  1803       $header .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
       
  1804       $header .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
       
  1805       $header .= "\"MIME-Version: 1.0\\n\"\n";
       
  1806       $header .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
       
  1807       $header .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
       
  1808       if ($language->formula && $language->plurals) {
       
  1809         $header .= "\"Plural-Forms: nplurals=". $language->plurals ."; plural=". strtr($language->formula, array('$' => '')) .";\\n\"\n";
       
  1810       }
       
  1811     }
       
  1812     else {
       
  1813       $header = "# LANGUAGE translation of PROJECT\n";
       
  1814       $header .= "# Copyright (c) YEAR NAME <EMAIL@ADDRESS>\n";
       
  1815       $header .= "#\n";
       
  1816       $header .= "msgid \"\"\n";
       
  1817       $header .= "msgstr \"\"\n";
       
  1818       $header .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
       
  1819       $header .= "\"POT-Creation-Date: ". date("Y-m-d H:iO") ."\\n\"\n";
       
  1820       $header .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
       
  1821       $header .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
       
  1822       $header .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
       
  1823       $header .= "\"MIME-Version: 1.0\\n\"\n";
       
  1824       $header .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
       
  1825       $header .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
       
  1826       $header .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n";
       
  1827     }
       
  1828   }
       
  1829 
       
  1830   $output = $header ."\n";
       
  1831 
       
  1832   foreach ($strings as $lid => $string) {
       
  1833     // Only process non-children, children are output below their parent.
       
  1834     if (!isset($string['child'])) {
       
  1835       if ($string['comment']) {
       
  1836         $output .= '#: '. $string['comment'] ."\n";
       
  1837       }
       
  1838       $output .= 'msgid '. _locale_export_string($string['source']);
       
  1839       if (!empty($string['plural'])) {
       
  1840         $plural = $string['plural'];
       
  1841         $output .= 'msgid_plural '. _locale_export_string($strings[$plural]['source']);
       
  1842         if (isset($language)) {
       
  1843           $translation = $string['translation'];
       
  1844           for ($i = 0; $i < $language->plurals; $i++) {
       
  1845             $output .= 'msgstr['. $i .'] '. _locale_export_string($translation);
       
  1846             if ($plural) {
       
  1847               $translation = _locale_export_remove_plural($strings[$plural]['translation']);
       
  1848               $plural = isset($strings[$plural]['plural']) ? $strings[$plural]['plural'] : 0;
       
  1849             }
       
  1850             else {
       
  1851               $translation = '';
       
  1852             }
       
  1853           }
       
  1854         }
       
  1855         else {
       
  1856           $output .= 'msgstr[0] ""'."\n";
       
  1857           $output .= 'msgstr[1] ""'."\n";
       
  1858         }
       
  1859       }
       
  1860       else {
       
  1861         $output .= 'msgstr '. _locale_export_string($string['translation']);
       
  1862       }
       
  1863       $output .= "\n";
       
  1864     }
       
  1865   }
       
  1866   return $output;
       
  1867 }
       
  1868 
       
  1869 /**
       
  1870  * Write a generated PO or POT file to the output.
       
  1871  *
       
  1872  * @param $language
       
  1873  *   Language object to generate the output for, or NULL if generating
       
  1874  *   translation template.
       
  1875  * @param $output
       
  1876  *   The PO(T) file to output as a string. See _locale_export_generate_po()
       
  1877  *   on how it can be generated.
       
  1878  */
       
  1879 function _locale_export_po($language = NULL, $output = NULL) {
       
  1880   // Log the export event.
       
  1881   if (isset($language)) {
       
  1882     $filename = $language->language .'.po';
       
  1883     watchdog('locale', 'Exported %locale translation file: %filename.', array('%locale' => $language->name, '%filename' => $filename));
       
  1884   }
       
  1885   else {
       
  1886     $filename = 'drupal.pot';
       
  1887     watchdog('locale', 'Exported translation file: %filename.', array('%filename' => $filename));
       
  1888   }
       
  1889   // Download the file fo the client.
       
  1890   header("Content-Disposition: attachment; filename=$filename");
       
  1891   header("Content-Type: text/plain; charset=utf-8");
       
  1892   print $output;
       
  1893   die();
       
  1894 }
       
  1895 
       
  1896 /**
       
  1897  * Print out a string on multiple lines
       
  1898  */
       
  1899 function _locale_export_string($str) {
       
  1900   $stri = addcslashes($str, "\0..\37\\\"");
       
  1901   $parts = array();
       
  1902 
       
  1903   // Cut text into several lines
       
  1904   while ($stri != "") {
       
  1905     $i = strpos($stri, "\\n");
       
  1906     if ($i === FALSE) {
       
  1907       $curstr = $stri;
       
  1908       $stri = "";
       
  1909     }
       
  1910     else {
       
  1911       $curstr = substr($stri, 0, $i + 2);
       
  1912       $stri = substr($stri, $i + 2);
       
  1913     }
       
  1914     $curparts = explode("\n", _locale_export_wrap($curstr, 70));
       
  1915     $parts = array_merge($parts, $curparts);
       
  1916   }
       
  1917 
       
  1918   // Multiline string
       
  1919   if (count($parts) > 1) {
       
  1920     return "\"\"\n\"". implode("\"\n\"", $parts) ."\"\n";
       
  1921   }
       
  1922   // Single line string
       
  1923   elseif (count($parts) == 1) {
       
  1924     return "\"$parts[0]\"\n";
       
  1925   }
       
  1926   // No translation
       
  1927   else {
       
  1928     return "\"\"\n";
       
  1929   }
       
  1930 }
       
  1931 
       
  1932 /**
       
  1933  * Custom word wrapping for Portable Object (Template) files.
       
  1934  */
       
  1935 function _locale_export_wrap($str, $len) {
       
  1936   $words = explode(' ', $str);
       
  1937   $ret = array();
       
  1938 
       
  1939   $cur = "";
       
  1940   $nstr = 1;
       
  1941   while (count($words)) {
       
  1942     $word = array_shift($words);
       
  1943     if ($nstr) {
       
  1944       $cur = $word;
       
  1945       $nstr = 0;
       
  1946     }
       
  1947     elseif (strlen("$cur $word") > $len) {
       
  1948       $ret[] = $cur ." ";
       
  1949       $cur = $word;
       
  1950     }
       
  1951     else {
       
  1952       $cur = "$cur $word";
       
  1953     }
       
  1954   }
       
  1955   $ret[] = $cur;
       
  1956 
       
  1957   return implode("\n", $ret);
       
  1958 }
       
  1959 
       
  1960 /**
       
  1961  * Removes plural index information from a string
       
  1962  */
       
  1963 function _locale_export_remove_plural($entry) {
       
  1964   return preg_replace('/(@count)\[[0-9]\]/', '\\1', $entry);
       
  1965 }
       
  1966 /**
       
  1967  * @} End of "locale-api-export"
       
  1968  */
       
  1969 
       
  1970 /**
       
  1971  * @defgroup locale-api-seek String search functions.
       
  1972  * @{
       
  1973  */
       
  1974 
       
  1975 /**
       
  1976  * Perform a string search and display results in a table
       
  1977  */
       
  1978 function _locale_translate_seek() {
       
  1979   $output = '';
       
  1980 
       
  1981   // We have at least one criterion to match
       
  1982   if ($query = _locale_translate_seek_query()) {
       
  1983     $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 ";
       
  1984 
       
  1985     $arguments = array();
       
  1986     $limit_language = FALSE;
       
  1987     // Compute LIKE section
       
  1988     switch ($query['translation']) {
       
  1989       case 'translated':
       
  1990         $where = "WHERE (t.translation LIKE '%%%s%%')";
       
  1991         $orderby = "ORDER BY t.translation";
       
  1992         $arguments[] = $query['string'];
       
  1993         break;
       
  1994       case 'untranslated':
       
  1995         $where = "WHERE (s.source LIKE '%%%s%%' AND t.translation IS NULL)";
       
  1996         $orderby = "ORDER BY s.source";
       
  1997         $arguments[] = $query['string'];
       
  1998         break;
       
  1999       case 'all' :
       
  2000       default:
       
  2001         $where = "WHERE (s.source LIKE '%%%s%%' OR t.translation LIKE '%%%s%%')";
       
  2002         $orderby = '';
       
  2003         $arguments[] = $query['string'];
       
  2004         $arguments[] = $query['string'];
       
  2005         break;
       
  2006     }
       
  2007     $grouplimit = '';
       
  2008     if (!empty($query['group']) && $query['group'] != 'all') {
       
  2009       $grouplimit = " AND s.textgroup = '%s'";
       
  2010       $arguments[] = $query['group'];
       
  2011     }
       
  2012 
       
  2013     switch ($query['language']) {
       
  2014       // Force search in source strings
       
  2015       case "en":
       
  2016         $sql = $join ." WHERE s.source LIKE '%%%s%%' $grouplimit ORDER BY s.source";
       
  2017         $arguments = array($query['string']); // $where is not used, discard its arguments
       
  2018         if (!empty($grouplimit)) {
       
  2019           $arguments[] = $query['group'];
       
  2020         }
       
  2021         break;
       
  2022       // Search in all languages
       
  2023       case "all":
       
  2024         $sql = "$join $where $grouplimit $orderby";
       
  2025         break;
       
  2026       // Some different language
       
  2027       default:
       
  2028         $sql = "$join AND t.language = '%s' $where $grouplimit $orderby";
       
  2029         array_unshift($arguments, $query['language']);
       
  2030         // Don't show translation flags for other languages, we can't see them with this search.
       
  2031         $limit_language = $query['language'];
       
  2032     }
       
  2033 
       
  2034     $result = pager_query($sql, 50, 0, NULL, $arguments);
       
  2035 
       
  2036     $groups = module_invoke_all('locale', 'groups');
       
  2037     $header = array(t('Text group'), t('String'), ($limit_language) ? t('Language') : t('Languages'), array('data' => t('Operations'), 'colspan' => '2'));
       
  2038     $arr = array();
       
  2039     while ($locale = db_fetch_object($result)) {
       
  2040       $arr[$locale->lid]['group'] = $groups[$locale->textgroup];
       
  2041       $arr[$locale->lid]['languages'][$locale->language] = $locale->translation;
       
  2042       $arr[$locale->lid]['location'] = $locale->location;
       
  2043       $arr[$locale->lid]['source'] = $locale->source;
       
  2044     }
       
  2045     $rows = array();
       
  2046     foreach ($arr as $lid => $value) {
       
  2047       $rows[] = array(
       
  2048         $value['group'],
       
  2049         array('data' => check_plain(truncate_utf8($value['source'], 150, FALSE, TRUE)) .'<br /><small>'. $value['location'] .'</small>'),
       
  2050         array('data' => _locale_translate_language_list($value['languages'], $limit_language), 'align' => 'center'),
       
  2051         array('data' => l(t('edit'), "admin/build/translate/edit/$lid"), 'class' => 'nowrap'),
       
  2052         array('data' => l(t('delete'), "admin/build/translate/delete/$lid"), 'class' => 'nowrap'),
       
  2053       );
       
  2054     }
       
  2055 
       
  2056     if (count($rows)) {
       
  2057       $output .= theme('table', $header, $rows);
       
  2058       if ($pager = theme('pager', NULL, 50)) {
       
  2059         $output .= $pager;
       
  2060       }
       
  2061     }
       
  2062     else {
       
  2063       $output .= t('No strings found for your search.');
       
  2064     }
       
  2065   }
       
  2066 
       
  2067   return $output;
       
  2068 }
       
  2069 
       
  2070 /**
       
  2071  * Build array out of search criteria specified in request variables
       
  2072  */
       
  2073 function _locale_translate_seek_query() {
       
  2074   static $query = NULL;
       
  2075   if (!isset($query)) {
       
  2076     $query = array();
       
  2077     $fields = array('string', 'language', 'translation', 'group');
       
  2078     foreach ($fields as $field) {
       
  2079       if (isset($_REQUEST[$field])) {
       
  2080         $query[$field] = $_REQUEST[$field];
       
  2081       }
       
  2082     }
       
  2083   }
       
  2084   return $query;
       
  2085 }
       
  2086 
       
  2087 /**
       
  2088  * Force the JavaScript translation file(s) to be refreshed.
       
  2089  *
       
  2090  * This function sets a refresh flag for a specified language, or all
       
  2091  * languages except English, if none specified. JavaScript translation
       
  2092  * files are rebuilt (with locale_update_js_files()) the next time a
       
  2093  * request is served in that language.
       
  2094  *
       
  2095  * @param $langcode
       
  2096  *   The language code for which the file needs to be refreshed.
       
  2097  * @return
       
  2098  *   New content of the 'javascript_parsed' variable.
       
  2099  */
       
  2100 function _locale_invalidate_js($langcode = NULL) {
       
  2101   $parsed = variable_get('javascript_parsed', array());
       
  2102 
       
  2103   if (empty($langcode)) {
       
  2104     // Invalidate all languages.
       
  2105     $languages = language_list();
       
  2106     unset($languages['en']);
       
  2107     foreach ($languages as $lcode => $data) {
       
  2108       $parsed['refresh:'. $lcode] = 'waiting';
       
  2109     }
       
  2110   }
       
  2111   else {
       
  2112     // Invalidate single language.
       
  2113     $parsed['refresh:'. $langcode] = 'waiting';
       
  2114   }
       
  2115 
       
  2116   variable_set('javascript_parsed', $parsed);
       
  2117   return $parsed;
       
  2118 }
       
  2119 
       
  2120 /**
       
  2121  * (Re-)Creates the JavaScript translation file for a language.
       
  2122  *
       
  2123  * @param $language
       
  2124  *   The language, the translation file should be (re)created for.
       
  2125  */
       
  2126 function _locale_rebuild_js($langcode = NULL) {
       
  2127   if (!isset($langcode)) {
       
  2128     global $language;
       
  2129   }
       
  2130   else {
       
  2131     // Get information about the locale.
       
  2132     $languages = language_list();
       
  2133     $language = $languages[$langcode];
       
  2134   }
       
  2135 
       
  2136   // Construct the array for JavaScript translations.
       
  2137   // We sort on plural so that we have all plural forms before singular forms.
       
  2138   $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);
       
  2139 
       
  2140   $translations = $plurals = array();
       
  2141   while ($data = db_fetch_object($result)) {
       
  2142     // Only add this to the translations array when there is actually a translation.
       
  2143     if (!empty($data->translation)) {
       
  2144       if ($data->plural) {
       
  2145         // When the translation is a plural form, first add it to another array and
       
  2146         // wait for the singular (parent) translation.
       
  2147         if (!isset($plurals[$data->plid])) {
       
  2148           $plurals[$data->plid] = array($data->plural => $data->translation);
       
  2149         }
       
  2150         else {
       
  2151           $plurals[$data->plid] += array($data->plural => $data->translation);
       
  2152         }
       
  2153       }
       
  2154       elseif (isset($plurals[$data->lid])) {
       
  2155         // There are plural translations for this translation, so get them from
       
  2156         // the plurals array and add them to the final translations array.
       
  2157         $translations[$data->source] = array($data->plural => $data->translation) + $plurals[$data->lid];
       
  2158         unset($plurals[$data->lid]);
       
  2159       }
       
  2160       else {
       
  2161         // There are no plural forms for this translation, so just add it to
       
  2162         // the translations array.
       
  2163         $translations[$data->source] = $data->translation;
       
  2164       }
       
  2165     }
       
  2166   }
       
  2167 
       
  2168   // Construct the JavaScript file, if there are translations.
       
  2169   $data = $status = '';
       
  2170   if (!empty($translations)) {
       
  2171 
       
  2172     $data = "Drupal.locale = { ";
       
  2173 
       
  2174     if (!empty($language->formula)) {
       
  2175       $data .= "'pluralFormula': function(\$n) { return Number({$language->formula}); }, ";
       
  2176     }
       
  2177 
       
  2178     $data .= "'strings': ". drupal_to_js($translations) ." };";
       
  2179     $data_hash = md5($data);
       
  2180   }
       
  2181 
       
  2182   // Construct the filepath where JS translation files are stored.
       
  2183   // There is (on purpose) no front end to edit that variable.
       
  2184   $dir = file_create_path(variable_get('locale_js_directory', 'languages'));
       
  2185 
       
  2186   // Delete old file, if we have no translations anymore, or a different file to be saved.
       
  2187   if (!empty($language->javascript) && (!$data || $language->javascript != $data_hash)) {
       
  2188     file_delete(file_create_path($dir .'/'. $language->language .'_'. $language->javascript .'.js'));
       
  2189     $language->javascript = '';
       
  2190     $status = 'deleted';
       
  2191   }
       
  2192 
       
  2193   // Only create a new file if the content has changed.
       
  2194   if ($data && $language->javascript != $data_hash) {
       
  2195     // Ensure that the directory exists and is writable, if possible.
       
  2196     file_check_directory($dir, TRUE);
       
  2197 
       
  2198     // Save the file.
       
  2199     $dest = $dir .'/'. $language->language .'_'. $data_hash .'.js';
       
  2200     if (file_save_data($data, $dest)) {
       
  2201       $language->javascript = $data_hash;
       
  2202       $status = ($status == 'deleted') ? 'updated' : 'created';
       
  2203     }
       
  2204     else {
       
  2205       $language->javascript = '';
       
  2206       $status = 'error';
       
  2207     }
       
  2208   }
       
  2209 
       
  2210   // Save the new JavaScript hash (or an empty value if the file
       
  2211   // just got deleted). Act only if some operation was executed.
       
  2212   if ($status) {
       
  2213     db_query("UPDATE {languages} SET javascript = '%s' WHERE language = '%s'", $language->javascript, $language->language);
       
  2214 
       
  2215     // Update the default language variable if the default language has been altered.
       
  2216     // This is necessary to keep the variable consistent with the database
       
  2217     // version of the language and to prevent checking against an outdated hash.
       
  2218     $default_langcode = language_default('language');
       
  2219     if ($default_langcode == $language->language) {
       
  2220       $default = db_fetch_object(db_query("SELECT * FROM {languages} WHERE language = '%s'", $default_langcode));
       
  2221       variable_set('language_default', $default);
       
  2222     }
       
  2223   }
       
  2224 
       
  2225   // Log the operation and return success flag.
       
  2226   switch ($status) {
       
  2227     case 'updated':
       
  2228       watchdog('locale', 'Updated JavaScript translation file for the language %language.', array('%language' => t($language->name)));
       
  2229       return TRUE;
       
  2230     case 'created':
       
  2231       watchdog('locale', 'Created JavaScript translation file for the language %language.', array('%language' => t($language->name)));
       
  2232       return TRUE;
       
  2233     case 'deleted':
       
  2234       watchdog('locale', 'Removed JavaScript translation file for the language %language, because no translations currently exist for that language.', array('%language' => t($language->name)));
       
  2235       return TRUE;
       
  2236     case 'error':
       
  2237       watchdog('locale', 'An error occurred during creation of the JavaScript translation file for the language %language.', array('%language' => t($language->name)), WATCHDOG_ERROR);
       
  2238       return FALSE;
       
  2239     default:
       
  2240       // No operation needed.
       
  2241       return TRUE;
       
  2242   }
       
  2243 }
       
  2244 
       
  2245 /**
       
  2246  * List languages in search result table
       
  2247  */
       
  2248 function _locale_translate_language_list($translation, $limit_language) {
       
  2249   // Add CSS
       
  2250   drupal_add_css(drupal_get_path('module', 'locale') .'/locale.css', 'module', 'all', FALSE);
       
  2251 
       
  2252   $languages = language_list();
       
  2253   unset($languages['en']);
       
  2254   $output = '';
       
  2255   foreach ($languages as $langcode => $language) {
       
  2256     if (!$limit_language || $limit_language == $langcode) {
       
  2257       $output .= (!empty($translation[$langcode])) ? $langcode .' ' : "<em class=\"locale-untranslated\">$langcode</em> ";
       
  2258     }
       
  2259   }
       
  2260 
       
  2261   return $output;
       
  2262 }
       
  2263 /**
       
  2264  * @} End of "locale-api-seek"
       
  2265  */
       
  2266 
       
  2267 /**
       
  2268  * @defgroup locale-api-predefined List of predefined languages
       
  2269  * @{
       
  2270  */
       
  2271 
       
  2272 /**
       
  2273  * Prepares the language code list for a select form item with only the unsupported ones
       
  2274  */
       
  2275 function _locale_prepare_predefined_list() {
       
  2276   $languages = language_list();
       
  2277   $predefined = _locale_get_predefined_list();
       
  2278   foreach ($predefined as $key => $value) {
       
  2279     if (isset($languages[$key])) {
       
  2280       unset($predefined[$key]);
       
  2281       continue;
       
  2282     }
       
  2283     // Include native name in output, if possible
       
  2284     if (count($value) > 1) {
       
  2285       $tname = t($value[0]);
       
  2286       $predefined[$key] = ($tname == $value[1]) ? $tname : "$tname ($value[1])";
       
  2287     }
       
  2288     else {
       
  2289       $predefined[$key] = t($value[0]);
       
  2290     }
       
  2291   }
       
  2292   asort($predefined);
       
  2293   return $predefined;
       
  2294 }
       
  2295 
       
  2296 /**
       
  2297  * Some of the common languages with their English and native names
       
  2298  *
       
  2299  * Based on ISO 639 and http://people.w3.org/rishida/names/languages.html
       
  2300  */
       
  2301 function _locale_get_predefined_list() {
       
  2302   return array(
       
  2303     "aa" => array("Afar"),
       
  2304     "ab" => array("Abkhazian", "аҧсуа бызшәа"),
       
  2305     "ae" => array("Avestan"),
       
  2306     "af" => array("Afrikaans"),
       
  2307     "ak" => array("Akan"),
       
  2308     "am" => array("Amharic", "አማርኛ"),
       
  2309     "ar" => array("Arabic", /* Left-to-right marker "‭" */ "العربية", LANGUAGE_RTL),
       
  2310     "as" => array("Assamese"),
       
  2311     "av" => array("Avar"),
       
  2312     "ay" => array("Aymara"),
       
  2313     "az" => array("Azerbaijani", "azərbaycan"),
       
  2314     "ba" => array("Bashkir"),
       
  2315     "be" => array("Belarusian", "Беларуская"),
       
  2316     "bg" => array("Bulgarian", "Български"),
       
  2317     "bh" => array("Bihari"),
       
  2318     "bi" => array("Bislama"),
       
  2319     "bm" => array("Bambara", "Bamanankan"),
       
  2320     "bn" => array("Bengali"),
       
  2321     "bo" => array("Tibetan"),
       
  2322     "br" => array("Breton"),
       
  2323     "bs" => array("Bosnian", "Bosanski"),
       
  2324     "ca" => array("Catalan", "Català"),
       
  2325     "ce" => array("Chechen"),
       
  2326     "ch" => array("Chamorro"),
       
  2327     "co" => array("Corsican"),
       
  2328     "cr" => array("Cree"),
       
  2329     "cs" => array("Czech", "Čeština"),
       
  2330     "cu" => array("Old Slavonic"),
       
  2331     "cv" => array("Chuvash"),
       
  2332     "cy" => array("Welsh", "Cymraeg"),
       
  2333     "da" => array("Danish", "Dansk"),
       
  2334     "de" => array("German", "Deutsch"),
       
  2335     "dv" => array("Maldivian"),
       
  2336     "dz" => array("Bhutani"),
       
  2337     "ee" => array("Ewe", "Ɛʋɛ"),
       
  2338     "el" => array("Greek", "Ελληνικά"),
       
  2339     "en" => array("English"),
       
  2340     "eo" => array("Esperanto"),
       
  2341     "es" => array("Spanish", "Español"),
       
  2342     "et" => array("Estonian", "Eesti"),
       
  2343     "eu" => array("Basque", "Euskera"),
       
  2344     "fa" => array("Persian", /* Left-to-right marker "‭" */ "فارسی", LANGUAGE_RTL),
       
  2345     "ff" => array("Fulah", "Fulfulde"),
       
  2346     "fi" => array("Finnish", "Suomi"),
       
  2347     "fj" => array("Fiji"),
       
  2348     "fo" => array("Faeroese"),
       
  2349     "fr" => array("French", "Français"),
       
  2350     "fy" => array("Frisian", "Frysk"),
       
  2351     "ga" => array("Irish", "Gaeilge"),
       
  2352     "gd" => array("Scots Gaelic"),
       
  2353     "gl" => array("Galician", "Galego"),
       
  2354     "gn" => array("Guarani"),
       
  2355     "gu" => array("Gujarati"),
       
  2356     "gv" => array("Manx"),
       
  2357     "ha" => array("Hausa"),
       
  2358     "he" => array("Hebrew", /* Left-to-right marker "‭" */ "עברית", LANGUAGE_RTL),
       
  2359     "hi" => array("Hindi", "हिन्दी"),
       
  2360     "ho" => array("Hiri Motu"),
       
  2361     "hr" => array("Croatian", "Hrvatski"),
       
  2362     "hu" => array("Hungarian", "Magyar"),
       
  2363     "hy" => array("Armenian", "Հայերեն"),
       
  2364     "hz" => array("Herero"),
       
  2365     "ia" => array("Interlingua"),
       
  2366     "id" => array("Indonesian", "Bahasa Indonesia"),
       
  2367     "ie" => array("Interlingue"),
       
  2368     "ig" => array("Igbo"),
       
  2369     "ik" => array("Inupiak"),
       
  2370     "is" => array("Icelandic", "Íslenska"),
       
  2371     "it" => array("Italian", "Italiano"),
       
  2372     "iu" => array("Inuktitut"),
       
  2373     "ja" => array("Japanese", "日本語"),
       
  2374     "jv" => array("Javanese"),
       
  2375     "ka" => array("Georgian"),
       
  2376     "kg" => array("Kongo"),
       
  2377     "ki" => array("Kikuyu"),
       
  2378     "kj" => array("Kwanyama"),
       
  2379     "kk" => array("Kazakh", "Қазақ"),
       
  2380     "kl" => array("Greenlandic"),
       
  2381     "km" => array("Cambodian"),
       
  2382     "kn" => array("Kannada", "ಕನ್ನಡ"),
       
  2383     "ko" => array("Korean", "한국어"),
       
  2384     "kr" => array("Kanuri"),
       
  2385     "ks" => array("Kashmiri"),
       
  2386     "ku" => array("Kurdish", "Kurdî"),
       
  2387     "kv" => array("Komi"),
       
  2388     "kw" => array("Cornish"),
       
  2389     "ky" => array("Kirghiz", "Кыргыз"),
       
  2390     "la" => array("Latin", "Latina"),
       
  2391     "lb" => array("Luxembourgish"),
       
  2392     "lg" => array("Luganda"),
       
  2393     "ln" => array("Lingala"),
       
  2394     "lo" => array("Laothian"),
       
  2395     "lt" => array("Lithuanian", "Lietuvių"),
       
  2396     "lv" => array("Latvian", "Latviešu"),
       
  2397     "mg" => array("Malagasy"),
       
  2398     "mh" => array("Marshallese"),
       
  2399     "mi" => array("Maori"),
       
  2400     "mk" => array("Macedonian", "Македонски"),
       
  2401     "ml" => array("Malayalam", "മലയാളം"),
       
  2402     "mn" => array("Mongolian"),
       
  2403     "mo" => array("Moldavian"),
       
  2404     "mr" => array("Marathi"),
       
  2405     "ms" => array("Malay", "Bahasa Melayu"),
       
  2406     "mt" => array("Maltese", "Malti"),
       
  2407     "my" => array("Burmese"),
       
  2408     "na" => array("Nauru"),
       
  2409     "nd" => array("North Ndebele"),
       
  2410     "ne" => array("Nepali"),
       
  2411     "ng" => array("Ndonga"),
       
  2412     "nl" => array("Dutch", "Nederlands"),
       
  2413     "nb" => array("Norwegian Bokmål", "Bokmål"),
       
  2414     "nn" => array("Norwegian Nynorsk", "Nynorsk"),
       
  2415     "nr" => array("South Ndebele"),
       
  2416     "nv" => array("Navajo"),
       
  2417     "ny" => array("Chichewa"),
       
  2418     "oc" => array("Occitan"),
       
  2419     "om" => array("Oromo"),
       
  2420     "or" => array("Oriya"),
       
  2421     "os" => array("Ossetian"),
       
  2422     "pa" => array("Punjabi"),
       
  2423     "pi" => array("Pali"),
       
  2424     "pl" => array("Polish", "Polski"),
       
  2425     "ps" => array("Pashto", /* Left-to-right marker "‭" */ "پښتو", LANGUAGE_RTL),
       
  2426     "pt-pt" => array("Portuguese, Portugal", "Português"),
       
  2427     "pt-br" => array("Portuguese, Brazil", "Português"),
       
  2428     "qu" => array("Quechua"),
       
  2429     "rm" => array("Rhaeto-Romance"),
       
  2430     "rn" => array("Kirundi"),
       
  2431     "ro" => array("Romanian", "Română"),
       
  2432     "ru" => array("Russian", "Русский"),
       
  2433     "rw" => array("Kinyarwanda"),
       
  2434     "sa" => array("Sanskrit"),
       
  2435     "sc" => array("Sardinian"),
       
  2436     "sd" => array("Sindhi"),
       
  2437     "se" => array("Northern Sami"),
       
  2438     "sg" => array("Sango"),
       
  2439     "sh" => array("Serbo-Croatian"),
       
  2440     "si" => array("Sinhala", "සිංහල"),
       
  2441     "sk" => array("Slovak", "Slovenčina"),
       
  2442     "sl" => array("Slovenian", "Slovenščina"),
       
  2443     "sm" => array("Samoan"),
       
  2444     "sn" => array("Shona"),
       
  2445     "so" => array("Somali"),
       
  2446     "sq" => array("Albanian", "Shqip"),
       
  2447     "sr" => array("Serbian", "Српски"),
       
  2448     "ss" => array("Siswati"),
       
  2449     "st" => array("Sesotho"),
       
  2450     "su" => array("Sudanese"),
       
  2451     "sv" => array("Swedish", "Svenska"),
       
  2452     "sw" => array("Swahili", "Kiswahili"),
       
  2453     "ta" => array("Tamil", "தமிழ்"),
       
  2454     "te" => array("Telugu", "తెలుగు"),
       
  2455     "tg" => array("Tajik"),
       
  2456     "th" => array("Thai", "ภาษาไทย"),
       
  2457     "ti" => array("Tigrinya"),
       
  2458     "tk" => array("Turkmen"),
       
  2459     "tl" => array("Tagalog"),
       
  2460     "tn" => array("Setswana"),
       
  2461     "to" => array("Tonga"),
       
  2462     "tr" => array("Turkish", "Türkçe"),
       
  2463     "ts" => array("Tsonga"),
       
  2464     "tt" => array("Tatar", "Tatarça"),
       
  2465     "tw" => array("Twi"),
       
  2466     "ty" => array("Tahitian"),
       
  2467     "ug" => array("Uighur"),
       
  2468     "uk" => array("Ukrainian", "Українська"),
       
  2469     "ur" => array("Urdu", /* Left-to-right marker "‭" */ "اردو", LANGUAGE_RTL),
       
  2470     "uz" => array("Uzbek", "o'zbek"),
       
  2471     "ve" => array("Venda"),
       
  2472     "vi" => array("Vietnamese", "Tiếng Việt"),
       
  2473     "wo" => array("Wolof"),
       
  2474     "xh" => array("Xhosa", "isiXhosa"),
       
  2475     "yi" => array("Yiddish"),
       
  2476     "yo" => array("Yoruba", "Yorùbá"),
       
  2477     "za" => array("Zhuang"),
       
  2478     "zh-hans" => array("Chinese, Simplified", "简体中文"),
       
  2479     "zh-hant" => array("Chinese, Traditional", "繁體中文"),
       
  2480     "zu" => array("Zulu", "isiZulu"),
       
  2481   );
       
  2482 }
       
  2483 /**
       
  2484  * @} End of "locale-api-languages-predefined"
       
  2485  */
       
  2486 
       
  2487 /**
       
  2488  * @defgroup locale-autoimport Automatic interface translation import
       
  2489  * @{
       
  2490  */
       
  2491 
       
  2492 /**
       
  2493  * Prepare a batch to import translations for all enabled
       
  2494  * modules in a given language.
       
  2495  *
       
  2496  * @param $langcode
       
  2497  *   Language code to import translations for.
       
  2498  * @param $finished
       
  2499  *   Optional finished callback for the batch.
       
  2500  * @param $skip
       
  2501  *   Array of component names to skip. Used in the installer for the
       
  2502  *   second pass import, when most components are already imported.
       
  2503  * @return
       
  2504  *   A batch structure or FALSE if no files found.
       
  2505  */
       
  2506 function locale_batch_by_language($langcode, $finished = NULL, $skip = array()) {
       
  2507   // Collect all files to import for all enabled modules and themes.
       
  2508   $files = array();
       
  2509   $components = array();
       
  2510   $query = "SELECT name, filename FROM {system} WHERE status = 1";
       
  2511   if (count($skip)) {
       
  2512     $query .= " AND name NOT IN (". db_placeholders($skip, 'varchar') .")";
       
  2513   }
       
  2514   $result = db_query($query, $skip);
       
  2515   while ($component = db_fetch_object($result)) {
       
  2516     // Collect all files for all components, names as $langcode.po or
       
  2517     // with names ending with $langcode.po. This allows for filenames
       
  2518     // like node-module.de.po to let translators use small files and
       
  2519     // be able to import in smaller chunks.
       
  2520     $files = array_merge($files, file_scan_directory(dirname($component->filename) .'/translations', '(^|\.)'. $langcode .'\.po$', array('.', '..', 'CVS'), 0, FALSE));
       
  2521     $components[] = $component->name;
       
  2522   }
       
  2523 
       
  2524   return _locale_batch_build($files, $finished, $components);
       
  2525 }
       
  2526 
       
  2527 /**
       
  2528  * Prepare a batch to run when installing modules or enabling themes.
       
  2529  * This batch will import translations for the newly added components
       
  2530  * in all the languages already set up on the site.
       
  2531  *
       
  2532  * @param $components
       
  2533  *   An array of component (theme and/or module) names to import
       
  2534  *   translations for.
       
  2535  * @param $finished
       
  2536  *   Optional finished callback for the batch.
       
  2537  */
       
  2538 function locale_batch_by_component($components, $finished = '_locale_batch_system_finished') {
       
  2539   $files = array();
       
  2540   $languages = language_list('enabled');
       
  2541   unset($languages[1]['en']);
       
  2542   if (count($languages[1])) {
       
  2543     $language_list = join('|', array_keys($languages[1]));
       
  2544     // Collect all files to import for all $components.
       
  2545     $result = db_query("SELECT name, filename FROM {system} WHERE status = 1");
       
  2546     while ($component = db_fetch_object($result)) {
       
  2547       if (in_array($component->name, $components)) {
       
  2548         // Collect all files for this component in all enabled languages, named
       
  2549         // as $langcode.po or with names ending with $langcode.po. This allows
       
  2550         // for filenames like node-module.de.po to let translators use small
       
  2551         // files and be able to import in smaller chunks.
       
  2552         $files = array_merge($files, file_scan_directory(dirname($component->filename) .'/translations', '(^|\.)('. $language_list .')\.po$', array('.', '..', 'CVS'), 0, FALSE));
       
  2553       }
       
  2554     }
       
  2555     return _locale_batch_build($files, $finished);
       
  2556   }
       
  2557   return FALSE;
       
  2558 }
       
  2559 
       
  2560 /**
       
  2561  * Build a locale batch from an array of files.
       
  2562  *
       
  2563  * @param $files
       
  2564  *   Array of files to import
       
  2565  * @param $finished
       
  2566  *   Optional finished callback for the batch.
       
  2567  * @param $components
       
  2568  *   Optional list of component names the batch covers. Used in the installer.
       
  2569  * @return
       
  2570  *   A batch structure
       
  2571  */
       
  2572 function _locale_batch_build($files, $finished = NULL, $components = array()) {
       
  2573   $t = get_t();
       
  2574   if (count($files)) {
       
  2575     $operations = array();
       
  2576     foreach ($files as $file) {
       
  2577       // We call _locale_batch_import for every batch operation.
       
  2578       $operations[] = array('_locale_batch_import', array($file->filename));    }
       
  2579       $batch = array(
       
  2580         'operations'    => $operations,
       
  2581         'title'         => $t('Importing interface translations'),
       
  2582         'init_message'  => $t('Starting import'),
       
  2583         'error_message' => $t('Error importing interface translations'),
       
  2584         'file'          => './includes/locale.inc',
       
  2585         // This is not a batch API construct, but data passed along to the
       
  2586         // installer, so we know what did we import already.
       
  2587         '#components'   => $components,
       
  2588       );
       
  2589       if (isset($finished)) {
       
  2590         $batch['finished'] = $finished;
       
  2591       }
       
  2592     return $batch;
       
  2593   }
       
  2594   return FALSE;
       
  2595 }
       
  2596 
       
  2597 /**
       
  2598  * Perform interface translation import as a batch step.
       
  2599  *
       
  2600  * @param $filepath
       
  2601  *   Path to a file to import.
       
  2602  * @param $results
       
  2603  *   Contains a list of files imported.
       
  2604  */
       
  2605 function _locale_batch_import($filepath, &$context) {
       
  2606   // The filename is either {langcode}.po or {prefix}.{langcode}.po, so
       
  2607   // we can extract the language code to use for the import from the end.
       
  2608   if (preg_match('!(/|\.)([^\./]+)\.po$!', $filepath, $langcode)) {
       
  2609     $file = (object) array('filename' => basename($filepath), 'filepath' => $filepath);
       
  2610     _locale_import_read_po('db-store', $file, LOCALE_IMPORT_KEEP, $langcode[2]);
       
  2611     $context['results'][] = $filepath;
       
  2612   }
       
  2613 }
       
  2614 
       
  2615 /**
       
  2616  * Finished callback of system page locale import batch.
       
  2617  * Inform the user of translation files imported.
       
  2618  */
       
  2619 function _locale_batch_system_finished($success, $results) {
       
  2620   if ($success) {
       
  2621     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.'));
       
  2622   }
       
  2623 }
       
  2624 
       
  2625 /**
       
  2626  * Finished callback of language addition locale import batch.
       
  2627  * Inform the user of translation files imported.
       
  2628  */
       
  2629 function _locale_batch_language_finished($success, $results) {
       
  2630   if ($success) {
       
  2631     drupal_set_message(format_plural(count($results), 'One translation file imported for the enabled modules.', '@count translation files imported for the enabled modules.'));
       
  2632   }
       
  2633 }
       
  2634 
       
  2635 /**
       
  2636  * @} End of "locale-autoimport"
       
  2637  */