locale.inc 109 KB
Newer Older
1 2
<?php
// $Id$
3

4 5
/**
 * @file
6
 * Administration functions for locale.module.
7 8
 */

9 10 11
/**
 * Regular expression pattern used to localize JavaScript strings.
 */
12 13
define('LOCALE_JS_STRING', '(?:(?:\'(?:\\\\\'|[^\'])*\'|"(?:\\\\"|[^"])*")(?:\s*\+\s*)?)+');

14 15 16 17 18 19 20 21 22 23 24 25
/**
 * Translation import mode overwriting all existing translations
 * if new translated version available.
 */
define('LOCALE_IMPORT_OVERWRITE', 0);

/**
 * Translation import mode keeping existing translations and only
 * inserting new strings.
 */
define('LOCALE_IMPORT_KEEP', 1);

26 27 28 29 30 31 32 33 34 35 36 37
/**
 * URL language negotiation: use the path prefix as URL language
 * indicator.
 */
define('LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX', 0);

/**
 * URL language negotiation: use the domain as URL language
 * indicator.
 */
define('LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN', 1);

38
/**
39 40
 * @defgroup locale-language-overview Language overview functionality
 * @{
41 42 43
 */

/**
44
 * User interface for the language overview screen.
45
 */
46
function locale_languages_overview_form() {
47 48
  drupal_static_reset('language');
  $languages = language_list('language');
49

50
  $options = array();
51 52
  $form['weight'] = array('#tree' => TRUE);
  foreach ($languages as $langcode => $language) {
53

54 55 56
    $options[$langcode] = '';
    if ($language->enabled) {
      $enabled[] = $langcode;
57
    }
58 59
    $form['weight'][$langcode] = array(
      '#type' => 'weight',
60
      '#default_value' => $language->weight,
61
      '#attributes' => array('class' => array('language-order-weight')),
62
    );
63 64 65
    $form['name'][$langcode] = array('#markup' => check_plain($language->name));
    $form['native'][$langcode] = array('#markup' => check_plain($language->native));
    $form['direction'][$langcode] = array('#markup' => ($language->direction == LANGUAGE_RTL ? t('Right to left') : t('Left to right')));
66
  }
67 68 69 70 71 72
  $form['enabled'] = array('#type' => 'checkboxes',
    '#options' => $options,
    '#default_value' => $enabled,
  );
  $form['site_default'] = array('#type' => 'radios',
    '#options' => $options,
73
    '#default_value' => language_default('language'),
74
  );
75
  $form['submit'] = array('#type' => 'submit', '#value' => t('Save configuration'));
76
  $form['#theme'] = 'locale_languages_overview_form';
77

78
  return $form;
79
}
80

81
/**
82
 * Theme the language overview form.
83
 *
84 85 86 87 88 89 90
 * @param $variables
 *   An associative array containing:
 *   - form: @todo: document
 *
 * @return
 *   A themed HTML string representing the form.
 *
91
 * @ingroup themeable
92
 */
93 94
function theme_locale_languages_overview_form($variables) {
  $form = $variables['form'];
95
  $default = language_default();
96
  foreach ($form['name'] as $key => $element) {
97
    // Do not take form control structures.
98
    if (is_array($element) && element_child($key)) {
99 100
      // Disable checkbox for the default language, because it cannot be disabled.
      if ($key == $default->language) {
101
        $form['enabled'][$key]['#attributes']['disabled'] = 'disabled';
102 103
      }
      $rows[] = array(
104 105 106 107 108 109 110 111
        'data' => array(
          '<strong>' . drupal_render($form['name'][$key]) . '</strong>',
          drupal_render($form['native'][$key]),
          check_plain($key),
          drupal_render($form['direction'][$key]),
          array('data' => drupal_render($form['enabled'][$key]), 'align' => 'center'),
          drupal_render($form['site_default'][$key]),
          drupal_render($form['weight'][$key]),
112
          l(t('edit'), 'admin/config/regional/language/edit/' . $key) . (($key != 'en' && $key != $default->language) ? ' ' . l(t('delete'), 'admin/config/regional/language/delete/' . $key) : '')
113
        ),
114
        'class' => array('draggable'),
115
      );
116 117
    }
  }
118
  $header = array(array('data' => t('English name')), array('data' => t('Native name')), array('data' => t('Code')), array('data' => t('Direction')), array('data' => t('Enabled')), array('data' => t('Default')), array('data' => t('Weight')), array('data' => t('Operations')));
119
  $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'language-order')));
120
  $output .= drupal_render_children($form);
121

122
  drupal_add_tabledrag('language-order', 'order', 'sibling', 'language-order-weight');
Dries's avatar
Dries committed
123

124
  return $output;
125 126 127
}

/**
128
 * Process language overview form submissions, updating existing languages.
129
 */
130
function locale_languages_overview_form_submit($form, &$form_state) {
131
  $languages = language_list();
132
  $default = language_default();
133 134
  $enabled_count = 0;
  foreach ($languages as $langcode => $language) {
135 136 137 138
    if ($form_state['values']['site_default'] == $langcode || $default->language == $langcode) {
      // Automatically enable the default language and the language
      // which was default previously (because we will not get the
      // value from that disabled checkox).
139
      $form_state['values']['enabled'][$langcode] = 1;
140
    }
141
    if ($form_state['values']['enabled'][$langcode]) {
142 143
      $enabled_count++;
      $language->enabled = 1;
144 145
    }
    else {
146
      $language->enabled = 0;
147
    }
148
    $language->weight = $form_state['values']['weight'][$langcode];
149 150 151 152 153 154 155
    db_update('languages')
      ->fields(array(
        'enabled' => $language->enabled,
        'weight' => $language->weight,
      ))
      ->condition('language', $langcode)
      ->execute();
156
    $languages[$langcode] = $language;
157 158
  }
  drupal_set_message(t('Configuration saved.'));
159
  variable_set('language_default', $languages[$form_state['values']['site_default']]);
160
  variable_set('language_count', $enabled_count);
Dries's avatar
Dries committed
161

162
  // Changing the language settings impacts the interface.
163
  cache_clear_all('*', 'cache_page', TRUE);
164

165
  $form_state['redirect'] = 'admin/config/regional/language';
166
  return;
167 168 169 170 171 172 173 174 175 176 177 178 179 180
}
/**
 * @} End of "locale-language-overview"
 */

/**
 * @defgroup locale-language-add-edit Language addition and editing functionality
 * @{
 */

/**
 * User interface for the language addition screen.
 */
function locale_languages_add_screen() {
181 182 183
  $build['predefined'] = drupal_get_form('locale_languages_predefined_form');
  $build['custom'] = drupal_get_form('locale_languages_custom_form');
  return $build;
184 185
}

186 187 188
/**
 * Predefined language setup form.
 */
189
function locale_languages_predefined_form($form) {
190
  $predefined = _locale_prepare_predefined_list();
191
  $form['language list'] = array('#type' => 'fieldset',
192
    '#title' => t('Predefined language'),
193 194 195 196
    '#collapsible' => TRUE,
  );
  $form['language list']['langcode'] = array('#type' => 'select',
    '#title' => t('Language name'),
197 198
    '#default_value' => key($predefined),
    '#options' => $predefined,
199
    '#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.)'),
200 201
  );
  $form['language list']['submit'] = array('#type' => 'submit', '#value' => t('Add language'));
202 203
  return $form;
}
Dries's avatar
Dries committed
204

205 206 207
/**
 * Custom language addition form.
 */
208
function locale_languages_custom_form($form) {
209 210 211
  $form['custom language'] = array('#type' => 'fieldset',
    '#title' => t('Custom language'),
    '#collapsible' => TRUE,
212
    '#collapsed' => TRUE,
213
  );
214
  _locale_languages_common_controls($form['custom language']);
215 216 217
  $form['custom language']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add custom language')
218
  );
219
  // Reuse the validation and submit functions of the predefined language setup form.
220 221
  $form['#submit'][] = 'locale_languages_predefined_form_submit';
  $form['#validate'][] = 'locale_languages_predefined_form_validate';
222 223 224 225 226 227 228
  return $form;
}

/**
 * Editing screen for a particular language.
 *
 * @param $langcode
229
 *   Language code of the language to edit.
230
 */
231
function locale_languages_edit_form($form, &$form_state, $langcode) {
232
  if ($language = db_query("SELECT * FROM {languages} WHERE language = :language", array(':language' => $langcode))->fetchObject()) {
233
    _locale_languages_common_controls($form, $language);
234 235 236 237
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Save language')
    );
238 239
    $form['#submit'][] = 'locale_languages_edit_form_submit';
    $form['#validate'][] = 'locale_languages_edit_form_validate';
240 241 242 243 244 245 246 247
    return $form;
  }
  else {
    drupal_not_found();
  }
}

/**
248
 * Common elements of the language addition and editing form.
249 250 251 252 253 254
 *
 * @param $form
 *   A parent form item (or empty array) to add items below.
 * @param $language
 *   Language object to edit.
 */
255
function _locale_languages_common_controls(&$form, $language = NULL) {
256 257 258 259 260 261 262
  if (!is_object($language)) {
    $language = new stdClass();
  }
  if (isset($language->language)) {
    $form['langcode_view'] = array(
      '#type' => 'item',
      '#title' => t('Language code'),
263
      '#markup' => $language->language
264 265 266 267 268 269 270 271 272 273 274 275 276 277
    );
    $form['langcode'] = array(
      '#type' => 'value',
      '#value' => $language->language
    );
  }
  else {
    $form['langcode'] = array('#type' => 'textfield',
      '#title' => t('Language code'),
      '#size' => 12,
      '#maxlength' => 60,
      '#required' => TRUE,
      '#default_value' => @$language->language,
      '#disabled' => (isset($language->language)),
278
      '#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')),
279 280
    );
  }
281
  $form['name'] = array('#type' => 'textfield',
282 283
    '#title' => t('Language name in English'),
    '#maxlength' => 64,
284
    '#default_value' => @$language->name,
285
    '#required' => TRUE,
286
    '#description' => t('Name of the language in English. Will be available for translation in all languages.'),
287
  );
288
  $form['native'] = array('#type' => 'textfield',
289 290 291 292 293 294 295 296 297 298
    '#title' => t('Native language name'),
    '#maxlength' => 64,
    '#default_value' => @$language->native,
    '#required' => TRUE,
    '#description' => t('Name of the language in the language being added.'),
  );
  $form['prefix'] = array('#type' => 'textfield',
    '#title' => t('Path prefix'),
    '#maxlength' => 64,
    '#default_value' => @$language->prefix,
299
    '#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>')
300 301 302
  );
  $form['domain'] = array('#type' => 'textfield',
    '#title' => t('Language domain'),
303
    '#maxlength' => 128,
304
    '#default_value' => @$language->domain,
305
    '#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>'),
306 307 308 309
  );
  $form['direction'] = array('#type' => 'radios',
    '#title' => t('Direction'),
    '#required' => TRUE,
310
    '#description' => t('Direction that text in this language is presented.'),
311
    '#default_value' => @$language->direction,
312
    '#options' => array(LANGUAGE_LTR => t('Left to right'), LANGUAGE_RTL => t('Right to left'))
313
  );
314 315
  return $form;
}
316 317

/**
318 319
 * Validate the language addition form.
 */
320 321
function locale_languages_predefined_form_validate($form, &$form_state) {
  $langcode = $form_state['values']['langcode'];
322

323
  if (($duplicate = db_query("SELECT COUNT(*) FROM {languages} WHERE language = :language", array(':language' => $langcode))->fetchField()) != 0) {
324
    form_set_error('langcode', t('The language %language (%code) already exists.', array('%language' => $form_state['values']['name'], '%code' => $langcode)));
325 326
  }

327
  if (!isset($form_state['values']['name'])) {
328
    // Predefined language selection.
329
    include_once DRUPAL_ROOT . '/includes/iso.inc';
330
    $predefined = _locale_get_predefined_list();
331
    if (!isset($predefined[$langcode])) {
332 333 334
      form_set_error('langcode', t('Invalid language code.'));
    }
  }
335
  else {
336
    // Reuse the editing form validation routine if we add a custom language.
337
    locale_languages_edit_form_validate($form, $form_state);
338
  }
339 340 341 342 343
}

/**
 * Process the language addition form submission.
 */
344 345 346
function locale_languages_predefined_form_submit($form, &$form_state) {
  $langcode = $form_state['values']['langcode'];
  if (isset($form_state['values']['name'])) {
347
    // Custom language form.
348 349
    locale_add_language($langcode, $form_state['values']['name'], $form_state['values']['native'], $form_state['values']['direction'], $form_state['values']['domain'], $form_state['values']['prefix']);
    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'))));
350 351
  }
  else {
352
    // Predefined language selection.
353
    include_once DRUPAL_ROOT . '/includes/iso.inc';
354
    $predefined = _locale_get_predefined_list();
355 356
    locale_add_language($langcode);
    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'))));
357 358
  }

359 360 361 362 363 364
  // See if we have language files to import for the newly added
  // language, collect and import them.
  if ($batch = locale_batch_by_language($langcode, '_locale_batch_language_finished')) {
    batch_set($batch);
  }

365
  $form_state['redirect'] = 'admin/config/regional/language';
366
  return;
367 368 369 370 371
}

/**
 * Validate the language editing form. Reused for custom language addition too.
 */
372 373
function locale_languages_edit_form_validate($form, &$form_state) {
  if (!empty($form_state['values']['domain']) && !empty($form_state['values']['prefix'])) {
374 375
    form_set_error('prefix', t('Domain and path prefix values should not be set at the same time.'));
  }
376
  if (!empty($form_state['values']['domain']) && $duplicate = db_query("SELECT language FROM {languages} WHERE domain = :domain AND language <> :language", array(':domain' => $form_state['values']['domain'], ':language' => $form_state['values']['langcode']))->fetchField()) {
377
    form_set_error('domain', t('The domain (%domain) is already tied to a language (%language).', array('%domain' => $form_state['values']['domain'], '%language' => $duplicate->language)));
378
  }
379
  if (empty($form_state['values']['prefix']) && language_default('language') != $form_state['values']['langcode'] && empty($form_state['values']['domain'])) {
380 381
    form_set_error('prefix', t('Only the default language can have both the domain and prefix empty.'));
  }
382
  if (!empty($form_state['values']['prefix']) && $duplicate = db_query("SELECT language FROM {languages} WHERE prefix = :prefix AND language <> :language", array(':prefix' => $form_state['values']['prefix'], ':language' => $form_state['values']['langcode']))->fetchField()) {
383
    form_set_error('prefix', t('The prefix (%prefix) is already tied to a language (%language).', array('%prefix' => $form_state['values']['prefix'], '%language' => $duplicate->language)));
384 385 386 387 388 389
  }
}

/**
 * Process the language editing form submission.
 */
390
function locale_languages_edit_form_submit($form, &$form_state) {
391 392 393 394 395 396 397 398 399 400
  db_update('languages')
    ->fields(array(
      'name' => $form_state['values']['name'],
      'native' => $form_state['values']['native'],
      'domain' => $form_state['values']['domain'],
      'prefix' => $form_state['values']['prefix'],
      'direction' => $form_state['values']['direction'],
    ))
    ->condition('language',  $form_state['values']['langcode'])
    ->execute();
401
  $default = language_default();
402
  if ($default->language == $form_state['values']['langcode']) {
403
    $properties = array('name', 'native', 'direction', 'enabled', 'plurals', 'formula', 'domain', 'prefix', 'weight');
404
    foreach ($properties as $keyname) {
405 406 407
      if (isset($form_state['values'][$keyname])) {
        $default->$keyname = $form_state['values'][$keyname];
      }
408
    }
409
    variable_set('language_default', $default);
410
  }
411
  $form_state['redirect'] = 'admin/config/regional/language';
412
  return;
413
}
414 415 416 417 418 419 420 421 422 423 424 425
/**
 * @} End of "locale-language-add-edit"
 */

/**
 * @defgroup locale-language-delete Language deletion functionality
 * @{
 */

/**
 * User interface for the language deletion confirmation screen.
 */
426
function locale_languages_delete_form($form, &$form_state, $langcode) {
427 428 429 430

  // Do not allow deletion of English locale.
  if ($langcode == 'en') {
    drupal_set_message(t('The English language cannot be deleted.'));
431
    drupal_goto('admin/config/regional/language');
432 433
  }

434
  if (language_default('language') == $langcode) {
435
    drupal_set_message(t('The default language cannot be deleted.'));
436
    drupal_goto('admin/config/regional/language');
437 438 439 440 441 442 443 444 445 446
  }

  // For other languages, warn user that data loss is ahead.
  $languages = language_list();

  if (!isset($languages[$langcode])) {
    drupal_not_found();
  }
  else {
    $form['langcode'] = array('#type' => 'value', '#value' => $langcode);
447
    return confirm_form($form, t('Are you sure you want to delete the language %name?', array('%name' => t($languages[$langcode]->name))), 'admin/config/regional/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'));
448 449 450 451 452 453
  }
}

/**
 * Process language deletion submissions.
 */
454
function locale_languages_delete_form_submit($form, &$form_state) {
455
  $languages = language_list();
456
  if (isset($languages[$form_state['values']['langcode']])) {
457
    // Remove translations first.
458 459 460
    db_delete('locales_target')
      ->condition('language', $form_state['values']['langcode'])
      ->execute();
461
    cache_clear_all('locale:' . $form_state['values']['langcode'], 'cache');
462 463 464
    // With no translations, this removes existing JavaScript translations file.
    _locale_rebuild_js($form_state['values']['langcode']);
    // Remove the language.
465 466 467 468 469 470 471
    db_delete('languages')
      ->condition('language', $form_state['values']['langcode'])
      ->execute();
    db_update('node')
      ->fields(array('language' => ''))
      ->condition('language', $form_state['values']['langcode'])
      ->execute();
472
    $variables = array('%locale' => $languages[$form_state['values']['langcode']]->name);
473 474 475 476 477 478 479
    drupal_set_message(t('The language %locale has been removed.', $variables));
    watchdog('locale', 'The language %locale has been removed.', $variables);
  }

  // Changing the language settings impacts the interface:
  cache_clear_all('*', 'cache_page', TRUE);

480
  $form_state['redirect'] = 'admin/config/regional/language';
481
  return;
482 483 484 485 486 487
}
/**
 * @} End of "locale-language-add-edit"
 */

/**
488
 * @defgroup locale-languages-negotiation Language negotiation options
489 490
 * @{
 */
491 492 493 494

/**
 * Setting for language negotiation options
 */
495
function locale_languages_configure_form() {
496 497 498 499 500 501 502 503
  include_once DRUPAL_ROOT . '/includes/language.inc';

  $form = array(
    '#submit' => array('locale_languages_configure_form_submit'),
    '#theme' => 'locale_languages_configure_form',
    '#language_types' => language_types_configurable(),
    '#language_types_info' => language_types_info(),
    '#language_providers' => language_negotiation_info(),
504
  );
505 506 507 508 509

  foreach ($form['#language_types'] as $type) {
    _locale_languages_configure_form_language_table($form, $type);
  }

510 511
  $form['submit'] = array(
    '#type' => 'submit',
512
    '#value' => t('Save settings'),
513
  );
514

515 516
  return $form;
}
Dries's avatar
Dries committed
517

518
/**
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
 * Helper function to build a language provider table.
 */
function _locale_languages_configure_form_language_table(&$form, $type) {
  $info = $form['#language_types_info'][$type];

  $table_form = array(
    '#title' => t('@type language', array('@type' => $info['name'])),
    '#tree' => TRUE,
    '#description' => $info['description'],
    '#language_providers' => array(),
    '#show_operations' => FALSE,
    'weight' => array('#tree' => TRUE),
    'enabled' => array('#tree' => TRUE),
  );

  $language_providers = $form['#language_providers'];
  $enabled_providers = variable_get("locale_language_providers_enabled_$type", array());
  $providers_weight = variable_get("locale_language_providers_weight_$type", array());

  // Add missing data to the providers lists.
  foreach ($language_providers as $id => $provider) {
    if (!isset($providers_weight[$id])) {
      $providers_weight[$id] = language_provider_weight($provider);
    }
    if (!isset($enabled_providers[$id])) {
      $enabled_providers[$id] = FALSE;
    }
  }

  // Order providers list by weight.
  asort($providers_weight);

  foreach ($providers_weight as $id => $weight) {
    $enabled = $enabled_providers[$id];
    $provider = $language_providers[$id];

    // List the provider only if the current type is defined in its 'types' key.
    // If it is not defined default to all the configurabe language types.
    $types = array_flip(isset($provider['types']) ? $provider['types'] : $form['#language_types']);

    if (isset($types[$type])) {
      $table_form['#language_providers'][$id] = $provider;

      $table_form['weight'][$id] = array(
        '#type' => 'weight',
        '#default_value' => $weight,
        '#attributes' => array('class' => array("language-provider-weight-$type")),
      );

      $table_form['title'][$id] = array('#markup' => check_plain($provider['name']));

      $table_form['enabled'][$id] = array('#type' => 'checkbox', '#default_value' => $enabled);
      if ($id === LANGUAGE_NEGOTIATION_DEFAULT) {
        $table_form['enabled'][$id]['#default_value'] = TRUE;
        $table_form['enabled'][$id]['#attributes'] = array('disabled' => 'disabled');
      }

      $table_form['description'][$id] = array('#markup' => filter_xss_admin($provider['description']));

      $config_op = '';
      if (isset($provider['config'])) {
        $config_op = l(t('Configure'), $provider['config']);
        // If there is at least one operation enabled show the operation column.
        $table_form['#show_operations'] = TRUE;
      }
      $table_form['operation'][$id] = array('#markup' => $config_op);
    }
  }

  $form[$type] = $table_form;
}

/**
 * Theme the language configure form.
 *
 * @ingroup themeable
 */
function theme_locale_languages_configure_form($variables) {
  $form = $variables['form'];
  $output = '';

  foreach ($form['#language_types'] as $type) {
    $rows = array();
    $info = $form['#language_types_info'][$type];
    $title = '<label>' . $form[$type]['#title'] . '</label>';
    $description = '<div class="description">' . $form[$type]['#description'] . '</div>';

    foreach ($form[$type]['title'] as $id => $element) {
      // Do not take form control structures.
      if (is_array($element) && element_child($id)) {
        $row = array(
          'data' => array(
            '<strong>' . drupal_render($form[$type]['title'][$id]) . '</strong>',
            drupal_render($form[$type]['description'][$id]),
            drupal_render($form[$type]['enabled'][$id]),
            drupal_render($form[$type]['weight'][$id]),
          ),
          'class' => array('draggable'),
        );
        if ($form[$type]['#show_operations']) {
          $row['data'][] = drupal_render($form[$type]['operation'][$id]);
        }
        $rows[] = $row;
      }
    }

    $header = array(
      array('data' => t('Detection method')),
      array('data' => t('Description')),
      array('data' => t('Enabled')),
      array('data' => t('Weight')),
    );

    // If there is at least one operation enabled show the operation column.
    if ($form[$type]['#show_operations']) {
      $header[] = array('data' => t('Operations'));
    }

    $variables = array(
      'header' => $header,
      'rows' => $rows,
      'attributes' => array('id' => "language-negotiation-providers-$type"),
    );
    $table  = theme('table', $variables);
    $table .= drupal_render_children($form[$type]);

    drupal_add_tabledrag("language-negotiation-providers-$type", 'order', 'sibling', "language-provider-weight-$type");

    $output .= '<div class="form-item">' . $title . $description . $table . '</div>';
  }

  $output .= drupal_render_children($form);
  return $output;
}

/**
 * Submit handler for language negotiation settings.
656
 */
657
function locale_languages_configure_form_submit($form, &$form_state) {
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
  $language_types = array();
  $configurable_types = $form['#language_types'];

  foreach ($configurable_types as $type) {
    $negotiation = array();
    $enabled_providers = $form_state['values'][$type]['enabled'];
    $enabled_providers[LANGUAGE_NEGOTIATION_DEFAULT] = TRUE;
    $providers_weight = $form_state['values'][$type]['weight'];
    $language_types[$type] = TRUE;

    foreach ($providers_weight as $id => $weight) {
      if ($enabled_providers[$id]) {
        $provider = $form[$type]['#language_providers'][$id];
        $provider['weight'] = $weight;
        $negotiation[$id] = $provider;
      }
    }

    language_negotiation_set($type, $negotiation);
    variable_set("locale_language_providers_enabled_$type", $enabled_providers);
    variable_set("locale_language_providers_weight_$type", $providers_weight);
  }

  // Save non-configurable language types negotiation.
  $language_types_info = language_types_info();
  $defined_providers = $form['#language_providers'];
  foreach ($language_types_info as $type => $info) {
    if (isset($info['fixed'])) {
      $language_types[$type] = FALSE;
      $negotiation = array();
      foreach ($info['fixed'] as $id) {
        if (isset($defined_providers[$id])) {
          $negotiation[$id] = $defined_providers[$id];
        }
      }
      language_negotiation_set($type, $negotiation);
    }
  }

  // Save language types.
  variable_set('language_types', $language_types);

700
  $form_state['redirect'] = 'admin/config/regional/language';
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
  drupal_set_message(t('Language negotiation configuration saved.'));
}

/**
 * The URL language provider configuration form.
 */
function locale_language_providers_url_form() {
  $form = array();

  $form['locale_language_negotiation_url_part'] = array(
    '#title' => t('URL language indicator'),
    '#type' => 'radios',
    '#options' => array(
      LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX => t('Path prefix'),
      LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN => t('Domain'),
    ),
    '#default_value' => variable_get('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX),
    '#description' => t('Select which part of the URL will determine the language.'),
  );

  $form['#redirect'] = 'admin/config/regional/language/configure';

  return system_settings_form($form);
724
}
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996

/**
 * The URL language provider configuration form.
 */
function locale_language_providers_session_form() {
  $form = array();

  $form['locale_language_negotiation_session_param'] = array(
    '#title' => t('Request/session parameter'),
    '#type' => 'textfield',
    '#default_value' => variable_get('locale_language_negotiation_session_param', 'language'),
    '#description' => t('This value will be the name of the request/session parameter which will be used to determine the desired language.'),
  );

  $form['#redirect'] = 'admin/config/regional/language/configure';

  return system_settings_form($form);
}

/**
 * Identify the language from the current content language.
 *
 * @return
 *   The current content language code.
 */
function locale_language_from_content() {
  global $language;
  return isset($language->language) ? $language->language : FALSE;
}

/**
 * Identify language from the Accept-language HTTP header we got.
 *
 * We perform browser accept-language parsing only if page cache is disabled,
 * otherwise we would cache a user-specific preference.
 *
 * @param $languages
 *   An array of valid language objects.
 *
 * @return
 *   A valid language code on success, FALSE otherwise.
 */
function locale_language_from_browser($languages) {
  // Specified by the user via the browser's Accept Language setting
  // Samples: "hu, en-us;q=0.66, en;q=0.33", "hu,en-us;q=0.5"
  $browser_langs = array();

  if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
    $browser_accept = explode(",", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
    foreach ($browser_accept as $langpart) {
      // The language part is either a code or a code with a quality.
      // We cannot do anything with a * code, so it is skipped.
      // If the quality is missing, it is assumed to be 1 according to the RFC.
      if (preg_match("!([a-z-]+)(;q=([0-9\\.]+))?!", trim($langpart), $found)) {
        $browser_langs[$found[1]] = (isset($found[3]) ? (float) $found[3] : 1.0);
      }
    }
  }

  // Order the codes by quality
  arsort($browser_langs);

  // Try to find the first preferred language we have
  foreach ($browser_langs as $langcode => $q) {
    if (isset($languages[$langcode])) {
      return $langcode;
    }
  }

  return FALSE;
}

/**
 * Identify language from the user preferences.
 *
 * @param $languages
 *   An array of valid language objects.
 *
 * @return
 *   A valid language code on succes, FALSE otherwise.
 */
function locale_language_from_user($languages) {
  // User preference (only for logged users).
  global $user;

  if ($user->uid) {
    return $user->language;
  }

  // No language preference from the user.
  return FALSE;
}

/**
 * Identify language from a request/session parameter.
 *
 * @param $languages
 *   An array of valid language objects.
 *
 * @return
 *   A valid language code on succes, FALSE otherwise.
 */
function locale_language_from_session($languages) {
  $param = variable_get('locale_language_negotiation_session_param', 'language');

  // Request parameter.
  if (isset($_GET[$param]) && isset($languages[$langcode = $_GET[$param]])) {
    return $_SESSION[$param] = $langcode;
  }

  // Session parameter.
  if (isset($_SESSION[$param])) {
    return $_SESSION[$param];
  }

  return FALSE;
}

/**
 * Identify language via URL prefix or domain.
 *
 * @param $languages
 *   An array of valid language objects.
 *
 * @return
 *   A valid language code on succes, FALSE otherwise.
 */
function locale_language_from_url($languages) {
  $language_url = FALSE;

  switch (variable_get('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX)) {
    case LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX:
      // $_GET['q'] might not be available at this time, because
      // path initialization runs after the language bootstrap phase.
      list($language, $_GET['q']) = language_url_split_prefix(isset($_GET['q']) ? $_GET['q'] : NULL, $languages);
      if ($language !== FALSE) {
        $language_url = $language->language;
      }
      break;

    case LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN:
      foreach ($languages as $language) {
        $host = parse_url($language->domain, PHP_URL_HOST);
        if ($host && ($_SERVER['HTTP_HOST'] == $host)) {
          $language_url = $language->language;
          break;
        }
      }
      break;
  }

  return $language_url;
}

/**
 * Return the URL language switcher block. Translation links may be provided by
 * other modules.
 */
function locale_language_switcher_url($type, $path) {
  $languages = language_list('enabled');
  $links = array();

  foreach ($languages[1] as $language) {
    $links[$language->language] = array(
      'href'       => $path,
      'title'      => $language->native,
      'language'   => $language,
      'attributes' => array('class' => array('language-link')),
    );
  }

  return $links;
}

/**
 * Return the session language switcher block.
 */
function locale_language_switcher_session($type, $path) {
  drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');

  $param = variable_get('locale_language_negotiation_session_param', 'language');
  $language_query = isset($_SESSION[$param]) ? $_SESSION[$param] : $GLOBALS[$type]->language;

  $languages = language_list('enabled');
  $links = array();

  $query = $_GET;
  unset($query['q']);

  foreach ($languages[1] as $language) {
    $langcode = $language->language;
    $links[$langcode] = array(
      'href'       => $path,
      'title'      => $language->native,
      'attributes' => array('class' => array('language-link')),
      'query'      => $query,
    );
    if ($language_query != $langcode) {
      $links[$langcode]['query'][$param] = $langcode;
    }
    else {
      $links[$langcode]['attributes']['class'][] = ' session-active';
    }
  }

  return $links;
}

/**
 * Rewrite URLs for the URL language provider.
 */
function locale_language_url_rewrite_url(&$path, &$options) {
  // Language can be passed as an option, or we go for current URL language.
  if (!isset($options['language'])) {
    global $language_url;
    $options['language'] = $language_url;
  }

  if (isset($options['language'])) {
    switch (variable_get('locale_language_negotiation_url_part', LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX)) {
      case LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN:
        if ($options['language']->domain) {
          // Ask for an absolute URL with our modified base_url.
          $options['absolute'] = TRUE;
          $options['base_url'] = $options['language']->domain;
        }
        break;

      case LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX:
        if (!empty($options['language']->prefix)) {
          $options['prefix'] = $options['language']->prefix . '/';
        }
        break;
    }
  }
}

/**
 * Rewrite URLs for the Session language provider.
 */
function locale_language_url_rewrite_session(&$path, &$options) {
  static $query_rewrite, $query_param, $query_value;

  // The following values are not supposed to change during a single page
  // request processing.
  if (!isset($query_rewrite)) {
    global $user;
    if (!$user->uid) {
      $languages = language_list('enabled');
      $languages = $languages[1];
      $query_param = check_plain(variable_get('locale_language_negotiation_session_param', 'language'));
      $query_value = isset($_GET[$query_param]) ? check_plain($_GET[$query_param]) : NULL;
      $query_rewrite = isset($languages[$query_value]) && language_negotiation_get_any(LOCALE_LANGUAGE_NEGOTIATION_SESSION);
    }
    else {
      $query_rewrite = FALSE;
    }
  }

  // If the user is anonymous, the user language provider is enabled, and the
  // corresponding option has been set, we must preserve any explicit user
  // language preference even with cookies disabled.
  if ($query_rewrite) {
    if (is_string($options['query'])) {
      $options['query'] = drupal_get_query_array($options['query']);
    }
    if (!isset($options['query'][$query_param])) {
      $options['query'][$query_param] = $query_value;
    }
  }
}

997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
/**
 * @} End of "locale-languages-negotiation"
 */

/**
 * @defgroup locale-translate-overview Translation overview screen.
 * @{
 */

/**
 * Overview screen for translations.
 */
function locale_translate_overview_screen() {
1010 1011
  drupal_static_reset('language_list');
  $languages = language_list('language');
1012 1013 1014 1015 1016 1017 1018 1019
  $groups = module_invoke_all('locale', 'groups');

  // Build headers with all groups in order.
  $headers = array_merge(array(t('Language')), array_values($groups));

  // Collect summaries of all source strings in all groups.
  $sums = db_query("SELECT COUNT(*) AS strings, textgroup FROM {locales_source} GROUP BY textgroup");
  $groupsums = array();
1020
  foreach ($sums as $group) {
1021 1022 1023
    $groupsums[$group->textgroup] = $group->strings;
  }

1024
  // Set up overview table with default values, ensuring common order for values.
1025 1026 1027 1028
  $rows = array();
  foreach ($languages as $langcode => $language) {
    $rows[$langcode] = array('name' => ($langcode == 'en' ? t('English (built-in)') : t($language->name)));
    foreach ($groups as $group => $name) {
1029
      $rows[$langcode][$group] = ($langcode == 'en' ? t('n/a') : '0/' . (isset($groupsums[$group]) ? $groupsums[$group] : 0) . ' (0%)');
1030 1031 1032 1033
    }
  }

  // Languages with at least one record in the locale table.
1034
  $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");
1035
  foreach ($translations as $data) {
1036
    $ratio = (!empty($groupsums[$data->textgroup]) && $data->translation > 0) ? round(($data->translation/$groupsums[$data->textgroup]) * 100.0, 2) : 0;
1037
    $rows[$data->language][$data->textgroup] = $data->translation . '/' . $groupsums[$data->textgroup] . " ($ratio%)";
1038 1039
  }

1040
  return theme('table', array('header' => $headers, 'rows' => $rows));
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
}
/**
 * @} End of "locale-translate-overview"
 */

/**
 * @defgroup locale-translate-seek Translation search screen.
 * @{
 */

/**
 * String search screen.
 */
function locale_translate_seek_screen() {
1055 1056 1057
  // Add CSS.
  drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css', array('preprocess' => FALSE));

1058
  $output = drupal_render(drupal_get_form('locale_translation_filter_form'));
1059
  $output .= _locale_translate_seek();
1060 1061
  return $output;
}
1062 1063 1064
/**
 * @} End of "locale-translate-seek"
 */
1065 1066

/**
1067
 * List locale translation filters that can be applied.
1068
 */
1069 1070 1071
function locale_translation_filters() {
  $filters = array();

1072
  // Get all languages, except English
1073 1074
  drupal_static_reset('language_list');
  $languages = locale_language_list('name');
1075 1076
  unset($languages['en']);

1077 1078 1079
  $filters['string'] = array(
    'title' => t('String contains'),
    'description' => t('Leave blank to show all strings. The search is case sensitive.'),
1080
  );
1081 1082 1083 1084

  $filters['language'] = array(
    'title' => t('Language'),
    'options' => array_merge(array('all' => t('All languages'), 'en' => t('English (provided by Drupal)')), $languages),
1085
  );
1086 1087 1088 1089

  $filters['translation'] = array(
    'title' => t('Search in'),
    'options' => array('all' => t('Both translated and untranslated strings'), 'translated' => t('Only translated strings'), 'untranslated' => t('Only untranslated strings')),
1090
  );
1091

1092
  $groups = module_invoke_all('locale', 'groups');
1093 1094 1095
  $filters['group'] = array(
    'title' => t('Limit search to'),
    'options' => array_merge(array('all' => t('All text groups')), $groups),
1096 1097
  );

1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
  return $filters;
}

/**
 * Return form for locale translation filters.
 *
 * @ingroup forms
 */
function locale_translation_filter_form() {
  $filters = locale_translation_filters();

  $form['filters'] = array(
    '#type' => 'fieldset',
    '#title' => t('Filter translatable strings'),
    '#theme' => 'locale_translation_filters',
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  foreach ($filters as $key => $filter) {
    // Special case for 'string' filter.
    if ($key == 'string') {
      $form['filters']['status']['string'] = array(
        '#type' => 'textfield',
        '#title' => $filter['title'],
        '#description' => $filter['description'],
      );
    }
    else {
      $form['filters']['status'][$key] = array(
        '#title' => $filter['title'],
        '#type' => 'select',
        '#multiple' => FALSE,
        '#size' => 0,
        '#options' => $filter['options'],
      );
    }
1134 1135
    if (!empty($_SESSION['locale_translation_filter'][$key])) {
      $form['filters']['status'][$key]['#default_value'] = $_SESSION['locale_translation_filter'][$key];
1136 1137 1138 1139 1140 1141 1142
    }
  }

  $form['filters']['buttons']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Filter'),
  );
1143
  if (!empty($_SESSION['locale_translation_filter'])) {
1144 1145 1146 1147 1148
    $form['filters']['buttons']['reset'] = array(
      '#type' => 'submit',
      '#value' => t('Reset')
    );
  }
1149 1150

  return $form;
1151
}
1152

1153
/**
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
 * Validate result from locale translation filter form.
 */
function locale_translation_filter_form_validate($form, &$form_state) {
  if ($form_state['values']['op'] == t('Filter') && empty($form_state['values']['language']) && empty($form_state['values']['group'])) {
    form_set_error('type', t('You must select something to filter by.'));
  }
}

/**
 * Process result from locale translation filter form.
1164
 */
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
function locale_translation_filter_form_submit($form, &$form_state) {
  $op = $form_state['values']['op'];
  $filters = locale_translation_filters();
  switch ($op) {
    case t('Filter'):
      foreach ($filters as $name => $filter) {
        if (isset($form_state['values'][$name])) {
          $_SESSION['locale_translation_filter'][$name] = $form_state['values'][$name];
        }
      }
      break;
    case t('Reset'):
      $_SESSION['locale_translation_filter'] = array();
      break;
  }
1180

1181
  $form_state['redirect'] = 'admin/config/regional/translate/translate';
1182
}
1183

1184 1185 1186 1187
/**
 * @defgroup locale-translate-import Translation import screen.
 * @{
 */
1188

1189 1190
/**
 * User interface for the translation import screen.
1191
 */
1192
function locale_translate_import_form($form) {
1193
  // Get all languages, except English
1194 1195
  drupal_static_reset('language_list');
  $names = locale_language_list('name');
1196
  unset($names['en']);
1197

1198
  if (!count($names)) {
1199
    $languages = _locale_prepare_predefined_list();
1200
    $default = key($languages);
1201 1202 1203
  }
  else {
    $languages = array(
1204
      t('Already added languages') => $names,
1205
      t('Languages not yet added') => _locale_prepare_predefined_list()
1206
    );
1207
    $default = key($names);
1208
  }
Steven Wittens's avatar
Steven Wittens committed
1209

1210
  $form['import'] = array('#type' => 'fieldset',
drumm's avatar
drumm committed
1211
    '#title' => t('Import translation'),
1212 1213 1214 1215
  );
  $form['import']['file'] = array('#type' => 'file',
    '#title' => t('Language file'),
    '#size' => 50,
1216
    '#description' => t('A Gettext Portable Object (<em>.po</em>) file.'),
1217 1218 1219
  );
  $form['import']['langcode'] = array('#type' => 'select',
    '#title' => t('Import into'),
1220 1221
    '#options' => $languages,
    '#default_value' => $default,
1222 1223 1224 1225 1226 1227 1228
    '#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.'),
  );
  $form['import']['group'] = array('#type' => 'radios',
    '#title' => t('Text group'),
    '#default_value' => 'default',
    '#options' => module_invoke_all('locale', 'groups'),
    '#description' => t('Imported translations will be added to this text group.'),
1229 1230 1231
  );
  $form['import']['mode'] = array('#type' => 'radios',
    '#title' => t('Mode'),
1232 1233 1234 1235 1236
    '#default_value' => LOCALE_IMPORT_KEEP,
    '#options' => array(
      LOCALE_IMPORT_OVERWRITE => t('Strings in the uploaded file replace existing ones, new ones are added'),
      LOCALE_IMPORT_KEEP => t('Existing strings are kept, only new strings are added')
    ),
1237 1238
  );
  $form['import']['submit'] = array('#type' => 'submit', '#value' => t('Import'));
1239

1240
  return $form;
1241 1242
}

1243 1244 1245
/**
 * Process the locale import form submission.
 */
1246
function locale_translate_import_form_submit($form, &$form_state) {
1247
  // Ensure we have the file uploaded
1248
  if ($file = file_save_upload('file')) {
1249 1250

    // Add language, if not yet supported
1251 1252
    drupal_static_reset('language_list');
    $languages = language_list('language');
1253
    $langcode = $form_state['values']['langcode'];
1254
    if (!isset($languages[$langcode])) {
1255
      include_once DRUPAL_ROOT . '/includes/iso.inc';
1256
      $predefined = _locale_get_predefined_list();
1257 1258
      locale_add_language($langcode);
      drupal_set_message(t('The language %language has been created.', array('%language' => t($predefined[$langcode][0]))));
1259
    }
1260

1261
    // Now import strings into the language
1262
    if ($return = _locale_import_po($file, $langcode, $form_state['values']['mode'], $form_state['values']['group']) == FALSE) {
1263 1264 1265
      $variables = array('%filename' => $file->filename);
      drupal_set_message(t('The translation import of %filename failed.', $variables), 'error');
      watchdog('locale', 'The translation import of %filename failed.', $variables, WATCHDOG_ERROR);
1266 1267 1268 1269
    }
  }
  else {
    drupal_set_message(t('File to import not found.'), 'error');
1270
    $form_state['redirect'] = 'admin/config/regional/translate/import';
1271
    return;
1272 1273
  }

1274
  $form_state['redirect'] = 'admin/config/regional/translate';
1275
  return;
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
}
/**
 * @} End of "locale-translate-import"
 */

/**
 * @defgroup locale-translate-export Translation export screen.
 * @{
 */

/**
 * User interface for the translation export screen.
 */
function locale_translate_export_screen() {
  // Get all languages, except English
1291 1292
  drupal_static_reset('language_list');
  $names = locale_language_list('name');
1293 1294 1295 1296
  unset($names['en']);
  $output = '';
  // Offer translation export if any language is set up.
  if (count($names)) {
1297
    $output = drupal_render(drupal_get_form('locale_translate_export_po_form', $names));
1298
  }
1299
  $output .= drupal_render(drupal_get_form('locale_translate_export_pot_form'));
1300
  return $output;
1301 1302
}

1303 1304 1305 1306 1307 1308
/**
 * Form to export PO files for the languages provided.
 *
 * @param $names
 *   An associate array with localized language names
 */
1309
function locale_translate_export_po_form($form, &$form_state, $names) {
1310 1311 1312 1313 1314 1315
  $form['export'] = array('#type' => 'fieldset',
    '#title' => t('Export translation'),
    '#collapsible' => TRUE,
  );
  $form['export']['langcode'] = array('#type' => 'select',
    '#title' => t('Language name'),
1316
    '#options' => $names,
1317
    '#description' => t('Select the language to export in Gettext Portable Object (<em>.po</em>) format.'),
1318
  );
1319 1320 1321 1322 1323
  $form['export']['group'] = array('#type' => 'radios',
    '#title' => t('Text group'),
    '#default_value' => 'default',
    '#options' => module_invoke_all('locale', 'groups'),
  );
1324 1325 1326 1327
  $form['export']['submit'] = array('#type' => 'submit', '#value' => t('Export'));
  return $form;
}

1328 1329 1330 1331
/**
 * Translation template export form.
 */
function locale_translate_export_pot_form() {
1332 1333 1334 1335
  // Complete template export of the strings
  $form['export'] = array('#type' => 'fieldset',
    '#title' => t('Export template'),
    '#collapsible' => TRUE,
1336
    '#description' => t('Generate a Gettext Portable Object Template (<em>.pot</em>) file with all strings from the Drupal locale database.'),
1337 1338 1339 1340 1341
  );
  $form['export']['group'] = array('#type' => 'radios',
    '#title' => t('Text group'),
    '#default_value' => 'default',
    '#options' => module_invoke_all('locale', 'groups'),
1342 1343
  );
  $form['export']['submit'] = array('#type' => 'submit', '#value' => t('Export'));
1344
  // Reuse PO export submission callback.
1345 1346
  $form['#submit'][] = 'locale_translate_export_po_form_submit';
  $form['#validate'][] = 'locale_translate_export_po_form_validate';
1347 1348 1349
  return $form;
}

1350
/**
1351
 * Process a translation (or template) export form submission.
1352
 */
1353
function locale_translate_export_po_form_submit($form, &$form_state) {
1354
  // If template is required, language code is not given.
1355 1356 1357 1358 1359 1360
  $language = NULL;
  if (isset($form_state['values']['langcode'])) {
    $languages = language_list();
    $language = $languages[$form_state['values']['langcode']];
  }
  _locale_export_po($language, _locale_export_po_generate($language, _locale_export_get_strings($language, $form_state['values']['group'])));
1361 1362
}
/**
1363
 * @} End of "locale-translate-export"
1364
 */
1365

1366
/**
1367 1368
 * @defgroup locale-translate-edit Translation text editing
 * @{
1369 1370 1371 1372 1373
 */

/**
 * User interface for string editing.
 */
1374
function locale_translate_edit_form($form, &$form_state, $lid) {
1375
  // Fetch source string, if possible.
1376
  $source = db_query('SELECT source, context, textgroup, location FROM {locales_source} WHERE lid = :lid', array(':lid' => $lid))->fetchObject();
1377
  if (!$source) {
1378
    drupal_set_message(t('String not found.'), 'error');
1379
    drupal_goto('admin/config/regional/translate/translate');
1380 1381
  }

1382
  // Add original text to the top and some values for form altering.
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
  $form['original'] = array(
    '#type'  => 'item',
    '#title' => t('Original text'),
    '#markup' => check_plain(wordwrap($source->source, 0)),
  );
  if (!empty($source->context)) {
    $form['context'] = array(
      '#type' => 'item',
      '#title' => t('Context'),
      '#markup' => check_plain($source->context),
    );
  }
  $form['lid'] = array(
    '#type'  => 'value',
    '#value' => $lid
  );
  $form['textgroup'] = array(
    '#type'  => 'value',
    '#value' => $source->textgroup,
  );
  $form['location'] = array(
    '#type'  => 'value',
    '#value' => $source->location
1406 1407
  );

1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
  // Include default form controls with empty values for all languages.
  // This ensures that the languages are always in the same order in forms.
  $languages = language_list();
  $default = language_default();
  // We don't need the default language value, that value is in $source.
  $omit = $source->textgroup == 'default' ? 'en' : $default->language;
  unset($languages[($omit)]);
  $form['translations'] = array('#tree' => TRUE);
  // Approximate the number of rows to use in the default textarea.
  $rows = min(ceil(str_word_count($source->source) / 12), 10);
1418 1419
  foreach ($languages as $langcode => $language) {
    $form['translations'][$langcode] = array(
1420
      '#type' => 'textarea',
1421
      '#title' => t($language->name),
1422
      '#rows' => $rows,
1423
      '#default_value' => '',
1424 1425
    );
  }
1426

1427
  // Fetch translations and fill in default values in the form.
1428 1429
  $result = db_query("SELECT DISTINCT translation, language FROM {locales_target} WHERE lid = :lid AND language <> :omit", array(':lid' => $lid, ':omit' => $omit));
  foreach ($result as $translation) {
1430 1431
    $form['translations'][$translation->language]['#default_value'] = $translation->translation;
  }
1432 1433

  $form['submit'] = array('#type' => 'submit', '#value' => t('Save translations'));
1434
  return $form;
1435 1436
}

1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
/**
 * Check that a string is safe to be added or imported as a translation.
 *
 * This test can be used to detect possibly bad translation strings. It should
 * not have any false positives. But it is only a test, not a transformation,
 * as it destroys valid HTML. We cannot reliably filter translation strings
 * on inport becuase some strings are irreversibly corrupted. For example,
 * a &amp; in the translation would get encoded to &amp;amp; by filter_xss()
 * before being put in the database, and thus would be displayed incorrectly.
 *
 * The allowed tag list is like filter_xss_admin(), but omitting div and img as
 * not needed for translation and likely to cause layout issues (div) or a
 * possible attack vector (img).
 */
function locale_string_is_safe($string) {
  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')));
}

/**
 * Validate string editing form submissions.
 */
function locale_translate_edit_form_validate($form, &$form_state) {
1459 1460
  // Locale string check is needed for default textgroup only.
  $safe_check_needed = $form_state['values']['textgroup'] == 'default';
1461
  foreach ($form_state['values']['translations'] as $key => $value) {
1462
    if ($safe_check_needed && !locale_string_is_safe($value)) {
1463 1464 1465 1466 1467 1468
      form_set_error('translations', t('The submitted string contains disallowed HTML: %string', array('%string' => $value)));
      watchdog('locale', 'Attempted submission of a translation string with disallowed HTML: %string', array('%string' => $value), WATCHDOG_WARNING);
    }
  }
}

1469 1470
/**
 * Process string editing form submissions.
1471
 *
1472 1473
 * Saves all translations of one string submitted from a form.
 */
1474 1475 1476
function locale_translate_edit_form_submit($form, &$form_state) {
  $lid = $form_state['values']['lid'];
  foreach ($form_state['values']['translations'] as $key => $value) {
1477
    $translation = db_query("SELECT translation FROM {locales_target} WHERE lid = :lid AND language = :language", array(':lid' => $lid, ':language' => $key))->fetchField();
1478 1479 1480
    if (!empty($value)) {
      // Only update or insert if we have a value to use.
      if (!empty($translation)) {
1481 1482 1483 1484 1485 1486 1487
        db_update('locales_target')
          ->fields(array(
            'translation' => $value,
          ))
          ->condition('lid', $lid)
          ->condition('language', $key)
          ->execute();
1488 1489
      }
      else {
1490 1491 1492 1493 1494 1495 1496
        db_insert('locales_target')
          ->fields(array(
            'lid' => $lid,
            'translation' => $value,
            'language' => $key,
          ))
          ->execute();
1497
      }
1498
    }
1499 1500
    elseif (!empty($translation)) {
      // Empty translation entered: remove existing entry from database.
1501 1502 1503 1504
      db_delete('locales_target')
        ->condition('lid', $lid)
        ->condition('language', $key)
        ->execute();