locale.inc

  1. drupal
    1. 4.6 includes/locale.inc
    2. 4.7 includes/locale.inc
    3. 5 includes/locale.inc
    4. 6 includes/locale.inc
    5. 7 includes/locale.inc

Admin-related functions for locale.module.

Functions & methods

NameDescription
locale_add_language_form
locale_add_language_form_submitProcess the language addition form submission.
locale_add_language_form_validateValidate the language addition form.
locale_custom_language_form
theme_locale_admin_manage_screenTheme the locale admin manager form.
_locale_add_languageHelper function to add a language
_locale_admin_export_screenUser interface for the translation export screen
_locale_admin_importUser interface for the translation import screen.
_locale_admin_import_submitProcess the locale import form submission.
_locale_admin_manage_add_screenUser interface for the language addition screen.
_locale_admin_manage_screenUser interface for the language management screen.
_locale_admin_manage_screen_submitProcess locale admin manager form submissions.
_locale_admin_manage_screen_validate
_locale_export_poExports a Portable Object (Template) file for a language
_locale_export_pot_form
_locale_export_po_form
_locale_export_po_form_submitProcess a locale export form submissions.
_locale_export_printPrint out a string on multiple lines
_locale_export_remove_pluralRemoves plural index information from a string
_locale_export_wrapCustom word wrapping for Portable Object (Template) files.
_locale_get_iso639_listSome of the common languages with their English and native names
_locale_import_append_pluralModify a string to contain proper count indices
_locale_import_messageSets an error message occurred during locale file parsing.
_locale_import_one_stringImports a string into the database
_locale_import_parse_arithmeticParses and sanitizes an arithmetic formula into a PHP expression
_locale_import_parse_headerParses a Gettext Portable Object file header
_locale_import_parse_plural_formsParses a Plural-Forms entry from a Gettext Portable Object file header
_locale_import_parse_quotedParses a string in quotes
_locale_import_poParses Gettext Portable Object file information and inserts into database
_locale_import_read_poParses Gettext Portable Object file into an array
_locale_import_shorten_commentsGenerate a short, one string version of the passed comment array
_locale_import_tokenize_formulaBackward compatible implementation of token_get_all() for formula parsing
_locale_prepare_iso_listPrepares the language code list for a select form item with only the unsupported ones
_locale_string_deleteDelete a language string.
_locale_string_editUser interface for string editing.
_locale_string_edit_submitProcess string editing form submissions. Saves all translations of one string submitted from a form.
_locale_string_language_listList languages in search result table
_locale_string_seekPerform a string search and display results in a table
_locale_string_seek_formUser interface for the string search screen
_locale_string_seek_queryBuild object out of search criteria specified in request variables

File

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