i18n_string.module

Tracking 7.x-1.x branch
  1. drupal
    1. 7 contributions/i18n/i18n_string/i18n_string.module

Internationalization (i18n) package - translatable strings.

Object oriented string translation using locale and textgroups. As opposed to core locale strings, all strings handled by this module will have a unique id (name), composed by several parts

A string name or string id will have the form 'textgroup:type:objectid:property'. Examples:

  • 'profile:field:profile_name:title', will be the title for the profile field 'profile_name'
  • 'taxonomy:term:tid:name', will be the name for the taxonomy term tid
  • 'views:view_name:display_id:footer', footer text

Notes:

  • The object id must be an integer. This is intended for quick indexing of some properties

Some concepts

  • Textgroup. Group the string belongs to, defined by locale hook.
  • Location. Unique id of the string for this textgroup.
  • Name. Unique absolute id of the string: textgroup + location.
  • Context. Object with textgroup, type, objectid, property.

Default language

  • Default language may be English or not. It will be the language set as default. Source strings will be stored in default language.
  • In the traditional i18n use case you shouldn't change the default language once defined.

Default language changes

  • You might result in the need to change the default language at a later point.
  • Enabling translation of default language will curcumvent previous limitations.
  • Check i18n_string_translate_langcode() for more details.

The API other modules to translate/update/remove user defined strings consists of

@author Jose A. Reyero, 2007

See also

i18n_string($name, $string, $langcode)

i18n_string_update($name, $string, $format)

i18n_string_remove($name, $string)

Functions & methods

NameDescription
i18n_string_allowed_formatCheck whether a string format is allowed for translation.
i18n_string_buildCreate string class from string name
i18n_string_contextConvert string name into textgroup and string context
i18n_string_element_markMark form element as localizable
i18n_string_formatFormat the resulting translation or the default string applying callbacks
i18n_string_form_l10n_client_form_alterImplements hook_form_FORM_ID_alter()
i18n_string_form_locale_translate_export_po_form_alterImplements hook_form_FORM_ID_alter()
i18n_string_form_locale_translate_import_form_alterImplements hook_form_FORM_ID_alter()
i18n_string_get_by_lidGet full string object by lid.
i18n_string_get_sourceGet source string object.
i18n_string_get_stringGet full string object.
i18n_string_group_infoGet textgroup info, from hook_locale('info')
i18n_string_helpImplements hook_help().
i18n_string_hook_infoImplements hook_hook_info().
i18n_string_i18n_object_info_alterImplements hook_i18n_object_info_alter().
i18n_string_l10n_client_addAdd string to l10n strings if enabled and allowed for this string
i18n_string_load_multipleLoad multiple strings, including string source
i18n_string_localeImplements hook_locale().
i18n_string_locale_translate_import_form_submitUpdate string data after import form submit
i18n_string_menuImplements hook_menu().
i18n_string_menu_alterImplements hook_menu_alter().
i18n_string_modules_enabledImplements hook_modules_enabled().
i18n_string_modules_uninstalledImplements hook_modules_uninstalled().
i18n_string_multipleTranslate / update multiple strings
i18n_string_object_infoGet information about object string translation
i18n_string_object_removeRemove object strings, because object is deleted
i18n_string_object_translateTranslate object properties
i18n_string_object_translate_pageGeneric translation page for i18n_strings objects.
i18n_string_object_updateUpdate object properties.
i18n_string_permissionImplements hook_permission().
i18n_string_plainTranslation for plain string. In case it finds a translation it applies check_plain() to it
i18n_string_removeRemove source and translations for user defined string.
i18n_string_source_languageGet source language code for translations
i18n_string_textGet filtered translation.
i18n_string_textgroupGet textgroup handler
i18n_string_translateGet translation for user defined string.
i18n_string_translate_accessCheck user access to translate a specific string.
i18n_string_translate_check_stringCheck whether there is any problem for the user to translate a specific string.
i18n_string_translate_langcodeCheck if translation is required for this language code.
i18n_string_translate_listTranslation for list of options
i18n_string_translation_searchPreload all strings for this textroup/context.
i18n_string_translation_updateUpdate / create translation for a certain source.
i18n_string_updateUpdate / create translation source for user defined strings.
i18n_string_update_contextUpdate context for strings.
_i18n_string_result_countCount operation results by result value

Constants

NameDescription
I18N_STRING_FILTER_XSSSpecial string formats/filters: Run through filter_xss
I18N_STRING_FILTER_XSS_ADMINSpecial string formats/filters: Run through filter_xss_admin
I18N_STRING_STATUS_CURRENTTranslated string is current.
I18N_STRING_STATUS_DELETESource string is obsoleted, cannot be found anymore. To be deleted.
I18N_STRING_STATUS_UPDATETranslated string needs updating as the source has been edited.

File

View source
  1. <?php
  2. /**
  3. * @file
  4. * Internationalization (i18n) package - translatable strings.
  5. *
  6. * Object oriented string translation using locale and textgroups. As opposed to core locale strings,
  7. * all strings handled by this module will have a unique id (name), composed by several parts
  8. *
  9. * A string name or string id will have the form 'textgroup:type:objectid:property'. Examples:
  10. *
  11. * - 'profile:field:profile_name:title', will be the title for the profile field 'profile_name'
  12. * - 'taxonomy:term:tid:name', will be the name for the taxonomy term tid
  13. * - 'views:view_name:display_id:footer', footer text
  14. *
  15. * Notes:
  16. * - The object id must be an integer. This is intended for quick indexing of some properties
  17. *
  18. * Some concepts
  19. * - Textgroup. Group the string belongs to, defined by locale hook.
  20. * - Location. Unique id of the string for this textgroup.
  21. * - Name. Unique absolute id of the string: textgroup + location.
  22. * - Context. Object with textgroup, type, objectid, property.
  23. *
  24. * Default language
  25. * - Default language may be English or not. It will be the language set as default.
  26. * Source strings will be stored in default language.
  27. * - In the traditional i18n use case you shouldn't change the default language once defined.
  28. *
  29. * Default language changes
  30. * - You might result in the need to change the default language at a later point.
  31. * - Enabling translation of default language will curcumvent previous limitations.
  32. * - Check i18n_string_translate_langcode() for more details.
  33. *
  34. * The API other modules to translate/update/remove user defined strings consists of
  35. *
  36. * @see i18n_string($name, $string, $langcode)
  37. * @see i18n_string_update($name, $string, $format)
  38. * @see i18n_string_remove($name, $string)
  39. *
  40. * @author Jose A. Reyero, 2007
  41. */
  42. /**
  43. * Translated string is current.
  44. */
  45. define('I18N_STRING_STATUS_CURRENT', 0);
  46. /**
  47. * Translated string needs updating as the source has been edited.
  48. */
  49. define('I18N_STRING_STATUS_UPDATE', 1);
  50. /**
  51. * Source string is obsoleted, cannot be found anymore. To be deleted.
  52. */
  53. define('I18N_STRING_STATUS_DELETE', 2);
  54. /**
  55. * Special string formats/filters: Run through filter_xss
  56. */
  57. define('I18N_STRING_FILTER_XSS', 'FILTER_XSS');
  58. /**
  59. * Special string formats/filters: Run through filter_xss_admin
  60. */
  61. define('I18N_STRING_FILTER_XSS_ADMIN', 'FILTER_XSS_ADMIN');
  62. /**
  63. * Implements hook_help().
  64. */
  65. function i18n_string_help($path, $arg) {
  66. switch ($path) {
  67. case 'admin/help#i18n_string':
  68. $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>';
  69. $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>';
  70. $output .= '<ul>';
  71. $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>';
  72. $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>';
  73. $output .= '</ul>';
  74. $output .= '<p>' . t('Read more on the <em>Internationalization handbook</em>: <a href="http://drupal.org/node/313293">Translating user defined strings</a>.') . '</p>';
  75. return $output;
  76. case 'admin/config/regional/translate/i18n_string':
  77. $output = '<p>' . t('On this page you can refresh and update values for user defined strings.') . '</p>';
  78. $output .= '<ul>';
  79. $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>';
  80. $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>';
  81. $output .= '</ul>';
  82. $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>';
  83. $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>';
  84. return $output;
  85. case 'admin/config/regional/language':
  86. $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>';
  87. return $output;
  88. case 'admin/config/regional/i18n/strings':
  89. $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>';
  90. $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>';
  91. $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>';
  92. return $output;
  93. case 'admin/config/filters':
  94. 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>';
  95. }
  96. }
  97. /**
  98. * Implements hook_menu().
  99. */
  100. function i18n_string_menu() {
  101. $items['admin/config/regional/translate/i18n_string'] = array(
  102. 'title' => 'Strings',
  103. 'description' => 'Refresh user defined strings.',
  104. 'weight' => 20,
  105. 'type' => MENU_LOCAL_TASK,
  106. 'page callback' => 'drupal_get_form',
  107. 'page arguments' => array('i18n_string_admin_refresh_form'),
  108. 'file' => 'i18n_string.admin.inc',
  109. 'access arguments' => array('translate interface'),
  110. );
  111. $items['admin/config/regional/i18n/strings'] = array(
  112. 'title' => 'Strings',
  113. 'description' => 'Options for user defined strings.',
  114. 'weight' => 20,
  115. 'type' => MENU_LOCAL_TASK,
  116. 'page callback' => 'drupal_get_form',
  117. 'page arguments' => array('variable_edit_form', array('i18n_string_allowed_formats', 'i18n_string_source_language')),
  118. 'access arguments' => array('administer site configuration'),
  119. );
  120. // AJAX callback path for strings.
  121. $items['i18n_string/save'] = array(
  122. 'title' => 'Save string',
  123. 'page callback' => 'i18n_string_l10n_client_save_string',
  124. 'access arguments' => array('use on-page translation'),
  125. 'file' => 'i18n_string.pages.inc',
  126. 'type' => MENU_CALLBACK,
  127. );
  128. return $items;
  129. }
  130. /**
  131. * Implements hook_menu_alter().
  132. *
  133. * Take over the locale translation page.
  134. */
  135. function i18n_string_menu_alter(&$items) {
  136. $items['admin/config/regional/translate/edit/%'] = array(
  137. 'title' => 'Edit string',
  138. 'page callback' => 'drupal_get_form',
  139. 'page arguments' => array('i18n_string_locale_translate_edit_form', 5),
  140. 'access arguments' => array('translate interface'),
  141. 'file' => 'i18n_string.pages.inc',
  142. 'file path' => drupal_get_path('module', 'i18n_string'),
  143. );
  144. }
  145. /**
  146. * Implements hook_hook_info().
  147. */
  148. function i18n_string_hook_info() {
  149. $hooks['i18n_string_info'] =
  150. $hooks['i18n_string_list'] =
  151. $hooks['i18n_string_refresh'] =
  152. $hooks['i18n_string_objects'] = array(
  153. 'group' => 'i18n',
  154. );
  155. return $hooks;
  156. }
  157. /**
  158. * Implements hook_locale().
  159. *
  160. * Provide the information from i18n_string groups to locale module
  161. */
  162. function i18n_string_locale($op = 'groups') {
  163. if ($op == 'groups') {
  164. $groups = array();
  165. foreach (i18n_string_group_info() as $name => $info) {
  166. $groups[$name] = $info['title'];
  167. }
  168. return $groups;
  169. }
  170. }
  171. /**
  172. * Implements hook_permission().
  173. */
  174. function i18n_string_permission() {
  175. return array(
  176. 'translate user-defined strings' => array(
  177. 'title' => t('Translate user-defined strings'),
  178. 'description' => t('Translate user-defined strings that are created as part of content or configuration.'),
  179. 'restrict access' => TRUE,
  180. ),
  181. 'translate admin strings' => array(
  182. 'title' => t('Translate admin strings'),
  183. 'description' => t('Translate administrative strings with a very permissive XSS/HTML filter that allows all HTML tags.'),
  184. 'restrict access' => TRUE,
  185. ),
  186. );
  187. }
  188. /**
  189. * Implements hook_modules_enabled().
  190. */
  191. function i18n_string_modules_enabled($modules) {
  192. module_load_include('admin.inc', 'i18n_string');
  193. i18n_string_refresh_enabled_modules($modules);
  194. }
  195. /**
  196. * Implements hook_modules_uninstalled().
  197. */
  198. function i18n_string_modules_uninstalled($modules) {
  199. module_load_include('admin.inc', 'i18n_string');
  200. i18n_string_refresh_uninstalled_modules($modules);
  201. }
  202. /**
  203. * Implements hook_form_FORM_ID_alter()
  204. */
  205. function i18n_string_form_l10n_client_form_alter(&$form, &$form_state) {
  206. $form['#action'] = url('i18n_string/save');
  207. }
  208. /**
  209. * Implements hook_form_FORM_ID_alter()
  210. */
  211. function i18n_string_form_locale_translate_export_po_form_alter(&$form, $form_state) {
  212. $names = locale_language_list('name', TRUE);
  213. if (i18n_string_source_language() != 'en' && array_key_exists('en', $names)) {
  214. $form['langcode']['#options']['en'] = $names['en'];
  215. }
  216. }
  217. /**
  218. * Implements hook_form_FORM_ID_alter()
  219. */
  220. function i18n_string_form_locale_translate_import_form_alter(&$form, $form_state) {
  221. if (i18n_string_source_language() != 'en') {
  222. $names = locale_language_list('name', TRUE);
  223. if (array_key_exists('en', $names)) {
  224. $form['import']['langcode']['#options'][t('Already added languages')]['en'] = $names['en'];
  225. }
  226. else {
  227. $form['import']['langcode']['#options'][t('Languages not yet added')]['en'] = t('English');
  228. }
  229. }
  230. $form['#submit'][] = 'i18n_string_locale_translate_import_form_submit';
  231. }
  232. /**
  233. * Update string data after import form submit
  234. */
  235. function i18n_string_locale_translate_import_form_submit($form, &$form_state) {
  236. if (!drupal_get_messages('error', FALSE) && i18n_string_group_info($form_state['values']['group'])) {
  237. i18n_string_textgroup($form_state['values']['group'])->update_check();
  238. }
  239. }
  240. /**
  241. * Check if translation is required for this language code.
  242. *
  243. * Translation is required when default language is different from the given
  244. * language, or when default language translation is explicitly enabled.
  245. *
  246. * No UI is provided to enable translation of default language. On the other
  247. * hand, you can enable/disable translation for a specific language by adding
  248. * the following to your settings.php
  249. *
  250. * @param $langcode
  251. * Optional language code to check. It will default to current request language.
  252. * @code
  253. * // Enable translation of specific language. Language code is 'xx'
  254. * $conf['i18n_string_translate_langcode_xx'] = TRUE;
  255. * // Disable translation of specific language. Language code is 'yy'
  256. * $conf['i18n_string_translate_langcode_yy'] = FALSE;
  257. * @endcode
  258. */
  259. function i18n_string_translate_langcode($langcode = NULL) {
  260. $translate = &drupal_static(__FUNCTION__);
  261. $langcode = isset($langcode) ? $langcode : i18n_langcode();
  262. if (!isset($translate[$langcode])) {
  263. $translate[$langcode] = variable_get('i18n_string_translate_langcode_' . $langcode, i18n_string_source_language() != $langcode);
  264. }
  265. return $translate[$langcode];
  266. }
  267. /**
  268. * Create string class from string name
  269. */
  270. function i18n_string_build($name, $string = NULL) {
  271. list ($group, $context) = i18n_string_context($name);
  272. return i18n_string_textgroup($group)->build_string($context, $string);
  273. }
  274. /**
  275. * Update / create translation source for user defined strings.
  276. *
  277. * @param $name
  278. * Array or string concatenated with ':' that contains textgroup and string context
  279. * @param $string
  280. * Source string in default language. Default language may or may not be English.
  281. * Array of key => string to update multiple strings at once
  282. * @param $options
  283. * Array with additional options:
  284. * - 'format', String format if the string has text format
  285. * - 'messages', Whether to print out status messages
  286. */
  287. function i18n_string_update($name, $string, $options = array()) {
  288. if (is_array($string)) {
  289. return i18n_string_multiple('update', $name, $string, $options);
  290. }
  291. else {
  292. list($textgroup, $context) = i18n_string_context($name);
  293. return i18n_string_textgroup($textgroup)->context_update($context, $string, $options);
  294. }
  295. }
  296. /**
  297. * Update context for strings.
  298. *
  299. * As some string locations depend on configurable values, the field needs sometimes to be updated
  300. * without losing existing translations. I.e:
  301. * - profile fields indexed by field name.
  302. * - content types indexted by low level content type name.
  303. *
  304. * Example:
  305. * 'profile:field:oldfield:*' -> 'profile:field:newfield:*'
  306. */
  307. function i18n_string_update_context($oldname, $newname) {
  308. module_load_install('i18n_string');
  309. return i18n_string_install_update_context($oldname, $newname);
  310. }
  311. /**
  312. * Get textgroup handler
  313. */
  314. function i18n_string_textgroup($textgroup) {
  315. $groups = &drupal_static(__FUNCTION__);
  316. if (!isset($groups[$textgroup])) {
  317. $class = i18n_string_group_info($textgroup, 'class', 'i18n_string_textgroup_default');
  318. $groups[$textgroup] = new $class($textgroup);
  319. }
  320. return $groups[$textgroup];
  321. }
  322. /**
  323. * Check whether a string format is allowed for translation.
  324. */
  325. function i18n_string_allowed_format($format_id = NULL) {
  326. if (!$format_id || $format_id === I18N_STRING_FILTER_XSS || $format_id === I18N_STRING_FILTER_XSS_ADMIN) {
  327. return TRUE;
  328. }
  329. else {
  330. // Check the format still exists an it is in the allowed formats list.
  331. return filter_format_load($format_id) && in_array($format_id, variable_get('i18n_string_allowed_formats', array(filter_fallback_format())), TRUE);
  332. }
  333. }
  334. /**
  335. * Convert string name into textgroup and string context
  336. *
  337. * @param $name
  338. * Array or string concatenated with ':' that contains textgroup and string context
  339. * @param $replace
  340. * Parameter to replace the placeholder ('*') if we are dealing with multiple strings
  341. * Or parameter to append to context if there's no placeholder
  342. *
  343. * @return array
  344. * The first element will be the text group name
  345. * The second one will be an array with string name elements, without textgroup
  346. */
  347. function i18n_string_context($name, $replace = NULL) {
  348. $parts = is_array($name) ? $name : explode(':', $name);
  349. if ($replace) {
  350. $key = array_search('*', $parts);
  351. if ($key !== FALSE) {
  352. $parts[$key] = $replace;
  353. }
  354. elseif (count($parts) < 4) {
  355. array_push($parts, $replace);
  356. }
  357. }
  358. $textgroup = array_shift($parts);
  359. $context = $parts;
  360. return array($textgroup, $context);
  361. }
  362. /**
  363. * Mark form element as localizable
  364. */
  365. function i18n_string_element_mark(&$element) {
  366. $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>';
  367. if (empty($element['#description'])) {
  368. $element['#description'] = $description;
  369. }
  370. else {
  371. $element['#description'] .= ' ' . $description;
  372. }
  373. }
  374. /**
  375. * Get source string object.
  376. *
  377. * This returns the i18nstring object only when it has a source.
  378. *
  379. * @return i18n_string_object
  380. */
  381. function i18n_string_get_source($name) {
  382. return i18n_string_build($name)->get_source();
  383. }
  384. /**
  385. * Get full string object.
  386. *
  387. * Builds string and loads the source if available.
  388. *
  389. * @return i18n_string_object
  390. */
  391. function i18n_string_get_string($name, $default = NULL) {
  392. $i18nstring = i18n_string_build($name, $default);
  393. $i18nstring->get_source();
  394. return $i18nstring;
  395. }
  396. /**
  397. * Get full string object by lid.
  398. */
  399. function i18n_string_get_by_lid($lid) {
  400. $strings = i18n_string_load_multiple(array('lid' => $lid));
  401. return reset($strings);
  402. }
  403. /**
  404. * Load multiple strings, including string source
  405. *
  406. * @param $conditions
  407. * Array of conditions for i18n_string table.
  408. *
  409. * @return $strings
  410. * List of i18n string objects
  411. */
  412. function i18n_string_load_multiple($conditions) {
  413. // The primary table here will be i18n_string, though we add source too.
  414. $query = db_select('i18n_string', 'i')
  415. ->fields('i');
  416. $query->leftJoin('locales_source', 's', 'i.lid = s.lid');
  417. $query->fields('s', array('source', 'version', 'location'));
  418. // Add text group condition and add conditions to the query
  419. foreach ($conditions as $field => $value) {
  420. $alias = in_array($field, array('source', 'version', 'location')) ? 's' : 'i';
  421. $query->condition($alias . '.' . $field, $value);
  422. }
  423. // this patch is a workaround for core file bug in file
  424. // include/database/prefetch.inc (see: http://drupal.org/node/1567216)
  425. // return $query->execute()->fetchAll(PDO::FETCH_CLASS, 'i18n_string_object');
  426. $stmt = $query->execute();
  427. $stmt->setFetchMode(PDO::FETCH_CLASS, 'i18n_string_object');
  428. return $stmt->fetchAll();
  429. }
  430. /**
  431. * Get textgroup info, from hook_locale('info')
  432. *
  433. * @param $group
  434. * Text group name.
  435. * @param $default
  436. * Default value to return for a property if not set.
  437. */
  438. function i18n_string_group_info($group = NULL, $property = NULL, $default = NULL) {
  439. $info = &drupal_static(__FUNCTION__ , NULL);
  440. if (!isset($info)) {
  441. $info = module_invoke_all('i18n_string_info');
  442. drupal_alter('i18n_string_info', $info);
  443. }
  444. if ($group && $property) {
  445. return isset($info[$group][$property]) ? $info[$group][$property] : $default;
  446. }
  447. elseif ($group) {
  448. return isset($info[$group]) ? $info[$group] : array();
  449. }
  450. else {
  451. return $info;
  452. }
  453. }
  454. /**
  455. * Translate / update multiple strings
  456. *
  457. * @param $strings
  458. * Array of name => string pairs
  459. */
  460. function i18n_string_multiple($operation, $name, $strings, $options = array()) {
  461. $result = array();
  462. // Strings may be an array of properties, we need to shift it
  463. if ($operation == 'remove') {
  464. $strings = array_flip($strings);
  465. }
  466. foreach ($strings as $key => $string) {
  467. list($textgroup, $context) = i18n_string_context($name, $key);
  468. array_unshift($context, $textgroup);
  469. $result[$key] = call_user_func('i18n_string_' . $operation, $context, $string, $options);
  470. }
  471. return $result;
  472. }
  473. /**
  474. * @ingroup i18napi
  475. * @{
  476. */
  477. /**
  478. * Get translation for user defined string.
  479. *
  480. * This function is intended to return translations for plain strings that have NO text format
  481. *
  482. * @param $name
  483. * Array or string concatenated with ':' that contains textgroup and string context
  484. * @param $string
  485. * String in default language or array of strings to be translated
  486. * @param $options
  487. * An associative array of additional options, with the following keys:
  488. * - 'langcode' (defaults to the current language) The language code to translate to a language other than what is used to display the page.
  489. * - 'filter' Filtering callback to apply to the translated string only
  490. * - 'format' Input format to apply to the translated string only
  491. * - 'callback' Callback to apply to the result (both to translated or untranslated string
  492. * - 'sanitize' Whether to filter the translation applying the text format if any, default is TRUE
  493. * - 'sanitize default' Whether to filter the default value if no translation found, default is FALSE
  494. */
  495. function i18n_string_translate($name, $string, $options = array()) {
  496. if (is_array($string)) {
  497. return i18n_string_translate_list($name, $string, $options);
  498. }
  499. else {
  500. $options['langcode'] = $langcode = isset($options['langcode']) ? $options['langcode'] : i18n_langcode();
  501. if (i18n_string_translate_langcode($langcode)) {
  502. list($textgroup, $context) = i18n_string_context($name);
  503. $translation = i18n_string_textgroup($textgroup)->context_translate($context, $string, $options);
  504. // Add for l10n client if available, we pass translation object that contains the format
  505. i18n_string_l10n_client_add($translation, $langcode);
  506. return $translation->format_translation($langcode, $options);
  507. }
  508. else {
  509. // If we don't want to translate to this language, format and return
  510. $options['sanitize'] = !empty($options['sanitize default']);
  511. return i18n_string_format($string, $options);
  512. }
  513. }
  514. }
  515. /**
  516. * Check user access to translate a specific string.
  517. *
  518. * If the string has a format the user is not allowed to edit, it will return FALSE
  519. *
  520. * @param $string_format;
  521. * String object or $format_id
  522. */
  523. function i18n_string_translate_access($string_format, $account = NULL) {
  524. $format_id = is_object($string_format) ? i18n_object_field($string_format, 'format') : $string_format;
  525. return user_access('translate interface', $account) &&
  526. (empty($format_id) || i18n_string_allowed_format($format_id) && ($format = filter_format_load($format_id)) && filter_access($format, $account));
  527. }
  528. /**
  529. * Check whether there is any problem for the user to translate a specific string.
  530. *
  531. * Here we assume the user has 'translate interface' access that should have
  532. * been checked for the page. Possible reasons a user cannot translate a string:
  533. *
  534. * @param $i18nstring
  535. * String object.
  536. * @param $account
  537. * Optional user account, defaults to current user.
  538. *
  539. * @return
  540. * None or empty string if the user has access to translate the string.
  541. * Message if the user cannot translate that string.
  542. */
  543. function i18n_string_translate_check_string($i18nstring, $account = NULL) {
  544. if (!user_access('translate interface', $account) || !user_access('translate user-defined strings', $account)) {
  545. return t('This is a user-defined string. You are not allowed to translate these strings.');
  546. }
  547. elseif (!empty($i18nstring->format)) {
  548. if (!i18n_string_allowed_format($i18nstring->format)) {
  549. $format = filter_format_load($i18nstring->format);
  550. return t('This string uses the %name text format. Strings with this format are not allowed for translation.', array('%name' => $format->name));
  551. }
  552. elseif ($format = filter_format_load($i18nstring->format)) {
  553. // It is a text format, check user access to that text format.
  554. if (!filter_access($format, $account)) {
  555. 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));
  556. }
  557. }
  558. else {
  559. // This is one of our special formats, I18N_STRING_FILTER_*
  560. if ($i18nstring->format == I18N_STRING_FILTER_XSS_ADMIN && !user_access('translate admin strings', $account)) {
  561. return t('The source string is an administrative string. You are not allowed to translate these strings.');
  562. }
  563. }
  564. }
  565. // No error message, it should be OK to translate.
  566. return '';
  567. }
  568. /**
  569. * Format the resulting translation or the default string applying callbacks
  570. *
  571. * @param $string
  572. * Text string.
  573. * @param $options
  574. * Array of options for string formatting:
  575. * - 'format', text format to apply to the string, defaults to none.
  576. * - 'sanitize', whether to apply the text format, defaults to TRUE.
  577. * - 'cache', text format parameter.
  578. * - 'langcode', text format parameter, defaults to current page language.
  579. * - 'allowed_tags', allowed HTML tags when format is I18N_STRING_FILTER_XSS
  580. */
  581. function i18n_string_format($string, $options = array()) {
  582. $options += array('langcode' => i18n_langcode(), 'format' => FALSE, 'sanitize' => TRUE, 'cache' => FALSE);
  583. // Apply format and callback
  584. if ($string) {
  585. if ($options['sanitize']) {
  586. if ($options['format']) {
  587. // Handle special format values (xss, xss_admin)
  588. switch ($options['format']) {
  589. case I18N_STRING_FILTER_XSS:
  590. $string = !empty($options['allowed_tags']) ? filter_xss($string, $options['allowed_tags']) : filter_xss($string);
  591. break;
  592. case I18N_STRING_FILTER_XSS_ADMIN:
  593. $string = filter_xss_admin($string);
  594. break;
  595. default:
  596. $string = check_markup($string, $options['format'], $options['langcode'], $options['cache']);
  597. }
  598. }
  599. else {
  600. $string = check_plain($string);
  601. }
  602. }
  603. if (isset($options['callback'])) {
  604. $string = call_user_func($options['callback'], $string);
  605. }
  606. }
  607. // Finally, apply prefix and suffix
  608. $options += array('prefix' => '', 'suffix' => '');
  609. return $options['prefix'] . $string . $options['suffix'];
  610. }
  611. /**
  612. * Get filtered translation.
  613. *
  614. * This function is intended to return translations for strings that have a text format
  615. *
  616. * @param $name
  617. * Array or string concatenated with ':' that contains textgroup and string context
  618. * @param $default
  619. * Default string to return if not found, already filtered
  620. * @param $options
  621. * Array with additional options.
  622. */
  623. function i18n_string_text($name, $default, $options = array()) {
  624. $options += array('format' => filter_fallback_format(), 'sanitize' => TRUE);
  625. return i18n_string_translate($name, $default, $options);
  626. }
  627. /**
  628. * Translation for plain string. In case it finds a translation it applies check_plain() to it
  629. *
  630. * @param $name
  631. * Array or string concatenated with ':' that contains textgroup and string context
  632. * @param $default
  633. * Default string to return if not found
  634. * @param $options
  635. * Array with additional options
  636. */
  637. function i18n_string_plain($name, $default, $options = array()) {
  638. $options += array('filter' => 'check_plain');
  639. return i18n_string_translate($name, $default, $options);
  640. }
  641. /**
  642. * Get source language code for translations
  643. */
  644. function i18n_string_source_language() {
  645. return variable_get('i18n_string_source_language', language_default('language'));
  646. }
  647. /**
  648. * Translation for list of options
  649. *
  650. * @param $options
  651. * Array with additional options, some changes
  652. * - 'index' => field that will be mapped to the array key (defaults to 'property')
  653. */
  654. function i18n_string_translate_list($name, $strings, $options = array()) {
  655. $options['langcode'] = $langcode = isset($options['langcode']) ? $options['langcode'] : i18n_langcode();
  656. // If language is default, just return
  657. if (i18n_string_translate_langcode($langcode)) {
  658. // Get textgroup context, preserve placeholder
  659. list($textgroup, $context) = i18n_string_context($name, '*');
  660. $translations = i18n_string_textgroup($textgroup)->multiple_translate($context, $strings, $options);
  661. // Add for l10n client if available, we pass translation object that contains the format
  662. foreach ($translations as $index => $translation) {
  663. i18n_string_l10n_client_add($translation, $langcode);
  664. $strings[$index] = $translation->format_translation($langcode, $options);
  665. }
  666. }
  667. else {
  668. // Format and return
  669. foreach ($strings as $key => $string) {
  670. $strings[$key] = i18n_string_format($string, $options);
  671. }
  672. }
  673. return $strings;
  674. }
  675. /**
  676. * Remove source and translations for user defined string.
  677. *
  678. * Though for most strings the 'name' or 'string id' uniquely identifies that string,
  679. * there are some exceptions (like profile categories) for which we need to use the
  680. * source string itself as a search key.
  681. *
  682. * @param $name
  683. * String name
  684. * @param $string
  685. * Optional source string (string in default language).
  686. * Array of string properties to remove
  687. */
  688. function i18n_string_remove($name, $string = NULL, $options = array()) {
  689. if (is_array($string)) {
  690. return i18n_string_multiple('remove', $name, $string, $options);
  691. }
  692. else {
  693. list($textgroup, $context) = i18n_string_context($name);
  694. return i18n_string_textgroup($textgroup)->context_remove($context, $string, $options);
  695. }
  696. }
  697. /**
  698. * @} End of "ingroup i18napi".
  699. */
  700. /*** l10n client related functions ***/
  701. /**
  702. * Add string to l10n strings if enabled and allowed for this string
  703. *
  704. * @param $context
  705. * String object
  706. */
  707. function i18n_string_l10n_client_add($string, $langcode) {
  708. // If current language add to l10n client list for later on page translation.
  709. // If langcode translation was disabled we are not supossed to reach here.
  710. if (($langcode == i18n_langcode()) && function_exists('l10_client_add_string_to_page') && user_access('translate interface')) {
  711. if (!$string->check_translate_access()) {
  712. $translation = $string->get_translation($langcode);
  713. $source = !empty($string->source) ? $string->source : $string->string;
  714. l10_client_add_string_to_page($source, $translation ? $translation : TRUE, $string->textgroup, $string->context);
  715. }
  716. }
  717. }
  718. /**
  719. * Get information about object string translation
  720. */
  721. function i18n_string_object_info($type = NULL, $property = NULL) {
  722. if ($type) {
  723. if (($info = i18n_object_info($type, 'string translation'))) {
  724. if ($property) {
  725. return isset($info[$property]) ? $info[$property] : NULL;
  726. }
  727. else {
  728. return $info;
  729. }
  730. }
  731. }
  732. else {
  733. $list = array();
  734. foreach (i18n_object_info() as $type => $info) {
  735. if (!empty($info['string translation'])) {
  736. $list[$type] = $info;
  737. }
  738. }
  739. return $list;
  740. }
  741. }
  742. /**
  743. * Implements hook_i18n_object_info_alter().
  744. *
  745. * Set a different default object wrapper for objects that have string translation.
  746. */
  747. function i18n_string_i18n_object_info_alter(&$object_info) {
  748. foreach ($object_info as $type => &$info) {
  749. if (!empty($info['string translation']) && (empty($info['class']) || $info['class'] == 'i18n_object_wrapper')) {
  750. $info['class'] = 'i18n_string_object_wrapper';
  751. }
  752. }
  753. }
  754. /**
  755. * Translate object properties
  756. *
  757. * We clone the object previously so we don't risk translated properties being saved
  758. *
  759. * @param $type
  760. * Object type
  761. * @param $object
  762. * Object or array
  763. */
  764. function i18n_string_object_translate($type, $object, $options = array()) {
  765. $langcode = isset($options['langcode']) ? $options['langcode'] : i18n_langcode();
  766. if (i18n_string_translate_langcode($langcode)) {
  767. // Object properties will be returned without filtering as in the original one.
  768. $options += array('sanitize' => FALSE);
  769. return i18n_object($type, $object)->translate($langcode, $options);
  770. }
  771. else {
  772. return $object;
  773. }
  774. }
  775. /**
  776. * Remove object strings, because object is deleted
  777. *
  778. * @param $type
  779. * Object type
  780. * @param $object
  781. * Object or array
  782. */
  783. function i18n_string_object_remove($type, $object, $options = array()) {
  784. return i18n_object($type, $object)->strings_remove($options);
  785. }
  786. /**
  787. * Update object properties.
  788. *
  789. * @param $type
  790. * Object type
  791. * @param $object
  792. * Object or array
  793. */
  794. function i18n_string_object_update($type, $object, $options = array()) {
  795. return i18n_object($type, $object)->strings_update($options);
  796. }
  797. /**
  798. * Generic translation page for i18n_strings objects.
  799. */
  800. function i18n_string_object_translate_page($object_type, $object_value, $language = NULL) {
  801. module_load_include('inc', 'i18n_string', 'i18n_string.pages');
  802. return i18n_string_translate_page_object($object_type, $object_value, $language);
  803. }
  804. /**
  805. * Preload all strings for this textroup/context.
  806. *
  807. * This is a performance optimization to load all needed strings with a single query.
  808. *
  809. * Examples of valid string name to search are:
  810. * - 'taxonomy:term:*:title'
  811. * This will find all titles for taxonomy terms
  812. * - array('taxonomy', 'term', array(1,2), '*')
  813. * This will find all properties for taxonomy terms 1 and 2
  814. *
  815. * @param $name
  816. * Specially crafted string name, it may take '*' and array parameters for each element.
  817. * @param $langcode
  818. * Language code to search translations. Defaults to current language.
  819. *
  820. * @return array()
  821. * String objects indexed by context.
  822. */
  823. function i18n_string_translation_search($name, $langcode = NULL) {
  824. $langcode = isset($langcode) ? $langcode : i18n_langcode();
  825. list ($textgroup, $context) = i18n_string_context($name);
  826. return i18n_string_textgroup($textgroup)->multiple_translation_search($context, $langcode);
  827. }
  828. /**
  829. * Update / create translation for a certain source.
  830. *
  831. * @param $name
  832. * Array or string concatenated with ':' that contains textgroup and string context
  833. * @param $translation
  834. * Translation string for this language code
  835. * @param $langcode
  836. * The language code to translate to a language other than what is used to display the page.
  837. * @param $source_string
  838. * Optional source string, just in case it needs to be created.
  839. *
  840. * @return mixed
  841. * Source string object if update was successful.
  842. * Null if source string not found.
  843. * FALSE if use doesn't have permission to edit this translation.
  844. */
  845. function i18n_string_translation_update($name, $translation, $langcode, $source_string = NULL) {
  846. if (is_array($translation)) {
  847. return i18n_string_multiple('translation_update', $name, $translation, $langcode);
  848. }
  849. elseif ($source = i18n_string_get_source($name)) {
  850. if ($langcode == i18n_string_source_language()) {
  851. // It's the default language so we should update the string source as well.
  852. i18n_string_update($name, $translation);
  853. }
  854. else {
  855. list ($textgroup, $context) = i18n_string_context($name);
  856. i18n_string_textgroup($textgroup)->update_translation($context, $langcode, $translation);
  857. }
  858. return $source;
  859. }
  860. elseif ($source_string) {
  861. // We don't have a source in the database, so we need to create it, but only if we've got the source too.
  862. // Note this string won't have any format.
  863. i18n_string_update($name, $source_string);
  864. return i18n_string_translation_update($name, $translation, $langcode);
  865. }
  866. else {
  867. return NULL;
  868. }
  869. }
  870. /**
  871. * Count operation results by result value
  872. */
  873. function _i18n_string_result_count($list) {
  874. $result = array();
  875. foreach ($list as $value) {
  876. $key = (string)$value;
  877. $result[$key] = isset($result[$key]) ? $result[$key] +1 : 1;
  878. }
  879. return $result;
  880. }