locale.pages.inc 17.5 KB
Newer Older
1 2 3
<?php

/**
4 5
 * @file
 * Interface translation summary, editing and deletion user interfaces.
6 7
 */

8 9
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/**
 * String search screen.
 */
function locale_translate_seek_screen() {
  // Add CSS.
  drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');

  $elements = drupal_get_form('locale_translation_filter_form');
  $output = drupal_render($elements);
  $output .= _locale_translate_seek();
  return $output;
}

/**
 * Perform a string search and display results in a table
 */
function _locale_translate_seek() {
  $output = '';

  // We have at least one criterion to match
  if (!($query = _locale_translate_seek_query())) {
    $query = array(
      'translation' => 'all',
      'language' => 'all',
34
      'customized' => 'all',
35 36 37 38 39 40
      'string' => '',
    );
  }

  $sql_query = db_select('locales_source', 's');
  $sql_query->leftJoin('locales_target', 't', 't.lid = s.lid');
41
  $sql_query->fields('s', array('source', 'location', 'context', 'lid'));
42
  $sql_query->fields('t', array('translation', 'language', 'customized'));
43 44 45 46 47 48

  // Compute LIKE section.
  switch ($query['translation']) {
    case 'translated':
      $sql_query->condition('t.translation', '%' . db_like($query['string']) . '%', 'LIKE');
      $sql_query->orderBy('t.translation', 'DESC');
49 50 51
      if ($query['customized'] != 'all') {
        $sql_query->condition('t.customized', $query['customized']);
      }
52 53 54 55 56 57 58 59 60 61 62 63
      break;
    case 'untranslated':
      $sql_query->condition(db_and()
        ->condition('s.source', '%' . db_like($query['string']) . '%', 'LIKE')
        ->isNull('t.translation')
      );
      $sql_query->orderBy('s.source');
      break;
    case 'all' :
    default:
      $condition = db_or()
        ->condition('s.source', '%' . db_like($query['string']) . '%', 'LIKE');
64 65
      if ($query['language'] != LANGUAGE_SYSTEM) {
        // Only search in translations if the language is not forced to system language.
66 67 68 69 70 71 72
        $condition->condition('t.translation', '%' . db_like($query['string']) . '%', 'LIKE');
      }
      $sql_query->condition($condition);
      break;
  }

  $limit_language = NULL;
73
  if ($query['language'] != LANGUAGE_SYSTEM && $query['language'] != 'all') {
74 75 76 77
    $sql_query->condition('language', $query['language']);
    $limit_language = $query['language'];
  }

78 79 80
  $sql_query = $sql_query
    ->extend('Drupal\Core\Database\Query\PagerSelectExtender')
    ->limit(50);
81 82
  $locales = $sql_query->execute();

83
  $header = array(t('String'), t('Context'), ($limit_language) ? t('Language') : t('Languages'), array('data' => t('Operations'), 'colspan' => '2'));
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102

  $strings = array();
  foreach ($locales as $locale) {
    if (!isset($strings[$locale->lid])) {
      $strings[$locale->lid] = array(
        'languages' => array(),
        'location' => $locale->location,
        'source' => $locale->source,
        'context' => $locale->context,
      );
    }
    if (isset($locale->language)) {
      $strings[$locale->lid]['languages'][$locale->language] = $locale->translation;
    }
  }

  $rows = array();
  foreach ($strings as $lid => $string) {
    $rows[] = array(
103
      array('data' => check_plain(truncate_utf8(str_replace(LOCALE_PLURAL_DELIMITER, ', ', $string['source']), 150, FALSE, TRUE)) . '<br /><small>' . $string['location'] . '</small>'),
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
      $string['context'],
      array('data' => _locale_translate_language_list($string['languages'], $limit_language), 'align' => 'center'),
      array('data' => l(t('edit'), "admin/config/regional/translate/edit/$lid", array('query' => drupal_get_destination())), 'class' => array('nowrap')),
      array('data' => l(t('delete'), "admin/config/regional/translate/delete/$lid", array('query' => drupal_get_destination())), 'class' => array('nowrap')),
    );
  }

  $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('No strings available.')));
  $output .= theme('pager');

  return $output;
}

/**
 * List languages in search result table
 */
function _locale_translate_language_list($translation, $limit_language) {
  // Add CSS.
  drupal_add_css(drupal_get_path('module', 'locale') . '/locale.css');

  $languages = language_list();
125 126 127
  if (!locale_translate_english()) {
    unset($languages['en']);
  }
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
  $output = '';
  foreach ($languages as $langcode => $language) {
    if (!$limit_language || $limit_language == $langcode) {
      $output .= (!empty($translation[$langcode])) ? $langcode . ' ' : "<em class=\"locale-untranslated\">$langcode</em> ";
    }
  }

  return $output;
}

/**
 * Build array out of search criteria specified in request variables
 */
function _locale_translate_seek_query() {
  $query = &drupal_static(__FUNCTION__);
  if (!isset($query)) {
    $query = array();
145
    $fields = array('string', 'language', 'translation', 'customized');
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    foreach ($fields as $field) {
      if (isset($_SESSION['locale_translation_filter'][$field])) {
        $query[$field] = $_SESSION['locale_translation_filter'][$field];
      }
    }
  }
  return $query;
}

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

  // Get all languages, except English
  drupal_static_reset('language_list');
163
  $languages = language_list();
164 165 166 167 168
  $language_options = array();
  foreach ($languages as $langcode => $language) {
    if ($langcode != 'en' || locale_translate_english()) {
      $language_options[$langcode] = $language->name;
    }
169
  }
170 171 172 173 174 175 176 177

  $filters['string'] = array(
    'title' => t('String contains'),
    'description' => t('Leave blank to show all strings. The search is case sensitive.'),
  );

  $filters['language'] = array(
    'title' => t('Language'),
178
    'options' => array_merge(array('all' => t('All languages'), LANGUAGE_SYSTEM => t('System (English)')), $language_options),
179 180 181 182
  );

  $filters['translation'] = array(
    'title' => t('Search in'),
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    'options' => array(
      'all' => t('Both translated and untranslated strings'),
      'translated' => t('Only translated strings'),
      'untranslated' => t('Untranslated strings')
    ),
  );

  $filters['customized'] = array(
    'title' => t('Translation type'),
    'options' => array(
      'all' => t('All'),
      LOCALE_NOT_CUSTOMIZED => t('Non-customized translation'),
      LOCALE_CUSTOMIZED => t('Customized translation'),
    ),
    'states' => array(
      'visible' => array(
        ':input[name=translation]' => array('value' => 'translated'),
      )
    ),
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
  );

  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'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );
  foreach ($filters as $key => $filter) {
    // Special case for 'string' filter.
    if ($key == 'string') {
      $form['filters']['status']['string'] = array(
225
        '#type' => 'search',
226 227 228 229 230 231 232 233 234 235 236 237 238
        '#title' => $filter['title'],
        '#description' => $filter['description'],
      );
    }
    else {
      $form['filters']['status'][$key] = array(
        '#title' => $filter['title'],
        '#type' => 'select',
        '#empty_value' => 'all',
        '#empty_option' => $filter['options']['all'],
        '#size' => 0,
        '#options' => $filter['options'],
      );
239 240 241
      if (isset($filter['states'])) {
        $form['filters']['status'][$key]['#states'] = $filter['states'];
      }
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
    }
    if (!empty($_SESSION['locale_translation_filter'][$key])) {
      $form['filters']['status'][$key]['#default_value'] = $_SESSION['locale_translation_filter'][$key];
    }
  }

  $form['filters']['actions'] = array(
    '#type' => 'actions',
    '#attributes' => array('class' => array('container-inline')),
  );
  $form['filters']['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Filter'),
  );
  if (!empty($_SESSION['locale_translation_filter'])) {
    $form['filters']['actions']['reset'] = array(
      '#type' => 'submit',
      '#value' => t('Reset')
    );
  }

  return $form;
}

/**
 * Validate result from locale translation filter form.
 */
function locale_translation_filter_form_validate($form, &$form_state) {
270
  if ($form_state['values']['op'] == t('Filter') && empty($form_state['values']['language'])) {
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
    form_set_error('type', t('You must select something to filter by.'));
  }
}

/**
 * Process result from locale translation filter form.
 */
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;
  }

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


/**
 * User interface for string editing.
300 301
 *
 * @ingroup forms
302 303 304
 */
function locale_translate_edit_form($form, &$form_state, $lid) {
  // Fetch source string, if possible.
305
  $source = db_query('SELECT source, context, location FROM {locales_source} WHERE lid = :lid', array(':lid' => $lid))->fetchObject();
306 307 308 309
  if (!$source) {
    drupal_set_message(t('String not found.'), 'error');
    drupal_goto('admin/config/regional/translate/translate');
  }
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
  // Split source to work with plural values.
  $source_array = explode(LOCALE_PLURAL_DELIMITER, $source->source);
  if (count($source_array) == 1) {
    // Add original text value and mark as non-plural.
    $form['plural'] = array(
      '#type' => 'value',
      '#value' => 0
    );
    $form['original'] = array(
      '#type'  => 'item',
      '#title' => t('Original text'),
      '#markup' => check_plain($source_array[0]),
    );
  }
  else {
    // Add original text value and mark as plural.
    $form['plural'] = array(
      '#type' => 'value',
      '#value' => 1
    );
    $form['original_singular'] = array(
      '#type'  => 'item',
      '#title' => t('Original singular form'),
      '#markup' => check_plain($source_array[0]),
    );
    $form['original_plural'] = array(
      '#type'  => 'item',
      '#title' => t('Original plural form'),
      '#markup' => check_plain($source_array[1]),
    );
  }
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
  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['location'] = array(
    '#type'  => 'value',
    '#value' => $source->location
  );

  // 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();
360 361 362
  if (!locale_translate_english()) {
    unset($languages['en']);
  }
363 364 365 366 367 368 369 370 371
  // Store languages to iterate for validation and submission of the form.
  $form_state['langcodes'] = array_keys($languages);
  $plural_formulas = variable_get('locale_translation_plurals', array());

  $form['translations'] = array(
    '#type' => 'vertical_tabs',
    '#tree' => TRUE
  );

372
  // Approximate the number of rows to use in the default textarea.
373
  $rows = min(ceil(str_word_count($source_array[0]) / 12), 10);
374 375
  foreach ($languages as $langcode => $language) {
    $form['translations'][$langcode] = array(
376
      '#type' => 'fieldset',
377
      '#title' => $language->name,
378
    );
379 380 381 382 383 384 385 386 387 388
    if (empty($form['plural']['#value'])) {
      $form['translations'][$langcode][0] = array(
        '#type' => 'textarea',
        '#title' => $language->name,
        '#rows' => $rows,
        '#default_value' => '',
      );
    }
    else {
      // Dealing with plural strings.
389
      if (isset($plural_formulas[$langcode]['plurals']) && $plural_formulas[$langcode]['plurals'] > 2) {
390 391 392 393 394 395 396 397 398 399 400 401 402 403
        // Add a textarea for each plural variant.
        for ($i = 0; $i < $plural_formulas[$langcode]['plurals']; $i++) {
          $form['translations'][$langcode][$i] = array(
            '#type' => 'textarea',
            '#title' => ($i == 0 ? t('Singular form') : format_plural($i, 'First plural form', '@count. plural form')),
            '#rows' => $rows,
            '#default_value' => '',
          );
        }
      }
      else {
        // Fallback for unknown number of plurals.
        $form['translations'][$langcode][0] = array(
          '#type' => 'textarea',
404
          '#title' => t('Singular form'),
405 406 407 408 409 410 411 412 413 414 415
          '#rows' => $rows,
          '#default_value' => '',
        );
        $form['translations'][$langcode][1] = array(
          '#type' => 'textarea',
          '#title' => t('Plural form'),
          '#rows' => $rows,
          '#default_value' => '',
        );
      }
    }
416 417 418
  }

  // Fetch translations and fill in default values in the form.
419
  $result = db_query("SELECT DISTINCT translation, language FROM {locales_target} WHERE lid = :lid", array(':lid' => $lid));
420
  foreach ($result as $translation) {
421 422 423 424
    $translation_array = explode(LOCALE_PLURAL_DELIMITER, $translation->translation);
    for ($i = 0; $i < count($translation_array); $i++) {
      $form['translations'][$translation->language][$i]['#default_value'] = $translation_array[$i];
    }
425 426 427 428 429 430 431 432 433 434 435
  }

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

/**
 * Validate string editing form submissions.
 */
function locale_translate_edit_form_validate($form, &$form_state) {
436 437 438 439 440 441
  foreach ($form_state['langcodes'] as $langcode) {
    foreach ($form_state['values']['translations'][$langcode] as $key => $value) {
      if (!locale_string_is_safe($value)) {
        form_set_error("translations][$langcode][$key", 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);
      }
442 443 444 445 446 447 448 449 450 451 452
    }
  }
}

/**
 * Process string editing form submissions.
 *
 * Saves all translations of one string submitted from a form.
 */
function locale_translate_edit_form_submit($form, &$form_state) {
  $lid = $form_state['values']['lid'];
453 454 455 456 457 458 459 460 461 462 463 464 465
  foreach ($form_state['langcodes'] as $langcode) {
    // Serialize plural variants in one string by LOCALE_PLURAL_DELIMITER.
    $value = implode(LOCALE_PLURAL_DELIMITER, $form_state['values']['translations'][$langcode]);
    $translation = db_query("SELECT translation FROM {locales_target} WHERE lid = :lid AND language = :language", array(':lid' => $lid, ':language' => $langcode))->fetchField();
    // No translation when all strings are empty.
    $has_translation = FALSE;
    foreach ($form_state['values']['translations'][$langcode] as $string) {
      if (!empty($string)) {
        $has_translation = TRUE;
        break;
      }
    }
    if ($has_translation) {
466
      // Only update or insert if we have a value to use.
467
      if (!empty($translation) && $translation != $value) {
468 469 470
        db_update('locales_target')
          ->fields(array(
            'translation' => $value,
471
            'customized' => LOCALE_CUSTOMIZED,
472 473
          ))
          ->condition('lid', $lid)
474
          ->condition('language', $langcode)
475 476
          ->execute();
      }
477
      if (empty($translation)) {
478 479 480 481
        db_insert('locales_target')
          ->fields(array(
            'lid' => $lid,
            'translation' => $value,
482
            'language' => $langcode,
483
            'customized' => LOCALE_CUSTOMIZED,
484 485 486 487 488 489 490 491
          ))
          ->execute();
      }
    }
    elseif (!empty($translation)) {
      // Empty translation entered: remove existing entry from database.
      db_delete('locales_target')
        ->condition('lid', $lid)
492
        ->condition('language', $langcode)
493 494 495 496
        ->execute();
    }

    // Force JavaScript translation file recreation for this language.
497
    _locale_invalidate_js($langcode);
498 499 500 501 502 503
  }

  drupal_set_message(t('The string has been saved.'));

  // Clear locale cache.
  _locale_invalidate_js();
504
  cache()->deletePrefix('locale:');
505 506 507 508 509 510 511 512 513 514 515 516 517

  $form_state['redirect'] = 'admin/config/regional/translate/translate';
  return;
}

/**
 * String deletion confirmation page.
 */
function locale_translate_delete_page($lid) {
  if ($source = db_query('SELECT lid, source FROM {locales_source} WHERE lid = :lid', array(':lid' => $lid))->fetchObject()) {
    return drupal_get_form('locale_translate_delete_form', $source);
  }
  else {
518
    throw new NotFoundHttpException();
519 520 521 522 523
  }
}

/**
 * User interface for the string deletion confirmation screen.
524 525
 *
 * @ingroup forms
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
 */
function locale_translate_delete_form($form, &$form_state, $source) {
  $form['lid'] = array('#type' => 'value', '#value' => $source->lid);
  return confirm_form($form, t('Are you sure you want to delete the string "%source"?', array('%source' => $source->source)), 'admin/config/regional/translate/translate', t('Deleting the string will remove all translations of this string in all languages. This action cannot be undone.'), t('Delete'), t('Cancel'));
}

/**
 * Process string deletion submissions.
 */
function locale_translate_delete_form_submit($form, &$form_state) {
  db_delete('locales_source')
    ->condition('lid', $form_state['values']['lid'])
    ->execute();
  db_delete('locales_target')
    ->condition('lid', $form_state['values']['lid'])
    ->execute();
  // Force JavaScript translation file recreation for all languages.
  _locale_invalidate_js();
544
  cache()->deletePrefix('locale:');
545 546 547
  drupal_set_message(t('The string has been removed.'));
  $form_state['redirect'] = 'admin/config/regional/translate/translate';
}