2
// $Id: locale.inc,v 1.174.2.4 2008/09/17 08:47:04 goba Exp $
6
* Administration functions for locale.module.
9
define('LOCALE_JS_STRING', '(?:(?:\'(?:\\\\\'|[^\'])*\'|"(?:\\\\"|[^"])*")(?:\s*\+\s*)?)+');
12
* Translation import mode overwriting all existing translations
13
* if new translated version available.
15
define('LOCALE_IMPORT_OVERWRITE', 0);
18
* Translation import mode keeping existing translations and only
19
* inserting new strings.
21
define('LOCALE_IMPORT_KEEP', 1);
24
* @defgroup locale-language-overview Language overview functionality
29
* User interface for the language overview screen.
31
function locale_languages_overview_form() {
32
$languages = language_list('language', TRUE);
35
$form['weight'] = array('#tree' => TRUE);
36
foreach ($languages as $langcode => $language) {
38
$options[$langcode] = '';
39
if ($language->enabled) {
40
$enabled[] = $langcode;
42
$form['weight'][$langcode] = array(
44
'#default_value' => $language->weight
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')));
50
$form['enabled'] = array('#type' => 'checkboxes',
51
'#options' => $options,
52
'#default_value' => $enabled,
54
$form['site_default'] = array('#type' => 'radios',
55
'#options' => $options,
56
'#default_value' => language_default('language'),
58
$form['submit'] = array('#type' => 'submit', '#value' => t('Save configuration'));
59
$form['#theme'] = 'locale_languages_overview_form';
65
* Theme the language overview form.
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';
79
array('data' => drupal_render($form['enabled'][$key]), 'align' => 'center'),
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) : '')
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);
98
* Process language overview form submissions, updating existing languages.
100
function locale_languages_overview_form_submit($form, &$form_state) {
101
$languages = language_list();
102
$default = language_default();
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;
111
if ($form_state['values']['enabled'][$langcode]) {
113
$language->enabled = 1;
116
$language->enabled = 0;
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;
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);
126
// Changing the language settings impacts the interface.
127
cache_clear_all('*', 'cache_page', TRUE);
129
$form_state['redirect'] = 'admin/settings/language';
133
* @} End of "locale-language-overview"
137
* @defgroup locale-language-add-edit Language addition and editing functionality
142
* User interface for the language addition screen.
144
function locale_languages_add_screen() {
145
$output = drupal_get_form('locale_languages_predefined_form');
146
$output .= drupal_get_form('locale_languages_custom_form');
151
* Predefined language setup form.
153
function locale_languages_predefined_form() {
154
$predefined = _locale_prepare_predefined_list();
156
$form['language list'] = array('#type' => 'fieldset',
157
'#title' => t('Predefined language'),
158
'#collapsible' => TRUE,
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.)'),
166
$form['language list']['submit'] = array('#type' => 'submit', '#value' => t('Add language'));
171
* Custom language addition form.
173
function locale_languages_custom_form() {
175
$form['custom language'] = array('#type' => 'fieldset',
176
'#title' => t('Custom language'),
177
'#collapsible' => TRUE,
178
'#collapsed' => TRUE,
180
_locale_languages_common_controls($form['custom language']);
181
$form['custom language']['submit'] = array(
183
'#value' => t('Add custom language')
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';
192
* Editing screen for a particular language.
195
* Language code of the language to edit.
197
function locale_languages_edit_form(&$form_state, $langcode) {
198
if ($language = db_fetch_object(db_query("SELECT * FROM {languages} WHERE language = '%s'", $langcode))) {
200
_locale_languages_common_controls($form, $language);
201
$form['submit'] = array(
203
'#value' => t('Save language')
205
$form['#submit'][] = 'locale_languages_edit_form_submit';
206
$form['#validate'][] = 'locale_languages_edit_form_validate';
215
* Common elements of the language addition and editing form.
218
* A parent form item (or empty array) to add items below.
220
* Language object to edit.
222
function _locale_languages_common_controls(&$form, $language = NULL) {
223
if (!is_object($language)) {
224
$language = new stdClass();
226
if (isset($language->language)) {
227
$form['langcode_view'] = array(
229
'#title' => t('Language code'),
230
'#value' => $language->language
232
$form['langcode'] = array(
234
'#value' => $language->language
238
$form['langcode'] = array('#type' => 'textfield',
239
'#title' => t('Language code'),
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')),
248
$form['name'] = array('#type' => 'textfield',
249
'#title' => t('Language name in English'),
251
'#default_value' => @$language->name,
253
'#description' => t('Name of the language in English. Will be available for translation in all languages.'),
255
$form['native'] = array('#type' => 'textfield',
256
'#title' => t('Native language name'),
258
'#default_value' => @$language->native,
260
'#description' => t('Name of the language in the language being added.'),
262
$form['prefix'] = array('#type' => 'textfield',
263
'#title' => t('Path prefix'),
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>')
268
$form['domain'] = array('#type' => 'textfield',
269
'#title' => t('Language domain'),
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>'),
274
$form['direction'] = array('#type' => 'radios',
275
'#title' => t('Direction'),
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'))
285
* Validate the language addition form.
287
function locale_languages_predefined_form_validate($form, &$form_state) {
288
$langcode = $form_state['values']['langcode'];
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)));
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.'));
302
// Reuse the editing form validation routine if we add a custom language.
303
locale_languages_edit_form_validate($form, $form_state);
308
* Process the language addition form submission.
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'))));
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'))));
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')) {
330
$form_state['redirect'] = 'admin/settings/language';
335
* Validate the language editing form. Reused for custom language addition too.
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.'));
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)));
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.'));
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)));
353
* Process the language editing form submission.
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];
365
variable_set('language_default', $default);
367
$form_state['redirect'] = 'admin/settings/language';
371
* @} End of "locale-language-add-edit"
375
* @defgroup locale-language-delete Language deletion functionality
380
* User interface for the language deletion confirmation screen.
382
function locale_languages_delete_form(&$form_state, $langcode) {
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');
390
if (language_default('language') == $langcode) {
391
drupal_set_message(t('The default language cannot be deleted.'));
392
drupal_goto('admin/settings/language');
395
// For other languages, warn user that data loss is ahead.
396
$languages = language_list();
398
if (!isset($languages[$langcode])) {
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'));
408
* Process language deletion submissions.
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);
426
// Changing the language settings impacts the interface:
427
cache_clear_all('*', 'cache_page', TRUE);
429
$form_state['redirect'] = 'admin/settings/language';
433
* @} End of "locale-language-add-edit"
437
* @defgroup locale-languages-negotiation Language negotiation options screen
442
* Setting for language negotiation options
444
function locale_languages_configure_form() {
445
$form['language_negotiation'] = array(
446
'#title' => t('Language negotiation'),
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>")
456
$form['submit'] = array(
458
'#value' => t('Save settings')
464
* Submit function for language negotiation settings.
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';
473
* @} End of "locale-languages-negotiation"
477
* @defgroup locale-translate-overview Translation overview screen.
482
* Overview screen for translations.
484
function locale_translate_overview_screen() {
485
$languages = language_list('language', TRUE);
486
$groups = module_invoke_all('locale', 'groups');
488
// Build headers with all groups in order.
489
$headers = array_merge(array(t('Language')), array_values($groups));
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;
498
// Set up overview table with default values, ensuring common order for values.
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%)');
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%)";
514
return theme('table', $headers, $rows);
517
* @} End of "locale-translate-overview"
521
* @defgroup locale-translate-seek Translation search screen.
526
* String search screen.
528
function locale_translate_seek_screen() {
529
$output = _locale_translate_seek();
530
$output .= drupal_get_form('locale_translate_seek_form');
535
* User interface for the string search screen.
537
function locale_translate_seek_form() {
538
// Get all languages, except English
539
$languages = locale_language_list('name', TRUE);
540
unset($languages['en']);
542
// Present edit form preserving previous user settings
543
$query = _locale_translate_seek_query();
545
$form['search'] = array('#type' => 'fieldset',
546
'#title' => t('Search'),
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.'),
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),
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')),
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),
573
$form['search']['submit'] = array('#type' => 'submit', '#value' => t('Search'));
574
$form['#redirect'] = FALSE;
579
* @} End of "locale-translate-seek"
583
* @defgroup locale-translate-import Translation import screen.
588
* User interface for the translation import screen.
590
function locale_translate_import_form() {
591
// Get all languages, except English
592
$names = locale_language_list('name', TRUE);
595
if (!count($names)) {
596
$languages = _locale_prepare_predefined_list();
597
$default = array_shift(array_keys($languages));
601
t('Already added languages') => $names,
602
t('Languages not yet added') => _locale_prepare_predefined_list()
604
$default = array_shift(array_keys($names));
608
$form['import'] = array('#type' => 'fieldset',
609
'#title' => t('Import translation'),
611
$form['import']['file'] = array('#type' => 'file',
612
'#title' => t('Language file'),
614
'#description' => t('A Gettext Portable Object (<em>.po</em>) file.'),
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.'),
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.'),
628
$form['import']['mode'] = array('#type' => 'radios',
629
'#title' => t('Mode'),
630
'#default_value' => LOCALE_IMPORT_KEEP,
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')
636
$form['import']['submit'] = array('#type' => 'submit', '#value' => t('Import'));
637
$form['#attributes']['enctype'] = 'multipart/form-data';
643
* Process the locale import form submission.
645
function locale_translate_import_form_submit($form, &$form_state) {
646
// Ensure we have the file uploaded
647
if ($file = file_save_upload('file')) {
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]))));
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);
666
drupal_set_message(t('File to import not found.'), 'error');
667
return 'admin/build/translate/import';
670
$form_state['redirect'] = 'admin/build/translate';
674
* @} End of "locale-translate-import"
678
* @defgroup locale-translate-export Translation export screen.
683
* User interface for the translation export screen.
685
function locale_translate_export_screen() {
686
// Get all languages, except English
687
$names = locale_language_list('name', TRUE);
690
// Offer translation export if any language is set up.
692
$output = drupal_get_form('locale_translate_export_po_form', $names);
694
$output .= drupal_get_form('locale_translate_export_pot_form');
699
* Form to export PO files for the languages provided.
702
* An associate array with localized language names
704
function locale_translate_export_po_form(&$form_state, $names) {
705
$form['export'] = array('#type' => 'fieldset',
706
'#title' => t('Export translation'),
707
'#collapsible' => TRUE,
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.'),
714
$form['export']['group'] = array('#type' => 'radios',
715
'#title' => t('Text group'),
716
'#default_value' => 'default',
717
'#options' => module_invoke_all('locale', 'groups'),
719
$form['export']['submit'] = array('#type' => 'submit', '#value' => t('Export'));
724
* Translation template export form.
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.'),
733
$form['export']['group'] = array('#type' => 'radios',
734
'#title' => t('Text group'),
735
'#default_value' => 'default',
736
'#options' => module_invoke_all('locale', 'groups'),
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';
746
* Process a translation (or template) export form submission.
748
function locale_translate_export_po_form_submit($form, &$form_state) {
749
// If template is required, language code is not given.
751
if (isset($form_state['values']['langcode'])) {
752
$languages = language_list();
753
$language = $languages[$form_state['values']['langcode']];
755
_locale_export_po($language, _locale_export_po_generate($language, _locale_export_get_strings($language, $form_state['values']['group'])));
758
* @} End of "locale-translate-export"
762
* @defgroup locale-translate-edit Translation text editing
767
* User interface for string editing.
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));
773
drupal_set_message(t('String not found.'), 'error');
774
drupal_goto('admin/build/translate/search');
777
// Add original text to the top and some values for form altering.
781
'#title' => t('Original text'),
782
'#value' => check_plain(wordwrap($source->source, 0)),
788
'textgroup' => array(
790
'#value' => $source->textgroup,
794
'#value' => $source->location
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),
813
'#default_value' => '',
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;
823
$form['submit'] = array('#type' => 'submit', '#value' => t('Save translations'));
828
* Process string editing form submissions.
829
* Saves all translations of one string submitted from a form.
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);
841
db_query("INSERT INTO {locales_target} (lid, translation, language) VALUES (%d, '%s', '%s')", $lid, $value, $key);
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);
849
// Force JavaScript translation file recreation for this language.
850
_locale_invalidate_js($key);
853
drupal_set_message(t('The string has been saved.'));
855
// Clear locale cache.
856
_locale_invalidate_js();
857
cache_clear_all('locale:', 'cache', TRUE);
859
$form_state['redirect'] = 'admin/build/translate/search';
863
* @} End of "locale-translate-edit"
867
* @defgroup locale-translate-delete Translation delete interface.
872
* String deletion confirmation page.
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);
879
return drupal_not_found();
884
* User interface for the string deletion confirmation screen.
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'));
892
* Process string deletion submissions.
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';
904
* @} End of "locale-translate-delete"
908
* @defgroup locale-api-add Language addition API.
913
* API function to add a language.
918
* English name of the language
920
* Native name of the language
922
* LANGUAGE_LTR or LANGUAGE_RTL
924
* Optional custom domain name with protocol, without
925
* trailing slash (eg. http://de.example.com).
927
* Optional path prefix for the language. Defaults to the
928
* language code if omitted.
930
* Optionally TRUE to enable the language when created or FALSE to disable.
932
* Optionally set this language to be the default.
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)) {
940
// If name was not set, we add a predefined language.
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;
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);
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' => ''));
956
// Increment enabled language count if we are adding an enabled language.
957
variable_set('language_count', variable_get('language_count', 1) + 1);
960
// Force JavaScript translation file creation for the newly added language.
961
_locale_invalidate_js($langcode);
963
watchdog('locale', 'The %language language (%code) has been created.', array('%language' => $name, '%code' => $langcode));
966
* @} End of "locale-api-add"
970
* @defgroup locale-api-import Translation import API.
975
* Parses Gettext Portable Object file information and inserts into database
978
* Drupal file object corresponding to the PO file to import
982
* Should existing translations be replaced LOCALE_IMPORT_KEEP or LOCALE_IMPORT_OVERWRITE
984
* Text group to import PO file into (eg. 'default' for interface translations)
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')) {
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');
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().
1005
// Get status information on import process.
1006
list($headerdone, $additions, $updates, $deletes) = _locale_import_one_string('db-report');
1009
drupal_set_message(t('The translation file %filename appears to have a missing or malformed header.', array('%filename' => $file->filename)), 'error');
1012
// Clear cache and force refresh of JavaScript translations.
1013
_locale_invalidate_js($langcode);
1014
cache_clear_all('locale:', 'cache', TRUE);
1016
// Rebuild the menu, strings may have changed.
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));
1025
* Parses Gettext Portable Object file into an array
1028
* Storage operation type: db-store or mem-store
1030
* Drupal file object corresponding to the PO file to import
1032
* Should existing translations be replaced LOCALE_IMPORT_KEEP or LOCALE_IMPORT_OVERWRITE
1036
* Text group to import PO file into (eg. 'default' for interface translations)
1038
function _locale_import_read_po($op, $file, $mode = NULL, $lang = NULL, $group = 'default') {
1040
$fd = fopen($file->filepath, "rb"); // File will get closed by PHP on return
1042
_locale_import_message('The translation import failed, because the file %filename could not be read.', $file);
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
1051
while (!feof($fd)) {
1052
$line = fgets($fd, 10*1024); // A line should not be this long
1054
// The first line might come with a UTF-8 BOM, which should be removed.
1055
$line = str_replace("\xEF\xBB\xBF", '', $line);
1058
$line = trim(strtr($line, array("\\\n" => "")));
1060
if (!strncmp("#", $line, 1)) { // A comment
1061
if ($context == "COMMENT") { // Already in comment context: add
1062
$current["#"][] = substr($line, 1);
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);
1067
$current["#"][] = substr($line, 1);
1068
$context = "COMMENT";
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);
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);
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);
1086
$current["msgid"] = $current["msgid"] ."\0". $quoted;
1087
$context = "MSGID_PLURAL";
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);
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);
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);
1104
$current["msgid"] = $quoted;
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);
1112
if (strpos($line, "]") === FALSE) {
1113
_locale_import_message('The translation file %filename contains a syntax error on line %line.', $file, $lineno);
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);
1124
$current["msgstr"][$plural] = $quoted;
1125
$context = "MSGSTR_ARR";
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);
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);
1138
$current["msgstr"] = $quoted;
1139
$context = "MSGSTR";
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);
1147
if (($context == "MSGID") || ($context == "MSGID_PLURAL")) {
1148
$current["msgid"] .= $quoted;
1150
elseif ($context == "MSGSTR") {
1151
$current["msgstr"] .= $quoted;
1153
elseif ($context == "MSGSTR_ARR") {
1154
$current["msgstr"][$plural] .= $quoted;
1157
_locale_import_message('The translation file %filename contains an error: there is an unexpected string on line %line.', $file, $lineno);
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);
1167
elseif ($context != "COMMENT") {
1168
_locale_import_message('The translation file %filename ended unexpectedly at line %line.', $file, $lineno);
1175
* Sets an error message occurred during locale file parsing.
1178
* The message to be translated
1180
* Drupal file object corresponding to the PO file to import
1182
* An optional line number argument
1184
function _locale_import_message($message, $file, $lineno = NULL) {
1185
$vars = array('%filename' => $file->filename);
1186
if (isset($lineno)) {
1187
$vars['%line'] = $lineno;
1190
drupal_set_message($t($message, $vars), 'error');
1194
* Imports a string into the database
1197
* Operation to perform: 'db-store', 'db-report', 'mem-store' or 'mem-report'
1199
* Details of the string stored
1201
* Should existing translations be replaced LOCALE_IMPORT_KEEP or LOCALE_IMPORT_OVERWRITE
1203
* Language to store the string in
1205
* Object representation of file being imported, only required when op is 'db-store'
1207
* Text group to import PO file into (eg. 'default' for interface translations)
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();
1215
// Return stored strings
1219
// Store string in memory (only supports single strings)
1221
$strings[$value['msgid']] = $value['msgstr'];
1224
// Called at end of import to inform the user
1226
return array($headerdone, $report[0], $report[1], $report[2]);
1228
// Store the string we got in the database.
1230
// We got header information.
1231
if ($value['msgid'] == '') {
1232
$header = _locale_import_parse_header($value['msgstr']);
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);
1240
db_query("UPDATE {languages} SET plurals = %d, formula = '%s' WHERE language = '%s'", 0, '', $lang);
1246
// Some real string to import.
1247
$comments = _locale_import_shorten_comments(empty($value['#']) ? array() : $value['#']);
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];
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) {
1262
$plid = _locale_import_one_string_db($report, $lang, $english[$key], $trans, $group, $comments, $mode, $plid, $key);
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);
1273
} // end of db-store operation
1277
* Import one string into the database.
1280
* Report array summarizing the number of changes done in the form:
1281
* array(inserts, updates, deletes).
1283
* Language code to import string into.
1286
* @param $translation
1287
* Translation to language specified in $langcode.
1289
* Name of textgroup to store translation in.
1291
* Location value to save with source string.
1293
* Import mode to use, LOCALE_IMPORT_KEEP or LOCALE_IMPORT_OVERWRITE.
1295
* Optional plural ID to use.
1297
* Optional plural value to use.
1299
* The string ID of the existing string modified or the new string added.
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));
1304
if (!empty($translation)) {
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));
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);
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);
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);
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);
1338
* Parses a Gettext Portable Object file header
1341
* A string containing the complete header
1343
* An associative array of key-value pairs
1345
function _locale_import_parse_header($header) {
1346
$header_parsed = array();
1347
$lines = array_map('trim', explode("\n", $header));
1348
foreach ($lines as $line) {
1350
list($tag, $contents) = explode(":", $line, 2);
1351
$header_parsed[trim($tag)] = trim($contents);
1354
return $header_parsed;
1358
* Parses a Plural-Forms entry from a Gettext Portable Object file header
1360
* @param $pluralforms
1361
* A string containing the Plural-Forms entry
1363
* A string containing the filename
1365
* An array containing the number of plurals and a
1366
* formula in PHP for computing the plural form
1368
function _locale_import_parse_plural_forms($pluralforms, $filename) {
1369
// First, delete all whitespace
1370
$pluralforms = strtr($pluralforms, array(" " => "", "\t" => ""));
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);
1380
$plural = strstr($pluralforms, "plural=");
1381
if (strpos($plural, ";")) {
1382
$plural = substr($plural, 7, strpos($plural, ";") - 7);
1388
// Get PHP version of the plural formula
1389
$plural = _locale_import_parse_arithmetic($plural);
1391
if ($plural !== FALSE) {
1392
return array($nplurals, $plural);
1395
drupal_set_message(t('The translation file %filename contains an error: the plural formula could not be parsed.', array('%filename' => $filename)), 'error');
1401
* Parses and sanitizes an arithmetic formula into a PHP expression
1403
* While parsing, we ensure, that the operators have the right
1404
* precedence and associativity.
1407
* A string containing the arithmetic formula
1409
* The PHP version of the formula
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);
1417
$tokens = _locale_import_tokenize_formula($string);
1419
// Parse by converting into infix notation then back into postfix
1423
foreach ($tokens as $token) {
1426
// Numbers and the $n variable are simply pushed into $elarr
1427
if (is_numeric($token)) {
1430
elseif ($ctok == "n") {
1433
elseif ($ctok == "(") {
1436
elseif ($ctok == ")") {
1437
$topop = array_pop($opstk);
1438
while (isset($topop) && ($topop != "(")) {
1440
$topop = array_pop($opstk);
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]))) {
1449
$topop = array_pop($opstk);
1452
$opstk[] = $topop; // Return element to top
1454
$opstk[] = $ctok; // Parentheses are not needed
1461
// Flush operator stack
1462
$topop = array_pop($opstk);
1463
while ($topop != NULL) {
1465
$topop = array_pop($opstk);
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++) {
1474
if (!empty($prec[$op])) {
1477
$f = $elstk[$i - 2] ."):". $elstk[$i - 1] .")";
1479
elseif ($op == "?") {
1480
$f = "(". $elstk[$i - 2] ."?(". $elstk[$i - 1];
1483
$f = "(". $elstk[$i - 2] . $op . $elstk[$i - 1] .")";
1485
array_splice($elstk, $i - 2, 3, $f);
1491
// If only one element is left, the number of operators is appropriate
1492
if (count($elstk) == 1) {
1501
* Backward compatible implementation of token_get_all() for formula parsing
1504
* A string containing the arithmetic formula
1506
* The PHP version of the formula
1508
function _locale_import_tokenize_formula($formula) {
1509
$formula = str_replace(" ", "", $formula);
1511
for ($i = 0; $i < strlen($formula); $i++) {
1512
if (is_numeric($formula[$i])) {
1513
$num = $formula[$i];
1515
while ($j < strlen($formula) && is_numeric($formula[$j])) {
1516
$num .= $formula[$j];
1522
elseif ($pos = strpos(" =<>!&|", $formula[$i])) { // We won't have a space
1523
$next = $formula[$i + 1];
1530
$tokens[] = $formula[$i] .'=';
1534
$tokens[] = $formula[$i];
1543
$tokens[] = $formula[$i];
1552
$tokens[] = $formula[$i];
1558
$tokens[] = $formula[$i];
1565
* Modify a string to contain proper count indices
1567
* This is a callback function used via array_map()
1572
* Index of the array element
1574
function _locale_import_append_plural($entry, $key) {
1575
// No modifications for 0, 1
1576
if ($key == 0 || $key == 1) {
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);
1586
* Generate a short, one string version of the passed comment array
1589
* An array of strings containing a comment
1591
* Short one string version of the comment
1593
function _locale_import_shorten_comments($comment) {
1595
while (count($comment)) {
1596
$test = $comm . substr(array_shift($comment), 1) .', ';
1597
if (strlen($comm) < 130) {
1604
return substr($comm, 0, -2);
1608
* Parses a string in quotes
1611
* A string specified with enclosing quotes
1613
* The string parsed from inside the quotes
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
1619
$quote = substr($string, 0, 1);
1620
$string = substr($string, 1, -1);
1621
if ($quote == '"') { // Double quotes: strip slashes
1622
return stripcslashes($string);
1624
elseif ($quote == "'") { // Simple quote: return as-is
1628
return FALSE; // Unrecognized quote
1632
* @} End of "locale-api-import"
1636
* Parses a JavaScript file, extracts strings wrapped in Drupal.t() and
1637
* Drupal.formatPlural() and inserts them into the database.
1639
function _locale_parse_js_file($filepath) {
1642
// Load the JavaScript file.
1643
$file = file_get_contents($filepath);
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);
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);
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);
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];
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)));
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);
1672
if (!in_array($filepath, $locations)) {
1673
$locations[] = $filepath;
1674
$locations = implode('; ', $locations);
1676
// Save the new locations string to the database.
1677
db_query("UPDATE {locales_source} SET location = '%s' WHERE lid = %d", $locations, $source->lid);
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);
1689
* @defgroup locale-api-export Translation (template) export API.
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.
1699
* Language object to generate the output for, or NULL if generating
1700
* translation template.
1702
* Text group to export PO file from (eg. 'default' for interface translations)
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);
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);
1712
while ($child = db_fetch_object($result)) {
1714
'comment' => $child->location,
1715
'source' => $child->source,
1716
'translation' => isset($child->translation) ? $child->translation : ''
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
1723
$string['child'] = TRUE;
1724
$strings[$child->plid]['plural'] = $child->lid;
1726
$strings[$child->lid] = $string;
1732
* Generates the PO(T) file contents for given strings.
1735
* Language object to generate the output for, or NULL if generating
1736
* translation template.
1738
* Array of strings to export. See _locale_export_get_strings()
1739
* on how it should be formatted.
1741
* The header portion to use for the output file. Defaults
1742
* are provided for PO and POT files.
1744
function _locale_export_po_generate($language = NULL, $strings = array(), $header = NULL) {
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";
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";
1767
$header = "# LANGUAGE translation of PROJECT\n";
1768
$header .= "# Copyright (c) YEAR NAME <EMAIL@ADDRESS>\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";
1784
$output = $header ."\n";
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";
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);
1801
$translation = _locale_export_remove_plural($strings[$plural]['translation']);
1802
$plural = isset($strings[$plural]['plural']) ? $strings[$plural]['plural'] : 0;
1810
$output .= 'msgstr[0] ""'."\n";
1811
$output .= 'msgstr[1] ""'."\n";
1815
$output .= 'msgstr '. _locale_export_string($string['translation']);
1824
* Write a generated PO or POT file to the output.
1827
* Language object to generate the output for, or NULL if generating
1828
* translation template.
1830
* The PO(T) file to output as a string. See _locale_export_generate_po()
1831
* on how it can be generated.
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));
1840
$filename = 'drupal.pot';
1841
watchdog('locale', 'Exported translation file: %filename.', array('%filename' => $filename));
1843
// Download the file fo the client.
1844
header("Content-Disposition: attachment; filename=$filename");
1845
header("Content-Type: text/plain; charset=utf-8");
1851
* Print out a string on multiple lines
1853
function _locale_export_string($str) {
1854
$stri = addcslashes($str, "\0..\37\\\"");
1857
// Cut text into several lines
1858
while ($stri != "") {
1859
$i = strpos($stri, "\\n");
1865
$curstr = substr($stri, 0, $i + 2);
1866
$stri = substr($stri, $i + 2);
1868
$curparts = explode("\n", _locale_export_wrap($curstr, 70));
1869
$parts = array_merge($parts, $curparts);
1873
if (count($parts) > 1) {
1874
return "\"\"\n\"". implode("\"\n\"", $parts) ."\"\n";
1876
// Single line string
1877
elseif (count($parts) == 1) {
1878
return "\"$parts[0]\"\n";
1887
* Custom word wrapping for Portable Object (Template) files.
1889
function _locale_export_wrap($str, $len) {
1890
$words = explode(' ', $str);
1895
while (count($words)) {
1896
$word = array_shift($words);
1901
elseif (strlen("$cur $word") > $len) {
1906
$cur = "$cur $word";
1911
return implode("\n", $ret);
1915
* Removes plural index information from a string
1917
function _locale_export_remove_plural($entry) {
1918
return preg_replace('/(@count)\[[0-9]\]/', '\\1', $entry);
1921
* @} End of "locale-api-export"
1925
* @defgroup locale-api-seek String search functions.
1930
* Perform a string search and display results in a table
1932
function _locale_translate_seek() {
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 ";
1939
$arguments = array();
1940
$limit_language = FALSE;
1941
// Compute LIKE section
1942
switch ($query['translation']) {
1944
$where = "WHERE (t.translation LIKE '%%%s%%')";
1945
$orderby = "ORDER BY t.translation";
1946
$arguments[] = $query['string'];
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'];
1955
$where = "WHERE (s.source LIKE '%%%s%%' OR t.translation LIKE '%%%s%%')";
1957
$arguments[] = $query['string'];
1958
$arguments[] = $query['string'];
1962
if (!empty($query['group']) && $query['group'] != 'all') {
1963
$grouplimit = " AND s.textgroup = '%s'";
1964
$arguments[] = $query['group'];
1967
switch ($query['language']) {
1968
// Force search in source strings
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'];
1976
// Search in all languages
1978
$sql = "$join $where $grouplimit $orderby";
1980
// Some different language
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'];
1988
$result = pager_query($sql, 50, 0, NULL, $arguments);
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'));
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;
2000
foreach ($arr as $lid => $value) {
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'),
2011
$output .= theme('table', $header, $rows);
2012
if ($pager = theme('pager', NULL, 50)) {
2017
$output .= t('No strings found for your search.');
2025
* Build array out of search criteria specified in request variables
2027
function _locale_translate_seek_query() {
2028
static $query = NULL;
2029
if (!isset($query)) {
2031
$fields = array('string', 'language', 'translation', 'group');
2032
foreach ($fields as $field) {
2033
if (isset($_REQUEST[$field])) {
2034
$query[$field] = $_REQUEST[$field];
2042
* Force the JavaScript translation file(s) to be refreshed.
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.
2050
* The language code for which the file needs to be refreshed.
2052
* New content of the 'javascript_parsed' variable.
2054
function _locale_invalidate_js($langcode = NULL) {
2055
$parsed = variable_get('javascript_parsed', array());
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';
2066
// Invalidate single language.
2067
$parsed['refresh:'. $langcode] = 'waiting';
2070
variable_set('javascript_parsed', $parsed);
2075
* (Re-)Creates the JavaScript translation file for a language.
2078
* The language, the translation file should be (re)created for.
2080
function _locale_rebuild_js($langcode = NULL) {
2081
if (!isset($langcode)) {
2085
// Get information about the locale.
2086
$languages = language_list();
2087
$language = $languages[$langcode];
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);
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);
2105
$plurals[$data->plid] += array($data->plural => $data->translation);
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]);
2115
// There are no plural forms for this translation, so just add it to
2116
// the translations array.
2117
$translations[$data->source] = $data->translation;
2122
// Construct the JavaScript file, if there are translations.
2123
$data = $status = '';
2124
if (!empty($translations)) {
2126
$data = "Drupal.locale = { ";
2128
if (!empty($language->formula)) {
2129
$data .= "'pluralFormula': function(\$n) { return Number({$language->formula}); }, ";
2132
$data .= "'strings': ". drupal_to_js($translations) ." };";
2133
$data_hash = md5($data);
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'));
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';
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);
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';
2159
$language->javascript = '';
2164
// Save the new JavaScript hash (or an empty value if the file
2165
// just got deleted). Act only if some operation was executed.
2167
db_query("UPDATE {languages} SET javascript = '%s' WHERE language = '%s'", $language->javascript, $language->language);
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);
2179
// Log the operation and return success flag.
2182
watchdog('locale', 'Updated JavaScript translation file for the language %language.', array('%language' => t($language->name)));
2185
watchdog('locale', 'Created JavaScript translation file for the language %language.', array('%language' => t($language->name)));
2188
watchdog('locale', 'Removed JavaScript translation file for the language %language, because no translations currently exist for that language.', array('%language' => t($language->name)));
2191
watchdog('locale', 'An error occurred during creation of the JavaScript translation file for the language %language.', array('%language' => t($language->name)), WATCHDOG_ERROR);
2194
// No operation needed.
2200
* List languages in search result table
2202
function _locale_translate_language_list($translation, $limit_language) {
2204
drupal_add_css(drupal_get_path('module', 'locale') .'/locale.css', 'module', 'all', FALSE);
2206
$languages = language_list();
2207
unset($languages['en']);
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> ";
2218
* @} End of "locale-api-seek"
2222
* @defgroup locale-api-predefined List of predefined languages
2227
* Prepares the language code list for a select form item with only the unsupported ones
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]);
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])";
2243
$predefined[$key] = t($value[0]);
2251
* Some of the common languages with their English and native names
2253
* Based on ISO 639 and http://people.w3.org/rishida/names/languages.html
2255
function _locale_get_predefined_list() {
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"),
2438
* @} End of "locale-api-languages-predefined"
2442
* @defgroup locale-autoimport Automatic interface translation import
2447
* Prepare a batch to import translations for all enabled
2448
* modules in a given language.
2451
* Language code to import translations for.
2453
* Optional finished callback for the batch.
2455
* Array of component names to skip. Used in the installer for the
2456
* second pass import, when most components are already imported.
2458
* A batch structure or FALSE if no files found.
2460
function locale_batch_by_language($langcode, $finished = NULL, $skip = array()) {
2461
// Collect all files to import for all enabled modules and themes.
2463
$components = array();
2464
$query = "SELECT name, filename FROM {system} WHERE status = 1";
2466
$query .= " AND name NOT IN (". db_placeholders($skip, 'varchar') .")";
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;
2478
return _locale_batch_build($files, $finished, $components);
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.
2486
* @param $components
2487
* An array of component (theme and/or module) names to import
2490
* Optional finished callback for the batch.
2492
function locale_batch_by_component($components, $finished = '_locale_batch_system_finished') {
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));
2509
return _locale_batch_build($files, $finished);
2515
* Build a locale batch from an array of files.
2518
* Array of files to import
2520
* Optional finished callback for the batch.
2521
* @param $components
2522
* Optional list of component names the batch covers. Used in the installer.
2526
function _locale_batch_build($files, $finished = NULL, $components = array()) {
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)); }
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,
2543
if (isset($finished)) {
2544
$batch['finished'] = $finished;
2552
* Perform interface translation import as a batch step.
2555
* Path to a file to import.
2557
* Contains a list of files imported.
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;
2570
* Finished callback of system page locale import batch.
2571
* Inform the user of translation files imported.
2573
function _locale_batch_system_finished($success, $results) {
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.'));
2580
* Finished callback of language addition locale import batch.
2581
* Inform the user of translation files imported.
2583
function _locale_batch_language_finished($success, $results) {
2585
drupal_set_message(format_plural(count($results), 'One translation file imported for the enabled modules.', '@count translation files imported for the enabled modules.'));
2590
* @} End of "locale-autoimport"