locale.module

  1. drupal
    1. 4.6 modules/locale.module
    2. 4.7 modules/locale.module
    3. 5 modules/locale/locale.module
    4. 6 modules/locale/locale.module
    5. 7 modules/locale/locale.module
    6. 8 core/modules/locale/locale.module

Add language handling functionality and enables the translation of the user interface to languages other than English.

When enabled, multiple languages can be set up. The site interface can be displayed in different languages, as well as nodes can have languages assigned. The setup of languages and translations is completely web based. Gettext portable object files are supported.

Functions & methods

NameDescription
localeProvides interface translation services.
locale_date_format_saveSave locale specific date formats to the database.
locale_entity_info_alterImplements hook_entity_info_alter().
locale_field_language_alterImplements hook_field_language_alter().
locale_field_language_fallbackApplies language fallback rules to the fields attached to the given entity.
locale_field_node_form_submitForm submit handler for node_form().
locale_form_language_admin_add_form_alterImplements hook_form_FORM_ID_alter() for language_admin_add_form(().
locale_form_language_admin_add_form_alter_submitSet a batch for newly added language.
locale_form_language_admin_edit_form_alterImplements hook_form_FORM_ID_alter() for language_admin_edit_form().
locale_form_language_admin_edit_form_alter_submitSubmission handler to record our custom setting.
locale_form_language_admin_overview_form_alterImplements hook_form_FORM_ID_alter() for language_admin_overview_form().
locale_form_node_form_alterImplements hook_form_BASE_FORM_ID_alter().
locale_form_system_file_system_settings_alterImplements hook_form_FORM_ID_alter() for system_file_system_settings().
locale_get_localized_date_formatSelect locale date format details from database.
locale_get_pluralReturns plural form index for a specific number.
locale_helpImplements hook_help().
locale_initImplements hook_init().
locale_js_alterImplements hook_js_alter().
locale_language_deleteImplements hook_language_delete().
locale_language_insertImplements hook_language_insert().
locale_language_updateImplements hook_language_update().
locale_library_info_alterImplement hook_library_info_alter().
locale_menuImplements hook_menu().
locale_modules_installedImplements hook_modules_installed().
locale_permissionImplements hook_permission().
locale_preprocess_nodeImplements hook_preprocess_HOOK() for node.tpl.php.
locale_resetReset static variables used by locale().
locale_string_is_safeCheck that a string is safe to be added or imported as a translation.
locale_system_updateImports translations when new modules or themes are installed.
locale_themeImplements hook_theme().
locale_themes_enabledImplements hook_themes_enabled().
locale_translate_englishUtility function to tell if locale translates to English.
_locale_invalidate_jsForce the JavaScript translation file(s) to be refreshed.
_locale_parse_js_fileParses a JavaScript file, extracts strings wrapped in Drupal.t() and Drupal.formatPlural() and inserts them into the database.
_locale_rebuild_js(Re-)Creates the JavaScript translation file for a language.

Constants

NameDescription
LOCALE_CUSTOMIZEDFlag for locally customized interface translation.
LOCALE_JS_OBJECTRegular expression pattern used to match simple JS object literal.
LOCALE_JS_OBJECT_CONTEXTRegular expression to match an object containing a key 'context'.
LOCALE_JS_STRINGRegular expression pattern used to localize JavaScript strings.
LOCALE_NOT_CUSTOMIZEDFlag for locally not customized interface translation.

File

core/modules/locale/locale.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Add language handling functionality and enables the translation of the
  5. * user interface to languages other than English.
  6. *
  7. * When enabled, multiple languages can be set up. The site interface
  8. * can be displayed in different languages, as well as nodes can have languages
  9. * assigned. The setup of languages and translations is completely web based.
  10. * Gettext portable object files are supported.
  11. */
  12. /**
  13. * Regular expression pattern used to localize JavaScript strings.
  14. */
  15. const LOCALE_JS_STRING = '(?:(?:\'(?:\\\\\'|[^\'])*\'|"(?:\\\\"|[^"])*")(?:\s*\+\s*)?)+';
  16. /**
  17. * Regular expression pattern used to match simple JS object literal.
  18. *
  19. * This pattern matches a basic JS object, but will fail on an object with
  20. * nested objects. Used in JS file parsing for string arg processing.
  21. */
  22. const LOCALE_JS_OBJECT = '\{.*?\}';
  23. /**
  24. * Regular expression to match an object containing a key 'context'.
  25. *
  26. * Pattern to match a JS object containing a 'context key' with a string value,
  27. * which is captured. Will fail if there are nested objects.
  28. */
  29. define('LOCALE_JS_OBJECT_CONTEXT', '
  30. \{ # match object literal start
  31. .*? # match anything, non-greedy
  32. (?: # match a form of "context"
  33. \'context\'
  34. |
  35. "context"
  36. |
  37. context
  38. )
  39. \s*:\s* # match key-value separator ":"
  40. (' . LOCALE_JS_STRING . ') # match context string
  41. .*? # match anything, non-greedy
  42. \} # match end of object literal
  43. ');
  44. /**
  45. * Flag for locally not customized interface translation.
  46. *
  47. * Such translations are imported from .po files downloaded from
  48. * localize.drupal.org for example.
  49. */
  50. const LOCALE_NOT_CUSTOMIZED = 0;
  51. /**
  52. * Flag for locally customized interface translation.
  53. *
  54. * Such translations are edited from their imported originals on the user
  55. * interface or are imported as customized.
  56. */
  57. const LOCALE_CUSTOMIZED = 1;
  58. // ---------------------------------------------------------------------------------
  59. // Hook implementations
  60. /**
  61. * Implements hook_help().
  62. */
  63. function locale_help($path, $arg) {
  64. switch ($path) {
  65. case 'admin/help#locale':
  66. $output = '';
  67. $output .= '<h3>' . t('About') . '</h3>';
  68. $output .= '<p>' . t('The Locale module allows your Drupal site to be presented in languages other than the default English, and to be multilingual. The Locale module works by maintaining a database of translations, and examining text as it is about to be displayed. When a translation of the text is available in the language to be displayed, the translation is displayed rather than the original text. When a translation is unavailable, the original text is displayed, and then stored for review by a translator. For more information, see the online handbook entry for <a href="@locale">Locale module</a>.', array('@locale' => 'http://drupal.org/documentation/modules/locale/')) . '</p>';
  69. $output .= '<h3>' . t('Uses') . '</h3>';
  70. $output .= '<dl>';
  71. $output .= '<dt>' . t('Translating interface text') . '</dt>';
  72. $output .= '<dd>' . t('Translations of text in the Drupal interface may be provided by:');
  73. $output .= '<ul>';
  74. $output .= '<li>' . t("Translating within your site, using the Locale module's integrated <a href='@translate'>translation interface</a>.", array('@translate' => url('admin/config/regional/translate'))) . '</li>';
  75. $output .= '<li>' . t('Importing files from a set of existing translations, known as a translation package. A translation package enables the display of a specific version of Drupal in a specific language, and contains files in the Gettext Portable Object (<em>.po</em>) format. Although not all languages are available for every version of Drupal, translation packages for many languages are available for download from the <a href="@translations">Drupal translations page</a>.', array('@translations' => 'http://localize.drupal.org')) . '</li>';
  76. $output .= '<li>' . t("If an existing translation package does not meet your needs, the Gettext Portable Object (<em>.po</em>) files within a package may be modified, or new <em>.po</em> files may be created, using a desktop Gettext editor. The Locale module's <a href='@import'>import</a> feature allows the translated strings from a new or modified <em>.po</em> file to be added to your site. The Locale module's <a href='@export'>export</a> feature generates files from your site's translated strings, that can either be shared with others or edited offline by a Gettext translation editor.", array('@import' => url('admin/config/regional/translate/import'), '@export' => url('admin/config/regional/translate/export'))) . '</li>';
  77. $output .= '</ul></dd>';
  78. $output .= '</dl>';
  79. return $output;
  80. case 'admin/config/regional/language':
  81. return '<p>' . t('Interface text can be translated. <a href="@translations">Download contributed translations</a> from Drupal.org.', array('@translations' => 'http://localize.drupal.org')) . '</p>';
  82. case 'admin/config/regional/translate':
  83. $output = '<p>' . t('This page allows a translator to search for specific translated and untranslated strings, and is used when creating or editing translations. (Note: For translation tasks involving many strings, it may be more convenient to <a href="@export">export</a> strings for offline editing in a desktop Gettext translation editor.) Searches may be limited to strings in a specific language.', array('@export' => url('admin/config/regional/translate/export'))) . '</p>';
  84. return $output;
  85. case 'admin/config/regional/translate/import':
  86. $output = '<p>' . t('This page imports the translated strings contained in an individual Gettext Portable Object (<em>.po</em>) file. Normally distributed as part of a translation package (each translation package may contain several <em>.po</em> files), a <em>.po</em> file may need to be imported after offline editing in a Gettext translation editor. Importing an individual <em>.po</em> file may be a lengthy process.') . '</p>';
  87. $output .= '<p>' . t('Note that the <em>.po</em> files within a translation package are imported automatically (if available) when new modules or themes are enabled, or as new languages are added. Since this page only allows the import of one <em>.po</em> file at a time, it may be simpler to download and extract a translation package into your Drupal installation directory and <a href="@language-add">add the language</a> (which automatically imports all <em>.po</em> files within the package). Translation packages are available for download on the <a href="@translations">Drupal translation page</a>.', array('@language-add' => url('admin/config/regional/language/add'), '@translations' => 'http://localize.drupal.org')) . '</p>';
  88. return $output;
  89. case 'admin/config/regional/translate/export':
  90. return '<p>' . t('This page exports the translated strings used by your site. An export file may be in Gettext Portable Object (<em>.po</em>) form, which includes both the original string and the translation (used to share translations with others), or in Gettext Portable Object Template (<em>.pot</em>) form, which includes the original strings only (used to create new translations with a Gettext translation editor).') . '</p>';
  91. }
  92. }
  93. /**
  94. * Implements hook_menu().
  95. */
  96. function locale_menu() {
  97. // Translation functionality.
  98. $items['admin/config/regional/translate'] = array(
  99. 'title' => 'User interface translation',
  100. 'description' => 'Translate the built-in user interface.',
  101. 'page callback' => 'locale_translate_seek_screen',
  102. 'access arguments' => array('translate interface'),
  103. 'file' => 'locale.pages.inc',
  104. 'weight' => -5,
  105. );
  106. $items['admin/config/regional/translate/translate'] = array(
  107. 'title' => 'Translate',
  108. 'weight' => -10,
  109. 'type' => MENU_DEFAULT_LOCAL_TASK,
  110. );
  111. $items['admin/config/regional/translate/import'] = array(
  112. 'title' => 'Import',
  113. 'page callback' => 'drupal_get_form',
  114. 'page arguments' => array('locale_translate_import_form'),
  115. 'access arguments' => array('translate interface'),
  116. 'weight' => 20,
  117. 'type' => MENU_LOCAL_TASK,
  118. 'file' => 'locale.bulk.inc',
  119. );
  120. $items['admin/config/regional/translate/export'] = array(
  121. 'title' => 'Export',
  122. 'page callback' => 'drupal_get_form',
  123. 'page arguments' => array('locale_translate_export_form'),
  124. 'access arguments' => array('translate interface'),
  125. 'weight' => 30,
  126. 'type' => MENU_LOCAL_TASK,
  127. 'file' => 'locale.bulk.inc',
  128. );
  129. $items['admin/config/regional/translate/edit/%'] = array(
  130. 'title' => 'Edit string',
  131. 'page callback' => 'drupal_get_form',
  132. 'page arguments' => array('locale_translate_edit_form', 5),
  133. 'access arguments' => array('translate interface'),
  134. 'file' => 'locale.pages.inc',
  135. );
  136. $items['admin/config/regional/translate/delete/%'] = array(
  137. 'title' => 'Delete string',
  138. 'page callback' => 'locale_translate_delete_page',
  139. 'page arguments' => array(5),
  140. 'access arguments' => array('translate interface'),
  141. 'file' => 'locale.pages.inc',
  142. );
  143. // Localize date formats.
  144. $items['admin/config/regional/date-time/locale'] = array(
  145. 'title' => 'Localize',
  146. 'description' => 'Configure date formats for each locale',
  147. 'page callback' => 'locale_date_format_language_overview_page',
  148. 'access arguments' => array('administer site configuration'),
  149. 'type' => MENU_LOCAL_TASK,
  150. 'weight' => -8,
  151. 'file' => 'locale.admin.inc',
  152. );
  153. $items['admin/config/regional/date-time/locale/%/edit'] = array(
  154. 'title' => 'Localize date formats',
  155. 'description' => 'Configure date formats for each locale',
  156. 'page callback' => 'drupal_get_form',
  157. 'page arguments' => array('locale_date_format_form', 5),
  158. 'access arguments' => array('administer site configuration'),
  159. 'file' => 'locale.admin.inc',
  160. );
  161. $items['admin/config/regional/date-time/locale/%/reset'] = array(
  162. 'title' => 'Reset date formats',
  163. 'description' => 'Reset localized date formats to global defaults',
  164. 'page callback' => 'drupal_get_form',
  165. 'page arguments' => array('locale_date_format_reset_form', 5),
  166. 'access arguments' => array('administer site configuration'),
  167. 'file' => 'locale.admin.inc',
  168. );
  169. return $items;
  170. }
  171. /**
  172. * Implements hook_init().
  173. *
  174. * Initialize date formats according to the user's current locale.
  175. */
  176. function locale_init() {
  177. global $conf, $language_interface;
  178. // For each date type (e.g. long, short), get the localized date format
  179. // for the user's current language and override the default setting for it
  180. // in $conf. This should happen on all pages except the date and time formats
  181. // settings page, where we want to display the site default and not the
  182. // localized version.
  183. if (strpos(current_path(), 'admin/config/regional/date-time/formats') !== 0) {
  184. $languages = array($language_interface->langcode);
  185. // Setup appropriate date formats for this locale.
  186. $formats = locale_get_localized_date_format($languages);
  187. foreach ($formats as $format_type => $format) {
  188. $conf[$format_type] = $format;
  189. }
  190. }
  191. }
  192. /**
  193. * Implements hook_permission().
  194. */
  195. function locale_permission() {
  196. return array(
  197. 'translate interface' => array(
  198. 'title' => t('Translate interface texts'),
  199. 'restrict access' => TRUE,
  200. ),
  201. );
  202. }
  203. /**
  204. * Implements hook_form_BASE_FORM_ID_alter().
  205. */
  206. function locale_form_node_form_alter(&$form, &$form_state) {
  207. $form['#submit'][] = 'locale_field_node_form_submit';
  208. }
  209. /**
  210. * Form submit handler for node_form().
  211. *
  212. * Checks if Locale is registered as a translation handler and handle possible
  213. * node language changes.
  214. *
  215. * This submit handler needs to run before entity_form_submit_build_entity()
  216. * is invoked by node_form_submit_build_node(), because it alters the values of
  217. * attached fields. Therefore, it cannot be a hook_node_submit() implementation.
  218. */
  219. function locale_field_node_form_submit($form, &$form_state) {
  220. if (field_has_translation_handler('node', 'locale')) {
  221. $bundle = $form_state['values']['type'];
  222. $node_language = $form_state['values']['langcode'];
  223. foreach (field_info_instances('node', $bundle) as $instance) {
  224. $field_name = $instance['field_name'];
  225. $field = field_info_field($field_name);
  226. $previous_langcode = $form[$field_name]['#language'];
  227. // Handle a possible language change: new language values are inserted,
  228. // previous ones are deleted.
  229. if ($field['translatable'] && $previous_langcode != $node_language) {
  230. $form_state['values'][$field_name][$node_language] = $form_state['values'][$field_name][$previous_langcode];
  231. $form_state['values'][$field_name][$previous_langcode] = array();
  232. }
  233. }
  234. }
  235. }
  236. /**
  237. * Implements hook_theme().
  238. */
  239. function locale_theme() {
  240. return array(
  241. 'locale_date_format_form' => array(
  242. 'render element' => 'form',
  243. ),
  244. );
  245. }
  246. /**
  247. * Implements hook_field_language_alter().
  248. */
  249. function locale_field_language_alter(&$display_langcode, $context) {
  250. // Do not apply core language fallback rules if they are disabled or if Locale
  251. // is not registered as a translation handler.
  252. if (variable_get('locale_field_language_fallback', TRUE) && field_has_translation_handler($context['entity_type'], 'locale')) {
  253. locale_field_language_fallback($display_langcode, $context['entity'], $context['langcode']);
  254. }
  255. }
  256. /**
  257. * Applies language fallback rules to the fields attached to the given entity.
  258. *
  259. * Core language fallback rules simply check if fields have a field translation
  260. * for the requested language code. If so the requested language is returned,
  261. * otherwise all the fallback candidates are inspected to see if there is a
  262. * field translation available in another language.
  263. * By default this is called by locale_field_language_alter(), but this
  264. * behavior can be disabled by setting the 'locale_field_language_fallback'
  265. * variable to FALSE.
  266. *
  267. * @param $field_langcodes
  268. * A reference to an array of language codes keyed by field name.
  269. * @param $entity
  270. * The entity to be displayed.
  271. * @param $langcode
  272. * The language code $entity has to be displayed in.
  273. */
  274. function locale_field_language_fallback(&$field_langcodes, $entity, $langcode) {
  275. // Lazily init fallback candidates to avoid unnecessary calls.
  276. $fallback_candidates = NULL;
  277. $field_languages = array();
  278. foreach ($field_langcodes as $field_name => $field_langcode) {
  279. // If the requested language is defined for the current field use it,
  280. // otherwise search for a fallback value among the fallback candidates.
  281. if (isset($entity->{$field_name}[$langcode])) {
  282. $field_langcodes[$field_name] = $langcode;
  283. }
  284. elseif (!empty($entity->{$field_name})) {
  285. if (!isset($fallback_candidates)) {
  286. require_once DRUPAL_ROOT . '/core/includes/language.inc';
  287. $fallback_candidates = language_fallback_get_candidates();
  288. }
  289. foreach ($fallback_candidates as $fallback_langcode) {
  290. if (isset($entity->{$field_name}[$fallback_langcode])) {
  291. $field_langcodes[$field_name] = $fallback_langcode;
  292. break;
  293. }
  294. }
  295. }
  296. }
  297. }
  298. /**
  299. * Implements hook_entity_info_alter().
  300. */
  301. function locale_entity_info_alter(&$entity_info) {
  302. $entity_info['node']['translation']['locale'] = TRUE;
  303. }
  304. /**
  305. * Implements hook_language_insert().
  306. */
  307. function locale_language_insert($language) {
  308. // @todo move these two cache clears out. See http://drupal.org/node/1293252
  309. // Changing the language settings impacts the interface.
  310. cache('page')->flush();
  311. // Force JavaScript translation file re-creation for the new language.
  312. _locale_invalidate_js($language->langcode);
  313. }
  314. /**
  315. * Implements hook_language_update().
  316. */
  317. function locale_language_update($language) {
  318. // @todo move these two cache clears out. See http://drupal.org/node/1293252
  319. // Changing the language settings impacts the interface.
  320. cache('page')->flush();
  321. // Force JavaScript translation file re-creation for the modified language.
  322. _locale_invalidate_js($language->langcode);
  323. }
  324. /**
  325. * Implements hook_language_delete().
  326. */
  327. function locale_language_delete($language) {
  328. // Remove translations.
  329. db_delete('locales_target')
  330. ->condition('language', $language->langcode)
  331. ->execute();
  332. _locale_invalidate_js($language->langcode);
  333. // Changing the language settings impacts the interface:
  334. cache('page')->flush();
  335. // Clearing all locale cache from database
  336. cache()->delete('locale:' . $language->langcode);
  337. }
  338. // ---------------------------------------------------------------------------------
  339. // Locale core functionality
  340. /**
  341. * Provides interface translation services.
  342. *
  343. * This function is called from t() to translate a string if needed.
  344. *
  345. * @param $string
  346. * A string to look up translation for. If omitted, all the
  347. * cached strings will be returned in all languages already
  348. * used on the page.
  349. * @param $context
  350. * The context of this string.
  351. * @param $langcode
  352. * Language code to use for the lookup.
  353. */
  354. function locale($string = NULL, $context = NULL, $langcode = NULL) {
  355. global $language_interface;
  356. // Use the advanced drupal_static() pattern, since this is called very often.
  357. static $drupal_static_fast;
  358. if (!isset($drupal_static_fast)) {
  359. $drupal_static_fast['locale'] = &drupal_static(__FUNCTION__);
  360. }
  361. $locale_t = &$drupal_static_fast['locale'];
  362. if (!isset($string)) {
  363. // Return all cached strings if no string was specified
  364. return $locale_t;
  365. }
  366. $langcode = isset($langcode) ? $langcode : $language_interface->langcode;
  367. // Store database cached translations in a static variable. Only build the
  368. // cache after $language_interface has been set to avoid an unnecessary cache
  369. // rebuild.
  370. if (!isset($locale_t[$langcode]) && isset($language_interface)) {
  371. $locale_t[$langcode] = array();
  372. // Disabling the usage of string caching allows a module to watch for
  373. // the exact list of strings used on a page. From a performance
  374. // perspective that is a really bad idea, so we have no user
  375. // interface for this. Be careful when turning this option off!
  376. if (variable_get('locale_cache_strings', 1) == 1) {
  377. if ($cache = cache()->get('locale:' . $langcode)) {
  378. $locale_t[$langcode] = $cache->data;
  379. }
  380. elseif (lock_acquire('locale_cache_' . $langcode)) {
  381. // Refresh database stored cache of translations for given language.
  382. // We only store short strings used in current version, to improve
  383. // performance and consume less memory.
  384. $result = db_query("SELECT s.source, s.context, t.translation, t.language FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.version = :version AND LENGTH(s.source) < :length", array(':language' => $langcode, ':version' => VERSION, ':length' => variable_get('locale_cache_length', 75)));
  385. foreach ($result as $data) {
  386. $locale_t[$langcode][$data->context][$data->source] = (empty($data->translation) ? TRUE : $data->translation);
  387. }
  388. cache()->set('locale:' . $langcode, $locale_t[$langcode]);
  389. lock_release('locale_cache_' . $langcode);
  390. }
  391. }
  392. }
  393. // If we have the translation cached, skip checking the database
  394. if (!isset($locale_t[$langcode][$context][$string])) {
  395. // We do not have this translation cached, so get it from the DB.
  396. $translation = db_query("SELECT s.lid, t.translation, s.version FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.source = :source AND s.context = :context", array(
  397. ':language' => $langcode,
  398. ':source' => $string,
  399. ':context' => (string) $context,
  400. ))->fetchObject();
  401. if ($translation) {
  402. // We have the source string at least.
  403. // Cache translation string or TRUE if no translation exists.
  404. $locale_t[$langcode][$context][$string] = (empty($translation->translation) ? TRUE : $translation->translation);
  405. if ($translation->version != VERSION) {
  406. // This is the first use of this string under current Drupal version. Save version
  407. // and clear cache, to include the string into caching next time. Saved version is
  408. // also a string-history information for later pruning of the tables.
  409. db_update('locales_source')
  410. ->fields(array('version' => VERSION))
  411. ->condition('lid', $translation->lid)
  412. ->execute();
  413. cache()->deletePrefix('locale:');
  414. }
  415. }
  416. else {
  417. // We don't have the source string, cache this as untranslated.
  418. db_merge('locales_source')
  419. ->insertFields(array(
  420. 'location' => request_uri(),
  421. 'version' => VERSION,
  422. ))
  423. ->key(array(
  424. 'source' => $string,
  425. 'context' => (string) $context,
  426. ))
  427. ->execute();
  428. $locale_t[$langcode][$context][$string] = TRUE;
  429. // Clear locale cache so this string can be added in a later request.
  430. cache()->deletePrefix('locale:');
  431. }
  432. }
  433. return ($locale_t[$langcode][$context][$string] === TRUE ? $string : $locale_t[$langcode][$context][$string]);
  434. }
  435. /**
  436. * Reset static variables used by locale().
  437. */
  438. function locale_reset() {
  439. drupal_static_reset('locale');
  440. }
  441. /**
  442. * Returns plural form index for a specific number.
  443. *
  444. * The index is computed from the formula of this language.
  445. *
  446. * @param $count
  447. * Number to return plural for.
  448. * @param $langcode
  449. * Optional language code to translate to a language other than
  450. * what is used to display the page.
  451. * @return
  452. * The numeric index of the plural variant to use for this $langcode and
  453. * $count combination or -1 if the language was not found or does not have a
  454. * plural formula.
  455. */
  456. function locale_get_plural($count, $langcode = NULL) {
  457. global $language_interface;
  458. // Used to locally cache the plural formulas for all languages.
  459. $plural_formulas = &drupal_static(__FUNCTION__, array());
  460. // Used to store precomputed plural indexes corresponding to numbers
  461. // individually for each language.
  462. $plural_indexes = &drupal_static(__FUNCTION__ . ':plurals', array());
  463. $langcode = $langcode ? $langcode : $language_interface->langcode;
  464. if (!isset($plural_indexes[$langcode][$count])) {
  465. // Retrieve and statically cache the plural formulas for all languages.
  466. if (empty($plural_formulas)) {
  467. $plural_formulas = variable_get('locale_translation_plurals', array());
  468. }
  469. // If there is a plural formula for the language, evaluate it for the given
  470. // $count and statically cache the result for the combination of language
  471. // and count, since the result will always be identical.
  472. if (!empty($plural_formulas[$langcode])) {
  473. // $n is used inside the expression in the eval().
  474. $n = $count;
  475. $plural_indexes[$langcode][$count] = @eval('return intval(' . $plural_formulas[$langcode]['formula'] . ');');
  476. }
  477. // In case there is no plural formula for English (no imported translation
  478. // for English), use a default formula.
  479. elseif ($langcode == 'en') {
  480. $plural_indexes[$langcode][$count] = (int) ($count != 1);
  481. }
  482. // Otherwise, return -1 (unknown).
  483. else {
  484. $plural_indexes[$langcode][$count] = -1;
  485. }
  486. }
  487. return $plural_indexes[$langcode][$count];
  488. }
  489. /**
  490. * Implements hook_modules_installed().
  491. */
  492. function locale_modules_installed($modules) {
  493. locale_system_update($modules);
  494. }
  495. /**
  496. * Implements hook_themes_enabled().
  497. *
  498. * @todo This is technically wrong. We must not import upon enabling, but upon
  499. * initial installation. The theme system is missing an installation hook.
  500. */
  501. function locale_themes_enabled($themes) {
  502. locale_system_update($themes);
  503. }
  504. /**
  505. * Imports translations when new modules or themes are installed.
  506. *
  507. * This function will either import translation for the component change
  508. * right away, or start a batch if more files need to be imported.
  509. *
  510. * @param $components
  511. * An array of component (theme and/or module) names to import
  512. * translations for.
  513. *
  514. * @todo
  515. * This currently imports all .po files available, independent of
  516. * $components. Once we integrated with update status for project
  517. * identification, we should revisit and only import files for the
  518. * identified projects for the components.
  519. */
  520. function locale_system_update($components) {
  521. include_once drupal_get_path('module', 'locale') . '/locale.bulk.inc';
  522. if ($batch = locale_translate_batch_import_files(NULL, TRUE)) {
  523. batch_set($batch);
  524. }
  525. }
  526. /**
  527. * Implements hook_js_alter().
  528. *
  529. * This function checks all JavaScript files currently added via drupal_add_js()
  530. * and invokes parsing if they have not yet been parsed for Drupal.t()
  531. * and Drupal.formatPlural() calls. Also refreshes the JavaScript translation
  532. * file if necessary, and adds it to the page.
  533. */
  534. function locale_js_alter(&$javascript) {
  535. global $language_interface;
  536. $dir = 'public://' . variable_get('locale_js_directory', 'languages');
  537. $parsed = variable_get('javascript_parsed', array());
  538. $files = $new_files = FALSE;
  539. foreach ($javascript as $item) {
  540. if ($item['type'] == 'file') {
  541. $files = TRUE;
  542. $filepath = $item['data'];
  543. if (!in_array($filepath, $parsed)) {
  544. // Don't parse our own translations files.
  545. if (substr($filepath, 0, strlen($dir)) != $dir) {
  546. _locale_parse_js_file($filepath);
  547. $parsed[] = $filepath;
  548. $new_files = TRUE;
  549. }
  550. }
  551. }
  552. }
  553. // If there are any new source files we parsed, invalidate existing
  554. // JavaScript translation files for all languages, adding the refresh
  555. // flags into the existing array.
  556. if ($new_files) {
  557. $parsed += _locale_invalidate_js();
  558. }
  559. // If necessary, rebuild the translation file for the current language.
  560. if (!empty($parsed['refresh:' . $language_interface->langcode])) {
  561. // Don't clear the refresh flag on failure, so that another try will
  562. // be performed later.
  563. if (_locale_rebuild_js()) {
  564. unset($parsed['refresh:' . $language_interface->langcode]);
  565. }
  566. // Store any changes after refresh was attempted.
  567. variable_set('javascript_parsed', $parsed);
  568. }
  569. // If no refresh was attempted, but we have new source files, we need
  570. // to store them too. This occurs if current page is in English.
  571. elseif ($new_files) {
  572. variable_set('javascript_parsed', $parsed);
  573. }
  574. // Add the translation JavaScript file to the page.
  575. $locale_javascripts = variable_get('locale_translation_javascript', array());
  576. if ($files && !empty($locale_javascripts[$language_interface->langcode])) {
  577. // Add the translation JavaScript file to the page.
  578. $file = $dir . '/' . $language_interface->langcode . '_' . $locale_javascripts[$language_interface->langcode] . '.js';
  579. $javascript[$file] = drupal_js_defaults($file);
  580. }
  581. }
  582. /**
  583. * Implement hook_library_info_alter().
  584. *
  585. * Provides the language support for the jQuery UI Date Picker.
  586. */
  587. function locale_library_info_alter(&$libraries, $module) {
  588. global $language_interface;
  589. if ($module == 'system' && isset($libraries['system']['ui.datepicker'])) {
  590. $datepicker = drupal_get_path('module', 'locale') . '/locale.datepicker.js';
  591. $libraries['system']['ui.datepicker']['js'][$datepicker] = array('group' => JS_THEME);
  592. $libraries['system']['ui.datepicker']['js'][] = array(
  593. 'data' => array(
  594. 'jqueryuidatepicker' => array(
  595. 'rtl' => $language_interface->direction == LANGUAGE_RTL,
  596. 'firstDay' => variable_get('date_first_day', 0),
  597. ),
  598. ),
  599. 'type' => 'setting',
  600. );
  601. }
  602. }
  603. /**
  604. * Implements hook_form_FORM_ID_alter() for language_admin_overview_form().
  605. */
  606. function locale_form_language_admin_overview_form_alter(&$form, &$form_state) {
  607. $languages = $form['languages']['#languages'];
  608. $total_strings = db_query("SELECT COUNT(*) FROM {locales_source}")->fetchField();
  609. $stats = array_fill_keys(array_keys($languages), array());
  610. // If we have source strings, count translations and calculate progress.
  611. if (!empty($total_strings)) {
  612. $translations = db_query("SELECT COUNT(*) AS translated, t.language FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid GROUP BY language");
  613. foreach ($translations as $data) {
  614. $stats[$data->language]['translated'] = $data->translated;
  615. if ($data->translated > 0) {
  616. $stats[$data->language]['ratio'] = round($data->translated / $total_strings * 100, 2);
  617. }
  618. }
  619. }
  620. array_splice($form['languages']['#header'], -1, 0, t('Interface translation'));
  621. foreach ($languages as $langcode => $language) {
  622. $stats[$langcode] += array(
  623. 'translated' => 0,
  624. 'ratio' => 0,
  625. );
  626. if ($langcode != 'en' || locale_translate_english()) {
  627. $form['languages'][$langcode]['locale_statistics'] = array(
  628. '#type' => 'link',
  629. '#title' => t('@translated/@total (@ratio%)', array(
  630. '@translated' => $stats[$langcode]['translated'],
  631. '@total' => $total_strings,
  632. '@ratio' => $stats[$langcode]['ratio'],
  633. )),
  634. '#href' => 'admin/config/regional/translate/translate',
  635. );
  636. }
  637. else {
  638. $form['languages'][$langcode]['locale_statistics'] = array(
  639. '#markup' => t('not applicable'),
  640. );
  641. }
  642. }
  643. }
  644. /**
  645. * Implements hook_form_FORM_ID_alter() for language_admin_add_form(().
  646. */
  647. function locale_form_language_admin_add_form_alter(&$form, &$form_state) {
  648. $form['predefined_submit']['#submit'][] = 'locale_form_language_admin_add_form_alter_submit';
  649. $form['custom_language']['submit']['#submit'][] = 'locale_form_language_admin_add_form_alter_submit';
  650. }
  651. /**
  652. * Set a batch for newly added language.
  653. */
  654. function locale_form_language_admin_add_form_alter_submit($form, $form_state) {
  655. if (empty($form_state['values']['predefined_langcode']) || $form_state['values']['predefined_langcode'] == 'custom') {
  656. $langcode = $form_state['values']['langcode'];
  657. }
  658. else {
  659. $langcode = $form_state['values']['predefined_langcode'];
  660. }
  661. include_once drupal_get_path('module', 'locale') . '/locale.bulk.inc';
  662. locale_translate_add_language_set_batch($langcode);
  663. }
  664. /**
  665. * Implements hook_form_FORM_ID_alter() for language_admin_edit_form().
  666. */
  667. function locale_form_language_admin_edit_form_alter(&$form, &$form_state) {
  668. if ($form['langcode']['#type'] == 'value' && $form['langcode']['#value'] == 'en') {
  669. $form['locale_translate_english'] = array(
  670. '#title' => t('Enable interface translation to English'),
  671. '#type' => 'checkbox',
  672. '#default_value' => locale_translate_english(),
  673. );
  674. $form['#submit'][] = 'locale_form_language_admin_edit_form_alter_submit';
  675. }
  676. }
  677. /**
  678. * Submission handler to record our custom setting.
  679. */
  680. function locale_form_language_admin_edit_form_alter_submit($form, $form_state) {
  681. variable_set('locale_translate_english', $form_state['values']['locale_translate_english']);
  682. }
  683. /**
  684. * Utility function to tell if locale translates to English.
  685. */
  686. function locale_translate_english() {
  687. return variable_get('locale_translate_english', FALSE);
  688. }
  689. /**
  690. * Implements hook_form_FORM_ID_alter() for system_file_system_settings().
  691. *
  692. * Add interface translation directory setting to directories configuration.
  693. */
  694. function locale_form_system_file_system_settings_alter(&$form, $form_state) {
  695. $form['locale_translate_file_directory'] = array(
  696. '#type' => 'textfield',
  697. '#title' => t('Interface translations directory'),
  698. '#default_value' => variable_get('locale_translate_file_directory', conf_path() . '/files/translations'),
  699. '#maxlength' => 255,
  700. '#description' => t('A local file system path where interface translation files are looked for. This directory must exist.'),
  701. '#after_build' => array('system_check_directory'),
  702. '#weight' => 10,
  703. );
  704. if ($form['file_default_scheme']) {
  705. $form['file_default_scheme']['#weight'] = 20;
  706. }
  707. }
  708. /**
  709. * Implements hook_preprocess_HOOK() for node.tpl.php.
  710. */
  711. function locale_preprocess_node(&$variables) {
  712. if ($variables['langcode'] != LANGUAGE_NOT_SPECIFIED) {
  713. global $language_interface;
  714. $node_language = language_load($variables['langcode']);
  715. if ($node_language->langcode != $language_interface->langcode) {
  716. // If the node language was different from the page language, we should
  717. // add markup to identify the language. Otherwise the page language is
  718. // inherited.
  719. $variables['attributes_array']['lang'] = $variables['langcode'];
  720. if ($node_language->direction != $language_interface->direction) {
  721. // If text direction is different form the page's text direction, add
  722. // direction information as well.
  723. $dir = array('ltr', 'rtl');
  724. $variables['attributes_array']['dir'] = $dir[$node_language->direction];
  725. }
  726. }
  727. }
  728. }
  729. /**
  730. * Check that a string is safe to be added or imported as a translation.
  731. *
  732. * This test can be used to detect possibly bad translation strings. It should
  733. * not have any false positives. But it is only a test, not a transformation,
  734. * as it destroys valid HTML. We cannot reliably filter translation strings
  735. * on import because some strings are irreversibly corrupted. For example,
  736. * a &amp; in the translation would get encoded to &amp;amp; by filter_xss()
  737. * before being put in the database, and thus would be displayed incorrectly.
  738. *
  739. * The allowed tag list is like filter_xss_admin(), but omitting div and img as
  740. * not needed for translation and likely to cause layout issues (div) or a
  741. * possible attack vector (img).
  742. */
  743. function locale_string_is_safe($string) {
  744. return decode_entities($string) == decode_entities(filter_xss($string, array('a', 'abbr', 'acronym', 'address', 'b', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dl', 'dt', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'ins', 'kbd', 'li', 'ol', 'p', 'pre', 'q', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'tt', 'ul', 'var')));
  745. }
  746. /**
  747. * Parses a JavaScript file, extracts strings wrapped in Drupal.t() and
  748. * Drupal.formatPlural() and inserts them into the database.
  749. */
  750. function _locale_parse_js_file($filepath) {
  751. // The file path might contain a query string, so make sure we only use the
  752. // actual file.
  753. $parsed_url = drupal_parse_url($filepath);
  754. $filepath = $parsed_url['path'];
  755. // Load the JavaScript file.
  756. $file = file_get_contents($filepath);
  757. // Match all calls to Drupal.t() in an array.
  758. // Note: \s also matches newlines with the 's' modifier.
  759. preg_match_all('~
  760. [^\w]Drupal\s*\.\s*t\s* # match "Drupal.t" with whitespace
  761. \(\s* # match "(" argument list start
  762. (' . LOCALE_JS_STRING . ')\s* # capture string argument
  763. (?:,\s*' . LOCALE_JS_OBJECT . '\s* # optionally capture str args
  764. (?:,\s*' . LOCALE_JS_OBJECT_CONTEXT . '\s*) # optionally capture context
  765. ?)? # close optional args
  766. [,\)] # match ")" or "," to finish
  767. ~sx', $file, $t_matches);
  768. // Match all Drupal.formatPlural() calls in another array.
  769. preg_match_all('~
  770. [^\w]Drupal\s*\.\s*formatPlural\s* # match "Drupal.formatPlural" with whitespace
  771. \( # match "(" argument list start
  772. \s*.+?\s*,\s* # match count argument
  773. (' . LOCALE_JS_STRING . ')\s*,\s* # match singular string argument
  774. ( # capture plural string argument
  775. (?: # non-capturing group to repeat string pieces
  776. (?:
  777. \' # match start of single-quoted string
  778. (?:\\\\\'|[^\'])* # match any character except unescaped single-quote
  779. @count # match "@count"
  780. (?:\\\\\'|[^\'])* # match any character except unescaped single-quote
  781. \' # match end of single-quoted string
  782. |
  783. " # match start of double-quoted string
  784. (?:\\\\"|[^"])* # match any character except unescaped double-quote
  785. @count # match "@count"
  786. (?:\\\\"|[^"])* # match any character except unescaped double-quote
  787. " # match end of double-quoted string
  788. )
  789. (?:\s*\+\s*)? # match "+" with possible whitespace, for str concat
  790. )+ # match multiple because we supports concatenating strs
  791. )\s* # end capturing of plural string argument
  792. (?:,\s*' . LOCALE_JS_OBJECT . '\s* # optionally capture string args
  793. (?:,\s*' . LOCALE_JS_OBJECT_CONTEXT . '\s*)? # optionally capture context
  794. )?
  795. [,\)]
  796. ~sx', $file, $plural_matches);
  797. $matches = array();
  798. // Add strings from Drupal.t().
  799. foreach ($t_matches[1] as $key => $string) {
  800. $matches[] = array(
  801. 'string' => $string,
  802. 'context' => $t_matches[2][$key],
  803. );
  804. }
  805. // Add string from Drupal.formatPlural().
  806. foreach ($plural_matches[1] as $key => $string) {
  807. $matches[] = array(
  808. 'string' => $string,
  809. 'context' => $plural_matches[3][$key],
  810. );
  811. // If there is also a plural version of this string, add it to the strings array.
  812. if (isset($plural_matches[2][$key])) {
  813. $matches[] = array(
  814. 'string' => $plural_matches[2][$key],
  815. 'context' => $plural_matches[3][$key],
  816. );
  817. }
  818. }
  819. // Loop through all matches and process them.
  820. foreach ($matches as $key => $match) {
  821. // Remove the quotes and string concatenations from the string and context.
  822. $string = implode('', preg_split('~(?<!\\\\)[\'"]\s*\+\s*[\'"]~s', substr($match['string'], 1, -1)));
  823. $context = implode('', preg_split('~(?<!\\\\)[\'"]\s*\+\s*[\'"]~s', substr($match['context'], 1, -1)));
  824. $source = db_query("SELECT lid, location FROM {locales_source} WHERE source = :source AND context = :context", array(':source' => $string, ':context' => $context))->fetchObject();
  825. if ($source) {
  826. // We already have this source string and now have to add the location
  827. // to the location column, if this file is not yet present in there.
  828. $locations = preg_split('~\s*;\s*~', $source->location);
  829. if (!in_array($filepath, $locations)) {
  830. $locations[] = $filepath;
  831. $locations = implode('; ', $locations);
  832. // Save the new locations string to the database.
  833. db_update('locales_source')
  834. ->fields(array(
  835. 'location' => $locations,
  836. ))
  837. ->condition('lid', $source->lid)
  838. ->execute();
  839. }
  840. }
  841. else {
  842. // We don't have the source string yet, thus we insert it into the database.
  843. db_insert('locales_source')
  844. ->fields(array(
  845. 'location' => $filepath,
  846. 'source' => $string,
  847. 'context' => $context,
  848. ))
  849. ->execute();
  850. }
  851. }
  852. }
  853. /**
  854. * Force the JavaScript translation file(s) to be refreshed.
  855. *
  856. * This function sets a refresh flag for a specified language, or all
  857. * languages except English, if none specified. JavaScript translation
  858. * files are rebuilt (with locale_update_js_files()) the next time a
  859. * request is served in that language.
  860. *
  861. * @param $langcode
  862. * The language code for which the file needs to be refreshed.
  863. *
  864. * @return
  865. * New content of the 'javascript_parsed' variable.
  866. */
  867. function _locale_invalidate_js($langcode = NULL) {
  868. $parsed = variable_get('javascript_parsed', array());
  869. if (empty($langcode)) {
  870. // Invalidate all languages.
  871. $languages = language_list();
  872. if (!locale_translate_english()) {
  873. unset($languages['en']);
  874. }
  875. foreach ($languages as $lcode => $data) {
  876. $parsed['refresh:' . $lcode] = 'waiting';
  877. }
  878. }
  879. else {
  880. // Invalidate single language.
  881. $parsed['refresh:' . $langcode] = 'waiting';
  882. }
  883. variable_set('javascript_parsed', $parsed);
  884. return $parsed;
  885. }
  886. /**
  887. * (Re-)Creates the JavaScript translation file for a language.
  888. *
  889. * @param $langcode
  890. * The language, the translation file should be (re)created for.
  891. */
  892. function _locale_rebuild_js($langcode = NULL) {
  893. if (!isset($langcode)) {
  894. $language = drupal_container()->get(LANGUAGE_TYPE_INTERFACE);
  895. }
  896. else {
  897. // Get information about the locale.
  898. $languages = language_list();
  899. $language = $languages[$langcode];
  900. }
  901. // Construct the array for JavaScript translations.
  902. // Only add strings with a translation to the translations array.
  903. $result = db_query("SELECT s.lid, s.source, s.context, t.translation FROM {locales_source} s INNER JOIN {locales_target} t ON s.lid = t.lid AND t.language = :language WHERE s.location LIKE '%.js%'", array(':language' => $language->langcode));
  904. $translations = array();
  905. foreach ($result as $data) {
  906. $translations[$data->context][$data->source] = $data->translation;
  907. }
  908. // Construct the JavaScript file, if there are translations.
  909. $data_hash = NULL;
  910. $data = $status = '';
  911. if (!empty($translations)) {
  912. $data = "Drupal.locale = { ";
  913. $locale_plurals = variable_get('locale_translation_plurals', array());
  914. if (!empty($locale_plurals[$language->langcode])) {
  915. $data .= "'pluralFormula': function (\$n) { return Number({$locale_plurals[$language->langcode]['formula']}); }, ";
  916. }
  917. $data .= "'strings': " . drupal_json_encode($translations) . " };";
  918. $data_hash = drupal_hash_base64($data);
  919. }
  920. // Construct the filepath where JS translation files are stored.
  921. // There is (on purpose) no front end to edit that variable.
  922. $dir = 'public://' . variable_get('locale_js_directory', 'languages');
  923. // Delete old file, if we have no translations anymore, or a different file to be saved.
  924. $locale_javascripts = variable_get('locale_translation_javascript', array());
  925. $changed_hash = !isset($locale_javascripts[$language->langcode]) || ($locale_javascripts[$language->langcode] != $data_hash);
  926. if (!empty($locale_javascripts[$language->langcode]) && (!$data || $changed_hash)) {
  927. file_unmanaged_delete($dir . '/' . $language->langcode . '_' . $locale_javascripts[$language->langcode] . '.js');
  928. $locale_javascripts[$language->langcode] = '';
  929. $status = 'deleted';
  930. }
  931. // Only create a new file if the content has changed or the original file got
  932. // lost.
  933. $dest = $dir . '/' . $language->langcode . '_' . $data_hash . '.js';
  934. if ($data && ($changed_hash || !file_exists($dest))) {
  935. // Ensure that the directory exists and is writable, if possible.
  936. file_prepare_directory($dir, FILE_CREATE_DIRECTORY);
  937. // Save the file.
  938. if (file_unmanaged_save_data($data, $dest)) {
  939. $locale_javascripts[$language->langcode] = $data_hash;
  940. // If we deleted a previous version of the file and we replace it with a
  941. // new one we have an update.
  942. if ($status == 'deleted') {
  943. $status = 'updated';
  944. }
  945. // If the file did not exist previously and the data has changed we have
  946. // a fresh creation.
  947. elseif ($changed_hash) {
  948. $status = 'created';
  949. }
  950. // If the data hash is unchanged the translation was lost and has to be
  951. // rebuilt.
  952. else {
  953. $status = 'rebuilt';
  954. }
  955. }
  956. else {
  957. $locale_javascripts[$language->langcode] = '';
  958. $status = 'error';
  959. }
  960. }
  961. // Save the new JavaScript hash (or an empty value if the file just got
  962. // deleted). Act only if some operation was executed that changed the hash
  963. // code.
  964. if ($status && $changed_hash) {
  965. variable_set('locale_translation_javascript', $locale_javascripts);
  966. }
  967. // Log the operation and return success flag.
  968. switch ($status) {
  969. case 'updated':
  970. watchdog('locale', 'Updated JavaScript translation file for the language %language.', array('%language' => $language->name));
  971. return TRUE;
  972. case 'rebuilt':
  973. watchdog('locale', 'JavaScript translation file %file.js was lost.', array('%file' => $locale_javascripts[$language->langcode]), WATCHDOG_WARNING);
  974. // Proceed to the 'created' case as the JavaScript translation file has
  975. // been created again.
  976. case 'created':
  977. watchdog('locale', 'Created JavaScript translation file for the language %language.', array('%language' => $language->name));
  978. return TRUE;
  979. case 'deleted':
  980. watchdog('locale', 'Removed JavaScript translation file for the language %language because no translations currently exist for that language.', array('%language' => $language->name));
  981. return TRUE;
  982. case 'error':
  983. watchdog('locale', 'An error occurred during creation of the JavaScript translation file for the language %language.', array('%language' => $language->name), WATCHDOG_ERROR);
  984. return FALSE;
  985. default:
  986. // No operation needed.
  987. return TRUE;
  988. }
  989. }
  990. /**
  991. * Save locale specific date formats to the database.
  992. *
  993. * @param $langcode
  994. * Language code, can be 2 characters, e.g. 'en' or 5 characters, e.g.
  995. * 'en-CA'.
  996. * @param $type
  997. * Date format type, e.g. 'short', 'medium'.
  998. * @param $format
  999. * The date format string.
  1000. */
  1001. function locale_date_format_save($langcode, $type, $format) {
  1002. $locale_format = array();
  1003. $locale_format['language'] = $langcode;
  1004. $locale_format['type'] = $type;
  1005. $locale_format['format'] = $format;
  1006. $is_existing = (bool) db_query_range('SELECT 1 FROM {date_format_locale} WHERE language = :langcode AND type = :type', 0, 1, array(':langcode' => $langcode, ':type' => $type))->fetchField();
  1007. if ($is_existing) {
  1008. $keys = array('type', 'language');
  1009. drupal_write_record('date_format_locale', $locale_format, $keys);
  1010. }
  1011. else {
  1012. drupal_write_record('date_format_locale', $locale_format);
  1013. }
  1014. }
  1015. /**
  1016. * Select locale date format details from database.
  1017. *
  1018. * @param $languages
  1019. * An array of language codes.
  1020. *
  1021. * @return
  1022. * An array of date formats.
  1023. */
  1024. function locale_get_localized_date_format($languages) {
  1025. $formats = array();
  1026. // Get list of different format types.
  1027. $format_types = system_get_date_types();
  1028. $short_default = variable_get('date_format_short', 'm/d/Y - H:i');
  1029. // Loop through each language until we find one with some date formats
  1030. // configured.
  1031. foreach ($languages as $language) {
  1032. $date_formats = system_date_format_locale($language);
  1033. if (!empty($date_formats)) {
  1034. // We have locale-specific date formats, so check for their types. If
  1035. // we're missing a type, use the default setting instead.
  1036. foreach ($format_types as $type => $type_info) {
  1037. // If format exists for this language, use it.
  1038. if (!empty($date_formats[$type])) {
  1039. $formats['date_format_' . $type] = $date_formats[$type];
  1040. }
  1041. // Otherwise get default variable setting. If this is not set, default
  1042. // to the short format.
  1043. else {
  1044. $formats['date_format_' . $type] = variable_get('date_format_' . $type, $short_default);
  1045. }
  1046. }
  1047. // Return on the first match.
  1048. return $formats;
  1049. }
  1050. }
  1051. // No locale specific formats found, so use defaults.
  1052. $system_types = array('short', 'medium', 'long');
  1053. // Handle system types separately as they have defaults if no variable exists.
  1054. $formats['date_format_short'] = $short_default;
  1055. $formats['date_format_medium'] = variable_get('date_format_medium', 'D, m/d/Y - H:i');
  1056. $formats['date_format_long'] = variable_get('date_format_long', 'l, F j, Y - H:i');
  1057. // For non-system types, get the default setting, otherwise use the short
  1058. // format.
  1059. foreach ($format_types as $type => $type_info) {
  1060. if (!in_array($type, $system_types)) {
  1061. $formats['date_format_' . $type] = variable_get('date_format_' . $type, $short_default);
  1062. }
  1063. }
  1064. return $formats;
  1065. }
Login or register to post comments