locale.inc 49.6 KB
Newer Older
Dries's avatar
 
Dries committed
1 2
<?php
// $Id$
Dries's avatar
 
Dries committed
3

Dries's avatar
 
Dries committed
4 5
/**
 * @file
Dries's avatar
 
Dries committed
6
 * Admin-related functions for locale.module.
Dries's avatar
 
Dries committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20
 */

// ---------------------------------------------------------------------------------
// Language addition functionality (administration only)

/**
 * Helper function to add a language
 */
function _locale_add_language($code, $name, $onlylanguage = TRUE) {
  db_query("INSERT INTO {locales_meta} (locale, name) VALUES ('%s','%s')", $code, $name);
  $result = db_query("SELECT lid FROM {locales_source}");
  while ($string = db_fetch_object($result)) {
    db_query("INSERT INTO {locales_target} (lid, locale) VALUES (%d,'%s')", $string->lid, $code);
  }
Dries's avatar
 
Dries committed
21

Dries's avatar
 
Dries committed
22 23 24 25
  // If only the language was added, and not a PO file import triggered
  // the language addition, we need to inform the user on how to start
  // a translation
  if ($onlylanguage) {
26
    drupal_set_message(t('The language %locale has been created, and can now be used to import a translation. More information is available in the <a href="%locale-help">help screen</a>.', array('%locale' => theme('placeholder', t($name)), '%locale-help' => url('admin/help/locale'))));
Dries's avatar
 
Dries committed
27 28
  }
  else {
29
    drupal_set_message(t('The language %locale has been created.', array('%locale' => theme('placeholder', t($name)))));
Dries's avatar
 
Dries committed
30
  }
Dries's avatar
 
Dries committed
31

32
  watchdog('locale', t('The %language language (%locale) has been created.', array('%language' => theme('placeholder', $name), '%locale' => theme('placeholder', $code))));
Dries's avatar
 
Dries committed
33 34 35 36 37 38 39 40
}

/**
 * User interface for the language management screen
 */
function _locale_admin_manage_screen() {
  $languages = locale_supported_languages(TRUE, TRUE);

41
  $options = array();
42 43
  $form['#action'] = url('admin/locale');
  $form['name'] = array('#tree' => TRUE);
Dries's avatar
 
Dries committed
44
  foreach ($languages['name'] as $key => $lang) {
45
    $options[$key] = '';
Dries's avatar
 
Dries committed
46
    $status = db_fetch_object(db_query("SELECT isdefault, enabled FROM {locales_meta} WHERE locale = '%s'", $key));
47 48 49 50 51 52
    if ($status->enabled) {
      $enabled[] = $key;
    }
    if ($status->isdefault) {
      $isdefault = $key;
    }
Dries's avatar
 
Dries committed
53
    if ($key == 'en') {
54
      $form['name']['en'] = array('#type' => 'markup', '#value' => check_plain($lang));
Dries's avatar
 
Dries committed
55 56 57 58
    }
    else {
      $original = db_fetch_object(db_query("SELECT COUNT(*) AS strings FROM {locales_source}"));
      $translation = db_fetch_object(db_query("SELECT COUNT(*) AS translation FROM {locales_target} WHERE locale = '%s' AND translation != ''", $key));
Dries's avatar
 
Dries committed
59

Dries's avatar
 
Dries committed
60
      $ratio = ($original->strings > 0 && $translation->translation > 0) ? round(($translation->translation/$original->strings)*100., 2) : 0;
Dries's avatar
 
Dries committed
61

62
      $form['name'][$key] = array('#type' => 'textfield', '#default_value' => $lang, '#size' => 15, '#maxlength' => 64);
63
      $form['translation'][$key] = array('#type' => 'markup', '#value' => "$translation->translation/$original->strings ($ratio%)");
Dries's avatar
 
Dries committed
64 65
    }
  }
66 67 68
  $form['enabled'] = array('#type' => 'checkboxes', '#options' => $options, '#default_value' => $enabled, '#return_value' => 1);
  $form['sitedefault'] = array('#type' => 'radios', '#options' => $options, '#default_value' => $isdefault, '#return_value' => 1);
  $form['submit'] = array('#type' => 'submit', '#value' => t('Save configuration'));
69

70 71
  return drupal_get_form('_locale_admin_manage_screen', $form);
}
Dries's avatar
 
Dries committed
72

73 74 75 76
function theme__locale_admin_manage_screen($form) {
  foreach ($form['name'] as $key => $element) {
    // Don't take form control structures
    if (is_array($element) && element_child($key)) {
77
      $rows[] = array(check_plain($key), form_render($form['name'][$key]), form_render($form['enabled'][$key]), form_render($form['sitedefault'][$key]), ($key != 'en' ? form_render($form['translation'][$key]) : message_na()), ($key != 'en' ? l(t('delete'), 'admin/locale/language/delete/'. drupal_urlencode($key)) : ''));
78 79 80 81 82 83
    }
  }
  $header = array(array('data' => t('Code')), array('data' => t('English name')), array('data' => t('Enabled')), array('data' => t('Default')), array('data' => t('Translated')), array('data' => t('Operations')));
  $output = theme('table', $header, $rows);
  $output .= form_render($form);
  return $output;
Dries's avatar
 
Dries committed
84 85 86 87 88 89
}

/**
 * User interface for the language addition screen
 */
function _locale_admin_manage_add_screen() {
Dries's avatar
 
Dries committed
90

Dries's avatar
 
Dries committed
91
  $isocodes = _locale_prepare_iso_list();
Dries's avatar
 
Dries committed
92

93
  $form = array();
94 95 96
  $form['header'] = array('#prefix' => '<h2>', '#value' => t('Language list'), '#suffix' => '</h2>');
  $form['langcode'] = array('#type' => 'select', '#title' => t('Language name'), '#default_value' => key($isocodes), '#options' => $isocodes, '#description' => t('Select your language here, or add it below, if you are unable to find it.'));
  $form['submit'] = array('#type' => 'submit', '#value' => t('Add language'));
97
  $output = drupal_get_form('locale_add_language', $form);
Dries's avatar
 
Dries committed
98

Dries's avatar
 
Dries committed
99
  $edit = &$_POST['edit'];
100
  $form = array();
101 102
  $form['header'] = array('#prefix' => '<h2>', '#value' => t('Custom language') , '#suffix' => '</h2>');
  $form['langcode'] = array('#type' => 'textfield', '#title' => t('Language code'), '#default_value' => $edit['langcode'], '#size' => 12, '#maxlength' => 60, '#description' => t("Commonly this is an <a href=\"%iso-codes\">ISO 639 language code</a> with an optional country code for regional variants. Examples include 'en', 'en-US' and 'zh-cn'.", array('%iso-codes' => 'http://www.w3.org/WAI/ER/IG/ert/iso639.htm')));
103
  $form['langname'] = array('#type' => 'textfield', '#title' => t('Language name in English'), '#default_value' => $edit['langname'], '#maxlength' => 64, '#description' => t('Name of the language. Will be available for translation in all languages.'));
104
  $form['submit'] = array('#type' => 'submit', '#value' => t('Add custom language'));
105 106

  $output .= drupal_get_form('_locale_custom_language', $form);
Dries's avatar
 
Dries committed
107 108 109 110 111 112 113 114 115

  return $output;
}

/**
 * User interface for the translation import screen
 */
function _locale_admin_import_screen() {
  $languages = locale_supported_languages(FALSE, TRUE);
116
  $languages = array_map('t', $languages['name']);
Dries's avatar
 
Dries committed
117
  unset($languages['en']);
Dries's avatar
 
Dries committed
118

Dries's avatar
 
Dries committed
119
  if (!count($languages)) {
Steven Wittens's avatar
Locale:  
Steven Wittens committed
120
    $languages = _locale_prepare_iso_list();
Dries's avatar
 
Dries committed
121 122 123 124 125 126 127
  }
  else {
    $languages = array(
      t('Already added languages') => $languages,
      t('Languages not yet added') => _locale_prepare_iso_list()
    );
  }
Steven Wittens's avatar
Locale:  
Steven Wittens committed
128

129
  $form = array();
130 131 132 133 134 135
  $form['file'] = array('#type' => 'file', '#title' => t('Language file'), '#size' => 50, '#description' => t('A gettext Portable Object (.po) file.'));
  $form['langcode'] = array('#type' => 'select', '#title' => t('Import into'), '#options' => $languages, '#description' => t('Choose the language you want to add strings into. If you choose a language which is not yet set up, then it will be added.'));
  $form['mode'] = array('#type' => 'radios', '#title' => t('Mode'), '#default_value' => 'overwrite', '#options' => array('overwrite' => t('Strings in the uploaded file replace existing ones, new ones are added'), 'keep' => t('Existing strings are kept, only new strings are added')));
  $form['submit'] = array('#type' => 'submit', '#value' => t('Import'));
  $form['#attributes']['enctype'] = 'multipart/form-data';
  $form['#action'] = 'admin/locale/language/import';
136 137

  return drupal_get_form('_locale_admin_import', $form);
Dries's avatar
 
Dries committed
138 139 140 141 142
}

/**
 * Parses Gettext Portable Object file information and inserts into database
 *
143
 * @param $file Object contains properties of local file to be imported
Dries's avatar
 
Dries committed
144
 * @param $edit Language code
Dries's avatar
 
Dries committed
145
 * @param $mode should existing translations be replaced?
Dries's avatar
 
Dries committed
146 147
 */
function _locale_import_po($file, $lang, $mode) {
Steven Wittens's avatar
Locale:  
Steven Wittens committed
148 149 150
  // If not in 'safe mode', increase the maximum execution time:
  if (!ini_get('safe_mode')) {
    set_time_limit(240);
Dries's avatar
 
Dries committed
151
  }
Steven Wittens's avatar
Locale:  
Steven Wittens committed
152

Dries's avatar
 
Dries committed
153 154
  // Check if we have the language already in the database
  if (!db_fetch_object(db_query("SELECT locale FROM {locales_meta} WHERE locale = '%s'", $lang))) {
155
    drupal_set_message(t('The language selected for import is not supported.'), 'error');
Dries's avatar
 
Dries committed
156 157
    return FALSE;
  }
Dries's avatar
 
Dries committed
158

Dries's avatar
 
Dries committed
159 160
  // Check if we can get the strings from the file
  if (!($strings = _locale_import_read_po($file))) {
161
    drupal_set_message(t('The translation file %filename appears to contain errors and could not be read.', array('%filename' => theme('placeholder', $file->filename))), 'error');
Dries's avatar
 
Dries committed
162 163
    return FALSE;
  }
Dries's avatar
 
Dries committed
164

Dries's avatar
 
Dries committed
165 166 167
  // Strip out header from the string pairs
  $header = $strings[""]["msgstr"];
  unset($strings[""]);
Dries's avatar
 
Dries committed
168

Dries's avatar
 
Dries committed
169 170 171
  // Get information from the header into the database
  if ($header) {
    $hdr = _locale_import_parse_header($header);
Dries's avatar
 
Dries committed
172

Dries's avatar
 
Dries committed
173
    // Get the plural formula
174
    if ($hdr["Plural-Forms"] && $p = _locale_import_parse_plural_forms($hdr["Plural-Forms"], $file->filename)) {
Dries's avatar
 
Dries committed
175
      list($nplurals, $plural) = $p;
Dries's avatar
Dries committed
176
      db_query("UPDATE {locales_meta} SET plurals = %d, formula = '%s' WHERE locale = '%s'", $nplurals, $plural, $lang);
Dries's avatar
 
Dries committed
177 178
    }
    else {
Dries's avatar
Dries committed
179
      db_query("UPDATE {locales_meta} SET plurals = %d, formula = '%s' WHERE locale = '%s'", 0, '', $lang);
Dries's avatar
 
Dries committed
180 181 182
    }
  }
  else {
183
    drupal_set_message(t('The translation file %filename appears to have a missing or malformed header.', array('%filename' => theme('placeholder', $file->filename))), 'error');
Dries's avatar
 
Dries committed
184 185 186
    return FALSE;
  }

Dries's avatar
 
Dries committed
187 188
  $additions = 0;
  $updates = 0;
Dries's avatar
 
Dries committed
189 190
  foreach ($strings as $value) {
    $comments = _locale_import_shorten_comments($value['#']);
Dries's avatar
 
Dries committed
191

Dries's avatar
 
Dries committed
192 193 194 195 196 197 198
    // Handle a translation for some plural string
    if (strpos($value['msgid'], "\0")) {
      $english = explode("\0", $value['msgid'], 2);
      $entries = array_keys($value['msgstr']);
      for ($i = 3; $i <= count($entries); $i++) {
        $english[] = $english[1];
      }
Dries's avatar
 
Dries committed
199 200
      $translation = array_map('_locale_import_append_plural', $value['msgstr'], $entries);
      $english = array_map('_locale_import_append_plural', $english, $entries);
Dries's avatar
 
Dries committed
201
      foreach ($translation as $key => $trans) {
Dries's avatar
 
Dries committed
202 203 204 205 206
        if ($key == 0) {
          $plid = 0;
        }
        $loc = db_fetch_object(db_query("SELECT lid FROM {locales_source} WHERE source = '%s'", $english[$key]));
        if ($loc->lid) { // a string exists
Dries's avatar
 
Dries committed
207
          $lid = $loc->lid;
Dries's avatar
 
Dries committed
208
          // update location field
Dries's avatar
 
Dries committed
209
          db_query("UPDATE {locales_source} SET location = '%s' WHERE lid = %d", $comments, $lid);
Dries's avatar
 
Dries committed
210 211 212 213 214
          $trans2 = db_fetch_object(db_query("SELECT lid, translation, plid, plural FROM {locales_target} WHERE lid = %d AND locale = '%s'", $lid, $lang));
          if (!$trans2->lid) { // no translation in current language
            db_query("INSERT INTO {locales_target} (lid, locale, translation, plid, plural) VALUES (%d, '%s', '%s', %d, %d)", $lid, $lang, $trans, $plid, $key);
            $additions++;
          } // translation exists
Steven Wittens's avatar
Steven Wittens committed
215 216
          else if ($mode == 'overwrite' || $trans2->translation == '') {
            db_query("UPDATE {locales_target} SET translation = '%s', plid = %d, plural = %d WHERE locale = '%s' AND lid = %d", $trans, $plid, $key, $lang, $lid);
Dries's avatar
 
Dries committed
217 218 219 220 221 222
            if ($trans2->translation == '') {
              $additions++;
            }
            else {
              $updates++;
            }
Dries's avatar
 
Dries committed
223
          }
Dries's avatar
 
Dries committed
224
        }
Dries's avatar
 
Dries committed
225
        else { // no string
Steven Wittens's avatar
Steven Wittens committed
226 227
          db_query("INSERT INTO {locales_source} (location, source) VALUES ('%s', '%s')", $comments, $english[$key]);
          $loc = db_fetch_object(db_query("SELECT lid FROM {locales_source} WHERE source = '%s'", $english[$key]));
Dries's avatar
 
Dries committed
228
          $lid = $loc->lid;
229
          db_query("INSERT INTO {locales_target} (lid, locale, translation, plid, plural) VALUES (%d, '%s', '%s', %d, %d)", $lid, $lang, $trans, $plid, $key);
Dries's avatar
 
Dries committed
230 231 232
          if ($trans != '') {
            $additions++;
          }
Dries's avatar
 
Dries committed
233
        }
Dries's avatar
 
Dries committed
234
        $plid = $lid;
Dries's avatar
 
Dries committed
235 236
      }
    }
Dries's avatar
 
Dries committed
237

Dries's avatar
 
Dries committed
238 239 240 241
    // A simple translation
    else {
      $english = $value['msgid'];
      $translation = $value['msgstr'];
Dries's avatar
 
Dries committed
242 243
      $loc = db_fetch_object(db_query("SELECT lid FROM {locales_source} WHERE source = '%s'", $english));
      if ($loc->lid) { // a string exists
Dries's avatar
 
Dries committed
244
        $lid = $loc->lid;
Dries's avatar
 
Dries committed
245
        // update location field
Dries's avatar
 
Dries committed
246
        db_query("UPDATE {locales_source} SET location = '%s' WHERE source = '%s'", $comments, $english);
Dries's avatar
 
Dries committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
        $trans = db_fetch_object(db_query("SELECT lid, translation FROM {locales_target} WHERE lid = %d AND locale = '%s'", $lid, $lang));
        if (!$trans->lid) { // no translation in current language
          db_query("INSERT INTO {locales_target} (lid, locale, translation) VALUES (%d, '%s', '%s')", $lid, $lang, $translation);
          $additions++;
        } // translation exists
        else if ($mode == 'overwrite') { //overwrite in any case
          db_query("UPDATE {locales_target} SET translation = '%s' WHERE locale = '%s' AND lid = %d", $translation, $lang, $lid);
          if ($trans->translation == '') {
            $additions++;
          }
          else {
            $updates++;
          }
        } // overwrite if empty string
        else if ($trans->translation == '') {
          db_query("UPDATE {locales_target} SET translation = '%s' WHERE locale = '%s' AND lid = %d", $translation, $lang, $lid);
          $additions++;
Dries's avatar
 
Dries committed
264
        }
Dries's avatar
 
Dries committed
265
      }
Dries's avatar
 
Dries committed
266 267 268 269
      else { // no string
        db_query("INSERT INTO {locales_source} (location, source) VALUES ('%s', '%s')", $comments, $english);
        $loc = db_fetch_object(db_query("SELECT lid FROM {locales_source} WHERE source = '%s'", $english));
        $lid = $loc->lid;
Dries's avatar
 
Dries committed
270
        db_query("INSERT INTO {locales_target} (lid, locale, translation) VALUES (%d, '%s', '%s')", $lid, $lang, $translation);
Dries's avatar
 
Dries committed
271 272 273
        if ($translation != '') {
          $additions++;
        }
Dries's avatar
 
Dries committed
274 275 276
      }
    }
  }
Dries's avatar
 
Dries committed
277

278
  // rebuild locale cache
Dries's avatar
 
Dries committed
279
  cache_clear_all("locale:$lang");
280 281

  // rebuild the menu, strings may have changed
Dries's avatar
 
Dries committed
282
  menu_rebuild();
283

284
  drupal_set_message(t('The translation was successfully imported. There are %number newly created translated strings and %update strings were updated.', array('%number' => $additions, '%update' => $updates)));
285
  watchdog('locale', t('Imported %file into %locale: %number new strings added and %update updated.', array('%file' => theme('placeholder', $file->filename), '%locale' => theme('placeholder', $lang), '%number' => $additions, '%update' => $updates)));
Dries's avatar
 
Dries committed
286 287 288 289 290 291
  return TRUE;
}

/**
 * Parses Gettext Portable Object file into an array
 *
292
 * @param $file Object with properties of local file to parse
Dries's avatar
 
Dries committed
293 294
 * @author Jacobo Tarrio
 */
295
function _locale_import_read_po($file) {
Dries's avatar
 
Dries committed
296

297
  $message = theme('placeholder', $file->filename);
298
  $fd = fopen($file->filepath, "rb");
Dries's avatar
 
Dries committed
299
  if (!$fd) {
300
    drupal_set_message(t('The translation import failed, because the file %filename could not be read.', array('%filename' => $message)), 'error');
Dries's avatar
 
Dries committed
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
    return FALSE;
  }
  $info = fstat($fd);
  $len = $info["size"];
  $po = fread($fd, $len);
  fclose($fd);

  $context = "COMMENT"; // Parser context: COMMENT, MSGID, MSGID_PLURAL, MSGSTR and MSGSTR_ARR
  $current = array();   // Current entry being read
  $strings = array();   // List of entries read
  $plural = 0;          // Current plural form

  $po = strtr($po, array("\\\n" => ""));
  $lines = split("\n", $po);
  $lineno = 0;

  foreach ($lines as $line) {
    $lineno++;
    $line = trim($line);

    if (!strncmp("#", $line, 1)) { // A comment
      if ($context == "COMMENT") { // Already in comment context: add
        $current["#"][] = substr($line, 1);
      }
      elseif (($context == "MSGSTR") || ($context == "MSGSTR_ARR")) { // End current entry, start a new one
        $strings[$current["msgid"]] = $current;
        $current = array();
        $current["#"][] = substr($line, 1);
        $context = "COMMENT";
      }
      else { // Parse error
332
        drupal_set_message(t('The translation file %filename contains an error: "msgstr" was expected but not found on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
Dries's avatar
 
Dries committed
333 334 335 336 337
        return FALSE;
      }
    }
    elseif (!strncmp("msgid_plural", $line, 12)) {
      if ($context != "MSGID") { // Must be plural form for current entry
338
        drupal_set_message(t('The translation file %filename contains an error: "msgid_plural" was expected but not found on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
Dries's avatar
 
Dries committed
339 340 341 342 343
        return FALSE;
      }
      $line = trim(substr($line, 12));
      $quoted = _locale_import_parse_quoted($line);
      if ($quoted === false) {
344
        drupal_set_message(t('The translation file %filename contains a syntax error on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
Dries's avatar
 
Dries committed
345 346 347
        return FALSE;
      }
      $current["msgid"] = $current["msgid"] ."\0". $quoted;
Dries's avatar
 
Dries committed
348
      $context = "MSGID_PLURAL";
Dries's avatar
 
Dries committed
349 350 351 352 353 354 355
    }
    elseif (!strncmp("msgid", $line, 5)) {
      if ($context == "MSGSTR") {   // End current entry, start a new one
        $strings[$current["msgid"]] = $current;
        $current = array();
      }
      elseif ($context == "MSGID") { // Already in this context? Parse error
356
        drupal_set_message(t('The translation file %filename contains an error: "msgid" is unexpected on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
Dries's avatar
 
Dries committed
357 358 359 360 361
        return FALSE;
      }
      $line = trim(substr($line, 5));
      $quoted = _locale_import_parse_quoted($line);
      if ($quoted === false) {
362
        drupal_set_message(t('The translation file %filename contains a syntax error on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
Dries's avatar
 
Dries committed
363 364 365 366 367 368 369
        return FALSE;
      }
      $current["msgid"] = $quoted;
      $context = "MSGID";
    }
    elseif (!strncmp("msgstr[", $line, 7)) {
      if (($context != "MSGID") && ($context != "MSGID_PLURAL") && ($context != "MSGSTR_ARR")) { // Must come after msgid, msgid_plural, or msgstr[]
370
        drupal_set_message(t('The translation file %filename contains an error: "msgstr[]" is unexpected on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
Dries's avatar
 
Dries committed
371 372 373
        return FALSE;
      }
      if (strpos($line, "]") === false) {
374
        drupal_set_message(t('The translation file %filename contains a syntax error on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
Dries's avatar
 
Dries committed
375 376 377 378 379 380 381
        return FALSE;
      }
      $frombracket = strstr($line, "[");
      $plural = substr($frombracket, 1, strpos($frombracket, "]") - 1);
      $line = trim(strstr($line, " "));
      $quoted = _locale_import_parse_quoted($line);
      if ($quoted === false) {
382
        drupal_set_message(t('The translation file %filename contains a syntax error on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
Dries's avatar
 
Dries committed
383 384 385 386 387 388 389
        return FALSE;
      }
      $current["msgstr"][$plural] = $quoted;
      $context = "MSGSTR_ARR";
    }
    elseif (!strncmp("msgstr", $line, 6)) {
      if ($context != "MSGID") {   // Should come just after a msgid block
390
        drupal_set_message(t('The translation file %filename contains an error: "msgstr" is unexpected on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
Dries's avatar
 
Dries committed
391 392 393 394 395
        return FALSE;
      }
      $line = trim(substr($line, 6));
      $quoted = _locale_import_parse_quoted($line);
      if ($quoted === false) {
396
        drupal_set_message(t('The translation file %filename contains a syntax error on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
Dries's avatar
 
Dries committed
397 398 399 400 401 402 403 404
        return FALSE;
      }
      $current["msgstr"] = $quoted;
      $context = "MSGSTR";
    }
    elseif ($line != "") {
      $quoted = _locale_import_parse_quoted($line);
      if ($quoted === false) {
405
        drupal_set_message(t('The translation file %filename contains a syntax error on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
Dries's avatar
 
Dries committed
406 407 408 409 410 411 412 413 414 415 416 417
        return FALSE;
      }
      if (($context == "MSGID") || ($context == "MSGID_PLURAL")) {
        $current["msgid"] .= $quoted;
      }
      elseif ($context == "MSGSTR") {
        $current["msgstr"] .= $quoted;
      }
      elseif ($context == "MSGSTR_ARR") {
        $current["msgstr"][$plural] .= $quoted;
      }
      else {
418
        drupal_set_message(t('The translation file %filename contains an error: there is an unexpected string on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
Dries's avatar
 
Dries committed
419 420 421 422 423 424 425 426 427 428
        return FALSE;
      }
    }
  }

  // End of PO file, flush last entry
  if (($context == "MSGSTR") || ($context == "MSGSTR_ARR")) {
    $strings[$current["msgid"]] = $current;
  }
  elseif ($context != "COMMENT") {
429
    drupal_set_message(t('The translation file %filename ended unexpectedly at line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
Dries's avatar
 
Dries committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
    return FALSE;
  }

  return $strings;
}

/**
 * Parses a Gettext Portable Object file header
 *
 * @param $header A string containing the complete header
 * @return An associative array of key-value pairs
 * @author Jacobo Tarrio
 */
function _locale_import_parse_header($header) {
  $hdr = array();

  $lines = explode("\n", $header);
  foreach ($lines as $line) {
    $line = trim($line);
    if ($line) {
      list($tag, $contents) = explode(":", $line, 2);
      $hdr[trim($tag)] = trim($contents);
    }
  }

  return $hdr;
}

/**
 * Parses a Plural-Forms entry from a Gettext Portable Object file header
 *
 * @param $pluralforms A string containing the Plural-Forms entry
462
 * @param $filename A string containing the filename
Dries's avatar
 
Dries committed
463 464 465 466
 * @return An array containing the number of plurals and a
 *         formula in PHP for computing the plural form
 * @author Jacobo Tarrio
 */
467
function _locale_import_parse_plural_forms($pluralforms, $filename) {
Dries's avatar
 
Dries committed
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
  // First, delete all whitespace
  $pluralforms = strtr($pluralforms, array(" " => "", "\t" => ""));

  // Select the parts that define nplurals and plural
  $nplurals = strstr($pluralforms, "nplurals=");
  if (strpos($nplurals, ";")) {
    $nplurals = substr($nplurals, 9, strpos($nplurals, ";") - 9);
  }
  else {
    return FALSE;
  }
  $plural = strstr($pluralforms, "plural=");
  if (strpos($plural, ";")) {
    $plural = substr($plural, 7, strpos($plural, ";") - 7);
  }
  else {
    return FALSE;
  }

  // Get PHP version of the plural formula
  $plural = _locale_import_parse_arithmetic($plural);

  if ($plural) {
    return array($nplurals, $plural);
  }
  else {
494
    drupal_set_message(t('The translation file %filename contains an error: the plural formula could not be parsed.', array('%filename' => theme('placeholder', $filename))), 'error');
Dries's avatar
 
Dries committed
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 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 656 657 658 659 660 661 662 663 664 665 666 667 668 669
    return FALSE;
  }
}

/**
 * Parses and sanitizes an arithmetic formula into a PHP expression
 *
 * While parsing, we ensure, that the operators have the right
 * precedence and associativity.
 *
 * @param $string A string containing the arithmetic formula
 * @return The PHP version of the formula
 * @author Jacobo Tarrio
 */
function _locale_import_parse_arithmetic($string) {
  // Operator precedence table
  $prec = array("(" => -1, ")" => -1, "?" => 1, ":" => 1, "||" => 3, "&&" => 4, "==" => 5, "!=" => 5, "<" => 6, ">" => 6, "<=" => 6, ">=" => 6, "+" => 7, "-" => 7, "*" => 8, "/" => 8, "%" => 8);
  // Right associativity
  $rasc = array("?" => 1, ":" => 1);

  $tokens = _locale_import_tokenize_formula($string);

  // Parse by converting into infix notation then back into postfix
  $opstk = array();
  $elstk = array();

  foreach ($tokens as $token) {
    $ctok = $token;

    // Numbers and the $n variable are simply pushed into $elarr
    if (is_numeric($token)) {
      $elstk[] = $ctok;
    }
    elseif ($ctok == "n") {
      $elstk[] = '$n';
    }
    elseif ($ctok == "(") {
      $opstk[] = $ctok;
    }
    elseif ($ctok == ")") {
      $topop = array_pop($opstk);
      while (($topop != NULL) && ($topop != "(")) {
        $elstk[] = $topop;
        $topop = array_pop($opstk);
      }
    }
    elseif ($prec[$ctok]) {
      // If it's an operator, then pop from $oparr into $elarr until the
      // precedence in $oparr is less than current, then push into $oparr
      $topop = array_pop($opstk);
      while (($topop != NULL) && ($prec[$topop] >= $prec[$ctok]) && !(($prec[$topop] == $prec[$ctok]) && $rasc[$topop] && $rasc[$ctok])) {
        $elstk[] = $topop;
        $topop = array_pop($opstk);
      }
      if ($topop) {
        $opstk[] = $topop;   // Return element to top
      }
      $opstk[] = $ctok;      // Parentheses are not needed
    }
    else {
      return false;
    }
  }

  // Flush operator stack
  $topop = array_pop($opstk);
  while ($topop != NULL) {
    $elstk[] = $topop;
    $topop = array_pop($opstk);
  }

  // Now extract formula from stack
  $prevsize = count($elstk) + 1;
  while (count($elstk) < $prevsize) {
    $prevsize = count($elstk);
    for ($i = 2; $i < count($elstk); $i++) {
      $op = $elstk[$i];
      if ($prec[$op]) {
        $f = "";
        if ($op == ":") {
          $f = $elstk[$i - 2] ."):". $elstk[$i - 1] .")";
        }
        elseif ($op == "?") {
          $f = "(". $elstk[$i - 2] ."?(". $elstk[$i - 1];
        }
        else {
          $f = "(". $elstk[$i - 2] . $op . $elstk[$i - 1] .")";
        }
        array_splice($elstk, $i - 2, 3, $f);
        break;
      }
    }
  }

  // If only one element is left, the number of operators is appropriate
  if (count($elstk) == 1) {
    return $elstk[0];
  }
  else {
    return FALSE;
  }
}

/**
 * Backward compatible implementation of token_get_all() for formula parsing
 *
 * @param $string A string containing the arithmetic formula
 * @return The PHP version of the formula
 * @author Gerhard Killesreiter
 */
function _locale_import_tokenize_formula($formula) {
  $formula = str_replace(" ", "", $formula);
  $tokens = array();
  for ($i = 0; $i < strlen($formula); $i++) {
    if (is_numeric($formula{$i})) {
      $num = $formula{$i};
      $j = $i + 1;
      while($j < strlen($formula) && is_numeric($formula{$j})) {
        $num .= $formula{$j};
        $j++;
      }
      $i = $j - 1;
      $tokens[] = $num;
    }
    elseif ($pos = strpos(" =<>!&|", $formula{$i})) { // We won't have a space
      $next = $formula{($i+1)};
      switch ($pos) {
        case 1:
        case 2:
        case 3:
        case 4:
          if ($next == '=') {
            $tokens[] = $formula{$i} .'=';
            $i++;
          }
          else {
            $tokens[] = $formula{$i};
          }
          break;
        case 5:
          if ($next == '&') {
            $tokens[] = '&&';
            $i++;
          }
          else {
            $tokens[] = $formula{$i};
          }
          break;
        case 6:
          if ($next == '|') {
            $tokens[] = '||';
            $i++;
          }
          else {
            $tokens[] = $formula{$i};
          }
          break;
      }
    }
    else {
      $tokens[] = $formula{$i};
    }
  }
  return $tokens;
}

/**
 * Modify a string to contain proper count indices
 *
 * This is a callback function used via array_map()
 *
 * @param $entry An array element
 * @param $key Index of the array element
 */
function _locale_import_append_plural($entry, $key) {
Dries's avatar
 
Dries committed
670
  // No modifications for 0, 1
Dries's avatar
 
Dries committed
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
  if ($key == 0 || $key == 1) {
    return $entry;
  }

  // First remove any possibly false indices, then add new ones
  $entry = preg_replace('/(%count)\[[0-9]\]/', '\\1', $entry);
  return preg_replace('/(%count)/', "\\1[$key]", $entry);
}

/**
 * Generate a short, one string version of the passed comment array
 *
 * @param $comment An array of strings containing a comment
 * @return Short one string version of the comment
 */
function _locale_import_shorten_comments($comment) {
  $comm = '';
688 689 690 691 692 693 694 695
  while (count($comment)) {
    $test = $comm . substr(array_shift($comment), 1) .', ';
    if (strlen($comm) < 130) {
      $comm = $test;
    }
    else {
      break;
    }
Dries's avatar
 
Dries committed
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
  }
  return substr($comm, 0, -2);
}

/**
 * Parses a string in quotes
 *
 * @param $string A string specified with enclosing quotes
 * @return The string parsed from inside the quotes
 */
function _locale_import_parse_quoted($string) {
  if (substr($string, 0, 1) != substr($string, -1, 1)) {
    return FALSE;   // Start and end quotes must be the same
  }
  $quote = substr($string, 0, 1);
  $string = substr($string, 1, -1);
  if ($quote == '"') {        // Double quotes: strip slashes
    return stripcslashes($string);
  }
  elseif ($quote == "'") {  // Simple quote: return as-is
    return $string;
  }
  else {
    return FALSE;             // Unrecognized quote
  }
}

/**
 * User interface for the translation export screen
 */
function _locale_admin_export_screen() {
  $languages = locale_supported_languages(FALSE, TRUE);
  $languages = array_map("t", $languages['name']);
  unset($languages['en']);
  $output = '';

  // Offer language specific export if any language is set up
  if (count($languages)) {
    $output .= '<h2>'. t('Export translation') .'</h2>';
735
    $form = array();
736 737
    $form['langcode'] = array('#type' => 'select', '#title' => t('Language name'), '#options' => $languages, '#description' => t('Select the language you would like to export in gettext Portable Object (.po) format.'));
    $form['submit'] = array('#type' => 'submit', '#value' => t('Export'));
738
    $output .= drupal_get_form('_locale_export_po', $form);
Dries's avatar
 
Dries committed
739 740 741 742
  }

  // Complete template export of the strings
  $output .= '<h2>'. t('Export template') .'</h2>';
743 744
  $output .= t('<p>Generate a gettext Portable Object Template (.pot) file with all the interface strings from the Drupal locale database.</p>');
  $form = array();
745
  $form['submit'] = array('#type' => 'submit', '#value' => t('Export'));
746
  $output .= drupal_get_form('_locale_export_pot', $form);
Dries's avatar
 
Dries committed
747

Dries's avatar
 
Dries committed
748 749 750 751 752 753 754 755 756 757
  return $output;
}

/**
 * Exports a Portable Object (Template) file for a language
 *
 * @param $language Selects a language to generate the output for
 */
function _locale_export_po($language) {
  global $user;
Dries's avatar
 
Dries committed
758

Dries's avatar
 
Dries committed
759 760 761 762 763 764
  // Get language specific strings, or all strings
  if ($language) {
    $meta = db_fetch_object(db_query("SELECT * FROM {locales_meta} WHERE locale = '%s'", $language));
    $result = db_query("SELECT s.lid, s.source, s.location, t.translation, t.plid, t.plural FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid WHERE t.locale = '%s' ORDER BY t.plid, t.plural", $language);
  }
  else {
765
    $result = db_query("SELECT s.lid, s.source, s.location, t.plid, t.plural FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid ORDER BY t.plid, t.plural");
Dries's avatar
 
Dries committed
766
  }
Dries's avatar
 
Dries committed
767

Dries's avatar
 
Dries committed
768 769 770
  // Build array out of the database results
  $parent = array();
  while ($child = db_fetch_object($result)) {
Dries's avatar
 
Dries committed
771 772 773 774 775 776 777 778 779 780 781
    if ($child->source != '') {
      $parent[$child->lid]['comment'] = $child->location;
      $parent[$child->lid]['msgid'] = $child->source;
      if ($child->plid) {
        $parent[$child->lid][$child->plid]['plural'] = $child->lid;
        $parent[$child->lid][$child->plid]['translation'] = $child->translation;
        $parent[$child->lid][$child->plid]['msgid'] = $child->source;
      }
      else {
        $parent[$child->lid]['translation'] = $child->translation;
      }
Dries's avatar
 
Dries committed
782 783
    }
  }
Dries's avatar
 
Dries committed
784

Dries's avatar
 
Dries committed
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
  // Generating Portable Object file for a language
  if ($language) {
    $filename = $language .'.po';
    $header .= "# $meta->name translation of ". variable_get('site_name', 'Drupal') ."\n";
    $header .= '# Copyright (c) '. date('Y') .' '. $user->name .' <'. $user->mail .">\n";
    $header .= "#\n";
    $header .= "msgid \"\"\n";
    $header .= "msgstr \"\"\n";
    $header .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
    $header .= "\"POT-Creation-Date: ". date("Y-m-d H:iO") ."\\n\"\n";
    $header .= "\"PO-Revision-Date: ". date("Y-m-d H:iO") ."\\n\"\n";
    $header .= "\"Last-Translator: ". $user->name .' <'. $user->mail .">\\n\"\n";
    $header .= "\"Language-Team: ". $meta->name .' <'. $user->mail .">\\n\"\n";
    $header .= "\"MIME-Version: 1.0\\n\"\n";
    $header .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
    $header .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
    if ($meta->formula && $meta->plurals) {
      $header .= "\"Plural-Forms: nplurals=". $meta->plurals ."; plural=". strtr($meta->formula, '$', '') .";\\n\"\n";
    }
    $header .= "\n";
805
    watchdog('locale', t('Exported %locale translation file: %filename.', array('%locale' => theme('placeholder', $meta->name), '%filename' => theme('placeholder', $filename))));
Dries's avatar
 
Dries committed
806
  }
Dries's avatar
 
Dries committed
807

Dries's avatar
 
Dries committed
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
  // Generating Portable Object Template
  else {
    $filename = variable_get('site_name', 'drupal') .'.pot';
    $header .= "# LANGUAGE translation of PROJECT\n";
    $header .= "# Copyright (c) YEAR NAME <EMAIL@ADDRESS>\n";
    $header .= "#\n";
    $header .= "msgid \"\"\n";
    $header .= "msgstr \"\"\n";
    $header .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
    $header .= "\"POT-Creation-Date: ". date("Y-m-d H:iO") ."\\n\"\n";
    $header .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
    $header .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
    $header .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
    $header .= "\"MIME-Version: 1.0\\n\"\n";
    $header .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
    $header .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
    $header .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n";
    $header .= "\n";
826
    watchdog('locale', t('Exported translation file: %filename.', array('%filename' => theme('placeholder', $filename))));
Dries's avatar
 
Dries committed
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
  }

  // Start download process
  header("Content-Disposition: attachment; filename=$filename");
  header("Content-Type: text/plain; charset=utf-8");

  print $header;

  foreach ($parent as $lid => $message) {
    if (!isset($done[$lid])) {
      if ($message['comment']) {
        print '#: '. $message['comment'] ."\n";
      }
      print 'msgid '. _locale_export_print($message['msgid']);
      if (isset($message[1]['plural'])) {
        print 'msgid_plural '. _locale_export_print($message[1]['msgid']);
        if ($language) {
          for ($i = 0; $i < $meta->plurals; $i++) {
            print 'msgstr['. $i .'] '. _locale_export_print(_locale_export_remove_plural($message[${i}]['translation']));
            $done[$message[${i}]['plural']] = 1;
          }
        }
        else {
          print 'msgstr[0] ""'. "\n";
          print 'msgstr[1] ""'. "\n";
          $done[$message[0]['plural']] = 1;
          $done[$message[1]['plural']] = 1;
        }
      }
      else {
        if ($language) {
          print 'msgstr '. _locale_export_print($message['translation']);
        }
        else {
          print 'msgstr ""'. "\n";
        }
      }
      print "\n";
    }
  }
  die();
}

/**
 * Print out a string on multiple lines
 */
function _locale_export_print($str) {
  $stri = addcslashes($str, "\0..\37\\\"");
  $parts = array();

  // Cut text into several lines
  while ($stri != "") {
    $i = strpos($stri, "\\n");
    if ($i === FALSE) {
      $curstr = $stri;
      $stri = "";
    }
    else {
      $curstr = substr($stri, 0, $i + 2);
      $stri = substr($stri, $i + 2);
    }
    $curparts = explode("\n", _locale_export_wrap($curstr, 70));
    $parts = array_merge($parts, $curparts);
  }

  if (count($parts) > 1) {
    return "\"\"\n\"". implode("\"\n\"", $parts) ."\"\n";
  }
  else {
    return "\"$parts[0]\"\n";
  }
}

/**
 * Custom word wrapping for Portable Object (Template) files.
 *
 * @author Jacobo Tarrio
 */
function _locale_export_wrap($str, $len) {
  $words = split(" ", $str);
  $ret = array();

  $cur = "";
  $nstr = 1;
  while (count($words)) {
    $word = array_shift($words);
    if ($nstr) {
      $cur = $word;
      $nstr = 0;
    }
    elseif (strlen("$cur $word") > $len) {
      $ret[] = $cur . " ";
      $cur = $word;
    }
    else {
      $cur = "$cur $word";
    }
  }
  $ret[] = $cur;

  return implode("\n", $ret);
}

/**
 * Removes plural index information from a string
 */
function _locale_export_remove_plural($entry) {
  return preg_replace('/(%count)\[[0-9]\]/', '\\1', $entry);
}

function _locale_string_delete($lid) {
938 939
  db_query('DELETE FROM {locales_source} WHERE lid = %d', $lid);
  db_query('DELETE FROM {locales_target} WHERE lid = %d', $lid);
Dries's avatar
 
Dries committed
940
  locale_refresh_cache();
941
  drupal_set_message(t('The string has been removed.'));
Dries's avatar
 
Dries committed
942 943 944 945 946 947 948 949 950
}

/**
 * Action handler for string editing
 *
 * Saves all translations of one string submitted from a form
 */
function _locale_string_save($lid) {

951
  $edit =& $_POST['edit'];
Dries's avatar
 
Dries committed
952 953
  foreach ($edit as $key => $value) {
    $trans = db_fetch_object(db_query("SELECT translation FROM {locales_target} WHERE lid = %d AND locale = '%s'", $lid, $key));
Dries's avatar
 
Dries committed
954
    if (isset($trans->translation)) {
Dries's avatar
 
Dries committed
955 956 957 958 959 960
      db_query("UPDATE {locales_target} SET translation = '%s' WHERE lid = %d AND locale = '%s'", $value, $lid, $key);
    }
    else {
      db_query("INSERT INTO {locales_target}  (lid, translation, locale) VALUES (%d, '%s', '%s')", $lid, $value, $key);
    }
  }
961
  // refresh the locale cache
Dries's avatar
 
Dries committed
962
  locale_refresh_cache();
963 964
  // rebuild the menu, strings may have changed
  menu_rebuild();
Dries's avatar
 
Dries committed
965 966 967
  // delete form data so it will remember where it came from
  $edit = '';

968
  drupal_set_message(t('The string has been saved.'));
Dries's avatar
 
Dries committed
969 970 971 972 973 974 975 976
}

/**
 * User interface for string editing
 */
function _locale_string_edit($lid) {
  $languages = locale_supported_languages(FALSE, TRUE);
  unset($languages['name']['en']);
Dries's avatar
 
Dries committed
977

978
  $result = db_query('SELECT DISTINCT s.source, t.translation, t.locale FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid WHERE s.lid = %d', $lid);
979
  $form = array();
Dries's avatar
 
Dries committed
980 981
  while ($translation = db_fetch_object($result)) {
    $orig = $translation->source;
982
    $form[$translation->locale] = (strlen($orig) > 40) ?
983 984
   array('#type' => 'textarea', '#title' => $languages['name'][$translation->locale], '#default_value' => $translation->translation, '#rows' => 15)
 : array('#type' => 'textfield', '#title' => $languages['name'][$translation->locale], '#default_value' => $translation->translation);
Dries's avatar
 
Dries committed
985 986
    unset($languages['name'][$translation->locale]);
  }
987
  $form['item'] = array('#type' => 'item', '#title' => t('Original text'), '#value' => wordwrap(check_plain($orig, 0)));
Dries's avatar
 
Dries committed
988
  foreach ($languages['name'] as $key => $lang) {
989
    $form[$key] = (strlen($orig) > 40) ?
990 991
array('#type' => 'textarea', '#title' => $lang, '#rows' => 15) :
array('#type' => 'textfield', '#title' => $lang);
Dries's avatar
 
Dries committed
992 993
  }

994
  $form['submit'] = array('#type' => 'submit', '#value' => t('Save translations'));
Dries's avatar
 
Dries committed
995

996
  return drupal_get_form('_locale_string_edit', $form);
Dries's avatar
 
Dries committed
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
}

/**
 * List languages in search result table
 */
function _locale_string_language_list($translation) {
  $languages = locale_supported_languages(FALSE, TRUE);
  unset($languages['name']['en']);
  $output = '';
  foreach ($languages['name'] as $key => $value) {
    if (isset($translation[$key])) {
1008
      $output .= ($translation[$key] != '') ? $key .' ' : "<em class=\"locale-untranslated\">$key</em> ";
Dries's avatar
 
Dries committed
1009
    }
Dries's avatar
 
Dries committed
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
  }

  return $output;
}

/**
 * Build object out of search criteria specified in request variables
 */
function _locale_string_seek_query() {
  static $query = NULL;

Dries's avatar
 
Dries committed
1021
  if (is_null($query)) {
Dries's avatar
 
Dries committed
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
    $fields = array('string', 'language', 'searchin');
    $query = new StdClass;
    if (is_array($_REQUEST['edit'])) {
      foreach ($_REQUEST['edit'] as $key => $value) {
        if (!empty($value) && in_array($key, $fields)) {
          $query->$key = $value;
        }
      }
    }
    else {
      foreach ($_REQUEST as $key => $value) {
        if (!empty($value) && in_array($key, $fields)) {
          $query->$key = strpos(',', $value) ? explode(',', $value) : $value;
        }
      }
    }
  }
  return $query;
}

/**
 * Perform a string search and display results in a table
 */
function _locale_string_seek() {
1046
  // We have at least one criterion to match
Dries's avatar
 
Dries committed
1047 1048 1049 1050 1051 1052
  if ($query = _locale_string_seek_query()) {
    $join = "SELECT s.source, s.location, s.lid, t.translation, t.locale FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid ";

    // Compute LIKE section
    switch ($query->searchin) {
      case 'translated':
Dries's avatar
 
Dries committed
1053
        $where = "WHERE (t.translation LIKE '%". db_escape_string($query->string) ."%' AND t.translation != '')";
Dries's avatar
 
Dries committed
1054 1055 1056
        $orderby = "ORDER BY t.translation";
        break;
      case 'untranslated':
Dries's avatar
 
Dries committed
1057
        $where = "WHERE (s.source LIKE '%". db_escape_string($query->string) ."%' AND t.translation = '')";
Dries's avatar
 
Dries committed
1058 1059 1060 1061
        $orderby = "ORDER BY s.source";
        break;
      case 'all' :
      default:
Dries's avatar
 
Dries committed
1062
        $where = "WHERE (s.source LIKE '%". db_escape_string($query->string) ."%' OR t.translation LIKE '%". db_escape_string($query->string) ."%')";
Dries's avatar
 
Dries committed
1063 1064 1065 1066 1067 1068 1069
        $orderby = '';
        break;
    }

    switch ($query->language) {
      // Force search in source strings
      case "en":
Dries's avatar
 
Dries committed
1070
        $sql = $join ." WHERE s.source LIKE '%". db_escape_string($query->string) ."%' ORDER BY s.source";
Dries's avatar
 
Dries committed
1071 1072 1073 1074 1075 1076 1077
        break;
      // Search in all languages
      case "all":
        $sql = "$join $where $orderby";
        break;
      // Some different language
      default:
Dries's avatar
 
Dries committed
1078
        $sql = "$join $where AND t.locale = '". db_escape_string($query->language) ."' $orderby";
Dries's avatar
 
Dries committed
1079 1080 1081 1082
    }

    $result = pager_query($sql, 50);

Dries's avatar
 
Dries committed
1083
    $header = array(t('String'), t('Locales'), array('data' => t('Operations'), 'colspan' => '2'));
Dries's avatar
 
Dries committed
1084 1085 1086 1087 1088 1089 1090
    $arr = array();
    while ($locale = db_fetch_object($result)) {
      $arr[$locale->lid]['locales'][$locale->locale] = $locale->translation;
      $arr[$locale->lid]['location'] = $locale->location;
      $arr[$locale->lid]['source'] = $locale->source;
    }
    foreach ($arr as $lid => $value) {
1091
      $rows[] = array(array('data' => check_plain(truncate_utf8($value['source'], 150, FALSE, TRUE)) .'<br /><small>'. $value['location'] .'</small>'), array('data' => _locale_string_language_list($value['locales']), 'align' => 'center'), array('data' => l(t('edit'), "admin/locale/string/edit/$lid"), 'class' => 'nowrap'), array('data' => l(t('delete'), "admin/locale/string/delete/$lid"), 'class' => 'nowrap'));
Dries's avatar
 
Dries committed
1092 1093 1094 1095 1096 1097 1098 1099 1100
    }

    $request = array();
    if (count($query)) {
      foreach ($query as $key => $value) {
        $request[$key] = (is_array($value)) ? implode(',', $value) : $value;
      }
    }

1101 1102 1103 1104 1105 1106
    if (count($rows)) {
      $output .= theme('table', $header, $rows);
    }
    if ($pager = theme('pager', NULL, 50, 0, $request)) {
      $output .= $pager;
    }
Dries's avatar
 
Dries committed
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
  }

  return $output;
}

/**
 * User interface for the string search screen
 */
function _locale_string_seek_form() {

  // Get *all* languages set up
  $languages = locale_supported_languages(FALSE, TRUE);
  asort($languages['name']); unset($languages['name']['en']);
1120
  $languages['name'] = array_map('check_plain', $languages['name']);
Dries's avatar
 
Dries committed
1121 1122 1123

  // Present edit form preserving previous user settings
  $query = _locale_string_seek_query();
1124
  $form = array();
1125 1126 1127 1128 1129 1130
  $form['search'] = array('#type' => 'fieldset', '#title' => t('Search'));
  $form['search']['string'] = array('#type' => 'textfield', '#title' => t('Strings to search for'), '#default_value' => $query->string, '#size' => 30, '#maxlength' => 30, '#description' => t('Leave blank to show all strings. The search is case sensitive.'));
  $form['search']['language'] = array('#type' => 'radios', '#title' => t('Language'), '#default_value' => ($query->language ? $query->language : 'all'), '#options' => array_merge(array('all' => t('All languages'), 'en' => t('English (provided by Drupal)')), $languages['name']));
  $form['search']['searchin'] = array('#type' => 'radios', '#title' => t('Search in'), '#default_value' => ($query->searchin ? $query->searchin : 'all'), '#options' => array('all' => t('All strings in that language'), 'translated' => t('Only translated strings'), 'untranslated' => t('Only untranslated strings')));
  $form['search']['submit'] = array('#type' => 'submit', '#value' => t('Search'));
  $form['#action'] = 'admin/locale/string/search';
1131 1132

  return drupal_get_form('_locale_string_seek', $form);
Dries's avatar
 
Dries committed
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
}

// ---------------------------------------------------------------------------------
// List of some of the most common languages (administration only)

/**
 * Prepares the language code list for a select form item with only the unsupported ones
 */
function _locale_prepare_iso_list() {
  $languages = locale_supported_languages(FALSE, TRUE);
  $isocodes = _locale_get_iso639_list();
  foreach ($isocodes as $key => $value) {
    if (isset($languages['name'][$key])) {
      unset($isocodes[$key]);
      continue;
    }
    if (count($value) == 2) {
      $tname = t($value[0]);
      $isocodes[$key] = ($tname == $value[1]) ? $tname : "$tname ($value[1])";
    }
    else {
      $isocodes[$key] = t($value[0]);
    }
  }
  asort($isocodes);
  return $isocodes;
}

/**
 * Some of the common languages with their English and native names
 *
 * Based on ISO 639 and http://people.w3.org/rishida/names/languages.html
 */
function _locale_get_iso639_list() {
  return array(
    "aa" => array("Afar"),
    "ab" => array("Abkhazian", "аҧсуа бызшәа"),
    "ae" => array("Avestan"),
    "af" => array("Afrikaans"),
    "ak" => array("Akan"),
    "am" => array("Amharic", "አማርኛ"),
    "ar" => array("Arabic", "العربية"),
    "as" => array("Assamese"),
    "av" => array("Avar"),
    "ay" => array("Aymara"),
    "az" => array("Azerbaijani", "azərbaycan"),
    "ba" => array("Bashkir"),
    "be" => array("Belarusian", "Беларуская"),
    "bg" => array("Bulgarian", "Български"),
    "bh" => array("Bihari"),
    "bi" => array("Bislama"),
    "bm" => array("Bambara", "Bamanankan"),
    "bn" => array("Bengali"),
    "bo" => array("Tibetan"),
    "br" => array("Breton"),
    "bs" => array("Bosnian", "Bosanski"),
    "ca" => array("Catalan", "Català"),
    "ce" => array("Chechen"),
    "ch" => array("Chamorro"),
    "co" => array("Corsican"),
    "cr" => array("Cree"),
    "cs" => array("Czech", "Čeština"),
    "cu" => array("Old Slavonic"),
    "cv" => array("Welsh", "Cymraeg"),
    "cy" => array("Welch"),
    "da" => array("Danish"),
    "de" => array("German", "Deutsch"),
    "dv" => array("Maldivian"),
    "dz" => array("Bhutani"),
    "ee" => array("Ewe", "Ɛʋɛ"),
    "el" => array("Greek", "Ελληνικά"),
    "en" => array("English"),
    "eo" => array("Esperanto"),
    "es" => array("Spanish", "Español"),
    "et" => array("Estonian", "Eesti"),
    "eu" => array("Basque", "Euskera"),
    "fa" => array("Persian", "فارسی"),
    "ff" => array("Fulah", "Fulfulde"),
    "fi" => array("Finnish", "Suomi"),
    "fj" => array("Fiji"),
    "fo" => array("Faeroese"),
    "fr" => array("French", "Français"),
    "fy" => array("Frisian", "Frysk"),
    "ga" => array("Irish", "Gaeilge"),
    "gd" => array("Scots Gaelic"),
    "gl" => array("Galician", "Galego"),
    "gn" => array("Guarani"),
    "gu" => array("Gujarati"),
    "gv" => array("Manx"),
    "ha" => array("Hausa"),
    "he" => array("Hebrew", "עברית"),
    "hi" => array("Hindi", "हिन्दी"),
    "ho" => array("Hiri Motu"),
    "hr" => array("Croatian", "Hrvatski"),
    "hu" => array("Hungarian", "Magyar"),
    "hy" => array("Armenian", "Հայերեն"),
    "hz" => array("Herero"),
    "ia" => array("Interlingua"),
    "id" => array("Indonesian", "Bahasa Indonesia"),
    "ie" => array("Interlingue"),
    "ig" => array("Igbo"),
    "ik" => array("Inupiak"),
    "is" => array("Icelandic", "Íslenska"),
    "it" => array("Italian", "Italiano"),
    "iu" => array("Inuktitut"),
    "ja" => array("Japanese", "日本語"),
    "jv" => array("Javanese"),
    "ka" => array("Georgian"),
    "kg" => array("Kongo"),
    "ki" => array("Kikuyu"),
    "kj" => array("Kwanyama"),
    "kk" => array("Kazakh", "Қазақ"),
    "kl" => array("Greenlandic"),
    "km" => array("Cambodian"),
    "kn" => array("Kannada", "ಕನ್ನಡ"),
    "ko" => array("Korean", "한국어"),
    "kr" => array("Kanuri"),
    "ks" => array("Kashmiri"),
    "ku" => array("Kurdish", "Kurdî"),
    "kv" => array("Komi"),
    "kw" => array("Cornish"),
    "ky" => array("Kirghiz", "Кыргыз"),
    "la" => array("Latin", "Latina"),
    "lb" => array("Luxembourgish"),
    "lg" => array("Luganda"),
    "ln" => array("Lingala"),
    "lo" => array("Laothian"),
    "lt" => array("Lithuanian", "Lietuviškai"),
    "lv" => array("Latvian", "Latviešu"),
    "mg" => array("Malagasy"),
    "mh" => array("Marshallese"),
    "mi" => array("Maori"),
    "mk" => array("Macedonian", "Македонски"),
    "ml" => array("Malayalam", "മലയാളം"),
    "mn" => array("Mongolian"),
    "mo" => array("Moldavian"),
    "mr" => array("Marathi"),
    "ms" => array("Malay", "Bahasa Melayu"),
    "mt" => array("Maltese", "Malti"),
    "my" => array("Burmese"),
    "na" => array("Nauru"),
    "nd" => array("North Ndebele"),
    "ne" => array("Nepali"),
    "ng" => array("Ndonga"),
    "nl" => array("Dutch", "Nederlands"),
    "no" => array("Norwegian", "Norsk"),
    "nr" => array("South Ndebele"),
    "nv" => array("Navajo"),
    "ny" => array("Chichewa"),
    "oc" => array("Occitan"),
    "om" => array("Oromo"),
    "or" => array("Oriya"),
    "os" => array("Ossetian"),
    "pa" => array("Punjabi"),
    "pi" => array("Pali"),
    "pl" => array("Polish", "Polski"),
    "ps" => array("Pashto", "پښتو"),
    "pt" => array("Portuguese", "Português"),
    "qu" => array("Quechua"),
    "rm" => array("Rhaeto-Romance"),
    "rn" => array("Kirundi"),
    "ro" => array("Romanian", "Română"),
    "ru" => array("Russian", "Русский"),
    "rw" => array("Kinyarwanda"),
    "sa" => array("Sanskrit"),
    "sc" => array("Sardinian"),
    "sd" => array("Sindhi"),
    "se" => array("Northern Sami"),
    "sg" => array("Sango"),
    "sh" => array("Serbo-Croatian"),
    "si" => array("Singhalese"),
    "sk" => array("Slovak", "Slovenčina"),
    "sl" => array("Slovenian", "Slovenščina"),
    "sm" => array("Samoan"),
    "sn" => array("Shona"),
    "so" => array("Somali"),
    "sq" => array("Albanian", "Shqip"),
    "sr" => array("Serbian", "Српски"),
    "ss" => array("Siswati"),
    "st" => array("Sesotho"),
    "su" => array("Sudanese"),
    "sv" => array("Swedish", "Svenska"),
    "sw" => array("Swahili", "Kiswahili"),
    "ta" => array("Tamil", "தமிழ்"),
    "te" => array("Telugu", "తెలుగు"),
    "tg" => array("Tajik"),
    "th" => array("Thai", "ภาษาไทย"),
    "ti" => array("Tigrinya"),
    "tk" => array("Turkmen"),
    "tl" => array("Tagalog"),
    "tn" => array("Setswana"),
    "to" => array("Tonga"),
    "tr" => array("Turkish", "Türkçe"),
    "ts" => array("Tsonga"),
    "tt" => array("Tatar", "Tatarça"),
    "tw" => array("Twi"),
    "ty" => array("Tahitian"),
    "ug" => array("Uighur"),
    "uk" => array("Ukrainian", "Українська"),
    "ur" => array("Urdu", "اردو"),
    "uz" => array("Uzbek", "o'zbek"),
    "ve" => array("Venda"),
    "vi" => array("Vietnamese", "Tiếng Việt"),
    "vo" => array("Volapük"),
    "wo" => array("Wolof"),
    "xh" => array("Xhosa", "isiXhosa"),
    "yi" => array("Yiddish"),
    "yo" => array("Yoruba", "Yorùbá"),
    "za" => array("Zhuang"),
1342 1343
    "zh-hans" => array("Chinese, Simplified", "简体中文"),
    "zh-hant" => array("Chinese, Traditional", "繁體中文"),
Dries's avatar
 
Dries committed
1344 1345 1346 1347
    "zu" => array("Zulu", "isiZulu"),
  );
}

1348