initial import from onelab svn codebase
[plewww.git] / includes / locale.inc
1 <?php
2 // $Id: locale.inc 144 2007-03-28 07:52:20Z thierry $
3
4 /**
5  * @file
6  * Admin-related functions for locale.module.
7  */
8
9 // ---------------------------------------------------------------------------------
10 // Language addition functionality (administration only)
11
12 /**
13  * Helper function to add a language
14  */
15 function _locale_add_language($code, $name, $onlylanguage = TRUE) {
16   db_query("INSERT INTO {locales_meta} (locale, name) VALUES ('%s','%s')", $code, $name);
17   $result = db_query("SELECT lid FROM {locales_source}");
18   while ($string = db_fetch_object($result)) {
19     db_query("INSERT INTO {locales_target} (lid, locale, translation) VALUES (%d,'%s', '')", $string->lid, $code);
20   }
21
22   // If only the language was added, and not a PO file import triggered
23   // the language addition, we need to inform the user on how to start
24   // a translation
25   if ($onlylanguage) {
26     drupal_set_message(t('The language %locale has been created, and can now be used to import a translation. More information is available in the <a href="%locale-help">help screen</a>.', array('%locale' => theme('placeholder', t($name)), '%locale-help' => url('admin/help/locale'))));
27   }
28   else {
29     drupal_set_message(t('The language %locale has been created.', array('%locale' => theme('placeholder', t($name)))));
30   }
31
32   watchdog('locale', t('The %language language (%locale) has been created.', array('%language' => theme('placeholder', $name), '%locale' => theme('placeholder', $code))));
33 }
34
35 /**
36  * User interface for the language management screen.
37  */
38 function _locale_admin_manage_screen() {
39   $languages = locale_supported_languages(TRUE, TRUE);
40
41   $options = array();
42   $form['name'] = array('#tree' => TRUE);
43   foreach ($languages['name'] as $key => $lang) {
44     $options[$key] = '';
45     $status = db_fetch_object(db_query("SELECT isdefault, enabled FROM {locales_meta} WHERE locale = '%s'", $key));
46     if ($status->enabled) {
47       $enabled[] = $key;
48     }
49     if ($status->isdefault) {
50       $isdefault = $key;
51     }
52     if ($key == 'en') {
53       $form['name']['en'] = array('#value' => check_plain($lang));
54     }
55     else {
56       $original = db_fetch_object(db_query("SELECT COUNT(*) AS strings FROM {locales_source}"));
57       $translation = db_fetch_object(db_query("SELECT COUNT(*) AS translation FROM {locales_target} WHERE locale = '%s' AND translation != ''", $key));
58
59       $ratio = ($original->strings > 0 && $translation->translation > 0) ? round(($translation->translation/$original->strings)*100., 2) : 0;
60
61       $form['name'][$key] = array('#type' => 'textfield',
62         '#default_value' => $lang,
63         '#size' => 15,
64         '#maxlength' => 64,
65       );
66       $form['translation'][$key] = array('#value' => "$translation->translation/$original->strings ($ratio%)");
67     }
68   }
69   $form['enabled'] = array('#type' => 'checkboxes',
70     '#options' => $options,
71     '#default_value' => $enabled,
72   );
73   $form['site_default'] = array('#type' => 'radios',
74     '#options' => $options,
75     '#default_value' => $isdefault,
76   );
77   $form['submit'] = array('#type' => 'submit', '#value' => t('Save configuration'));
78
79   return drupal_get_form('_locale_admin_manage_screen', $form, 'locale_admin_manage_screen');
80 }
81
82 /**
83  * Theme the locale admin manager form.
84  */
85 function theme_locale_admin_manage_screen($form) {
86   foreach ($form['name'] as $key => $element) {
87     // Do not take form control structures.
88     if (is_array($element) && element_child($key)) {
89       $rows[] = array(check_plain($key), form_render($form['name'][$key]), form_render($form['enabled'][$key]), form_render($form['site_default'][$key]), ($key != 'en' ? form_render($form['translation'][$key]) : message_na()), ($key != 'en' ? l(t('delete'), 'admin/locale/language/delete/'. $key) : ''));
90     }
91   }
92   $header = array(array('data' => t('Code')), array('data' => t('English name')), array('data' => t('Enabled')), array('data' => t('Default')), array('data' => t('Translated')), array('data' => t('Operations')));
93   $output = theme('table', $header, $rows);
94   $output .= form_render($form);
95
96   return $output;
97 }
98
99 /**
100  * Process locale admin manager form submissions.
101  */
102 function _locale_admin_manage_screen_submit($form_id, $form_values) {
103   // Save changes to existing languages.
104   $languages = locale_supported_languages(FALSE, TRUE);
105   foreach($languages['name'] as $key => $value) {
106     if ($form_values['site_default'] == $key) {
107       $form_values['enabled'][$key] = 1; // autoenable the default language
108     }
109     $enabled = $form_values['enabled'][$key] ? 1 : 0;
110     if ($key == 'en') {
111       // Disallow name change for English locale.
112       db_query("UPDATE {locales_meta} SET isdefault = %d, enabled = %d WHERE locale = 'en'", ($form_values['site_default'] == $key), $enabled);
113     }
114     else {
115       db_query("UPDATE {locales_meta} SET name = '%s', isdefault = %d, enabled = %d WHERE locale = '%s'", $form_values['name'][$key], ($form_values['site_default'] == $key), $enabled, $key);
116     }
117   }
118   drupal_set_message(t('Configuration saved.'));
119
120   // Changing the locale settings impacts the interface:
121   cache_clear_all();
122
123   return 'admin/locale/language/overview';
124 }
125
126 /**
127  * User interface for the language addition screen.
128  */
129 function _locale_admin_manage_add_screen() {
130   $isocodes = _locale_prepare_iso_list();
131
132   $form = array();
133   $form['language list'] = array('#type' => 'fieldset',
134     '#title' => t('Language list'),
135     '#collapsible' => TRUE,
136   );
137   $form['language list']['langcode'] = array('#type' => 'select',
138     '#title' => t('Language name'),
139     '#default_value' => key($isocodes),
140     '#options' => $isocodes,
141     '#description' => t('Select your language here, or add it below, if you are unable to find it.'),
142   );
143   $form['language list']['submit'] = array('#type' => 'submit', '#value' => t('Add language'));
144
145   $output = drupal_get_form('locale_add_language_form', $form);
146
147   $form = array();
148   $form['custom language'] = array('#type' => 'fieldset',
149     '#title' => t('Custom language'),
150     '#collapsible' => TRUE,
151   );
152   $form['custom language']['langcode'] = array('#type' => 'textfield',
153     '#title' => t('Language code'),
154     '#size' => 12,
155     '#maxlength' => 60,
156     '#required' => TRUE,
157     '#description' => t("Commonly this is an <a href=\"%iso-codes\">ISO 639 language code</a> with an optional country code for regional variants. Examples include 'en', 'en-US' and 'zh-cn'.", array('%iso-codes' => 'http://www.w3.org/WAI/ER/IG/ert/iso639.htm')),
158   );
159   $form['custom language']['langname'] = array('#type' => 'textfield',
160     '#title' => t('Language name in English'),
161     '#maxlength' => 64,
162     '#required' => TRUE,
163     '#description' => t('Name of the language. Will be available for translation in all languages.'),
164   );
165   $form['custom language']['submit'] = array('#type' => 'submit', '#value' => t('Add custom language'));
166
167   // Use the validation and submit functions of the add language form.
168   $output .= drupal_get_form('locale_custom_language_form', $form, 'locale_add_language_form');
169
170   return $output;
171 }
172
173 /**
174  * Validate the language addition form.
175  */
176 function locale_add_language_form_validate($form_id, $form_values) {
177   if ($duplicate = db_num_rows(db_query("SELECT locale FROM {locales_meta} WHERE locale = '%s'", $form_values['langcode'])) != 0) {
178     form_set_error(t('The language %language (%code) already exists.', array('%language' => theme('placeholder', check_plain($form_values['langname'])), '%code' => theme('placeholder', $form_values['langcode']))));
179   }
180
181   if (!isset($form_values['langname'])) {
182     $isocodes = _locale_get_iso639_list();
183     if (!isset($isocodes[$form_values['langcode']])) {
184       form_set_error('langcode', t('Invalid language code.'));
185     }
186   }
187 }
188
189 /**
190  * Process the language addition form submission.
191  */
192 function locale_add_language_form_submit($form_id, $form_values) {
193   if (isset($form_values['langname'])) {
194     // Custom language form.
195     _locale_add_language($form_values['langcode'], $form_values['langname']);
196   }
197   else {
198     $isocodes = _locale_get_iso639_list();
199     _locale_add_language($form_values['langcode'], $isocodes[$form_values['langcode']][0]);
200   }
201
202   return 'admin/locale';
203 }
204
205 /**
206  * User interface for the translation import screen.
207  */
208 function _locale_admin_import_screen() {
209   $languages = locale_supported_languages(FALSE, TRUE);
210   $languages = array_map('t', $languages['name']);
211   unset($languages['en']);
212
213   if (!count($languages)) {
214     $languages = _locale_prepare_iso_list();
215   }
216   else {
217     $languages = array(
218       t('Already added languages') => $languages,
219       t('Languages not yet added') => _locale_prepare_iso_list()
220     );
221   }
222
223   $form = array();
224   $form['import'] = array('#type' => 'fieldset',
225     '#title' => t('Import translation'),
226   );
227   $form['import']['file'] = array('#type' => 'file',
228     '#title' => t('Language file'),
229     '#size' => 50,
230     '#description' => t('A gettext Portable Object (.po) file.'),
231   );
232   $form['import']['langcode'] = array('#type' => 'select',
233     '#title' => t('Import into'),
234     '#options' => $languages,
235     '#description' => t('Choose the language you want to add strings into. If you choose a language which is not yet set up, then it will be added.'),
236   );
237   $form['import']['mode'] = array('#type' => 'radios',
238     '#title' => t('Mode'),
239     '#default_value' => 'overwrite',
240     '#options' => array('overwrite' => t('Strings in the uploaded file replace existing ones, new ones are added'), 'keep' => t('Existing strings are kept, only new strings are added')),
241   );
242   $form['import']['submit'] = array('#type' => 'submit', '#value' => t('Import'));
243   $form['#attributes']['enctype'] = 'multipart/form-data';
244
245   return drupal_get_form('_locale_admin_import', $form);
246 }
247
248 /**
249  * Process the locale import form submission.
250  */
251 function _locale_admin_import_submit($form_id, $form_values) {
252   // Add language, if not yet supported
253   $languages = locale_supported_languages(TRUE, TRUE);
254   if (!isset($languages['name'][$form_values['langcode']])) {
255     $isocodes = _locale_get_iso639_list();
256     _locale_add_language($form_values['langcode'], $isocodes[$form_values['langcode']][0], FALSE);
257   }
258
259   // Now import strings into the language
260   $file = file_check_upload('file');
261   if ($ret = _locale_import_po($file, $form_values['langcode'], $form_values['mode']) == FALSE) {
262     $message = t('The translation import of %filename failed.', array('%filename' => theme('placeholder', $file->filename)));
263     drupal_set_message($message, 'error');
264     watchdog('locale', $message, WATCHDOG_ERROR);
265   }
266
267   return 'admin/locale';
268 }
269
270 /**
271  * User interface for the translation export screen
272  */
273 function _locale_admin_export_screen() {
274   $languages = locale_supported_languages(FALSE, TRUE);
275   $languages = array_map('t', $languages['name']);
276   unset($languages['en']);
277
278   // Offer language specific export if any language is set up
279   if (count($languages)) {
280     $form = array();
281     $form['export'] = array('#type' => 'fieldset',
282       '#title' => t('Export translation'),
283       '#collapsible' => TRUE,
284     );
285     $form['export']['langcode'] = array('#type' => 'select',
286       '#title' => t('Language name'),
287       '#options' => $languages,
288       '#description' => t('Select the language you would like to export in gettext Portable Object (.po) format.'),
289     );
290     $form['export']['submit'] = array('#type' => 'submit', '#value' => t('Export'));
291     $output = drupal_get_form('_locale_export_po', $form);
292   }
293
294   // Complete template export of the strings
295   $form = array();
296   $form['export'] = array('#type' => 'fieldset',
297     '#title' => t('Export template'),
298     '#collapsible' => TRUE,
299     '#description' => t('Generate a gettext Portable Object Template (.pot) file with all the interface strings from the Drupal locale database.'),
300   );
301   $form['export']['submit'] = array('#type' => 'submit', '#value' => t('Export'));
302   $output .= drupal_get_form('_locale_export_pot', $form, '_locale_export_po');
303
304   return $output;
305 }
306
307 /**
308  * Process a locale export form submissions.
309  */
310 function _locale_export_po_submit($form_id, $form_values) {
311   _locale_export_po($form_values['langcode']);
312 }
313
314 /**
315  * User interface for the string search screen
316  */
317 function _locale_string_seek_form() {
318   // Get *all* languages set up
319   $languages = locale_supported_languages(FALSE, TRUE);
320   asort($languages['name']); unset($languages['name']['en']);
321   $languages['name'] = array_map('check_plain', $languages['name']);
322
323   // Present edit form preserving previous user settings
324   $query = _locale_string_seek_query();
325   $form = array();
326   $form['search'] = array('#type' => 'fieldset',
327     '#title' => t('Search'),
328   );
329   $form['search']['string'] = array('#type' => 'textfield',
330     '#title' => t('Strings to search for'),
331     '#default_value' => $query->string,
332     '#size' => 30,
333     '#maxlength' => 30,
334     '#description' => t('Leave blank to show all strings. The search is case sensitive.'),
335   );
336   $form['search']['language'] = array('#type' => 'radios',
337     '#title' => t('Language'),
338     '#default_value' => ($query->language ? $query->language : 'all'),
339     '#options' => array_merge(array('all' => t('All languages'), 'en' => t('English (provided by Drupal)')), $languages['name']),
340   );
341   $form['search']['searchin'] = array('#type' => 'radios',
342     '#title' => t('Search in'),
343     '#default_value' => ($query->searchin ? $query->searchin : 'all'),
344     '#options' => array('all' => t('All strings in that language'), 'translated' => t('Only translated strings'), 'untranslated' => t('Only untranslated strings')),
345   );
346   $form['search']['submit'] = array('#type' => 'submit', '#value' => t('Search'));
347   $form['#redirect'] = FALSE;
348
349   return drupal_get_form('_locale_string_seek', $form);
350 }
351
352 /**
353  * User interface for string editing.
354  */
355 function _locale_string_edit($lid) {
356   $languages = locale_supported_languages(FALSE, TRUE);
357   unset($languages['name']['en']);
358
359   $result = db_query('SELECT DISTINCT s.source, t.translation, t.locale FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid WHERE s.lid = %d', $lid);
360   $form = array();
361   $form['translations'] = array('#tree' => TRUE);
362   while ($translation = db_fetch_object($result)) {
363     $orig = $translation->source;
364
365     // Approximate the number of rows in a textfield with a maximum of 10.
366     $rows = min(ceil(str_word_count($orig) / 12), 10);
367
368     $form['translations'][$translation->locale] = array(
369       '#type' => 'textarea',
370       '#title' => $languages['name'][$translation->locale],
371       '#default_value' => $translation->translation,
372       '#rows' => $rows,
373     );
374     unset($languages['name'][$translation->locale]);
375   }
376
377   // Handle erroneous lid.
378   if (!isset($orig)){
379     drupal_set_message(t('String not found.'));
380     drupal_goto('admin/locale/string/search');
381   }
382
383   // Add original text. Assign negative weight so that it floats to the top.
384   $form['item'] = array('#type' => 'item',
385     '#title' => t('Original text'),
386     '#value' => check_plain(wordwrap($orig, 0)),
387     '#weight' => -1,
388   );
389
390   foreach ($languages['name'] as $key => $lang) {
391     $form['translations'][$key] = array(
392       '#type' => 'textarea',
393       '#title' => $lang,
394       '#rows' => $rows,
395     );
396   }
397
398   $form['lid'] = array('#type' => 'value', '#value' => $lid);
399   $form['submit'] = array('#type' => 'submit', '#value' => t('Save translations'));
400
401   return drupal_get_form('_locale_string_edit', $form);
402 }
403
404 /**
405  * Process string editing form submissions.
406  * Saves all translations of one string submitted from a form.
407  */
408 function _locale_string_edit_submit($form_id, $form_values) {
409   $lid = $form_values['lid'];
410   foreach ($form_values['translations'] as $key => $value) {
411     $value = filter_xss_admin($value);
412     $trans = db_fetch_object(db_query("SELECT translation FROM {locales_target} WHERE lid = %d AND locale = '%s'", $lid, $key));
413     if (isset($trans->translation)) {
414       db_query("UPDATE {locales_target} SET translation = '%s' WHERE lid = %d AND locale = '%s'", $value, $lid, $key);
415     }
416     else {
417       db_query("INSERT INTO {locales_target} (lid, translation, locale) VALUES (%d, '%s', '%s')", $lid, $value, $key);
418     }
419   }
420   drupal_set_message(t('The string has been saved.'));
421
422   // Refresh the locale cache.
423   locale_refresh_cache();
424   // Rebuild the menu, strings may have changed.
425   menu_rebuild();
426
427   return 'admin/locale/string/search';
428 }
429
430 /**
431  * Delete a language string.
432  */
433 function _locale_string_delete($lid) {
434   db_query('DELETE FROM {locales_source} WHERE lid = %d', $lid);
435   db_query('DELETE FROM {locales_target} WHERE lid = %d', $lid);
436   locale_refresh_cache();
437   drupal_set_message(t('The string has been removed.'));
438
439   drupal_goto('admin/locale/string/search');
440 }
441
442 /**
443  * Parses Gettext Portable Object file information and inserts into database
444  *
445  * @param $file Object contains properties of local file to be imported
446  * @param $lang Language code
447  * @param $mode should existing translations be replaced?
448  */
449 function _locale_import_po($file, $lang, $mode) {
450   // If not in 'safe mode', increase the maximum execution time:
451   if (!ini_get('safe_mode')) {
452     set_time_limit(240);
453   }
454
455   // Check if we have the language already in the database
456   if (!db_fetch_object(db_query("SELECT locale FROM {locales_meta} WHERE locale = '%s'", $lang))) {
457     drupal_set_message(t('The language selected for import is not supported.'), 'error');
458     return FALSE;
459   }
460
461   // Get strings from file (returns on failure after a partial import, or on success)
462   $status = _locale_import_read_po($file, $mode, $lang);
463   if ($status === FALSE) {
464     // error messages are set in _locale_import_read_po
465     return FALSE;
466   }
467
468   // Get status information on import process
469   list($headerdone, $additions, $updates) = _locale_import_one_string('report', $mode);
470
471   if (!$headerdone) {
472     drupal_set_message(t('The translation file %filename appears to have a missing or malformed header.', array('%filename' => theme('placeholder', $file->filename))), 'error');
473   }
474
475   // rebuild locale cache
476   cache_clear_all("locale:$lang");
477
478   // rebuild the menu, strings may have changed
479   menu_rebuild();
480
481   drupal_set_message(t('The translation was successfully imported. There are %number newly created translated strings and %update strings were updated.', array('%number' => $additions, '%update' => $updates)));
482   watchdog('locale', t('Imported %file into %locale: %number new strings added and %update updated.', array('%file' => theme('placeholder', $file->filename), '%locale' => theme('placeholder', $lang), '%number' => $additions, '%update' => $updates)));
483   return TRUE;
484 }
485
486 /**
487  * Parses Gettext Portable Object file into an array
488  *
489  * @param $file Object with properties of local file to parse
490  * @author Jacobo Tarrio
491  */
492 function _locale_import_read_po($file, $mode, $lang) {
493
494   $message = theme('placeholder', $file->filename);
495   $fd = fopen($file->filepath, "rb"); // File will get closed by PHP on return
496   if (!$fd) {
497     drupal_set_message(t('The translation import failed, because the file %filename could not be read.', array('%filename' => $message)), 'error');
498     return FALSE;
499   }
500
501   $context = "COMMENT"; // Parser context: COMMENT, MSGID, MSGID_PLURAL, MSGSTR and MSGSTR_ARR
502   $current = array();   // Current entry being read
503   $plural = 0;          // Current plural form
504   $lineno = 0;          // Current line
505
506   while (!feof($fd)) {
507     $line = fgets($fd, 10*1024); // A line should not be this long
508     $lineno++;
509     $line = trim(strtr($line, array("\\\n" => "")));
510
511     if (!strncmp("#", $line, 1)) { // A comment
512       if ($context == "COMMENT") { // Already in comment context: add
513         $current["#"][] = substr($line, 1);
514       }
515       elseif (($context == "MSGSTR") || ($context == "MSGSTR_ARR")) { // End current entry, start a new one
516         _locale_import_one_string($current, $mode, $lang);
517         $current = array();
518         $current["#"][] = substr($line, 1);
519         $context = "COMMENT";
520       }
521       else { // Parse error
522         drupal_set_message(t('The translation file %filename contains an error: "msgstr" was expected but not found on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
523         return FALSE;
524       }
525     }
526     elseif (!strncmp("msgid_plural", $line, 12)) {
527       if ($context != "MSGID") { // Must be plural form for current entry
528         drupal_set_message(t('The translation file %filename contains an error: "msgid_plural" was expected but not found on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
529         return FALSE;
530       }
531       $line = trim(substr($line, 12));
532       $quoted = _locale_import_parse_quoted($line);
533       if ($quoted === false) {
534         drupal_set_message(t('The translation file %filename contains a syntax error on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
535         return FALSE;
536       }
537       $current["msgid"] = $current["msgid"] ."\0". $quoted;
538       $context = "MSGID_PLURAL";
539     }
540     elseif (!strncmp("msgid", $line, 5)) {
541       if ($context == "MSGSTR") {   // End current entry, start a new one
542         _locale_import_one_string($current, $mode, $lang);
543         $current = array();
544       }
545       elseif ($context == "MSGID") { // Already in this context? Parse error
546         drupal_set_message(t('The translation file %filename contains an error: "msgid" is unexpected on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
547         return FALSE;
548       }
549       $line = trim(substr($line, 5));
550       $quoted = _locale_import_parse_quoted($line);
551       if ($quoted === false) {
552         drupal_set_message(t('The translation file %filename contains a syntax error on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
553         return FALSE;
554       }
555       $current["msgid"] = $quoted;
556       $context = "MSGID";
557     }
558     elseif (!strncmp("msgstr[", $line, 7)) {
559       if (($context != "MSGID") && ($context != "MSGID_PLURAL") && ($context != "MSGSTR_ARR")) { // Must come after msgid, msgid_plural, or msgstr[]
560         drupal_set_message(t('The translation file %filename contains an error: "msgstr[]" is unexpected on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
561         return FALSE;
562       }
563       if (strpos($line, "]") === false) {
564         drupal_set_message(t('The translation file %filename contains a syntax error on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
565         return FALSE;
566       }
567       $frombracket = strstr($line, "[");
568       $plural = substr($frombracket, 1, strpos($frombracket, "]") - 1);
569       $line = trim(strstr($line, " "));
570       $quoted = _locale_import_parse_quoted($line);
571       if ($quoted === false) {
572         drupal_set_message(t('The translation file %filename contains a syntax error on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
573         return FALSE;
574       }
575       $current["msgstr"][$plural] = $quoted;
576       $context = "MSGSTR_ARR";
577     }
578     elseif (!strncmp("msgstr", $line, 6)) {
579       if ($context != "MSGID") {   // Should come just after a msgid block
580         drupal_set_message(t('The translation file %filename contains an error: "msgstr" is unexpected on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
581         return FALSE;
582       }
583       $line = trim(substr($line, 6));
584       $quoted = _locale_import_parse_quoted($line);
585       if ($quoted === false) {
586         drupal_set_message(t('The translation file %filename contains a syntax error on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
587         return FALSE;
588       }
589       $current["msgstr"] = $quoted;
590       $context = "MSGSTR";
591     }
592     elseif ($line != "") {
593       $quoted = _locale_import_parse_quoted($line);
594       if ($quoted === false) {
595         drupal_set_message(t('The translation file %filename contains a syntax error on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
596         return FALSE;
597       }
598       if (($context == "MSGID") || ($context == "MSGID_PLURAL")) {
599         $current["msgid"] .= $quoted;
600       }
601       elseif ($context == "MSGSTR") {
602         $current["msgstr"] .= $quoted;
603       }
604       elseif ($context == "MSGSTR_ARR") {
605         $current["msgstr"][$plural] .= $quoted;
606       }
607       else {
608         drupal_set_message(t('The translation file %filename contains an error: there is an unexpected string on line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
609         return FALSE;
610       }
611     }
612   }
613
614   // End of PO file, flush last entry
615   if (($context == "MSGSTR") || ($context == "MSGSTR_ARR")) {
616     _locale_import_one_string($current, $mode, $lang);
617   }
618   elseif ($context != "COMMENT") {
619     drupal_set_message(t('The translation file %filename ended unexpectedly at line %line.', array('%filename' => $message, '%line' => $lineno)), 'error');
620     return FALSE;
621   }
622
623 }
624
625 /**
626  * Imports a string into the database
627  *
628  * @param $value Information about the string
629  * @author Jacobo Tarrio
630  */
631 function _locale_import_one_string($value, $mode, $lang = NULL) {
632   static $additions = 0;
633   static $updates = 0;
634   static $headerdone = FALSE;
635
636   // Report the changes made (called at end of import)
637   if ($value == 'report') {
638     return array($headerdone, $additions, $updates);
639   }
640   // Current string is the header information
641   elseif ($value['msgid'] == '') {
642     $hdr = _locale_import_parse_header($value['msgstr']);
643
644     // Get the plural formula
645     if ($hdr["Plural-Forms"] && $p = _locale_import_parse_plural_forms($hdr["Plural-Forms"], $file->filename)) {
646       list($nplurals, $plural) = $p;
647       db_query("UPDATE {locales_meta} SET plurals = %d, formula = '%s' WHERE locale = '%s'", $nplurals, $plural, $lang);
648     }
649     else {
650       db_query("UPDATE {locales_meta} SET plurals = %d, formula = '%s' WHERE locale = '%s'", 0, '', $lang);
651     }
652     $headerdone = TRUE;
653   }
654   // Some real string to import
655   else {
656     $comments = filter_xss_admin(_locale_import_shorten_comments($value['#']));
657
658     // Handle a translation for some plural string
659     if (strpos($value['msgid'], "\0")) {
660       $english = explode("\0", $value['msgid'], 2);
661       $entries = array_keys($value['msgstr']);
662       for ($i = 3; $i <= count($entries); $i++) {
663         $english[] = $english[1];
664       }
665       $translation = array_map('_locale_import_append_plural', $value['msgstr'], $entries);
666       $english = array_map('_locale_import_append_plural', $english, $entries);
667       foreach ($translation as $key => $trans) {
668         if ($key == 0) {
669           $plid = 0;
670         }
671         $loc = db_fetch_object(db_query("SELECT lid FROM {locales_source} WHERE source = '%s'", $english[$key]));
672         if ($loc->lid) { // a string exists
673           $lid = $loc->lid;
674           // update location field
675           db_query("UPDATE {locales_source} SET location = '%s' WHERE lid = %d", $comments, $lid);
676           $trans2 = db_fetch_object(db_query("SELECT lid, translation, plid, plural FROM {locales_target} WHERE lid = %d AND locale = '%s'", $lid, $lang));
677           if (!$trans2->lid) { // no translation in current language
678             db_query("INSERT INTO {locales_target} (lid, locale, translation, plid, plural) VALUES (%d, '%s', '%s', %d, %d)", $lid, $lang, filter_xss_admin($trans), $plid, $key);
679             $additions++;
680           } // translation exists
681           else if ($mode == 'overwrite' || $trans2->translation == '') {
682             db_query("UPDATE {locales_target} SET translation = '%s', plid = %d, plural = %d WHERE locale = '%s' AND lid = %d", filter_xss_admin($trans), $plid, $key, $lang, $lid);
683             if ($trans2->translation == '') {
684               $additions++;
685             }
686             else {
687               $updates++;
688             }
689           }
690         }
691         else { // no string
692           db_query("INSERT INTO {locales_source} (location, source) VALUES ('%s', '%s')", $comments, filter_xss_admin($english[$key]));
693           $loc = db_fetch_object(db_query("SELECT lid FROM {locales_source} WHERE source = '%s'", $english[$key]));
694           $lid = $loc->lid;
695           db_query("INSERT INTO {locales_target} (lid, locale, translation, plid, plural) VALUES (%d, '%s', '%s', %d, %d)", $lid, $lang, filter_xss_admin($trans), $plid, $key);
696           if ($trans != '') {
697             $additions++;
698           }
699         }
700         $plid = $lid;
701       }
702     }
703
704     // A simple translation
705     else {
706       $english = $value['msgid'];
707       $translation = $value['msgstr'];
708       $loc = db_fetch_object(db_query("SELECT lid FROM {locales_source} WHERE source = '%s'", $english));
709       if ($loc->lid) { // a string exists
710         $lid = $loc->lid;
711         // update location field
712         db_query("UPDATE {locales_source} SET location = '%s' WHERE source = '%s'", $comments, $english);
713         $trans = db_fetch_object(db_query("SELECT lid, translation FROM {locales_target} WHERE lid = %d AND locale = '%s'", $lid, $lang));
714         if (!$trans->lid) { // no translation in current language
715           db_query("INSERT INTO {locales_target} (lid, locale, translation) VALUES (%d, '%s', '%s')", $lid, $lang, filter_xss_admin($translation));
716           $additions++;
717         } // translation exists
718         else if ($mode == 'overwrite') { //overwrite in any case
719           db_query("UPDATE {locales_target} SET translation = '%s' WHERE locale = '%s' AND lid = %d", filter_xss_admin($translation), $lang, $lid);
720           if ($trans->translation == '') {
721             $additions++;
722           }
723           else {
724             $updates++;
725           }
726         } // overwrite if empty string
727         else if ($trans->translation == '') {
728           db_query("UPDATE {locales_target} SET translation = '%s' WHERE locale = '%s' AND lid = %d", $translation, $lang, $lid);
729           $additions++;
730         }
731       }
732       else { // no string
733         db_query("INSERT INTO {locales_source} (location, source) VALUES ('%s', '%s')", $comments, $english);
734         $loc = db_fetch_object(db_query("SELECT lid FROM {locales_source} WHERE source = '%s'", $english));
735         $lid = $loc->lid;
736         db_query("INSERT INTO {locales_target} (lid, locale, translation) VALUES (%d, '%s', '%s')", $lid, $lang, filter_xss_admin($translation));
737         if ($translation != '') {
738           $additions++;
739         }
740       }
741     }
742   }
743 }
744
745 /**
746  * Parses a Gettext Portable Object file header
747  *
748  * @param $header A string containing the complete header
749  * @return An associative array of key-value pairs
750  * @author Jacobo Tarrio
751  */
752 function _locale_import_parse_header($header) {
753   $hdr = array();
754
755   $lines = explode("\n", $header);
756   foreach ($lines as $line) {
757     $line = trim($line);
758     if ($line) {
759       list($tag, $contents) = explode(":", $line, 2);
760       $hdr[trim($tag)] = trim($contents);
761     }
762   }
763
764   return $hdr;
765 }
766
767 /**
768  * Parses a Plural-Forms entry from a Gettext Portable Object file header
769  *
770  * @param $pluralforms A string containing the Plural-Forms entry
771  * @param $filename A string containing the filename
772  * @return An array containing the number of plurals and a
773  *         formula in PHP for computing the plural form
774  * @author Jacobo Tarrio
775  */
776 function _locale_import_parse_plural_forms($pluralforms, $filename) {
777   // First, delete all whitespace
778   $pluralforms = strtr($pluralforms, array(" " => "", "\t" => ""));
779
780   // Select the parts that define nplurals and plural
781   $nplurals = strstr($pluralforms, "nplurals=");
782   if (strpos($nplurals, ";")) {
783     $nplurals = substr($nplurals, 9, strpos($nplurals, ";") - 9);
784   }
785   else {
786     return FALSE;
787   }
788   $plural = strstr($pluralforms, "plural=");
789   if (strpos($plural, ";")) {
790     $plural = substr($plural, 7, strpos($plural, ";") - 7);
791   }
792   else {
793     return FALSE;
794   }
795
796   // Get PHP version of the plural formula
797   $plural = _locale_import_parse_arithmetic($plural);
798
799   if ($plural !== FALSE) {
800     return array($nplurals, $plural);
801   }
802   else {
803     drupal_set_message(t('The translation file %filename contains an error: the plural formula could not be parsed.', array('%filename' => theme('placeholder', $filename))), 'error');
804     return FALSE;
805   }
806 }
807
808 /**
809  * Parses and sanitizes an arithmetic formula into a PHP expression
810  *
811  * While parsing, we ensure, that the operators have the right
812  * precedence and associativity.
813  *
814  * @param $string A string containing the arithmetic formula
815  * @return The PHP version of the formula
816  * @author Jacobo Tarrio
817  */
818 function _locale_import_parse_arithmetic($string) {
819   // Operator precedence table
820   $prec = array("(" => -1, ")" => -1, "?" => 1, ":" => 1, "||" => 3, "&&" => 4, "==" => 5, "!=" => 5, "<" => 6, ">" => 6, "<=" => 6, ">=" => 6, "+" => 7, "-" => 7, "*" => 8, "/" => 8, "%" => 8);
821   // Right associativity
822   $rasc = array("?" => 1, ":" => 1);
823
824   $tokens = _locale_import_tokenize_formula($string);
825
826   // Parse by converting into infix notation then back into postfix
827   $opstk = array();
828   $elstk = array();
829
830   foreach ($tokens as $token) {
831     $ctok = $token;
832
833     // Numbers and the $n variable are simply pushed into $elarr
834     if (is_numeric($token)) {
835       $elstk[] = $ctok;
836     }
837     elseif ($ctok == "n") {
838       $elstk[] = '$n';
839     }
840     elseif ($ctok == "(") {
841       $opstk[] = $ctok;
842     }
843     elseif ($ctok == ")") {
844       $topop = array_pop($opstk);
845       while (($topop != NULL) && ($topop != "(")) {
846         $elstk[] = $topop;
847         $topop = array_pop($opstk);
848       }
849     }
850     elseif ($prec[$ctok]) {
851       // If it's an operator, then pop from $oparr into $elarr until the
852       // precedence in $oparr is less than current, then push into $oparr
853       $topop = array_pop($opstk);
854       while (($topop != NULL) && ($prec[$topop] >= $prec[$ctok]) && !(($prec[$topop] == $prec[$ctok]) && $rasc[$topop] && $rasc[$ctok])) {
855         $elstk[] = $topop;
856         $topop = array_pop($opstk);
857       }
858       if ($topop) {
859         $opstk[] = $topop;   // Return element to top
860       }
861       $opstk[] = $ctok;      // Parentheses are not needed
862     }
863     else {
864       return false;
865     }
866   }
867
868   // Flush operator stack
869   $topop = array_pop($opstk);
870   while ($topop != NULL) {
871     $elstk[] = $topop;
872     $topop = array_pop($opstk);
873   }
874
875   // Now extract formula from stack
876   $prevsize = count($elstk) + 1;
877   while (count($elstk) < $prevsize) {
878     $prevsize = count($elstk);
879     for ($i = 2; $i < count($elstk); $i++) {
880       $op = $elstk[$i];
881       if ($prec[$op]) {
882         $f = "";
883         if ($op == ":") {
884           $f = $elstk[$i - 2] ."):". $elstk[$i - 1] .")";
885         }
886         elseif ($op == "?") {
887           $f = "(". $elstk[$i - 2] ."?(". $elstk[$i - 1];
888         }
889         else {
890           $f = "(". $elstk[$i - 2] . $op . $elstk[$i - 1] .")";
891         }
892         array_splice($elstk, $i - 2, 3, $f);
893         break;
894       }
895     }
896   }
897
898   // If only one element is left, the number of operators is appropriate
899   if (count($elstk) == 1) {
900     return $elstk[0];
901   }
902   else {
903     return FALSE;
904   }
905 }
906
907 /**
908  * Backward compatible implementation of token_get_all() for formula parsing
909  *
910  * @param $string A string containing the arithmetic formula
911  * @return The PHP version of the formula
912  * @author Gerhard Killesreiter
913  */
914 function _locale_import_tokenize_formula($formula) {
915   $formula = str_replace(" ", "", $formula);
916   $tokens = array();
917   for ($i = 0; $i < strlen($formula); $i++) {
918     if (is_numeric($formula[$i])) {
919       $num = $formula[$i];
920       $j = $i + 1;
921       while($j < strlen($formula) && is_numeric($formula[$j])) {
922         $num .= $formula[$j];
923         $j++;
924       }
925       $i = $j - 1;
926       $tokens[] = $num;
927     }
928     elseif ($pos = strpos(" =<>!&|", $formula[$i])) { // We won't have a space
929       $next = $formula[$i + 1];
930       switch ($pos) {
931         case 1:
932         case 2:
933         case 3:
934         case 4:
935           if ($next == '=') {
936             $tokens[] = $formula[$i] .'=';
937             $i++;
938           }
939           else {
940             $tokens[] = $formula[$i];
941           }
942           break;
943         case 5:
944           if ($next == '&') {
945             $tokens[] = '&&';
946             $i++;
947           }
948           else {
949             $tokens[] = $formula[$i];
950           }
951           break;
952         case 6:
953           if ($next == '|') {
954             $tokens[] = '||';
955             $i++;
956           }
957           else {
958             $tokens[] = $formula[$i];
959           }
960           break;
961       }
962     }
963     else {
964       $tokens[] = $formula[$i];
965     }
966   }
967   return $tokens;
968 }
969
970 /**
971  * Modify a string to contain proper count indices
972  *
973  * This is a callback function used via array_map()
974  *
975  * @param $entry An array element
976  * @param $key Index of the array element
977  */
978 function _locale_import_append_plural($entry, $key) {
979   // No modifications for 0, 1
980   if ($key == 0 || $key == 1) {
981     return $entry;
982   }
983
984   // First remove any possibly false indices, then add new ones
985   $entry = preg_replace('/(%count)\[[0-9]\]/', '\\1', $entry);
986   return preg_replace('/(%count)/', "\\1[$key]", $entry);
987 }
988
989 /**
990  * Generate a short, one string version of the passed comment array
991  *
992  * @param $comment An array of strings containing a comment
993  * @return Short one string version of the comment
994  */
995 function _locale_import_shorten_comments($comment) {
996   $comm = '';
997   while (count($comment)) {
998     $test = $comm . substr(array_shift($comment), 1) .', ';
999     if (strlen($comm) < 130) {
1000       $comm = $test;
1001     }
1002     else {
1003       break;
1004     }
1005   }
1006   return substr($comm, 0, -2);
1007 }
1008
1009 /**
1010  * Parses a string in quotes
1011  *
1012  * @param $string A string specified with enclosing quotes
1013  * @return The string parsed from inside the quotes
1014  */
1015 function _locale_import_parse_quoted($string) {
1016   if (substr($string, 0, 1) != substr($string, -1, 1)) {
1017     return FALSE;   // Start and end quotes must be the same
1018   }
1019   $quote = substr($string, 0, 1);
1020   $string = substr($string, 1, -1);
1021   if ($quote == '"') {        // Double quotes: strip slashes
1022     return stripcslashes($string);
1023   }
1024   elseif ($quote == "'") {  // Simple quote: return as-is
1025     return $string;
1026   }
1027   else {
1028     return FALSE;             // Unrecognized quote
1029   }
1030 }
1031
1032 /**
1033  * Exports a Portable Object (Template) file for a language
1034  *
1035  * @param $language Selects a language to generate the output for
1036  */
1037 function _locale_export_po($language) {
1038   global $user;
1039
1040   // Get language specific strings, or all strings
1041   if ($language) {
1042     $meta = db_fetch_object(db_query("SELECT * FROM {locales_meta} WHERE locale = '%s'", $language));
1043     $result = db_query("SELECT s.lid, s.source, s.location, t.translation, t.plid, t.plural FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid WHERE t.locale = '%s' ORDER BY t.plid, t.plural", $language);
1044   }
1045   else {
1046     $result = db_query("SELECT s.lid, s.source, s.location, t.plid, t.plural FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid ORDER BY t.plid, t.plural");
1047   }
1048
1049   // Build array out of the database results
1050   $parent = array();
1051   while ($child = db_fetch_object($result)) {
1052     if ($child->source != '') {
1053       $parent[$child->lid]['comment'] = $child->location;
1054       $parent[$child->lid]['msgid'] = $child->source;
1055       if ($child->plid) {
1056         $parent[$child->lid][$child->plid]['plural'] = $child->lid;
1057         $parent[$child->lid][$child->plid]['translation'] = $child->translation;
1058         $parent[$child->lid][$child->plid]['msgid'] = $child->source;
1059       }
1060       else {
1061         $parent[$child->lid]['translation'] = $child->translation;
1062       }
1063     }
1064   }
1065
1066   // Generating Portable Object file for a language
1067   if ($language) {
1068     $filename = $language .'.po';
1069     $header .= "# $meta->name translation of ". variable_get('site_name', 'Drupal') ."\n";
1070     $header .= '# Copyright (c) '. date('Y') .' '. $user->name .' <'. $user->mail .">\n";
1071     $header .= "#\n";
1072     $header .= "msgid \"\"\n";
1073     $header .= "msgstr \"\"\n";
1074     $header .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
1075     $header .= "\"POT-Creation-Date: ". date("Y-m-d H:iO") ."\\n\"\n";
1076     $header .= "\"PO-Revision-Date: ". date("Y-m-d H:iO") ."\\n\"\n";
1077     $header .= "\"Last-Translator: ". $user->name .' <'. $user->mail .">\\n\"\n";
1078     $header .= "\"Language-Team: ". $meta->name .' <'. $user->mail .">\\n\"\n";
1079     $header .= "\"MIME-Version: 1.0\\n\"\n";
1080     $header .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
1081     $header .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
1082     if ($meta->formula && $meta->plurals) {
1083       $header .= "\"Plural-Forms: nplurals=". $meta->plurals ."; plural=". strtr($meta->formula, '$', '') .";\\n\"\n";
1084     }
1085     $header .= "\n";
1086     watchdog('locale', t('Exported %locale translation file: %filename.', array('%locale' => theme('placeholder', $meta->name), '%filename' => theme('placeholder', $filename))));
1087   }
1088
1089   // Generating Portable Object Template
1090   else {
1091     $filename = 'drupal.pot';
1092     $header .= "# LANGUAGE translation of PROJECT\n";
1093     $header .= "# Copyright (c) YEAR NAME <EMAIL@ADDRESS>\n";
1094     $header .= "#\n";
1095     $header .= "msgid \"\"\n";
1096     $header .= "msgstr \"\"\n";
1097     $header .= "\"Project-Id-Version: PROJECT VERSION\\n\"\n";
1098     $header .= "\"POT-Creation-Date: ". date("Y-m-d H:iO") ."\\n\"\n";
1099     $header .= "\"PO-Revision-Date: YYYY-mm-DD HH:MM+ZZZZ\\n\"\n";
1100     $header .= "\"Last-Translator: NAME <EMAIL@ADDRESS>\\n\"\n";
1101     $header .= "\"Language-Team: LANGUAGE <EMAIL@ADDRESS>\\n\"\n";
1102     $header .= "\"MIME-Version: 1.0\\n\"\n";
1103     $header .= "\"Content-Type: text/plain; charset=utf-8\\n\"\n";
1104     $header .= "\"Content-Transfer-Encoding: 8bit\\n\"\n";
1105     $header .= "\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\\n\"\n";
1106     $header .= "\n";
1107     watchdog('locale', t('Exported translation file: %filename.', array('%filename' => theme('placeholder', $filename))));
1108   }
1109
1110   // Start download process
1111   header("Content-Disposition: attachment; filename=$filename");
1112   header("Content-Type: text/plain; charset=utf-8");
1113
1114   print $header;
1115
1116   foreach ($parent as $lid => $message) {
1117     if (!isset($done[$lid])) {
1118       if ($message['comment']) {
1119         print '#: '. $message['comment'] ."\n";
1120       }
1121       print 'msgid '. _locale_export_print($message['msgid']);
1122       if (isset($message[1]['plural'])) {
1123         print 'msgid_plural '. _locale_export_print($message[1]['msgid']);
1124         if ($language) {
1125           for ($i = 0; $i < $meta->plurals; $i++) {
1126             print 'msgstr['. $i .'] '. _locale_export_print(_locale_export_remove_plural($message[${i}]['translation']));
1127             $done[$message[${i}]['plural']] = 1;
1128           }
1129         }
1130         else {
1131           print 'msgstr[0] ""'. "\n";
1132           print 'msgstr[1] ""'. "\n";
1133           $done[$message[0]['plural']] = 1;
1134           $done[$message[1]['plural']] = 1;
1135         }
1136       }
1137       else {
1138         if ($language) {
1139           print 'msgstr '. _locale_export_print($message['translation']);
1140         }
1141         else {
1142           print 'msgstr ""'. "\n";
1143         }
1144       }
1145       print "\n";
1146     }
1147   }
1148   die();
1149 }
1150
1151 /**
1152  * Print out a string on multiple lines
1153  */
1154 function _locale_export_print($str) {
1155   $stri = addcslashes($str, "\0..\37\\\"");
1156   $parts = array();
1157
1158   // Cut text into several lines
1159   while ($stri != "") {
1160     $i = strpos($stri, "\\n");
1161     if ($i === FALSE) {
1162       $curstr = $stri;
1163       $stri = "";
1164     }
1165     else {
1166       $curstr = substr($stri, 0, $i + 2);
1167       $stri = substr($stri, $i + 2);
1168     }
1169     $curparts = explode("\n", _locale_export_wrap($curstr, 70));
1170     $parts = array_merge($parts, $curparts);
1171   }
1172
1173   if (count($parts) > 1) {
1174     return "\"\"\n\"". implode("\"\n\"", $parts) ."\"\n";
1175   }
1176   else {
1177     return "\"$parts[0]\"\n";
1178   }
1179 }
1180
1181 /**
1182  * Custom word wrapping for Portable Object (Template) files.
1183  *
1184  * @author Jacobo Tarrio
1185  */
1186 function _locale_export_wrap($str, $len) {
1187   $words = explode(' ', $str);
1188   $ret = array();
1189
1190   $cur = "";
1191   $nstr = 1;
1192   while (count($words)) {
1193     $word = array_shift($words);
1194     if ($nstr) {
1195       $cur = $word;
1196       $nstr = 0;
1197     }
1198     elseif (strlen("$cur $word") > $len) {
1199       $ret[] = $cur . " ";
1200       $cur = $word;
1201     }
1202     else {
1203       $cur = "$cur $word";
1204     }
1205   }
1206   $ret[] = $cur;
1207
1208   return implode("\n", $ret);
1209 }
1210
1211 /**
1212  * Removes plural index information from a string
1213  */
1214 function _locale_export_remove_plural($entry) {
1215   return preg_replace('/(%count)\[[0-9]\]/', '\\1', $entry);
1216 }
1217
1218 /**
1219  * List languages in search result table
1220  */
1221 function _locale_string_language_list($translation) {
1222   $languages = locale_supported_languages(FALSE, TRUE);
1223   unset($languages['name']['en']);
1224   $output = '';
1225   foreach ($languages['name'] as $key => $value) {
1226     if (isset($translation[$key])) {
1227       $output .= ($translation[$key] != '') ? $key .' ' : "<em class=\"locale-untranslated\">$key</em> ";
1228     }
1229   }
1230
1231   return $output;
1232 }
1233
1234 /**
1235  * Build object out of search criteria specified in request variables
1236  */
1237 function _locale_string_seek_query() {
1238   static $query = NULL;
1239
1240   if (is_null($query)) {
1241     $fields = array('string', 'language', 'searchin');
1242     $query = new StdClass;
1243     if (is_array($_REQUEST['edit'])) {
1244       foreach ($_REQUEST['edit'] as $key => $value) {
1245         if (!empty($value) && in_array($key, $fields)) {
1246           $query->$key = $value;
1247         }
1248       }
1249     }
1250     else {
1251       foreach ($_REQUEST as $key => $value) {
1252         if (!empty($value) && in_array($key, $fields)) {
1253           $query->$key = strpos(',', $value) ? explode(',', $value) : $value;
1254         }
1255       }
1256     }
1257   }
1258   return $query;
1259 }
1260
1261 /**
1262  * Perform a string search and display results in a table
1263  */
1264 function _locale_string_seek() {
1265   // We have at least one criterion to match
1266   if ($query = _locale_string_seek_query()) {
1267     $join = "SELECT s.source, s.location, s.lid, t.translation, t.locale FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid ";
1268
1269     $arguments = array();
1270     // Compute LIKE section
1271     switch ($query->searchin) {
1272       case 'translated':
1273         $where = "WHERE (t.translation LIKE '%%%s%%' AND t.translation != '')";
1274         $orderby = "ORDER BY t.translation";
1275         $arguments[] = $query->string;
1276         break;
1277       case 'untranslated':
1278         $where = "WHERE (s.source LIKE '%%%s%%' AND t.translation = '')";
1279         $orderby = "ORDER BY s.source";
1280         $arguments[] = $query->string;
1281         break;
1282       case 'all' :
1283       default:
1284         $where = "WHERE (s.source LIKE '%%%s%%' OR t.translation LIKE '%%%s%%')";
1285         $orderby = '';
1286         $arguments[] = $query->string;
1287         $arguments[] = $query->string;
1288         break;
1289     }
1290
1291     switch ($query->language) {
1292       // Force search in source strings
1293       case "en":
1294         $sql = $join ." WHERE s.source LIKE '%%%s%%' ORDER BY s.source";
1295         $arguments = array($query->string); // $where is not used, discard its arguments
1296         break;
1297       // Search in all languages
1298       case "all":
1299         $sql = "$join $where $orderby";
1300         break;
1301       // Some different language
1302       default:
1303         $sql = "$join $where AND t.locale = '%s' $orderby";
1304         $arguments[] = $query->language;
1305     }
1306
1307     $result = pager_query($sql, 50, 0, NULL, $arguments);
1308
1309     $header = array(t('String'), t('Locales'), array('data' => t('Operations'), 'colspan' => '2'));
1310     $arr = array();
1311     while ($locale = db_fetch_object($result)) {
1312       $arr[$locale->lid]['locales'][$locale->locale] = $locale->translation;
1313       $arr[$locale->lid]['location'] = $locale->location;
1314       $arr[$locale->lid]['source'] = $locale->source;
1315     }
1316     foreach ($arr as $lid => $value) {
1317       $rows[] = array(array('data' => check_plain(truncate_utf8($value['source'], 150, FALSE, TRUE)) .'<br /><small>'. $value['location'] .'</small>'), array('data' => _locale_string_language_list($value['locales']), 'align' => 'center'), array('data' => l(t('edit'), "admin/locale/string/edit/$lid"), 'class' => 'nowrap'), array('data' => l(t('delete'), "admin/locale/string/delete/$lid"), 'class' => 'nowrap'));
1318     }
1319
1320     $request = array();
1321     if (count($query)) {
1322       foreach ($query as $key => $value) {
1323         $request[$key] = (is_array($value)) ? implode(',', $value) : $value;
1324       }
1325     }
1326
1327     if (count($rows)) {
1328       $output .= theme('table', $header, $rows);
1329     }
1330     if ($pager = theme('pager', NULL, 50, 0, $request)) {
1331       $output .= $pager;
1332     }
1333   }
1334
1335   return $output;
1336 }
1337
1338 // ---------------------------------------------------------------------------------
1339 // List of some of the most common languages (administration only)
1340
1341 /**
1342  * Prepares the language code list for a select form item with only the unsupported ones
1343  */
1344 function _locale_prepare_iso_list() {
1345   $languages = locale_supported_languages(FALSE, TRUE);
1346   $isocodes = _locale_get_iso639_list();
1347   foreach ($isocodes as $key => $value) {
1348     if (isset($languages['name'][$key])) {
1349       unset($isocodes[$key]);
1350       continue;
1351     }
1352     if (count($value) == 2) {
1353       $tname = t($value[0]);
1354       $isocodes[$key] = ($tname == $value[1]) ? $tname : "$tname ($value[1])";
1355     }
1356     else {
1357       $isocodes[$key] = t($value[0]);
1358     }
1359   }
1360   asort($isocodes);
1361   return $isocodes;
1362 }
1363
1364 /**
1365  * Some of the common languages with their English and native names
1366  *
1367  * Based on ISO 639 and http://people.w3.org/rishida/names/languages.html
1368  */
1369 function _locale_get_iso639_list() {
1370   return array(
1371     "aa" => array("Afar"),
1372     "ab" => array("Abkhazian", "аҧсуа бызшәа"),
1373     "ae" => array("Avestan"),
1374     "af" => array("Afrikaans"),
1375     "ak" => array("Akan"),
1376     "am" => array("Amharic", "አማርኛ"),
1377     "ar" => array("Arabic", "العربية"),
1378     "as" => array("Assamese"),
1379     "av" => array("Avar"),
1380     "ay" => array("Aymara"),
1381     "az" => array("Azerbaijani", "azərbaycan"),
1382     "ba" => array("Bashkir"),
1383     "be" => array("Belarusian", "Беларуская"),
1384     "bg" => array("Bulgarian", "Български"),
1385     "bh" => array("Bihari"),
1386     "bi" => array("Bislama"),
1387     "bm" => array("Bambara", "Bamanankan"),
1388     "bn" => array("Bengali"),
1389     "bo" => array("Tibetan"),
1390     "br" => array("Breton"),
1391     "bs" => array("Bosnian", "Bosanski"),
1392     "ca" => array("Catalan", "Català"),
1393     "ce" => array("Chechen"),
1394     "ch" => array("Chamorro"),
1395     "co" => array("Corsican"),
1396     "cr" => array("Cree"),
1397     "cs" => array("Czech", "Čeština"),
1398     "cu" => array("Old Slavonic"),
1399     "cv" => array("Welsh", "Cymraeg"),
1400     "cy" => array("Welch"),
1401     "da" => array("Danish", "Dansk"),
1402     "de" => array("German", "Deutsch"),
1403     "dv" => array("Maldivian"),
1404     "dz" => array("Bhutani"),
1405     "ee" => array("Ewe", "Ɛʋɛ"),
1406     "el" => array("Greek", "Ελληνικά"),
1407     "en" => array("English"),
1408     "eo" => array("Esperanto"),
1409     "es" => array("Spanish", "Español"),
1410     "et" => array("Estonian", "Eesti"),
1411     "eu" => array("Basque", "Euskera"),
1412     "fa" => array("Persian", "فارسی"),
1413     "ff" => array("Fulah", "Fulfulde"),
1414     "fi" => array("Finnish", "Suomi"),
1415     "fj" => array("Fiji"),
1416     "fo" => array("Faeroese"),
1417     "fr" => array("French", "Français"),
1418     "fy" => array("Frisian", "Frysk"),
1419     "ga" => array("Irish", "Gaeilge"),
1420     "gd" => array("Scots Gaelic"),
1421     "gl" => array("Galician", "Galego"),
1422     "gn" => array("Guarani"),
1423     "gu" => array("Gujarati"),
1424     "gv" => array("Manx"),
1425     "ha" => array("Hausa"),
1426     "he" => array("Hebrew", "עברית"),
1427     "hi" => array("Hindi", "हिन्दी"),
1428     "ho" => array("Hiri Motu"),
1429     "hr" => array("Croatian", "Hrvatski"),
1430     "hu" => array("Hungarian", "Magyar"),
1431     "hy" => array("Armenian", "Հայերեն"),
1432     "hz" => array("Herero"),
1433     "ia" => array("Interlingua"),
1434     "id" => array("Indonesian", "Bahasa Indonesia"),
1435     "ie" => array("Interlingue"),
1436     "ig" => array("Igbo"),
1437     "ik" => array("Inupiak"),
1438     "is" => array("Icelandic", "Íslenska"),
1439     "it" => array("Italian", "Italiano"),
1440     "iu" => array("Inuktitut"),
1441     "ja" => array("Japanese", "日本語"),
1442     "jv" => array("Javanese"),
1443     "ka" => array("Georgian"),
1444     "kg" => array("Kongo"),
1445     "ki" => array("Kikuyu"),
1446     "kj" => array("Kwanyama"),
1447     "kk" => array("Kazakh", "Қазақ"),
1448     "kl" => array("Greenlandic"),
1449     "km" => array("Cambodian"),
1450     "kn" => array("Kannada", "ಕನ್ನಡ"),
1451     "ko" => array("Korean", "한국어"),
1452     "kr" => array("Kanuri"),
1453     "ks" => array("Kashmiri"),
1454     "ku" => array("Kurdish", "Kurdî"),
1455     "kv" => array("Komi"),
1456     "kw" => array("Cornish"),
1457     "ky" => array("Kirghiz", "Кыргыз"),
1458     "la" => array("Latin", "Latina"),
1459     "lb" => array("Luxembourgish"),
1460     "lg" => array("Luganda"),
1461     "ln" => array("Lingala"),
1462     "lo" => array("Laothian"),
1463     "lt" => array("Lithuanian", "Lietuviškai"),
1464     "lv" => array("Latvian", "Latviešu"),
1465     "mg" => array("Malagasy"),
1466     "mh" => array("Marshallese"),
1467     "mi" => array("Maori"),
1468     "mk" => array("Macedonian", "Македонски"),
1469     "ml" => array("Malayalam", "മലയാളം"),
1470     "mn" => array("Mongolian"),
1471     "mo" => array("Moldavian"),
1472     "mr" => array("Marathi"),
1473     "ms" => array("Malay", "Bahasa Melayu"),
1474     "mt" => array("Maltese", "Malti"),
1475     "my" => array("Burmese"),
1476     "na" => array("Nauru"),
1477     "nd" => array("North Ndebele"),
1478     "ne" => array("Nepali"),
1479     "ng" => array("Ndonga"),
1480     "nl" => array("Dutch", "Nederlands"),
1481     "no" => array("Norwegian", "Norsk"),
1482     "nr" => array("South Ndebele"),
1483     "nv" => array("Navajo"),
1484     "ny" => array("Chichewa"),
1485     "oc" => array("Occitan"),
1486     "om" => array("Oromo"),
1487     "or" => array("Oriya"),
1488     "os" => array("Ossetian"),
1489     "pa" => array("Punjabi"),
1490     "pi" => array("Pali"),
1491     "pl" => array("Polish", "Polski"),
1492     "ps" => array("Pashto", "پښتو"),
1493     "pt" => array("Portuguese", "Português"),
1494     "qu" => array("Quechua"),
1495     "rm" => array("Rhaeto-Romance"),
1496     "rn" => array("Kirundi"),
1497     "ro" => array("Romanian", "Română"),
1498     "ru" => array("Russian", "Русский"),
1499     "rw" => array("Kinyarwanda"),
1500     "sa" => array("Sanskrit"),
1501     "sc" => array("Sardinian"),
1502     "sd" => array("Sindhi"),
1503     "se" => array("Northern Sami"),
1504     "sg" => array("Sango"),
1505     "sh" => array("Serbo-Croatian"),
1506     "si" => array("Singhalese"),
1507     "sk" => array("Slovak", "Slovenčina"),
1508     "sl" => array("Slovenian", "Slovenščina"),
1509     "sm" => array("Samoan"),
1510     "sn" => array("Shona"),
1511     "so" => array("Somali"),
1512     "sq" => array("Albanian", "Shqip"),
1513     "sr" => array("Serbian", "Српски"),
1514     "ss" => array("Siswati"),
1515     "st" => array("Sesotho"),
1516     "su" => array("Sudanese"),
1517     "sv" => array("Swedish", "Svenska"),
1518     "sw" => array("Swahili", "Kiswahili"),
1519     "ta" => array("Tamil", "தமிழ்"),
1520     "te" => array("Telugu", "తెలుగు"),
1521     "tg" => array("Tajik"),
1522     "th" => array("Thai", "ภาษาไทย"),
1523     "ti" => array("Tigrinya"),
1524     "tk" => array("Turkmen"),
1525     "tl" => array("Tagalog"),
1526     "tn" => array("Setswana"),
1527     "to" => array("Tonga"),
1528     "tr" => array("Turkish", "Türkçe"),
1529     "ts" => array("Tsonga"),
1530     "tt" => array("Tatar", "Tatarça"),
1531     "tw" => array("Twi"),
1532     "ty" => array("Tahitian"),
1533     "ug" => array("Uighur"),
1534     "uk" => array("Ukrainian", "Українська"),
1535     "ur" => array("Urdu", "اردو"),
1536     "uz" => array("Uzbek", "o'zbek"),
1537     "ve" => array("Venda"),
1538     "vi" => array("Vietnamese", "Tiếng Việt"),
1539     "wo" => array("Wolof"),
1540     "xh" => array("Xhosa", "isiXhosa"),
1541     "yi" => array("Yiddish"),
1542     "yo" => array("Yoruba", "Yorùbá"),
1543     "za" => array("Zhuang"),
1544     "zh-hans" => array("Chinese, Simplified", "简体中文"),
1545     "zh-hant" => array("Chinese, Traditional", "繁體中文"),
1546     "zu" => array("Zulu", "isiZulu"),
1547   );
1548 }