Upgraded drupal core with security updates
[yaffs-website] / web / core / includes / update.inc
1 <?php
2
3 /**
4  * @file
5  * Drupal database update API.
6  *
7  * This file contains functions to perform database updates for a Drupal
8  * installation. It is included and used extensively by update.php.
9  */
10
11 use Drupal\Component\Graph\Graph;
12 use Drupal\Core\Utility\Error;
13
14 /**
15  * Disables any extensions that are incompatible with the current core version.
16  */
17 function update_fix_compatibility() {
18   $extension_config = \Drupal::configFactory()->getEditable('core.extension');
19   $save = FALSE;
20   foreach (['module', 'theme'] as $type) {
21     foreach ($extension_config->get($type) as $name => $weight) {
22       if (update_check_incompatibility($name, $type)) {
23         $extension_config->clear("$type.$name");
24         $save = TRUE;
25       }
26     }
27   }
28   if ($save) {
29     $extension_config->set('module', module_config_sort($extension_config->get('module')));
30     $extension_config->save();
31   }
32 }
33
34 /**
35  * Tests the compatibility of a module or theme.
36  */
37 function update_check_incompatibility($name, $type = 'module') {
38   static $themes, $modules;
39
40   // Store values of expensive functions for future use.
41   if (empty($themes) || empty($modules)) {
42     // We need to do a full rebuild here to make sure the database reflects any
43     // code changes that were made in the filesystem before the update script
44     // was initiated.
45     $themes = \Drupal::service('theme_handler')->rebuildThemeData();
46     $modules = system_rebuild_module_data();
47   }
48
49   if ($type == 'module' && isset($modules[$name])) {
50     $file = $modules[$name];
51   }
52   elseif ($type == 'theme' && isset($themes[$name])) {
53     $file = $themes[$name];
54   }
55   if (!isset($file)
56       || !isset($file->info['core'])
57       || $file->info['core'] != \Drupal::CORE_COMPATIBILITY
58       || version_compare(phpversion(), $file->info['php']) < 0) {
59     return TRUE;
60   }
61   return FALSE;
62 }
63
64 /**
65  * Returns whether the minimum schema requirement has been satisfied.
66  *
67  * @return array
68  *   A requirements info array.
69  */
70 function update_system_schema_requirements() {
71   $requirements = [];
72
73   $system_schema = drupal_get_installed_schema_version('system');
74
75   $requirements['minimum schema']['title'] = 'Minimum schema version';
76   if ($system_schema >= \Drupal::CORE_MINIMUM_SCHEMA_VERSION) {
77     $requirements['minimum schema'] += [
78       'value' => 'The installed schema version meets the minimum.',
79       'description' => 'Schema version: ' . $system_schema,
80     ];
81   }
82   else {
83     $requirements['minimum schema'] += [
84       'value' => 'The installed schema version does not meet the minimum.',
85       'severity' => REQUIREMENT_ERROR,
86       'description' => 'Your system schema version is ' . $system_schema . '. Updating directly from a schema version prior to 8000 is not supported. You must <a href="https://www.drupal.org/node/2179269">migrate your site to Drupal 8</a> first.',
87     ];
88   }
89
90   return $requirements;
91 }
92
93 /**
94  * Checks update requirements and reports errors and (optionally) warnings.
95  */
96 function update_check_requirements() {
97   // Check requirements of all loaded modules.
98   $requirements = \Drupal::moduleHandler()->invokeAll('requirements', ['update']);
99   $requirements += update_system_schema_requirements();
100   return $requirements;
101 }
102
103 /**
104  * Forces a module to a given schema version.
105  *
106  * This function is rarely necessary.
107  *
108  * @param string $module
109  *   Name of the module.
110  * @param string $schema_version
111  *   The schema version the module should be set to.
112  */
113 function update_set_schema($module, $schema_version) {
114   \Drupal::keyValue('system.schema')->set($module, $schema_version);
115   // system_list_reset() is in module.inc but that would only be available
116   // once the variable bootstrap is done.
117   require_once __DIR__ . '/module.inc';
118   system_list_reset();
119 }
120
121 /**
122  * Implements callback_batch_operation().
123  *
124  * Performs one update and stores the results for display on the results page.
125  *
126  * If an update function completes successfully, it should return a message
127  * as a string indicating success, for example:
128  * @code
129  * return t('New index added successfully.');
130  * @endcode
131  *
132  * Alternatively, it may return nothing. In that case, no message
133  * will be displayed at all.
134  *
135  * If it fails for whatever reason, it should throw an instance of
136  * Drupal\Core\Utility\UpdateException with an appropriate error message, for
137  * example:
138  * @code
139  * use Drupal\Core\Utility\UpdateException;
140  * throw new UpdateException(t('Description of what went wrong'));
141  * @endcode
142  *
143  * If an exception is thrown, the current update and all updates that depend on
144  * it will be aborted. The schema version will not be updated in this case, and
145  * all the aborted updates will continue to appear on update.php as updates
146  * that have not yet been run.
147  *
148  * If an update function needs to be re-run as part of a batch process, it
149  * should accept the $sandbox array by reference as its first parameter
150  * and set the #finished property to the percentage completed that it is, as a
151  * fraction of 1.
152  *
153  * @param $module
154  *   The module whose update will be run.
155  * @param $number
156  *   The update number to run.
157  * @param $dependency_map
158  *   An array whose keys are the names of all update functions that will be
159  *   performed during this batch process, and whose values are arrays of other
160  *   update functions that each one depends on.
161  * @param $context
162  *   The batch context array.
163  *
164  * @see update_resolve_dependencies()
165  */
166 function update_do_one($module, $number, $dependency_map, &$context) {
167   $function = $module . '_update_' . $number;
168
169   // If this update was aborted in a previous step, or has a dependency that
170   // was aborted in a previous step, go no further.
171   if (!empty($context['results']['#abort']) && array_intersect($context['results']['#abort'], array_merge($dependency_map, [$function]))) {
172     return;
173   }
174
175   $ret = [];
176   if (function_exists($function)) {
177     try {
178       $ret['results']['query'] = $function($context['sandbox']);
179       $ret['results']['success'] = TRUE;
180     }
181     // @TODO We may want to do different error handling for different
182     // exception types, but for now we'll just log the exception and
183     // return the message for printing.
184     // @see https://www.drupal.org/node/2564311
185     catch (Exception $e) {
186       watchdog_exception('update', $e);
187
188       $variables = Error::decodeException($e);
189       unset($variables['backtrace']);
190       $ret['#abort'] = ['success' => FALSE, 'query' => t('%type: @message in %function (line %line of %file).', $variables)];
191     }
192   }
193
194   if (isset($context['sandbox']['#finished'])) {
195     $context['finished'] = $context['sandbox']['#finished'];
196     unset($context['sandbox']['#finished']);
197   }
198
199   if (!isset($context['results'][$module])) {
200     $context['results'][$module] = [];
201   }
202   if (!isset($context['results'][$module][$number])) {
203     $context['results'][$module][$number] = [];
204   }
205   $context['results'][$module][$number] = array_merge($context['results'][$module][$number], $ret);
206
207   if (!empty($ret['#abort'])) {
208     // Record this function in the list of updates that were aborted.
209     $context['results']['#abort'][] = $function;
210   }
211
212   // Record the schema update if it was completed successfully.
213   if ($context['finished'] == 1 && empty($ret['#abort'])) {
214     drupal_set_installed_schema_version($module, $number);
215   }
216
217   $context['message'] = t('Updating @module', ['@module' => $module]);
218 }
219
220 /**
221  * Executes a single hook_post_update_NAME().
222  *
223  * @param string $function
224  *   The function name, that should be executed.
225  * @param array $context
226  *   The batch context array.
227  */
228 function update_invoke_post_update($function, &$context) {
229   $ret = [];
230
231   // If this update was aborted in a previous step, or has a dependency that was
232   // aborted in a previous step, go no further.
233   if (!empty($context['results']['#abort'])) {
234     return;
235   }
236
237   list($module, $name) = explode('_post_update_', $function, 2);
238   module_load_include('php', $module, $module . '.post_update');
239   if (function_exists($function)) {
240     try {
241       $ret['results']['query'] = $function($context['sandbox']);
242       $ret['results']['success'] = TRUE;
243
244       if (!isset($context['sandbox']['#finished']) || (isset($context['sandbox']['#finished']) && $context['sandbox']['#finished'] >= 1)) {
245         \Drupal::service('update.post_update_registry')->registerInvokedUpdates([$function]);
246       }
247     }
248     // @TODO We may want to do different error handling for different exception
249     // types, but for now we'll just log the exception and return the message
250     // for printing.
251     // @see https://www.drupal.org/node/2564311
252     catch (Exception $e) {
253       watchdog_exception('update', $e);
254
255       $variables = Error::decodeException($e);
256       unset($variables['backtrace']);
257       $ret['#abort'] = [
258         'success' => FALSE,
259         'query' => t('%type: @message in %function (line %line of %file).', $variables),
260       ];
261     }
262   }
263
264   if (isset($context['sandbox']['#finished'])) {
265     $context['finished'] = $context['sandbox']['#finished'];
266     unset($context['sandbox']['#finished']);
267   }
268   if (!isset($context['results'][$module][$name])) {
269     $context['results'][$module][$name] = [];
270   }
271   $context['results'][$module][$name] = array_merge($context['results'][$module][$name], $ret);
272
273   if (!empty($ret['#abort'])) {
274     // Record this function in the list of updates that were aborted.
275     $context['results']['#abort'][] = $function;
276   }
277
278   $context['message'] = t('Post updating @module', ['@module' => $module]);
279 }
280
281 /**
282  * Returns a list of all the pending database updates.
283  *
284  * @return
285  *   An associative array keyed by module name which contains all information
286  *   about database updates that need to be run, and any updates that are not
287  *   going to proceed due to missing requirements. The system module will
288  *   always be listed first.
289  *
290  *   The subarray for each module can contain the following keys:
291  *   - start: The starting update that is to be processed. If this does not
292  *       exist then do not process any updates for this module as there are
293  *       other requirements that need to be resolved.
294  *   - warning: Any warnings about why this module can not be updated.
295  *   - pending: An array of all the pending updates for the module including
296  *       the update number and the description from source code comment for
297  *       each update function. This array is keyed by the update number.
298  */
299 function update_get_update_list() {
300   // Make sure that the system module is first in the list of updates.
301   $ret = ['system' => []];
302
303   $modules = drupal_get_installed_schema_version(NULL, FALSE, TRUE);
304   foreach ($modules as $module => $schema_version) {
305     // Skip uninstalled and incompatible modules.
306     if ($schema_version == SCHEMA_UNINSTALLED || update_check_incompatibility($module)) {
307       continue;
308     }
309     // Display a requirements error if the user somehow has a schema version
310     // from the previous Drupal major version.
311     if ($schema_version < \Drupal::CORE_MINIMUM_SCHEMA_VERSION) {
312       $ret[$module]['warning'] = '<em>' . $module . '</em> module cannot be updated. Its schema version is ' . $schema_version . ', which is from an earlier major release of Drupal. You will need to <a href="https://www.drupal.org/node/2127611">migrate the data for this module</a> instead.';
313       continue;
314     }
315     // Otherwise, get the list of updates defined by this module.
316     $updates = drupal_get_schema_versions($module);
317     if ($updates !== FALSE) {
318       // \Drupal::moduleHandler()->invoke() returns NULL for non-existing hooks,
319       // so if no updates are removed, it will == 0.
320       $last_removed = \Drupal::moduleHandler()->invoke($module, 'update_last_removed');
321       if ($schema_version < $last_removed) {
322         $ret[$module]['warning'] = '<em>' . $module . '</em> module cannot be updated. Its schema version is ' . $schema_version . '. Updates up to and including ' . $last_removed . ' have been removed in this release. In order to update <em>' . $module . '</em> module, you will first <a href="https://www.drupal.org/upgrade">need to upgrade</a> to the last version in which these updates were available.';
323         continue;
324       }
325
326       $updates = array_combine($updates, $updates);
327       foreach (array_keys($updates) as $update) {
328         if ($update == \Drupal::CORE_MINIMUM_SCHEMA_VERSION) {
329           $ret[$module]['warning'] = '<em>' . $module . '</em> module cannot be updated. It contains an update numbered as ' . \Drupal::CORE_MINIMUM_SCHEMA_VERSION . ' which is reserved for the earliest installation of a module in Drupal ' . \Drupal::CORE_COMPATIBILITY . ', before any updates. In order to update <em>' . $module . '</em> module, you will need to install a version of the module with valid updates.';
330           continue 2;
331         }
332         if ($update > $schema_version) {
333           // The description for an update comes from its Doxygen.
334           $func = new ReflectionFunction($module . '_update_' . $update);
335           $description = str_replace(["\n", '*', '/'], '', $func->getDocComment());
336           $ret[$module]['pending'][$update] = "$update - $description";
337           if (!isset($ret[$module]['start'])) {
338             $ret[$module]['start'] = $update;
339           }
340         }
341       }
342       if (!isset($ret[$module]['start']) && isset($ret[$module]['pending'])) {
343         $ret[$module]['start'] = $schema_version;
344       }
345     }
346   }
347
348   if (empty($ret['system'])) {
349     unset($ret['system']);
350   }
351   return $ret;
352 }
353
354 /**
355  * Resolves dependencies in a set of module updates, and orders them correctly.
356  *
357  * This function receives a list of requested module updates and determines an
358  * appropriate order to run them in such that all update dependencies are met.
359  * Any updates whose dependencies cannot be met are included in the returned
360  * array but have the key 'allowed' set to FALSE; the calling function should
361  * take responsibility for ensuring that these updates are ultimately not
362  * performed.
363  *
364  * In addition, the returned array also includes detailed information about the
365  * dependency chain for each update, as provided by the depth-first search
366  * algorithm in Drupal\Component\Graph\Graph::searchAndSort().
367  *
368  * @param $starting_updates
369  *   An array whose keys contain the names of modules with updates to be run
370  *   and whose values contain the number of the first requested update for that
371  *   module.
372  *
373  * @return
374  *   An array whose keys are the names of all update functions within the
375  *   provided modules that would need to be run in order to fulfill the
376  *   request, arranged in the order in which the update functions should be
377  *   run. (This includes the provided starting update for each module and all
378  *   subsequent updates that are available.) The values are themselves arrays
379  *   containing all the keys provided by the
380  *   Drupal\Component\Graph\Graph::searchAndSort() algorithm, which encode
381  *   detailed information about the dependency chain for this update function
382  *   (for example: 'paths', 'reverse_paths', 'weight', and 'component'), as
383  *   well as the following additional keys:
384  *   - 'allowed': A boolean which is TRUE when the update function's
385  *     dependencies are met, and FALSE otherwise. Calling functions should
386  *     inspect this value before running the update.
387  *   - 'missing_dependencies': An array containing the names of any other
388  *     update functions that are required by this one but that are unavailable
389  *     to be run. This array will be empty when 'allowed' is TRUE.
390  *   - 'module': The name of the module that this update function belongs to.
391  *   - 'number': The number of this update function within that module.
392  *
393  * @see \Drupal\Component\Graph\Graph::searchAndSort()
394  */
395 function update_resolve_dependencies($starting_updates) {
396   // Obtain a dependency graph for the requested update functions.
397   $update_functions = update_get_update_function_list($starting_updates);
398   $graph = update_build_dependency_graph($update_functions);
399
400   // Perform the depth-first search and sort on the results.
401   $graph_object = new Graph($graph);
402   $graph = $graph_object->searchAndSort();
403   uasort($graph, ['Drupal\Component\Utility\SortArray', 'sortByWeightElement']);
404
405   foreach ($graph as $function => &$data) {
406     $module = $data['module'];
407     $number = $data['number'];
408     // If the update function is missing and has not yet been performed, mark
409     // it and everything that ultimately depends on it as disallowed.
410     if (update_is_missing($module, $number, $update_functions) && !update_already_performed($module, $number)) {
411       $data['allowed'] = FALSE;
412       foreach (array_keys($data['paths']) as $dependent) {
413         $graph[$dependent]['allowed'] = FALSE;
414         $graph[$dependent]['missing_dependencies'][] = $function;
415       }
416     }
417     elseif (!isset($data['allowed'])) {
418       $data['allowed'] = TRUE;
419       $data['missing_dependencies'] = [];
420     }
421     // Now that we have finished processing this function, remove it from the
422     // graph if it was not part of the original list. This ensures that we
423     // never try to run any updates that were not specifically requested.
424     if (!isset($update_functions[$module][$number])) {
425       unset($graph[$function]);
426     }
427   }
428
429   return $graph;
430 }
431
432 /**
433  * Returns an organized list of update functions for a set of modules.
434  *
435  * @param $starting_updates
436  *   An array whose keys contain the names of modules and whose values contain
437  *   the number of the first requested update for that module.
438  *
439  * @return
440  *   An array containing all the update functions that should be run for each
441  *   module, including the provided starting update and all subsequent updates
442  *   that are available. The keys of the array contain the module names, and
443  *   each value is an ordered array of update functions, keyed by the update
444  *   number.
445  *
446  * @see update_resolve_dependencies()
447  */
448 function update_get_update_function_list($starting_updates) {
449   // Go through each module and find all updates that we need (including the
450   // first update that was requested and any updates that run after it).
451   $update_functions = [];
452   foreach ($starting_updates as $module => $version) {
453     $update_functions[$module] = [];
454     $updates = drupal_get_schema_versions($module);
455     if ($updates !== FALSE) {
456       $max_version = max($updates);
457       if ($version <= $max_version) {
458         foreach ($updates as $update) {
459           if ($update >= $version) {
460             $update_functions[$module][$update] = $module . '_update_' . $update;
461           }
462         }
463       }
464     }
465   }
466   return $update_functions;
467 }
468
469 /**
470  * Constructs a graph which encodes the dependencies between module updates.
471  *
472  * This function returns an associative array which contains a "directed graph"
473  * representation of the dependencies between a provided list of update
474  * functions, as well as any outside update functions that they directly depend
475  * on but that were not in the provided list. The vertices of the graph
476  * represent the update functions themselves, and each edge represents a
477  * requirement that the first update function needs to run before the second.
478  * For example, consider this graph:
479  *
480  * system_update_8001 ---> system_update_8002 ---> system_update_8003
481  *
482  * Visually, this indicates that system_update_8001() must run before
483  * system_update_8002(), which in turn must run before system_update_8003().
484  *
485  * The function takes into account standard dependencies within each module, as
486  * shown above (i.e., the fact that each module's updates must run in numerical
487  * order), but also finds any cross-module dependencies that are defined by
488  * modules which implement hook_update_dependencies(), and builds them into the
489  * graph as well.
490  *
491  * @param $update_functions
492  *   An organized array of update functions, in the format returned by
493  *   update_get_update_function_list().
494  *
495  * @return
496  *   A multidimensional array representing the dependency graph, suitable for
497  *   passing in to Drupal\Component\Graph\Graph::searchAndSort(), but with extra
498  *   information about each update function also included. Each array key
499  *   contains the name of an update function, including all update functions
500  *   from the provided list as well as any outside update functions which they
501  *   directly depend on. Each value is an associative array containing the
502  *   following keys:
503  *   - 'edges': A representation of any other update functions that immediately
504  *     depend on this one. See Drupal\Component\Graph\Graph::searchAndSort() for
505  *     more details on the format.
506  *   - 'module': The name of the module that this update function belongs to.
507  *   - 'number': The number of this update function within that module.
508  *
509  * @see \Drupal\Component\Graph\Graph::searchAndSort()
510  * @see update_resolve_dependencies()
511  */
512 function update_build_dependency_graph($update_functions) {
513   // Initialize an array that will define a directed graph representing the
514   // dependencies between update functions.
515   $graph = [];
516
517   // Go through each update function and build an initial list of dependencies.
518   foreach ($update_functions as $module => $functions) {
519     $previous_function = NULL;
520     foreach ($functions as $number => $function) {
521       // Add an edge to the directed graph representing the fact that each
522       // update function in a given module must run after the update that
523       // numerically precedes it.
524       if ($previous_function) {
525         $graph[$previous_function]['edges'][$function] = TRUE;
526       }
527       $previous_function = $function;
528
529       // Define the module and update number associated with this function.
530       $graph[$function]['module'] = $module;
531       $graph[$function]['number'] = $number;
532     }
533   }
534
535   // Now add any explicit update dependencies declared by modules.
536   $update_dependencies = update_retrieve_dependencies();
537   foreach ($graph as $function => $data) {
538     if (!empty($update_dependencies[$data['module']][$data['number']])) {
539       foreach ($update_dependencies[$data['module']][$data['number']] as $module => $number) {
540         $dependency = $module . '_update_' . $number;
541         $graph[$dependency]['edges'][$function] = TRUE;
542         $graph[$dependency]['module'] = $module;
543         $graph[$dependency]['number'] = $number;
544       }
545     }
546   }
547
548   return $graph;
549 }
550
551 /**
552  * Determines if a module update is missing or unavailable.
553  *
554  * @param $module
555  *   The name of the module.
556  * @param $number
557  *   The number of the update within that module.
558  * @param $update_functions
559  *   An organized array of update functions, in the format returned by
560  *   update_get_update_function_list(). This should represent all module
561  *   updates that are requested to run at the time this function is called.
562  *
563  * @return
564  *   TRUE if the provided module update is not installed or is not in the
565  *   provided list of updates to run; FALSE otherwise.
566  */
567 function update_is_missing($module, $number, $update_functions) {
568   return !isset($update_functions[$module][$number]) || !function_exists($update_functions[$module][$number]);
569 }
570
571 /**
572  * Determines if a module update has already been performed.
573  *
574  * @param $module
575  *   The name of the module.
576  * @param $number
577  *   The number of the update within that module.
578  *
579  * @return
580  *   TRUE if the database schema indicates that the update has already been
581  *   performed; FALSE otherwise.
582  */
583 function update_already_performed($module, $number) {
584   return $number <= drupal_get_installed_schema_version($module);
585 }
586
587 /**
588  * Invokes hook_update_dependencies() in all installed modules.
589  *
590  * This function is similar to \Drupal::moduleHandler()->invokeAll(), with the
591  * main difference that it does not require that a module be enabled to invoke
592  * its hook, only that it be installed. This allows the update system to
593  * properly perform updates even on modules that are currently disabled.
594  *
595  * @return
596  *   An array of return values obtained by merging the results of the
597  *   hook_update_dependencies() implementations in all installed modules.
598  *
599  * @see \Drupal\Core\Extension\ModuleHandlerInterface::invokeAll()
600  * @see hook_update_dependencies()
601  */
602 function update_retrieve_dependencies() {
603   $return = [];
604   // Get a list of installed modules, arranged so that we invoke their hooks in
605   // the same order that \Drupal::moduleHandler()->invokeAll() does.
606   foreach (\Drupal::keyValue('system.schema')->getAll() as $module => $schema) {
607     if ($schema == SCHEMA_UNINSTALLED) {
608       // Nothing to upgrade.
609       continue;
610     }
611     $function = $module . '_update_dependencies';
612     // Ensure install file is loaded.
613     module_load_install($module);
614     if (function_exists($function)) {
615       $updated_dependencies = $function();
616       // Each implementation of hook_update_dependencies() returns a
617       // multidimensional, associative array containing some keys that
618       // represent module names (which are strings) and other keys that
619       // represent update function numbers (which are integers). We cannot use
620       // array_merge_recursive() to properly merge these results, since it
621       // treats strings and integers differently. Therefore, we have to
622       // explicitly loop through the expected array structure here and perform
623       // the merge manually.
624       if (isset($updated_dependencies) && is_array($updated_dependencies)) {
625         foreach ($updated_dependencies as $module_name => $module_data) {
626           foreach ($module_data as $update_version => $update_data) {
627             foreach ($update_data as $module_dependency => $update_dependency) {
628               // If there are redundant dependencies declared for the same
629               // update function (so that it is declared to depend on more than
630               // one update from a particular module), record the dependency on
631               // the highest numbered update here, since that automatically
632               // implies the previous ones. For example, if one module's
633               // implementation of hook_update_dependencies() required this
634               // ordering:
635               //
636               // system_update_8002 ---> user_update_8001
637               //
638               // but another module's implementation of the hook required this
639               // one:
640               //
641               // system_update_8003 ---> user_update_8001
642               //
643               // we record the second one, since system_update_8002() is always
644               // guaranteed to run before system_update_8003() anyway (within
645               // an individual module, updates are always run in numerical
646               // order).
647               if (!isset($return[$module_name][$update_version][$module_dependency]) || $update_dependency > $return[$module_name][$update_version][$module_dependency]) {
648                 $return[$module_name][$update_version][$module_dependency] = $update_dependency;
649               }
650             }
651           }
652         }
653       }
654     }
655   }
656
657   return $return;
658 }
659
660 /**
661  * Replace permissions during update.
662  *
663  * This function can replace one permission to several or even delete an old
664  * one.
665  *
666  * @param array $replace
667  *   An associative array. The keys are the old permissions the values are lists
668  *   of new permissions. If the list is an empty array, the old permission is
669  *   removed.
670  */
671 function update_replace_permissions($replace) {
672   $prefix = 'user.role.';
673   $cut = strlen($prefix);
674   $role_names = \Drupal::service('config.storage')->listAll($prefix);
675   foreach ($role_names as $role_name) {
676     $rid = substr($role_name, $cut);
677     $config = \Drupal::config("user.role.$rid");
678     $permissions = $config->get('permissions') ?: [];
679     foreach ($replace as $old_permission => $new_permissions) {
680       if (($index = array_search($old_permission, $permissions)) !== FALSE) {
681         unset($permissions[$index]);
682         $permissions = array_unique(array_merge($permissions, $new_permissions));
683       }
684     }
685     $config
686       ->set('permissions', $permissions)
687       ->save();
688   }
689 }