~ubuntu-branches/ubuntu/karmic/drupal6/karmic

« back to all changes in this revision

Viewing changes to includes/locale.inc

  • Committer: Bazaar Package Importer
  • Author(s): Luigi Gangitano
  • Date: 2008-10-24 23:06:15 UTC
  • Revision ID: james.westby@ubuntu.com-20081024230615-a33t46nwna16bynv
Tags: upstream-6.6
Import upstream version 6.6

Show diffs side-by-side

added added

removed removed

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