initial import from onelab svn codebase
[plewww.git] / modules / locale.module
1 <?php
2 // $Id: locale.module 144 2007-03-28 07:52:20Z thierry $
3
4 /**
5  * @file
6  * Enables administrators to manage the site interface languages.
7  *
8  * When enabled, the site interface can be displayed in different
9  * languages. The setup of languages and translations is completely
10  * web based. Gettext portable object files are supported.
11  */
12
13 // ---------------------------------------------------------------------------------
14 // Hook implementations (needed on all page loads)
15
16 /**
17  * Implementation of hook_help().
18  */
19 function locale_help($section) {
20   switch ($section) {
21     case 'admin/help#locale':
22       $output = '<p>'. t('The locale module allows you to present your Drupal site in a language other than the default English. You can use it to set up a multi-lingual web site or replace given <em>built-in</em> text with text which has been customized for your site. Whenever the locale module encounters text which needs to be displayed, it tries to translate it into the currently selected language. If a translation is not available, then the string is remembered, so you can look up untranslated strings easily.') .'</p>';
23       $output .= '<p>'. t('The locale module provides two options for providing translations. The first is the integrated web interface, via which you can search for untranslated strings, and specify their translations. An easier and less time-consuming method is to import existing translations for your language.  These translations are available as <em>GNU gettext Portable Object files</em> (<em>.po</em> files for short).  Translations for many languages are available for download from the translation page.') .'</p>';
24       $output .= '<p>'. t('If an existing translation does not meet your needs, the <em>.po</em> files are easily edited with special editing tools. The locale module\'s import feature allows you to add strings from such files into your site\'s database. The export functionality enables you to share your translations with others, generating Portable Object files from your site strings.') .'</p>';
25       $output .= t('<p>You can</p>
26 <ul>
27 <li>administer localization at <a href="%admin-locale">administer &gt;&gt; localization</a>.</li>
28 <li>manage strings for the localization: <a href="%admin-locale-string-search">administer &gt;&gt; localization &gt;&gt; manage strings</a>.</li>
29 <li>add a locale language: <a href="%admin-locale-language-add">administer &gt;&gt; localization &gt;&gt; add language</a>.</li>
30 <li>download translation files from the <a href="%external-http-drupal-org-project-Translations">Drupal translations page</a>.
31 </li>
32 </ul>
33 ', array('%admin-locale' => url('admin/locale'), '%admin-locale-string-search' => url('admin/locale/string/search'), '%admin-locale-language-add' => url('admin/locale/language/add'), '%external-http-drupal-org-project-Translations' => 'http://drupal.org/project/Translations'));
34       $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="%locale">Locale page</a>.', array('%locale' => 'http://drupal.org/handbook/modules/locale/')) .'</p>';
35       return $output;
36     case 'admin/modules#description':
37       return t('Enables the translation of the user interface to languages other than English.');
38     case 'admin/locale':
39     case 'admin/locale/language/overview':
40       return t("<p>Drupal provides support for the translation of its interface text into different languages.  This page provides an overview of the installed languages. You can add a language on the <a href=\"%add-language\">add language page</a>, or directly by <a href=\"%import\">importing a translation</a>. If multiple languages are enabled, registered users will be able to set their preferred language.  The site default will be used for anonymous visitors and for users without their own settings.</p><p>Drupal interface translations may be added or extended by several courses: by <a href=\"%import\">importing</a> an existing translation, by <a href=\"%search\">translating everything</a> from scratch, or by a combination of these approaches.</p>", array("%search" => url("admin/locale/string/search"), "%import" => url("admin/locale/language/import"), "%add-language" => url("admin/locale/language/add")));
41     case 'admin/locale/language/add':
42       return t("<p>You need to add all languages in which you would like to display the site interface. If you can't find the desired language in the quick-add dropdown, then you will need to provide the proper language code yourself. The language code may be used to negotiate with browsers and to present flags, etc., so it is important to pick a code that is standardised for the desired language. You can also add a language by <a href=\"%import\">importing a translation</a>.</p>", array("%import" => url("admin/locale/language/import")));
43     case 'admin/locale/language/import':
44       return t("<p>This page allows you to import a translation provided in the gettext Portable Object (.po) format.  The easiest way to get your site translated is to obtain an existing Drupal translation and to import it.  You can find existing translations on the <a href=\"%url\">Drupal translation page</a>. Note that importing a translation file might take a while.</p>", array('%url' => 'http://drupal.org/project/translations'));
45     case 'admin/locale/language/export':
46       return t("<p>This page allows you to export Drupal strings. The first option is to export a translation so it can be shared.  The second option generates a translation template, which contains all Drupal strings, but without their translations. You can use this template to start a new translation using various software packages designed for this task.</p>");
47     case 'admin/locale/string/search':
48       return t("<p>It is often convenient to get the strings from your setup on the <a href=\"%export\">export page</a>, and use a desktop Gettext translation editor to edit the translations.  On this page you can search in the translated and untranslated strings, and the default English texts provided by Drupal.</p>", array("%export" => url("admin/locale/language/export")));
49   }
50 }
51
52 /**
53  * Implementation of hook_menu().
54  */
55 function locale_menu($may_cache) {
56   $items = array();
57
58   if ($may_cache) {
59     $access = user_access('administer locales');
60
61     // Main admin menu item
62     $items[] = array('path' => 'admin/locale',
63       'title' => t('localization'),
64       'callback' => 'locale_admin_manage',
65       'access' => $access);
66
67     // Top level tabs
68     $items[] = array('path' => 'admin/locale/language',
69       'title' => t('manage languages'),
70       'access' => $access,
71       'weight' => -10,
72       'type' => MENU_DEFAULT_LOCAL_TASK);
73     $items[] = array('path' => 'admin/locale/string/search',
74       'title' => t('manage strings'),
75       'callback' => 'locale_string_search',
76       'access' => $access,
77       'weight' => 10,
78       'type' => MENU_LOCAL_TASK);
79
80     // Manage languages subtabs
81     $items[] = array('path' => 'admin/locale/language/overview',
82       'title' => t('list'),
83       'callback' => 'locale_admin_manage',
84       'access' => $access,
85       'weight' => 0,
86       'type' => MENU_DEFAULT_LOCAL_TASK);
87     $items[] = array('path' => 'admin/locale/language/add',
88       'title' => t('add language'),
89       'callback' => 'locale_admin_manage_add',
90       'access' => $access,
91       'weight' => 5,
92       'type' => MENU_LOCAL_TASK);
93     $items[] = array('path' => 'admin/locale/language/import',
94       'title' => t('import'),
95       'callback' => 'locale_admin_import',
96       'access' => $access,
97       'weight' => 10,
98       'type' => MENU_LOCAL_TASK);
99     $items[] = array('path' => 'admin/locale/language/export',
100       'title' => t('export'),
101       'callback' => 'locale_admin_export',
102       'access' => $access,
103       'weight' => 20,
104       'type' => MENU_LOCAL_TASK);
105
106     // Language related callbacks
107     $items[] = array('path' => 'admin/locale/language/delete',
108       'title' => t('confirm'),
109       'callback' => 'locale_admin_manage_delete_form',
110       'access' => $access,
111       'type' => MENU_CALLBACK);
112   }
113   else {
114     if (is_numeric(arg(4))) {
115       // String related callbacks
116       $items[] = array('path' => 'admin/locale/string/edit/'. arg(4),
117         'title' => t('edit string'),
118         'callback' => 'locale_admin_string_edit',
119         'callback arguments' => arg(4),
120         'access' => $access,
121         'type' => MENU_CALLBACK);
122       $items[] = array('path' => 'admin/locale/string/delete/'. arg(4),
123         'title' => t('delete string'),
124         'callback' => 'locale_admin_string_delete',
125         'callback arguments' => arg(4),
126         'access' => $access,
127         'type' => MENU_CALLBACK);
128     }
129   }
130
131   return $items;
132 }
133
134 /**
135  * Implementation of hook_perm().
136  */
137 function locale_perm() {
138   return array('administer locales');
139 }
140
141 /**
142  * Implementation of hook_user().
143  */
144 function locale_user($type, $edit, &$user, $category = NULL) {
145   $languages = locale_supported_languages();
146   if ($type == 'form' && $category == 'account' && count($languages['name']) > 1) {
147     if ($user->language == '') {
148       $user->language = key($languages['name']);
149     }
150     $languages['name'] = array_map('check_plain', $languages['name']);
151     $form['locale'] = array('#type' => 'fieldset',
152       '#title' => t('Interface language settings'),
153       '#weight' => 1,
154     );
155     $form['locale']['language'] = array('#type' => 'radios',
156       '#title' => t('Language'),
157       '#default_value' => $user->language,
158       '#options' => $languages['name'],
159       '#description' => t('Selecting a different locale will change the interface language of the site.'),
160     );
161     return $form;
162   }
163 }
164
165 // ---------------------------------------------------------------------------------
166 // Locale core functionality (needed on all page loads)
167
168 /**
169  * Provides interface translation services.
170  *
171  * This function is called from t() to translate a string if needed.
172  */
173 function locale($string) {
174   global $locale;
175   static $locale_t;
176
177   // Store database cached translations in a static var.
178   if (!isset($locale_t)) {
179     $cache = cache_get("locale:$locale");
180
181     if ($cache == 0) {
182       locale_refresh_cache();
183       $cache = cache_get("locale:$locale");
184     }
185     $locale_t = unserialize($cache->data);
186   }
187
188   // We have the translation cached (if it is TRUE, then there is no
189   // translation, so there is no point in checking the database)
190   if (isset($locale_t[$string])) {
191     $string = ($locale_t[$string] === TRUE ? $string : $locale_t[$string]);
192   }
193
194   // We do not have this translation cached, so get it from the DB.
195   else {
196     $result = db_query("SELECT s.lid, t.translation FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid WHERE s.source = '%s' AND t.locale = '%s'", $string, $locale);
197     // Translation found
198     if ($trans = db_fetch_object($result)) {
199       if (!empty($trans->translation)) {
200         $locale_t[$string] = $trans->translation;
201         $string = $trans->translation;
202       }
203     }
204
205     // Either we have no such source string, or no translation
206     else {
207       $result = db_query("SELECT lid, source FROM {locales_source} WHERE source = '%s'", $string);
208       // We have no such translation
209       if ($obj = db_fetch_object($result)) {
210         if ($locale) {
211           db_query("INSERT INTO {locales_target} (lid, locale, translation) VALUES (%d, '%s', '')", $obj->lid, $locale);
212         }
213       }
214       // We have no such source string
215       else {
216         db_query("INSERT INTO {locales_source} (location, source) VALUES ('%s', '%s')", request_uri(), $string);
217         if ($locale) {
218           $lid = db_fetch_object(db_query("SELECT lid FROM {locales_source} WHERE source = '%s'", $string));
219           db_query("INSERT INTO {locales_target} (lid, locale, translation) VALUES (%d, '%s', '')", $lid->lid, $locale);
220         }
221       }
222       // Clear locale cache in DB
223       cache_clear_all("locale:$locale");
224     }
225   }
226
227   return $string;
228 }
229
230 /**
231  * Refreshes database stored cache of translations.
232  *
233  * We only store short strings to improve performance and consume less memory.
234  */
235 function locale_refresh_cache() {
236   $languages = locale_supported_languages();
237
238   foreach (array_keys($languages['name']) as $locale) {
239     $result = db_query("SELECT s.source, t.translation, t.locale FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid WHERE t.locale = '%s' AND LENGTH(s.source) < 75", $locale);
240     $t = array();
241     while ($data = db_fetch_object($result)) {
242       $t[$data->source] = (empty($data->translation) ? TRUE : $data->translation);
243     }
244     cache_set("locale:$locale", serialize($t));
245   }
246 }
247
248 /**
249  * Returns list of languages supported on this site.
250  *
251  * @param $reset Refresh cached language list.
252  * @param $getall Return all languages (even disabled ones)
253  */
254 function locale_supported_languages($reset = FALSE, $getall = FALSE) {
255   static $enabled = NULL;
256   static $all = NULL;
257
258   if ($reset) {
259     unset($enabled); unset($all);
260   }
261
262   if (is_null($enabled)) {
263     $enabled = $all = array();
264     $all['name'] = $all['formula'] = $enabled['name'] = $enabled['formula'] = array();
265     $result = db_query('SELECT locale, name, formula, enabled FROM {locales_meta} ORDER BY isdefault DESC, enabled DESC, name ASC');
266     while ($row = db_fetch_object($result)) {
267       $all['name'][$row->locale] = $row->name;
268       $all['formula'][$row->locale] = $row->formula;
269       if ($row->enabled) {
270         $enabled['name'][$row->locale] = $row->name;
271         $enabled['formula'][$row->locale] = $row->formula;
272       }
273     }
274   }
275   return $getall ? $all : $enabled;
276 }
277
278 /**
279  * Returns plural form index for a specific number.
280  *
281  * The index is computed from the formula of this language.
282  */
283 function locale_get_plural($count) {
284   global $locale;
285   static $locale_formula, $plurals = array();
286
287   if (!isset($plurals[$count])) {
288     if (!isset($locale_formula)) {
289       $languages = locale_supported_languages();
290       $locale_formula = $languages['formula'][$locale];
291     }
292     if ($locale_formula) {
293       $n = $count;
294       $plurals[$count] = @eval("return intval($locale_formula);");
295       return $plurals[$count];
296     }
297     else {
298       $plurals[$count] = -1;
299       return -1;
300     }
301   }
302   return $plurals[$count];
303 }
304
305 // ---------------------------------------------------------------------------------
306 // Language management functionality (administration only)
307
308 /**
309  * Page handler for the language management screen.
310  */
311 function locale_admin_manage() {
312   include_once './includes/locale.inc';
313   return _locale_admin_manage_screen();
314 }
315
316 /**
317  * User interface for the language deletion confirmation screen.
318  */
319 function locale_admin_manage_delete_form() {
320   include_once './includes/locale.inc';
321   $langcode = arg(4);
322
323   // Do not allow deletion of English locale.
324   if ($langcode == 'en') {
325     drupal_set_message(t('The English locale cannot be deleted.'));
326     drupal_goto('admin/locale/language/overview');
327   }
328
329   // For other locales, warn user that data loss is ahead.
330   $languages = locale_supported_languages(FALSE, TRUE);
331
332   if (!isset($languages['name'][$langcode])) {
333     drupal_not_found();
334   }
335   else {
336     $form['langcode'] = array('#type' => 'value', '#value' => $langcode);
337     return confirm_form('locale_admin_manage_delete_form', $form, t('Are you sure you want to delete the language %name?', array('%name' => theme('placeholder', t($languages['name'][$langcode])))), 'admin/locale/language/overview', t('Deleting a language will remove all data associated with it. This action cannot be undone.'), t('Delete'), t('Cancel'));
338   }
339 }
340
341 /**
342  * Process language deletion submissions.
343  */
344 function locale_admin_manage_delete_form_submit($form_id, $form_values) {
345   $languages = locale_supported_languages(FALSE, TRUE);
346   if (isset($languages['name'][$form_values['langcode']])) {
347     db_query("DELETE FROM {locales_meta} WHERE locale = '%s'", $form_values['langcode']);
348     db_query("DELETE FROM {locales_target} WHERE locale = '%s'", $form_values['langcode']);
349     $message = t('The language %locale has been removed.', array('%locale' => theme('placeholder', t($languages['name'][$form_values['langcode']]))));
350     drupal_set_message($message);
351     watchdog('locale', $message);
352   }
353
354   // Changing the locale settings impacts the interface:
355   cache_clear_all();
356
357   return 'admin/locale/language/overview';
358 }
359
360 /**
361  * Page handler for the language addition screen
362  */
363 function locale_admin_manage_add() {
364   include_once './includes/locale.inc';
365   return _locale_admin_manage_add_screen();
366 }
367
368 // ---------------------------------------------------------------------------------
369 // Gettext Portable Object import functionality (administration only)
370
371 /**
372  * Page handler for the translation import screen
373  */
374 function locale_admin_import() {
375   include_once './includes/locale.inc';
376   return _locale_admin_import_screen();
377 }
378
379 // ---------------------------------------------------------------------------------
380 // Gettext Portable Object export functionality (administration only)
381
382 /**
383  * Page handler for the translation export screen
384  */
385 function locale_admin_export() {
386   include_once './includes/locale.inc';
387   return _locale_admin_export_screen();
388 }
389
390 // ---------------------------------------------------------------------------------
391 // String search and editing functionality (administration only)
392
393 /**
394  * Page handler for the string search.
395  */
396 function locale_string_search() {
397   include_once './includes/locale.inc';
398   $output = _locale_string_seek();
399   $output .= _locale_string_seek_form();
400   return $output;
401 }
402
403 /**
404  * Display the string edit form.
405  */
406 function locale_admin_string_edit($lid) {
407   include_once './includes/locale.inc';
408   return _locale_string_edit($lid);
409 }
410
411 /**
412  * Delete a string.
413  */
414 function locale_admin_string_delete($lid) {
415   include_once './includes/locale.inc';
416   _locale_string_delete($lid);
417 }