locale.bulk.inc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. <?php
  2. /**
  3. * @file
  4. * Mass import-export and batch import functionality for Gettext .po files.
  5. */
  6. use Drupal\Core\Language\LanguageInterface;
  7. use Drupal\file\FileInterface;
  8. use Drupal\locale\Gettext;
  9. use Drupal\locale\Locale;
  10. /**
  11. * Prepare a batch to import all translations.
  12. *
  13. * @param array $options
  14. * An array with options that can have the following elements:
  15. * - 'langcode': The language code. Optional, defaults to NULL, which means
  16. * that the language will be detected from the name of the files.
  17. * - 'overwrite_options': Overwrite options array as defined in
  18. * Drupal\locale\PoDatabaseWriter. Optional, defaults to an empty array.
  19. * - 'customized': Flag indicating whether the strings imported from $file
  20. * are customized translations or come from a community source. Use
  21. * LOCALE_CUSTOMIZED or LOCALE_NOT_CUSTOMIZED. Optional, defaults to
  22. * LOCALE_NOT_CUSTOMIZED.
  23. * - 'finish_feedback': Whether or not to give feedback to the user when the
  24. * batch is finished. Optional, defaults to TRUE.
  25. * @param bool $force
  26. * (optional) Import all available files, even if they were imported before.
  27. *
  28. * @return array|bool
  29. * The batch structure, or FALSE if no files are used to build the batch.
  30. *
  31. * @todo
  32. * Integrate with update status to identify projects needed and integrate
  33. * l10n_update functionality to feed in translation files alike.
  34. * See https://www.drupal.org/node/1191488.
  35. */
  36. function locale_translate_batch_import_files(array $options, $force = FALSE) {
  37. $options += [
  38. 'overwrite_options' => [],
  39. 'customized' => LOCALE_NOT_CUSTOMIZED,
  40. 'finish_feedback' => TRUE,
  41. ];
  42. if (!empty($options['langcode'])) {
  43. $langcodes = [$options['langcode']];
  44. }
  45. else {
  46. // If langcode was not provided, make sure to only import files for the
  47. // languages we have added.
  48. $langcodes = array_keys(\Drupal::languageManager()->getLanguages());
  49. }
  50. $files = locale_translate_get_interface_translation_files([], $langcodes);
  51. if (!$force) {
  52. $result = db_select('locale_file', 'lf')
  53. ->fields('lf', ['langcode', 'uri', 'timestamp'])
  54. ->condition('langcode', $langcodes)
  55. ->execute()
  56. ->fetchAllAssoc('uri');
  57. foreach ($result as $uri => $info) {
  58. if (isset($files[$uri]) && filemtime($uri) <= $info->timestamp) {
  59. // The file is already imported and not changed since the last import.
  60. // Remove it from file list and don't import it again.
  61. unset($files[$uri]);
  62. }
  63. }
  64. }
  65. return locale_translate_batch_build($files, $options);
  66. }
  67. /**
  68. * Get interface translation files present in the translations directory.
  69. *
  70. * @param array $projects
  71. * (optional) Project names from which to get the translation files and
  72. * history. Defaults to all projects.
  73. * @param array $langcodes
  74. * (optional) Language codes from which to get the translation files and
  75. * history. Defaults to all languages.
  76. *
  77. * @return array
  78. * An array of interface translation files keyed by their URI.
  79. */
  80. function locale_translate_get_interface_translation_files(array $projects = [], array $langcodes = []) {
  81. module_load_include('compare.inc', 'locale');
  82. $files = [];
  83. $projects = $projects ? $projects : array_keys(locale_translation_get_projects());
  84. $langcodes = $langcodes ? $langcodes : array_keys(locale_translatable_language_list());
  85. // Scan the translations directory for files matching a name pattern
  86. // containing a project name and language code: {project}.{langcode}.po or
  87. // {project}-{version}.{langcode}.po.
  88. // Only files of known projects and languages will be returned.
  89. $directory = \Drupal::config('locale.settings')->get('translation.path');
  90. $result = file_scan_directory($directory, '![a-z_]+(\-[0-9a-z\.\-\+]+|)\.[^\./]+\.po$!', ['recurse' => FALSE]);
  91. foreach ($result as $file) {
  92. // Update the file object with project name and version from the file name.
  93. $file = locale_translate_file_attach_properties($file);
  94. if (in_array($file->project, $projects)) {
  95. if (in_array($file->langcode, $langcodes)) {
  96. $files[$file->uri] = $file;
  97. }
  98. }
  99. }
  100. return $files;
  101. }
  102. /**
  103. * Build a locale batch from an array of files.
  104. *
  105. * @param array $files
  106. * Array of file objects to import.
  107. * @param array $options
  108. * An array with options that can have the following elements:
  109. * - 'langcode': The language code. Optional, defaults to NULL, which means
  110. * that the language will be detected from the name of the files.
  111. * - 'overwrite_options': Overwrite options array as defined in
  112. * Drupal\locale\PoDatabaseWriter. Optional, defaults to an empty array.
  113. * - 'customized': Flag indicating whether the strings imported from $file
  114. * are customized translations or come from a community source. Use
  115. * LOCALE_CUSTOMIZED or LOCALE_NOT_CUSTOMIZED. Optional, defaults to
  116. * LOCALE_NOT_CUSTOMIZED.
  117. * - 'finish_feedback': Whether or not to give feedback to the user when the
  118. * batch is finished. Optional, defaults to TRUE.
  119. *
  120. * @return array|bool
  121. * A batch structure or FALSE if $files was empty.
  122. */
  123. function locale_translate_batch_build(array $files, array $options) {
  124. $options += [
  125. 'overwrite_options' => [],
  126. 'customized' => LOCALE_NOT_CUSTOMIZED,
  127. 'finish_feedback' => TRUE,
  128. ];
  129. if (count($files)) {
  130. $operations = [];
  131. foreach ($files as $file) {
  132. // We call locale_translate_batch_import for every batch operation.
  133. $operations[] = ['locale_translate_batch_import', [$file, $options]];
  134. }
  135. // Save the translation status of all files.
  136. $operations[] = ['locale_translate_batch_import_save', []];
  137. // Add a final step to refresh JavaScript and configuration strings.
  138. $operations[] = ['locale_translate_batch_refresh', []];
  139. $batch = [
  140. 'operations' => $operations,
  141. 'title' => t('Importing interface translations'),
  142. 'progress_message' => '',
  143. 'error_message' => t('Error importing interface translations'),
  144. 'file' => drupal_get_path('module', 'locale') . '/locale.bulk.inc',
  145. ];
  146. if ($options['finish_feedback']) {
  147. $batch['finished'] = 'locale_translate_batch_finished';
  148. }
  149. return $batch;
  150. }
  151. return FALSE;
  152. }
  153. /**
  154. * Implements callback_batch_operation().
  155. *
  156. * Perform interface translation import.
  157. *
  158. * @param object $file
  159. * A file object of the gettext file to be imported. The file object must
  160. * contain a language parameter (other than
  161. * LanguageInterface::LANGCODE_NOT_SPECIFIED). This is used as the language of
  162. * the import.
  163. * @param array $options
  164. * An array with options that can have the following elements:
  165. * - 'langcode': The language code.
  166. * - 'overwrite_options': Overwrite options array as defined in
  167. * Drupal\locale\PoDatabaseWriter. Optional, defaults to an empty array.
  168. * - 'customized': Flag indicating whether the strings imported from $file
  169. * are customized translations or come from a community source. Use
  170. * LOCALE_CUSTOMIZED or LOCALE_NOT_CUSTOMIZED. Optional, defaults to
  171. * LOCALE_NOT_CUSTOMIZED.
  172. * - 'message': Alternative message to display during import. Note, this must
  173. * be sanitized text.
  174. * @param array|\ArrayAccess $context
  175. * Contains a list of files imported.
  176. */
  177. function locale_translate_batch_import($file, array $options, &$context) {
  178. // Merge the default values in the $options array.
  179. $options += [
  180. 'overwrite_options' => [],
  181. 'customized' => LOCALE_NOT_CUSTOMIZED,
  182. ];
  183. if (isset($file->langcode) && $file->langcode != LanguageInterface::LANGCODE_NOT_SPECIFIED) {
  184. try {
  185. if (empty($context['sandbox'])) {
  186. $context['sandbox']['parse_state'] = [
  187. 'filesize' => filesize(\Drupal::service('file_system')->realpath($file->uri)),
  188. 'chunk_size' => 200,
  189. 'seek' => 0,
  190. ];
  191. }
  192. // Update the seek and the number of items in the $options array().
  193. $options['seek'] = $context['sandbox']['parse_state']['seek'];
  194. $options['items'] = $context['sandbox']['parse_state']['chunk_size'];
  195. $report = Gettext::fileToDatabase($file, $options);
  196. // If not yet finished with reading, mark progress based on size and
  197. // position.
  198. if ($report['seek'] < filesize($file->uri)) {
  199. $context['sandbox']['parse_state']['seek'] = $report['seek'];
  200. // Maximize the progress bar at 95% before completion, the batch API
  201. // could trigger the end of the operation before file reading is done,
  202. // because of floating point inaccuracies. See
  203. // https://www.drupal.org/node/1089472.
  204. $context['finished'] = min(0.95, $report['seek'] / filesize($file->uri));
  205. if (isset($options['message'])) {
  206. $context['message'] = t('@message (@percent%).', ['@message' => $options['message'], '@percent' => (int) ($context['finished'] * 100)]);
  207. }
  208. else {
  209. $context['message'] = t('Importing translation file: %filename (@percent%).', ['%filename' => $file->filename, '@percent' => (int) ($context['finished'] * 100)]);
  210. }
  211. }
  212. else {
  213. // We are finished here.
  214. $context['finished'] = 1;
  215. // Store the file data for processing by the next batch operation.
  216. $file->timestamp = filemtime($file->uri);
  217. $context['results']['files'][$file->uri] = $file;
  218. $context['results']['languages'][$file->uri] = $file->langcode;
  219. }
  220. // Add the reported values to the statistics for this file.
  221. // Each import iteration reports statistics in an array. The results of
  222. // each iteration are added and merged here and stored per file.
  223. if (!isset($context['results']['stats']) || !isset($context['results']['stats'][$file->uri])) {
  224. $context['results']['stats'][$file->uri] = [];
  225. }
  226. foreach ($report as $key => $value) {
  227. if (is_numeric($report[$key])) {
  228. if (!isset($context['results']['stats'][$file->uri][$key])) {
  229. $context['results']['stats'][$file->uri][$key] = 0;
  230. }
  231. $context['results']['stats'][$file->uri][$key] += $report[$key];
  232. }
  233. elseif (is_array($value)) {
  234. $context['results']['stats'][$file->uri] += [$key => []];
  235. $context['results']['stats'][$file->uri][$key] = array_merge($context['results']['stats'][$file->uri][$key], $value);
  236. }
  237. }
  238. }
  239. catch (Exception $exception) {
  240. // Import failed. Store the data of the failing file.
  241. $context['results']['failed_files'][] = $file;
  242. \Drupal::logger('locale')->notice('Unable to import translations file: @file', ['@file' => $file->uri]);
  243. }
  244. }
  245. }
  246. /**
  247. * Implements callback_batch_operation().
  248. *
  249. * Save data of imported files.
  250. *
  251. * @param array|\ArrayAccess $context
  252. * Contains a list of imported files.
  253. */
  254. function locale_translate_batch_import_save($context) {
  255. if (isset($context['results']['files'])) {
  256. foreach ($context['results']['files'] as $file) {
  257. // Update the file history if both project and version are known. This
  258. // table is used by the automated translation update function which tracks
  259. // translation status of module and themes in the system. Other
  260. // translation files are not tracked and are therefore not stored in this
  261. // table.
  262. if ($file->project && $file->version) {
  263. $file->last_checked = REQUEST_TIME;
  264. locale_translation_update_file_history($file);
  265. }
  266. }
  267. $context['message'] = t('Translations imported.');
  268. }
  269. }
  270. /**
  271. * Implements callback_batch_operation().
  272. *
  273. * Refreshes translations after importing strings.
  274. *
  275. * @param array|\ArrayAccess $context
  276. * Contains a list of strings updated and information about the progress.
  277. */
  278. function locale_translate_batch_refresh(&$context) {
  279. if (!isset($context['sandbox']['refresh'])) {
  280. $strings = $langcodes = [];
  281. if (isset($context['results']['stats'])) {
  282. // Get list of unique string identifiers and language codes updated.
  283. $langcodes = array_unique(array_values($context['results']['languages']));
  284. foreach ($context['results']['stats'] as $report) {
  285. $strings = array_merge($strings, $report['strings']);
  286. }
  287. }
  288. if ($strings) {
  289. // Initialize multi-step string refresh.
  290. $context['message'] = t('Updating translations for JavaScript and default configuration.');
  291. $context['sandbox']['refresh']['strings'] = array_unique($strings);
  292. $context['sandbox']['refresh']['languages'] = $langcodes;
  293. $context['sandbox']['refresh']['names'] = [];
  294. $context['results']['stats']['config'] = 0;
  295. $context['sandbox']['refresh']['count'] = count($strings);
  296. // We will update strings on later steps.
  297. $context['finished'] = 0;
  298. }
  299. else {
  300. $context['finished'] = 1;
  301. }
  302. }
  303. elseif ($name = array_shift($context['sandbox']['refresh']['names'])) {
  304. // Refresh all languages for one object at a time.
  305. $count = Locale::config()->updateConfigTranslations([$name], $context['sandbox']['refresh']['languages']);
  306. $context['results']['stats']['config'] += $count;
  307. // Inherit finished information from the "parent" string lookup step so
  308. // visual display of status will make sense.
  309. $context['finished'] = $context['sandbox']['refresh']['names_finished'];
  310. $context['message'] = t('Updating default configuration (@percent%).', ['@percent' => (int) ($context['finished'] * 100)]);
  311. }
  312. elseif (!empty($context['sandbox']['refresh']['strings'])) {
  313. // Not perfect but will give some indication of progress.
  314. $context['finished'] = 1 - count($context['sandbox']['refresh']['strings']) / $context['sandbox']['refresh']['count'];
  315. // Pending strings, refresh 100 at a time, get next pack.
  316. $next = array_slice($context['sandbox']['refresh']['strings'], 0, 100);
  317. array_splice($context['sandbox']['refresh']['strings'], 0, count($next));
  318. // Clear cache and force refresh of JavaScript translations.
  319. _locale_refresh_translations($context['sandbox']['refresh']['languages'], $next);
  320. // Check whether we need to refresh configuration objects.
  321. if ($names = Locale::config()->getStringNames($next)) {
  322. $context['sandbox']['refresh']['names_finished'] = $context['finished'];
  323. $context['sandbox']['refresh']['names'] = $names;
  324. }
  325. }
  326. else {
  327. $context['message'] = t('Updated default configuration.');
  328. $context['finished'] = 1;
  329. }
  330. }
  331. /**
  332. * Implements callback_batch_finished().
  333. *
  334. * Finished callback of system page locale import batch.
  335. *
  336. * @param bool $success
  337. * TRUE if batch successfully completed.
  338. * @param array $results
  339. * Batch results.
  340. */
  341. function locale_translate_batch_finished($success, array $results) {
  342. $logger = \Drupal::logger('locale');
  343. if ($success) {
  344. $additions = $updates = $deletes = $skips = $config = 0;
  345. if (isset($results['failed_files'])) {
  346. if (\Drupal::moduleHandler()->moduleExists('dblog') && \Drupal::currentUser()->hasPermission('access site reports')) {
  347. $message = \Drupal::translation()->formatPlural(count($results['failed_files']), 'One translation file could not be imported. <a href=":url">See the log</a> for details.', '@count translation files could not be imported. <a href=":url">See the log</a> for details.', [':url' => \Drupal::url('dblog.overview')]);
  348. }
  349. else {
  350. $message = \Drupal::translation()->formatPlural(count($results['failed_files']), 'One translation file could not be imported. See the log for details.', '@count translation files could not be imported. See the log for details.');
  351. }
  352. \Drupal::messenger()->addError($message);
  353. }
  354. if (isset($results['files'])) {
  355. $skipped_files = [];
  356. // If there are no results and/or no stats (eg. coping with an empty .po
  357. // file), simply do nothing.
  358. if ($results && isset($results['stats'])) {
  359. foreach ($results['stats'] as $filepath => $report) {
  360. $additions += $report['additions'];
  361. $updates += $report['updates'];
  362. $deletes += $report['deletes'];
  363. $skips += $report['skips'];
  364. if ($report['skips'] > 0) {
  365. $skipped_files[] = $filepath;
  366. }
  367. }
  368. }
  369. \Drupal::messenger()->addStatus(\Drupal::translation()->formatPlural(count($results['files']),
  370. 'One translation file imported. %number translations were added, %update translations were updated and %delete translations were removed.',
  371. '@count translation files imported. %number translations were added, %update translations were updated and %delete translations were removed.',
  372. ['%number' => $additions, '%update' => $updates, '%delete' => $deletes]
  373. ));
  374. $logger->notice('Translations imported: %number added, %update updated, %delete removed.', ['%number' => $additions, '%update' => $updates, '%delete' => $deletes]);
  375. if ($skips) {
  376. if (\Drupal::moduleHandler()->moduleExists('dblog') && \Drupal::currentUser()->hasPermission('access site reports')) {
  377. $message = \Drupal::translation()->formatPlural($skips, 'One translation string was skipped because of disallowed or malformed HTML. <a href=":url">See the log</a> for details.', '@count translation strings were skipped because of disallowed or malformed HTML. <a href=":url">See the log</a> for details.', [':url' => \Drupal::url('dblog.overview')]);
  378. }
  379. else {
  380. $message = \Drupal::translation()->formatPlural($skips, 'One translation string was skipped because of disallowed or malformed HTML. See the log for details.', '@count translation strings were skipped because of disallowed or malformed HTML. See the log for details.');
  381. }
  382. \Drupal::messenger()->addWarning($message);
  383. $logger->warning('@count disallowed HTML string(s) in files: @files.', ['@count' => $skips, '@files' => implode(',', $skipped_files)]);
  384. }
  385. }
  386. }
  387. // Add messages for configuration too.
  388. if (isset($results['stats']['config'])) {
  389. locale_config_batch_finished($success, $results);
  390. }
  391. }
  392. /**
  393. * Creates a file object and populates the timestamp property.
  394. *
  395. * @param string $filepath
  396. * The filepath of a file to import.
  397. *
  398. * @return object
  399. * An object representing the file.
  400. */
  401. function locale_translate_file_create($filepath) {
  402. $file = new stdClass();
  403. $file->filename = drupal_basename($filepath);
  404. $file->uri = $filepath;
  405. $file->timestamp = filemtime($file->uri);
  406. return $file;
  407. }
  408. /**
  409. * Generates file properties from filename and options.
  410. *
  411. * An attempt is made to determine the translation language, project name and
  412. * project version from the file name. Supported file name patterns are:
  413. * {project}-{version}.{langcode}.po, {prefix}.{langcode}.po or {langcode}.po.
  414. * Alternatively the translation language can be set using the $options.
  415. *
  416. * @param object $file
  417. * A file object of the gettext file to be imported.
  418. * @param array $options
  419. * An array with options:
  420. * - 'langcode': The language code. Overrides the file language.
  421. *
  422. * @return object
  423. * Modified file object.
  424. */
  425. function locale_translate_file_attach_properties($file, array $options = []) {
  426. // If $file is a file entity, convert it to a stdClass.
  427. if ($file instanceof FileInterface) {
  428. $file = (object) [
  429. 'filename' => $file->getFilename(),
  430. 'uri' => $file->getFileUri(),
  431. ];
  432. }
  433. // Extract project, version and language code from the file name. Supported:
  434. // {project}-{version}.{langcode}.po, {prefix}.{langcode}.po or {langcode}.po
  435. preg_match('!
  436. ( # project OR project and version OR empty (group 1)
  437. ([a-z_]+) # project name (group 2)
  438. \. # .
  439. | # OR
  440. ([a-z_]+) # project name (group 3)
  441. \- # -
  442. ([0-9a-z\.\-\+]+) # version (group 4)
  443. \. # .
  444. | # OR
  445. ) # (empty)
  446. ([^\./]+) # language code (group 5)
  447. \. # .
  448. po # po extension
  449. $!x', $file->filename, $matches);
  450. if (isset($matches[5])) {
  451. $file->project = $matches[2] . $matches[3];
  452. $file->version = $matches[4];
  453. $file->langcode = isset($options['langcode']) ? $options['langcode'] : $matches[5];
  454. }
  455. else {
  456. $file->langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
  457. }
  458. return $file;
  459. }
  460. /**
  461. * Deletes interface translation files and translation history records.
  462. *
  463. * @param array $projects
  464. * (optional) Project names from which to delete the translation files and
  465. * history. Defaults to all projects.
  466. * @param array $langcodes
  467. * (optional) Language codes from which to delete the translation files and
  468. * history. Defaults to all languages.
  469. *
  470. * @return bool
  471. * TRUE if files are removed successfully. FALSE if one or more files could
  472. * not be deleted.
  473. */
  474. function locale_translate_delete_translation_files(array $projects = [], array $langcodes = []) {
  475. $fail = FALSE;
  476. locale_translation_file_history_delete($projects, $langcodes);
  477. // Delete all translation files from the translations directory.
  478. if ($files = locale_translate_get_interface_translation_files($projects, $langcodes)) {
  479. foreach ($files as $file) {
  480. $success = file_unmanaged_delete($file->uri);
  481. if (!$success) {
  482. $fail = TRUE;
  483. }
  484. }
  485. }
  486. return !$fail;
  487. }
  488. /**
  489. * Builds a locale batch to refresh configuration.
  490. *
  491. * @param array $options
  492. * An array with options that can have the following elements:
  493. * - 'finish_feedback': (optional) Whether or not to give feedback to the user
  494. * when the batch is finished. Defaults to TRUE.
  495. * @param array $langcodes
  496. * (optional) Array of language codes. Defaults to all translatable languages.
  497. * @param array $components
  498. * (optional) Array of component lists indexed by type. If not present or it
  499. * is an empty array, it will update all components.
  500. *
  501. * @return array
  502. * The batch definition.
  503. */
  504. function locale_config_batch_update_components(array $options, array $langcodes = [], array $components = []) {
  505. $langcodes = $langcodes ? $langcodes : array_keys(\Drupal::languageManager()->getLanguages());
  506. if ($langcodes && $names = Locale::config()->getComponentNames($components)) {
  507. return locale_config_batch_build($names, $langcodes, $options);
  508. }
  509. }
  510. /**
  511. * Creates a locale batch to refresh specific configuration.
  512. *
  513. * @param array $names
  514. * List of configuration object names (which are strings) to update.
  515. * @param array $langcodes
  516. * List of language codes to refresh.
  517. * @param array $options
  518. * (optional) An array with options that can have the following elements:
  519. * - 'finish_feedback': Whether or not to give feedback to the user when the
  520. * batch is finished. Defaults to TRUE.
  521. *
  522. * @return array
  523. * The batch definition.
  524. *
  525. * @see locale_config_batch_refresh_name()
  526. */
  527. function locale_config_batch_build(array $names, array $langcodes, array $options = []) {
  528. $options += ['finish_feedback' => TRUE];
  529. $i = 0;
  530. $batch_names = [];
  531. $operations = [];
  532. foreach ($names as $name) {
  533. $batch_names[] = $name;
  534. $i++;
  535. // During installation the caching of configuration objects is disabled so
  536. // it is very expensive to initialize the \Drupal::config() object on each
  537. // request. We batch a small number of configuration object upgrades
  538. // together to improve the overall performance of the process.
  539. if ($i % 20 == 0) {
  540. $operations[] = ['locale_config_batch_refresh_name', [$batch_names, $langcodes]];
  541. $batch_names = [];
  542. }
  543. }
  544. if (!empty($batch_names)) {
  545. $operations[] = ['locale_config_batch_refresh_name', [$batch_names, $langcodes]];
  546. }
  547. $batch = [
  548. 'operations' => $operations,
  549. 'title' => t('Updating configuration translations'),
  550. 'init_message' => t('Starting configuration update'),
  551. 'error_message' => t('Error updating configuration translations'),
  552. 'file' => drupal_get_path('module', 'locale') . '/locale.bulk.inc',
  553. ];
  554. if (!empty($options['finish_feedback'])) {
  555. $batch['completed'] = 'locale_config_batch_finished';
  556. }
  557. return $batch;
  558. }
  559. /**
  560. * Implements callback_batch_operation().
  561. *
  562. * Performs configuration translation refresh.
  563. *
  564. * @param array $names
  565. * An array of names of configuration objects to update.
  566. * @param array $langcodes
  567. * (optional) Array of language codes to update. Defaults to all languages.
  568. * @param array|\ArrayAccess $context
  569. * Contains a list of files imported.
  570. *
  571. * @see locale_config_batch_build()
  572. */
  573. function locale_config_batch_refresh_name(array $names, array $langcodes, &$context) {
  574. if (!isset($context['result']['stats']['config'])) {
  575. $context['result']['stats']['config'] = 0;
  576. }
  577. $context['result']['stats']['config'] += Locale::config()->updateConfigTranslations($names, $langcodes);
  578. foreach ($names as $name) {
  579. $context['result']['names'][] = $name;
  580. }
  581. $context['result']['langcodes'] = $langcodes;
  582. $context['finished'] = 1;
  583. }
  584. /**
  585. * Implements callback_batch_finished().
  586. *
  587. * Finishes callback of system page locale import batch.
  588. *
  589. * @param bool $success
  590. * Information about the success of the batch import.
  591. * @param array $results
  592. * Information about the results of the batch import.
  593. *
  594. * @see locale_config_batch_build()
  595. */
  596. function locale_config_batch_finished($success, array $results) {
  597. if ($success) {
  598. $configuration = isset($results['stats']['config']) ? $results['stats']['config'] : 0;
  599. if ($configuration) {
  600. \Drupal::messenger()->addStatus(t('The configuration was successfully updated. There are %number configuration objects updated.', ['%number' => $configuration]));
  601. \Drupal::logger('locale')->notice('The configuration was successfully updated. %number configuration objects updated.', ['%number' => $configuration]);
  602. }
  603. else {
  604. \Drupal::messenger()->addStatus(t('No configuration objects have been updated.'));
  605. \Drupal::logger('locale')->warning('No configuration objects have been updated.');
  606. }
  607. }
  608. }