Projet

Général

Profil

Paste
Télécharger (34,4 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / i18n / i18n_string / i18n_string.module @ 76df55b7

1
<?php
2

    
3
/**
4
 * @file
5
 * Internationalization (i18n) package - translatable strings.
6
 *
7
 * Object oriented string translation using locale and textgroups. As opposed to core locale strings,
8
 * all strings handled by this module will have a unique id (name), composed by several parts
9
 *
10
 * A string name or string id will have the form 'textgroup:type:objectid:property'. Examples:
11
 *
12
 * - 'profile:field:profile_name:title', will be the title for the profile field 'profile_name'
13
 * - 'taxonomy:term:tid:name', will be the name for the taxonomy term tid
14
 * - 'views:view_name:display_id:footer', footer text
15
 *
16
 * Notes:
17
 * - The object id must be an integer. This is intended for quick indexing of some properties
18
 *
19
 * Some concepts
20
 * - Textgroup. Group the string belongs to, defined by locale hook.
21
 * - Location. Unique id of the string for this textgroup.
22
 * - Name. Unique absolute id of the string: textgroup + location.
23
 * - Context. Object with textgroup, type, objectid, property.
24
 *
25
 * Default language
26
 * - Default language may be English or not. It will be the language set as default.
27
 *   Source strings will be stored in default language.
28
 * - In the traditional i18n use case you shouldn't change the default language once defined.
29
 *
30
 * Default language changes
31
 * - You might result in the need to change the default language at a later point.
32
 * - Enabling translation of default language will curcumvent previous limitations.
33
 * - Check i18n_string_translate_langcode() for more details.
34
 *
35
 * The API other modules to translate/update/remove user defined strings consists of
36
 *
37
 * @see i18n_string($name, $string, $langcode)
38
 * @see i18n_string_update($name, $string, $format)
39
 * @see i18n_string_remove($name, $string)
40
 *
41
 * @author Jose A. Reyero, 2007
42
 */
43

    
44
/**
45
 * Translated string is current.
46
 */
47
define('I18N_STRING_STATUS_CURRENT', 0);
48

    
49
/**
50
 * Translated string needs updating as the source has been edited.
51
 */
52
define('I18N_STRING_STATUS_UPDATE', 1);
53

    
54
/**
55
 * Source string is obsoleted, cannot be found anymore. To be deleted.
56
 */
57
define('I18N_STRING_STATUS_DELETE', 2);
58

    
59
/**
60
 * Special string formats/filters: Run through filter_xss
61
 */
62
define('I18N_STRING_FILTER_XSS', 'FILTER_XSS');
63

    
64
/**
65
 * Special string formats/filters: Run through filter_xss_admin
66
 */
67
define('I18N_STRING_FILTER_XSS_ADMIN', 'FILTER_XSS_ADMIN');
68

    
69
/**
70
 * Implements hook_help().
71
 */
72
function i18n_string_help($path, $arg) {
73
  switch ($path) {
74
    case 'admin/help#i18n_string':
75
      $output = '<p>' . t('This module adds support for other modules to translate user defined strings. Depending on which modules you have enabled that use this feature you may see different text groups to translate.') . '<p>';
76
      $output .= '<p>' . t('This works differently to Drupal standard localization system: The strings will be translated from the <a href="@configure-strings">source language</a>, which defaults to the site default language (it may not be English), so changing the default language may cause all these translations to be broken.', array('@configure-strings' => url('admin/config/regional/i18n/strings'))) . '</p>';
77
      $output .= '<ul>';
78
      $output .= '<li>' . t('To search and translate strings, use the <a href="@translate-interface">translation interface</a> pages.', array('@translate-interface' => url('admin/config/regional/translate'))) . '</li>';
79
      $output .= '<li>' . t('If you are missing strings to translate, use the <a href="@refresh-strings">refresh strings</a> page.', array('@refresh-strings' => url('admin/build/translate/refresh'))) . '</li>';
80
      $output .= '</ul>';
81
      $output .= '<p>' . t('Read more on the <em>Internationalization handbook</em>: <a href="http://drupal.org/node/313293">Translating user defined strings</a>.') . '</p>';
82
      return $output;
83

    
84
    case 'admin/config/regional/translate/i18n_string':
85
      $output = '<p>' . t('On this page you can refresh and update values for user defined strings.') . '</p>';
86
      $output .= '<ul>';
87
      $output .= '<li>' . t('Use the refresh option when you are missing strings to translate for a given text group. All the strings will be re-created keeping existing translations.') . '</li>';
88
      $output .= '<li>' . t('Use the update option when some of the strings had been previously translated with the localization system, but the translations are not showing up for the configurable strings.') . '</li>';
89
      $output .= '</ul>';
90
      $output .= '<p>' . t('To search and translate strings, use the <a href="@translate-interface">translation interface</a> pages.', array('@translate-interface' => url('admin/config/regional/translate'))) . '</p>';
91
      $output .= '<p>' . t('<strong>Important:</strong> To configure which text formats are safe for translation, visit the <a href="@configure-strings">configure strings</a> page before refreshing your strings.', array('@configure-strings' => url('admin/config/regional/i18n/strings'))) . '</p>';
92
      return $output;
93

    
94
    case 'admin/config/regional/language':
95
      $output = '<p>' . t('<strong>Warning</strong>: Changing the default language may have unwanted effects on string translations. Check also the <a href="@configure-strings">source language</a> for translations and read more about <a href="@i18n_string-help">String translation</a>', array('@configure-strings' => url('admin/config/regional/i18n/strings'), '@i18n_string-help' => url('admin/help/i18n_string'))) . '</p>';
96
      return $output;
97
    case 'admin/config/regional/i18n/strings':
98
      $output = '<p>' . t('When translating user defined strings that have a text format associated, translators will be able to edit the text before it is filtered which may be a security risk for some filters. An obvious example is when using the PHP filter but other filters may also be dangerous.') . '</p>';
99
      $output .= '<p>' . t('As a general rule <strong>do not allow any filtered text to be translated unless the translators already have access to that text format</strong>. However if you are doing all your translations through this site\'s translation UI or the Localization client, and never importing translations for other textgroups than <i>default</i>, filter access will be checked for translators on every translation page.') . '</p>';
100
      $output .= '<p>' . t('<strong>Important:</strong> After disallowing some text format, use the <a href="@refresh-strings">refresh strings</a> page so forbidden strings are deleted and not allowed anymore for translators.', array('@refresh-strings' => url('admin/config/regional/translate/i18n_string'))) . '</p>';
101
      return $output;
102
    case 'admin/config/filters':
103
      return '<p>' . t('After updating your text formats do not forget to review the list of formats allowed for string translations on the <a href="@configure-strings">configure translatable strings</a> page.', array('@configure-strings' => url('admin/config/regional/i18n/strings'))) . '</p>';
104
  }
105
}
106

    
107
/**
108
 * Implements hook_menu().
109
 */
110
function i18n_string_menu() {
111
  $items['admin/config/regional/translate/i18n_string'] = array(
112
    'title' => 'Strings',
113
    'description' => 'Refresh user defined strings.',
114
    'weight' => 20,
115
    'type' => MENU_LOCAL_TASK,
116
    'page callback' => 'drupal_get_form',
117
    'page arguments' => array('i18n_string_admin_refresh_form'),
118
    'file' => 'i18n_string.admin.inc',
119
    'access arguments' => array('translate interface'),
120
  );
121
  $items['admin/config/regional/i18n/strings'] = array(
122
    'title' => 'Strings',
123
    'description' => 'Options for user defined strings.',
124
    'weight' => 20,
125
    'type' => MENU_LOCAL_TASK,
126
    'page callback' => 'drupal_get_form',
127
    'page arguments' => array('variable_edit_form', array('i18n_string_allowed_formats', 'i18n_string_source_language')),
128
    'access arguments' => array('administer site configuration'),
129
  );
130
  // AJAX callback path for strings.
131
  $items['i18n_string/save'] = array(
132
    'title' => 'Save string',
133
    'page callback' => 'i18n_string_l10n_client_save_string',
134
    'access arguments' => array('use on-page translation'),
135
    'file' => 'i18n_string.pages.inc',
136
    'type' => MENU_CALLBACK,
137
  );
138
  return $items;
139
}
140

    
141
/**
142
 * Implements hook_menu_alter().
143
 *
144
 * Take over the locale translation page.
145
 */
146
function i18n_string_menu_alter(&$items) {
147
  $items['admin/config/regional/translate/edit/%'] = array(
148
    'title' => 'Edit string',
149
    'page callback' => 'drupal_get_form',
150
    'page arguments' => array('i18n_string_locale_translate_edit_form', 5),
151
    'access arguments' => array('translate interface'),
152
    'file' => 'i18n_string.pages.inc',
153
    'file path' => drupal_get_path('module', 'i18n_string'),
154
  );
155
}
156

    
157
/**
158
 * Implements hook_hook_info().
159
 */
160
function i18n_string_hook_info() {
161
  $hooks['i18n_string_info'] =
162
  $hooks['i18n_string_list'] =
163
  $hooks['i18n_string_refresh'] =
164
  $hooks['i18n_string_objects'] = array(
165
    'group' => 'i18n',
166
  );
167
  return $hooks;
168
}
169

    
170
/**
171
 * Implements hook_locale().
172
 *
173
 * Provide the information from i18n_string groups to locale module
174
 */
175
function i18n_string_locale($op = 'groups') {
176
  if ($op == 'groups') {
177
    $groups = array();
178
    foreach (i18n_string_group_info() as $name => $info) {
179
      $groups[$name] = $info['title'];
180
    }
181
    return $groups;
182
  }
183
}
184

    
185
/**
186
 * Implements hook_permission().
187
 */
188
function i18n_string_permission() {
189
  return array(
190
    'translate user-defined strings' => array(
191
      'title' => t('Translate user-defined strings'),
192
      'description' => t('Translate user-defined strings that are created as part of content or configuration.'),
193
      'restrict access' => TRUE,
194
    ),
195
    'translate admin strings' => array(
196
      'title' => t('Translate admin strings'),
197
      'description' => t('Translate administrative strings with a very permissive XSS/HTML filter that allows all HTML tags.'),
198
      'restrict access' => TRUE,
199
    ),
200
  );
201
}
202

    
203
/**
204
 * Implements hook_modules_enabled().
205
 */
206
function i18n_string_modules_enabled($modules) {
207
  module_load_include('admin.inc', 'i18n_string');
208
  i18n_string_refresh_enabled_modules($modules);
209
}
210

    
211
/**
212
 * Implements hook_modules_uninstalled().
213
 */
214
function i18n_string_modules_uninstalled($modules) {
215
  module_load_include('admin.inc', 'i18n_string');
216
  i18n_string_refresh_uninstalled_modules($modules);
217
}
218

    
219
/**
220
 * Implements hook_form_FORM_ID_alter()
221
 */
222
function i18n_string_form_l10n_client_form_alter(&$form, &$form_state) {
223
  $form['#action'] = url('i18n_string/save');
224
}
225

    
226
/**
227
 * Implements hook_form_FORM_ID_alter()
228
 */
229
function i18n_string_form_locale_translate_export_po_form_alter(&$form, $form_state) {
230
  $names = locale_language_list('name', TRUE);
231
  if (i18n_string_source_language() != 'en' && array_key_exists('en', $names)) {
232
    $form['langcode']['#options']['en'] = $names['en'];
233
  }
234
}
235

    
236
/**
237
 * Implements hook_form_FORM_ID_alter()
238
 */
239
function i18n_string_form_locale_translate_import_form_alter(&$form, $form_state) {
240
  if (i18n_string_source_language() != 'en') {
241
    $names = locale_language_list('name', TRUE);
242
    if (array_key_exists('en', $names)) {
243
      $form['import']['langcode']['#options'][t('Already added languages')]['en'] = $names['en'];
244
    }
245
    else {
246
      $form['import']['langcode']['#options'][t('Languages not yet added')]['en'] = t('English');
247
    }
248
  }
249
  $form['#submit'][] = 'i18n_string_locale_translate_import_form_submit';
250
}
251

    
252
/**
253
 * Update string data after import form submit
254
 */
255
function i18n_string_locale_translate_import_form_submit($form, &$form_state) {
256
  if (!drupal_get_messages('error', FALSE) && i18n_string_group_info($form_state['values']['group'])) {
257
    i18n_string_textgroup($form_state['values']['group'])->update_check();
258
  }
259
}
260

    
261
/**
262
 * Check if translation is required for this language code.
263
 *
264
 * Translation is required when default language is different from the given
265
 * language, or when default language translation is explicitly enabled.
266
 *
267
 * No UI is provided to enable translation of default language. On the other
268
 * hand, you can enable/disable translation for a specific language by adding
269
 * the following to your settings.php
270
 *
271
 * @param $langcode
272
 *   Optional language code to check. It will default to current request language.
273
 * @code
274
 *   // Enable translation of specific language. Language code is 'xx'
275
 *   $conf['i18n_string_translate_langcode_xx'] = TRUE;
276
 *   // Disable translation of specific language. Language code is 'yy'
277
 *   $conf['i18n_string_translate_langcode_yy'] = FALSE;
278
 * @endcode
279
 */
280
function i18n_string_translate_langcode($langcode = NULL) {
281
  $translate = &drupal_static(__FUNCTION__);
282
  $langcode = isset($langcode) ? $langcode : i18n_langcode();
283
  if (!isset($translate[$langcode])) {
284
    $translate[$langcode] = variable_get('i18n_string_translate_langcode_' . $langcode, i18n_string_source_language() != $langcode);
285
  }
286
  return $translate[$langcode];
287
}
288

    
289
/**
290
 * Create string class from string name
291
 */
292
function i18n_string_build($name, $string = NULL) {
293
  list ($group, $context) = i18n_string_context($name);
294
  return i18n_string_textgroup($group)->build_string($context, $string);
295
}
296

    
297
/**
298
 * Update / create translation source for user defined strings.
299
 *
300
 * @param $name
301
 *   Array or string concatenated with ':' that contains textgroup and string context
302
 * @param $string
303
 *   Source string in default language. Default language may or may not be English.
304
 *   Array of key => string to update multiple strings at once
305
 * @param $options
306
 *   Array with additional options:
307
 *   - 'format', String format if the string has text format
308
 *   - 'messages', Whether to print out status messages
309
 */
310
function i18n_string_update($name, $string, $options = array()) {
311
  if (is_array($string)) {
312
    return i18n_string_multiple('update', $name, $string, $options);
313
  }
314
  else {
315
    list($textgroup, $context) = i18n_string_context($name);
316
    return i18n_string_textgroup($textgroup)->context_update($context, $string, $options);
317
  }
318
}
319

    
320
/**
321
 * Update context for strings.
322
 *
323
 * As some string locations depend on configurable values, the field needs sometimes to be updated
324
 * without losing existing translations. I.e:
325
 * - profile fields indexed by field name.
326
 * - content types indexted by low level content type name.
327
 *
328
 * Example:
329
 *  'profile:field:oldfield:*' -> 'profile:field:newfield:*'
330
 */
331
function i18n_string_update_context($oldname, $newname) {
332
  module_load_install('i18n_string');
333
  return i18n_string_install_update_context($oldname, $newname);
334
}
335

    
336
/**
337
 * Get textgroup handler
338
 */
339
function i18n_string_textgroup($textgroup) {
340
  $groups = &drupal_static(__FUNCTION__);
341
  if (!isset($groups[$textgroup])) {
342
    $class = i18n_string_group_info($textgroup, 'class', 'i18n_string_textgroup_default');
343
    $groups[$textgroup] = new $class($textgroup);
344
  }
345
  return $groups[$textgroup];
346
}
347

    
348
/**
349
 * Check whether a string format is allowed for translation.
350
 */
351
function i18n_string_allowed_format($format_id = NULL) {
352
  if (!$format_id || $format_id === I18N_STRING_FILTER_XSS || $format_id === I18N_STRING_FILTER_XSS_ADMIN) {
353
    return TRUE;
354
  }
355
  else {
356
    // Check the format still exists an it is in the allowed formats list.
357
    return filter_format_load($format_id) && in_array($format_id, variable_get('i18n_string_allowed_formats', array(filter_fallback_format())), TRUE);
358
  }
359
}
360

    
361
/**
362
 * Convert string name into textgroup and string context
363
 *
364
 * @param $name
365
 *   Array or string concatenated with ':' that contains textgroup and string context
366
 * @param $replace
367
 *   Parameter to replace the placeholder ('*') if we are dealing with multiple strings
368
 *   Or parameter to append to context if there's no placeholder
369
 *
370
 * @return array
371
 *   The first element will be the text group name
372
 *   The second one will be an array with string name elements, without textgroup
373
 */
374
function i18n_string_context($name, $replace = NULL) {
375
  $parts = is_array($name) ? $name : explode(':', $name);
376
  if ($replace) {
377
    $key = array_search('*', $parts);
378
    if ($key !== FALSE) {
379
      $parts[$key] = $replace;
380
    }
381
    elseif (count($parts) < 4) {
382
      array_push($parts, $replace);
383
    }
384
  }
385
  $textgroup = array_shift($parts);
386
  $context = $parts;
387
  return array($textgroup, $context);
388
}
389

    
390
/**
391
 * Mark form element as localizable
392
 */
393
function i18n_string_element_mark(&$element) {
394
  $description = '<strong>' . t('This string will be localizable. You can translate it using the <a href="@translate-interface">translate interface</a> pages.', array('@translate-interface' => url('admin/config/regional/translate/translate'))) . '</strong>';
395
  if (empty($element['#description'])) {
396
    $element['#description'] = $description;
397
  }
398
  else {
399
    $element['#description'] .= ' ' . $description;
400
  }
401
}
402

    
403

    
404
/**
405
 * Get source string object.
406
 *
407
 * This returns the i18nstring object only when it has a source.
408
 *
409
 * @return i18n_string_object
410
 */
411
function i18n_string_get_source($name) {
412
  return i18n_string_build($name)->get_source();
413
}
414

    
415
/**
416
 * Get full string object.
417
 *
418
 * Builds string and loads the source if available.
419
 *
420
 * @return i18n_string_object
421
 */
422
function i18n_string_get_string($name, $default = NULL) {
423
  $i18nstring = i18n_string_build($name, $default);
424
  $i18nstring->get_source();
425
  return $i18nstring;
426
}
427

    
428
/**
429
 * Get full string object by lid.
430
 */
431
function i18n_string_get_by_lid($lid) {
432
  $strings = i18n_string_load_multiple(array('lid' => $lid));
433
  return reset($strings);
434
}
435

    
436
/**
437
 * Load multiple strings, including string source
438
 *
439
 * @param $conditions
440
 *   Array of conditions for i18n_string table.
441
 *
442
 * @return $strings
443
 *   List of i18n string objects
444
 */
445
function i18n_string_load_multiple($conditions) {
446
  // The primary table here will be i18n_string, though we add source too.
447
  $query = db_select('i18n_string', 'i')
448
    ->fields('i');
449
  $query->leftJoin('locales_source', 's', 'i.lid = s.lid');
450
  $query->fields('s', array('source', 'version', 'location'));
451
  // Add text group condition and add conditions to the query
452
  foreach ($conditions as $field => $value) {
453
    $alias = in_array($field, array('source', 'version', 'location')) ? 's' : 'i';
454
    $query->condition($alias . '.' . $field, $value);
455
  }
456
  // this patch  is a workaround for core file bug in file
457
  // include/database/prefetch.inc (see: http://drupal.org/node/1567216)
458
  // return $query->execute()->fetchAll(PDO::FETCH_CLASS, 'i18n_string_object');
459
  $stmt = $query->execute();
460
  $stmt->setFetchMode(PDO::FETCH_CLASS, 'i18n_string_object');
461
  return $stmt->fetchAll();
462
}
463

    
464
/**
465
 * Get textgroup info, from hook_locale('info')
466
 *
467
 * @param $group
468
 *   Text group name.
469
 * @param $default
470
 *   Default value to return for a property if not set.
471
 */
472
function i18n_string_group_info($group = NULL, $property = NULL, $default = NULL) {
473
  $info = &drupal_static(__FUNCTION__ , NULL);
474

    
475
  if (!isset($info)) {
476
    $info = module_invoke_all('i18n_string_info');
477
    drupal_alter('i18n_string_info', $info);
478
  }
479

    
480
  if ($group && $property) {
481
    return isset($info[$group][$property]) ? $info[$group][$property] : $default;
482
  }
483
  elseif ($group) {
484
    return isset($info[$group]) ? $info[$group] : array();
485
  }
486
  else {
487
    return $info;
488
  }
489
}
490

    
491

    
492
/**
493
 * Translate / update multiple strings
494
 *
495
 * @param $strings
496
 *   Array of name => string pairs
497
 */
498
function i18n_string_multiple($operation, $name, $strings, $options = array()) {
499
  $result = array();
500
  // Strings may be an array of properties, we need to shift it
501
  if ($operation == 'remove') {
502
    $strings = array_flip($strings);
503
  }
504
  foreach ($strings as $key => $string) {
505
    list($textgroup, $context) = i18n_string_context($name, $key);
506
    array_unshift($context, $textgroup);
507
    $result[$key] = call_user_func('i18n_string_' . $operation, $context, $string, $options);
508
  }
509
  return $result;
510
}
511

    
512
/**
513
 * @ingroup i18napi
514
 * @{
515
 */
516

    
517
/**
518
 * Get translation for user defined string.
519
 *
520
 * This function is intended to return translations for plain strings that have NO text format
521
 *
522
 * @param $name
523
 *   Array or string concatenated with ':' that contains textgroup and string context
524
 * @param $string
525
 *   String in default language or array of strings to be translated
526
 * @param $options
527
 *   An associative array of additional options, with the following keys:
528
 *   - 'langcode' (defaults to the current language) The language code to translate to a language other than what is used to display the page.
529
 *   - 'filter' Filtering callback to apply to the translated string only
530
 *   - 'format' Input format to apply to the translated string only
531
 *   - 'callback' Callback to apply to the result (both to translated or untranslated string
532
 *   - 'sanitize' Whether to filter the translation applying the text format if any, default is TRUE
533
 *   - 'sanitize default' Whether to filter the default value if no translation found, default is FALSE
534
 */
535
function i18n_string_translate($name, $string, $options = array()) {
536
  if (is_array($string)) {
537
    return i18n_string_translate_list($name, $string, $options);
538
  }
539
  else {
540
    $options['langcode'] = $langcode = isset($options['langcode']) ? $options['langcode'] : i18n_langcode();
541
    if (i18n_string_translate_langcode($langcode)) {
542
      list($textgroup, $context) = i18n_string_context($name);
543
      $translation = i18n_string_textgroup($textgroup)->context_translate($context, $string, $options);
544
      // Add for l10n client if available, we pass translation object that contains the format
545
      i18n_string_l10n_client_add($translation, $langcode);
546
      return $translation->format_translation($langcode, $options);
547
    }
548
    else {
549
      // If we don't want to translate to this language, format and return
550
      $options['sanitize'] = !empty($options['sanitize default']);
551
      return i18n_string_format($string, $options);
552
    }
553
  }
554
}
555

    
556
/**
557
 * Check user access to translate a specific string.
558
 *
559
 * If the string has a format the user is not allowed to edit, it will return FALSE
560
 *
561
 * @param $string_format;
562
 *   String object or $format_id
563
 */
564
function i18n_string_translate_access($string_format, $account = NULL) {
565
  $format_id = is_object($string_format) ? i18n_object_field($string_format, 'format') : $string_format;
566
  return user_access('translate interface', $account) &&
567
    (empty($format_id) || i18n_string_allowed_format($format_id) && ($format = filter_format_load($format_id)) && filter_access($format, $account));
568
}
569

    
570
/**
571
 * Check whether there is any problem for the  user to translate a specific string.
572
 *
573
 * Here we assume the user has 'translate interface' access that should have
574
 * been checked for the page. Possible reasons a user cannot translate a string:
575
 *
576
 * @param $i18nstring
577
 *   String object.
578
 * @param $account
579
 *   Optional user account, defaults to current user.
580
 *
581
 * @return
582
 *   None or empty string if the user has access to translate the string.
583
 *   Message if the user cannot translate that string.
584
 */
585
function i18n_string_translate_check_string($i18nstring, $account = NULL) {
586
  if (!user_access('translate interface', $account) || !user_access('translate user-defined strings', $account)) {
587
    return t('This is a user-defined string. You are not allowed to translate these strings.');
588
  }
589
  elseif (!empty($i18nstring->format)) {
590
    if (!i18n_string_allowed_format($i18nstring->format)) {
591
      $format = filter_format_load($i18nstring->format);
592
      return t('This string uses the %name text format. Strings with this format are not allowed for translation.', array('%name' => $format->name));
593
    }
594
    elseif ($format = filter_format_load($i18nstring->format)) {
595
      // It is a text format, check user access to that text format.
596
      if (!filter_access($format, $account)) {
597
        return t('This string uses the %name text format. You are not allowed to translate or edit texts with this format.', array('%name' => $format->name));
598
      }
599
    }
600
    else {
601
      // This is one of our special formats, I18N_STRING_FILTER_*
602
      if ($i18nstring->format == I18N_STRING_FILTER_XSS_ADMIN && !user_access('translate admin strings', $account)) {
603
        return t('The source string is an administrative string. You are not allowed to translate these strings.');
604
      }
605
    }
606
  }
607
  // No error message, it should be OK to translate.
608
  return '';
609
}
610

    
611
/**
612
 * Format the resulting translation or the default string applying callbacks
613
 *
614
 * @param $string
615
 *   Text string.
616
 * @param $options
617
 *   Array of options for string formatting:
618
 *   - 'format', text format to apply to the string, defaults to none.
619
 *   - 'sanitize', whether to apply the text format, defaults to TRUE.
620
 *   - 'cache', text format parameter.
621
 *   - 'langcode', text format parameter, defaults to current page language.
622
 *   - 'allowed_tags', allowed HTML tags when format is I18N_STRING_FILTER_XSS
623
 */
624
function i18n_string_format($string, $options = array()) {
625
  $options += array('langcode' => i18n_langcode(), 'format' => FALSE, 'sanitize' => TRUE, 'cache' => FALSE);
626
  // Apply format and callback
627
  if ($string) {
628
    if ($options['sanitize']) {
629
      if ($options['format']) {
630
        // Handle special format values (xss, xss_admin)
631
        switch ($options['format']) {
632
          case I18N_STRING_FILTER_XSS:
633
            $string = !empty($options['allowed_tags']) ? filter_xss($string, $options['allowed_tags']) : filter_xss($string);
634
            break;
635
          case I18N_STRING_FILTER_XSS_ADMIN:
636
            $string = filter_xss_admin($string);
637
            break;
638
          default:
639
            $string = check_markup($string, $options['format'], $options['langcode'], $options['cache']);
640
        }
641
      }
642
      else {
643
        $string = check_plain($string);
644
      }
645
    }
646
    if (isset($options['callback'])) {
647
      $string = call_user_func($options['callback'], $string);
648
    }
649
  }
650
  // Finally, apply prefix and suffix
651
  $options += array('prefix' => '', 'suffix' => '');
652
  return $options['prefix'] . $string . $options['suffix'];
653
}
654

    
655
/**
656
 * Get filtered translation.
657
 *
658
 * This function is intended to return translations for strings that have a text format
659
 *
660
 * @param $name
661
 *   Array or string concatenated with ':' that contains textgroup and string context
662
 * @param $default
663
 *   Default string to return if not found, already filtered
664
 * @param $options
665
 *   Array with additional options.
666
 */
667
function i18n_string_text($name, $default, $options = array()) {
668
  $options += array('format' => filter_fallback_format(), 'sanitize' => TRUE);
669
  return i18n_string_translate($name, $default, $options);
670
}
671

    
672
/**
673
 * Translation for plain string. In case it finds a translation it applies check_plain() to it
674
 *
675
 * @param $name
676
 *   Array or string concatenated with ':' that contains textgroup and string context
677
 * @param $default
678
 *   Default string to return if not found
679
 * @param $options
680
 *   Array with additional options
681
 */
682
function i18n_string_plain($name, $default, $options = array()) {
683
  $options += array('filter' => 'check_plain');
684
  return i18n_string_translate($name, $default, $options);
685
}
686

    
687
/**
688
 * Get source language code for translations
689
 */
690
function i18n_string_source_language() {
691
  return variable_get('i18n_string_source_language', language_default('language'));
692
}
693

    
694
/**
695
 * Translation for list of options
696
 *
697
 * @param $options
698
 *   Array with additional options, some changes
699
 *   - 'index' => field that will be mapped to the array key (defaults to 'property')
700
 */
701
function i18n_string_translate_list($name, $strings, $options = array()) {
702
  $options['langcode'] = $langcode = isset($options['langcode']) ? $options['langcode'] : i18n_langcode();
703
  // If language is default, just return
704
  if (i18n_string_translate_langcode($langcode)) {
705
    // Get textgroup context, preserve placeholder
706
    list($textgroup, $context) = i18n_string_context($name, '*');
707
    $translations = i18n_string_textgroup($textgroup)->multiple_translate($context, $strings, $options);
708
    // Add for l10n client if available, we pass translation object that contains the format
709
    foreach ($translations as $index => $translation) {
710
      i18n_string_l10n_client_add($translation, $langcode);
711
      $strings[$index] = $translation->format_translation($langcode, $options);
712
    }
713
  }
714
  else {
715
    // Format and return
716
    foreach ($strings as $key => $string) {
717
      $strings[$key] = i18n_string_format($string, $options);
718
    }
719
  }
720
  return $strings;
721
}
722

    
723
/**
724
 * Remove source and translations for user defined string.
725
 *
726
 * Though for most strings the 'name' or 'string id' uniquely identifies that string,
727
 * there are some exceptions (like profile categories) for which we need to use the
728
 * source string itself as a search key.
729
 *
730
 * @param $name
731
 *   String name
732
 * @param $string
733
 *   Optional source string (string in default language).
734
 *   Array of string properties to remove
735
 */
736
function i18n_string_remove($name, $string = NULL, $options = array()) {
737
  if (is_array($string)) {
738
    return i18n_string_multiple('remove', $name, $string, $options);
739
  }
740
  else {
741
    list($textgroup, $context) = i18n_string_context($name);
742
    return i18n_string_textgroup($textgroup)->context_remove($context, $string, $options);
743
  }
744
}
745

    
746
/**
747
 * @} End of "ingroup i18napi".
748
 */
749

    
750
/*** l10n client related functions ***/
751

    
752
/**
753
 * Add string to l10n strings if enabled and allowed for this string
754
 *
755
 * @param $context
756
 *   String object
757
 */
758
function i18n_string_l10n_client_add($string, $langcode) {
759
  // If current language add to l10n client list for later on page translation.
760
  // If langcode translation was disabled we are not supossed to reach here.
761
  if (($langcode == i18n_langcode()) && function_exists('l10_client_add_string_to_page') && user_access('translate interface')) {
762
    if (!$string->check_translate_access()) {
763
      $translation = $string->get_translation($langcode);
764
      $source = !empty($string->source) ? $string->source : $string->string;
765
      l10_client_add_string_to_page($source, $translation ? $translation : TRUE, $string->textgroup, $string->context);
766
    }
767
  }
768
}
769

    
770
/**
771
 * Get information about object string translation
772
 */
773
function i18n_string_object_info($type = NULL, $property = NULL) {
774
  if ($type) {
775
    if (($info = i18n_object_info($type, 'string translation'))) {
776
      if ($property) {
777
        return isset($info[$property]) ? $info[$property] : NULL;
778
      }
779
      else {
780
        return $info;
781
      }
782
    }
783
  }
784
  else {
785
    $list = array();
786
    foreach (i18n_object_info() as $type => $info) {
787
      if (!empty($info['string translation'])) {
788
        $list[$type] = $info;
789
      }
790
    }
791
    return $list;
792
  }
793
}
794

    
795
/**
796
 * Implements hook_i18n_object_info_alter().
797
 *
798
 * Set a different default object wrapper for objects that have string translation.
799
 */
800
function i18n_string_i18n_object_info_alter(&$object_info) {
801
  foreach ($object_info as $type => &$info) {
802
    if (!empty($info['string translation']) && (empty($info['class']) || $info['class'] == 'i18n_object_wrapper')) {
803
      $info['class'] = 'i18n_string_object_wrapper';
804
    }
805
  }
806
}
807

    
808
/**
809
 * Translate object properties
810
 *
811
 * We clone the object previously so we don't risk translated properties being saved
812
 *
813
 * @param $type
814
 *   Object type
815
 * @param $object
816
 *   Object or array
817
 */
818
function i18n_string_object_translate($type, $object, $options = array()) {
819
  $langcode = isset($options['langcode']) ? $options['langcode'] : i18n_langcode();
820
  if (i18n_string_translate_langcode($langcode)) {
821
    // Object properties will be returned without filtering as in the original one.
822
    $options += array('sanitize' => FALSE);
823
    return i18n_object($type, $object)->translate($langcode, $options);
824
  }
825
  else {
826
    return $object;
827
  }
828
}
829

    
830
/**
831
 * Remove object strings, because object is deleted
832
 *
833
 * @param $type
834
 *   Object type
835
 * @param $object
836
 *   Object or array
837
 */
838
function i18n_string_object_remove($type, $object, $options = array()) {
839
  return i18n_object($type, $object)->strings_remove($options);
840
}
841

    
842
/**
843
 * Update object properties.
844
 *
845
 * @param $type
846
 *   Object type
847
 * @param $object
848
 *   Object or array
849
 */
850
function i18n_string_object_update($type, $object, $options = array()) {
851
  return i18n_object($type, $object)->strings_update($options);
852
}
853

    
854
/**
855
 * Generic translation page for i18n_strings objects.
856
 */
857
function i18n_string_object_translate_page($object_type, $object_value, $language = NULL) {
858
  module_load_include('inc', 'i18n_string', 'i18n_string.pages');
859
  return i18n_string_translate_page_object($object_type, $object_value, $language);
860
}
861

    
862
/**
863
 * Preload all strings for this textroup/context.
864
 *
865
 * This is a performance optimization to load all needed strings with a single query.
866
 *
867
 * Examples of valid string name to search are:
868
 *  - 'taxonomy:term:*:title'
869
 *    This will find all titles for taxonomy terms
870
 *  - array('taxonomy', 'term', array(1,2), '*')
871
 *    This will find all properties for taxonomy terms 1 and 2
872
 *
873
 * @param $name
874
 *   Specially crafted string name, it may take '*' and array parameters for each element.
875
 * @param $langcode
876
 *   Language code to search translations. Defaults to current language.
877
 *
878
 * @return array()
879
 *   String objects indexed by context.
880
 */
881
function i18n_string_translation_search($name, $langcode = NULL) {
882
  $langcode = isset($langcode) ? $langcode : i18n_langcode();
883
  list ($textgroup, $context) = i18n_string_context($name);
884
  return i18n_string_textgroup($textgroup)->multiple_translation_search($context, $langcode);
885
}
886

    
887
/**
888
 * Update / create translation for a certain source.
889
 *
890
 * @param $name
891
 *   Array or string concatenated with ':' that contains textgroup and string context
892
 * @param $translation
893
 *   Translation string for this language code
894
 * @param $langcode
895
 *   The language code to translate to a language other than what is used to display the page.
896
 * @param $source_string
897
 *   Optional source string, just in case it needs to be created.
898
 *
899
 * @return mixed
900
 *   Source string object if update was successful.
901
 *   Null if source string not found.
902
 *   FALSE if use doesn't have permission to edit this translation.
903
 */
904
function i18n_string_translation_update($name, $translation, $langcode, $source_string = NULL) {
905
  if (is_array($translation)) {
906
    return i18n_string_multiple('translation_update', $name, $translation, $langcode);
907
  }
908
  elseif ($source = i18n_string_get_source($name)) {
909
    if ($langcode == i18n_string_source_language()) {
910
      // It's the default language so we should update the string source as well.
911
      i18n_string_update($name, $translation);
912
    }
913
    else {
914
      list ($textgroup, $context) = i18n_string_context($name);
915
      i18n_string_textgroup($textgroup)->update_translation($context, $langcode, $translation);
916
    }
917
    return $source;
918
  }
919
  elseif ($source_string) {
920
    // We don't have a source in the database, so we need to create it, but only if we've got the source too.
921
    // Note this string won't have any format.
922
    i18n_string_update($name, $source_string);
923
    return i18n_string_translation_update($name, $translation, $langcode);
924
  }
925
  else {
926
    return NULL;
927
  }
928
}
929

    
930
/**
931
 * Count operation results by result value
932
 */
933
function _i18n_string_result_count($list) {
934
  $result = array();
935
  foreach ($list as $value) {
936
    $key = (string)$value;
937
    $result[$key] = isset($result[$key]) ? $result[$key] +1 : 1;
938
  }
939
  return $result;
940
}