Yaffs site version 1.1
[yaffs-website] / vendor / drush / drush / commands / core / drupal / update.inc
1 <?php
2 /**
3  * @file
4  *   Update.php for provisioned sites.
5  *   This file is a derivative of the standard drupal update.php,
6  *   which has been modified to allow being run from the command
7  *   line.
8  */
9
10 use Drush\Log\LogLevel;
11
12 /**
13  * Drupal's update.inc has functions that are in previous update_X.inc files
14  * for example, update_check_incompatibility() which can prove useful when
15  * enabling modules.
16  */
17 require_once DRUSH_DRUPAL_CORE . '/includes/update.inc';
18
19 use Drupal\Core\Utility\Error;
20 use Drupal\Core\Entity\EntityStorageException;
21 /**
22  * Perform one update and store the results which will later be displayed on
23  * the finished page.
24  *
25  * An update function can force the current and all later updates for this
26  * module to abort by returning a $ret array with an element like:
27  * $ret['#abort'] = array('success' => FALSE, 'query' => 'What went wrong');
28  * The schema version will not be updated in this case, and all the
29  * aborted updates will continue to appear on update.php as updates that
30  * have not yet been run.
31  *
32  * @param $module
33  *   The module whose update will be run.
34  * @param $number
35  *   The update number to run.
36  * @param $context
37  *   The batch context array
38  */
39 function drush_update_do_one($module, $number, $dependency_map,  &$context) {
40   $function = $module . '_update_' . $number;
41
42   // If this update was aborted in a previous step, or has a dependency that
43   // was aborted in a previous step, go no further.
44   if (!empty($context['results']['#abort']) && array_intersect($context['results']['#abort'], array_merge($dependency_map, array($function)))) {
45     return;
46   }
47
48   $context['log'] = FALSE;
49
50   \Drupal::moduleHandler()->loadInclude($module, 'install');
51
52   $ret = array();
53   if (function_exists($function)) {
54     try {
55       if ($context['log']) {
56         Database::startLog($function);
57       }
58
59       drush_log("Executing " . $function);
60       $ret['results']['query'] = $function($context['sandbox']);
61       $ret['results']['success'] = TRUE;
62     }
63     // @TODO We may want to do different error handling for different exception
64     // types, but for now we'll just print the message.
65     catch (Exception $e) {
66       $ret['#abort'] = array('success' => FALSE, 'query' => $e->getMessage());
67       drush_set_error('DRUPAL_EXCEPTION', $e->getMessage());
68     }
69
70     if ($context['log']) {
71       $ret['queries'] = Database::getLog($function);
72     }
73   }
74   else {
75     $ret['#abort'] = array('success' => FALSE);
76     drush_set_error('DRUSH_UPDATE_FUNCTION_NOT_FOUND', dt('Update function @function not found', array('@function' => $function)));
77   }
78
79   if (isset($context['sandbox']['#finished'])) {
80     $context['finished'] = $context['sandbox']['#finished'];
81     unset($context['sandbox']['#finished']);
82   }
83
84   if (!isset($context['results'][$module])) {
85     $context['results'][$module] = array();
86   }
87   if (!isset($context['results'][$module][$number])) {
88     $context['results'][$module][$number] = array();
89   }
90   $context['results'][$module][$number] = array_merge($context['results'][$module][$number], $ret);
91
92   if (!empty($ret['#abort'])) {
93     // Record this function in the list of updates that were aborted.
94     $context['results']['#abort'][] = $function;
95   }
96
97   // Record the schema update if it was completed successfully.
98   if ($context['finished'] == 1 && empty($ret['#abort'])) {
99     drupal_set_installed_schema_version($module, $number);
100   }
101
102   $context['message'] = 'Performing ' . $function;
103 }
104
105 /**
106  * Clears caches and rebuilds the container.
107  *
108  * This is called in between regular updates and post updates. Do not use
109  * drush_drupal_cache_clear_all() as the cache clearing and container rebuild
110  * must happen in the same process that the updates are run in.
111  *
112  * Drupal core's update.php uses drupal_flush_all_caches() directly without
113  * explicitly rebuilding the container as the container is rebuilt on the next
114  * HTTP request of the batch.
115  *
116  * @see drush_drupal_cache_clear_all()
117  * @see \Drupal\system\Controller\DbUpdateController::triggerBatch()
118  */
119 function drush_update_cache_rebuild() {
120   drupal_flush_all_caches();
121   \Drupal::service('kernel')->rebuildContainer();
122 }
123
124 function update_main() {
125   // In D8, we expect to be in full bootstrap.
126   drush_bootstrap_to_phase(DRUSH_BOOTSTRAP_DRUPAL_FULL);
127
128   require_once DRUPAL_ROOT . '/core/includes/install.inc';
129   require_once DRUPAL_ROOT . '/core/includes/update.inc';
130   drupal_load_updates();
131   update_fix_compatibility();
132
133   // Pending hook_update_N() implementations.
134   $pending = update_get_update_list();
135
136   // Pending hook_post_update_X() implementations.
137   $post_updates = \Drupal::service('update.post_update_registry')->getPendingUpdateInformation();
138
139   $start = array();
140
141   $change_summary = [];
142   if (drush_get_option('entity-updates', FALSE)) {
143     $change_summary = \Drupal::entityDefinitionUpdateManager()->getChangeSummary();
144   }
145
146   // Print a list of pending updates for this module and get confirmation.
147   if (count($pending) || count($change_summary) || count($post_updates)) {
148     drush_print(dt('The following updates are pending:'));
149     drush_print();
150
151     foreach ($change_summary as $entity_type_id => $changes) {
152       drush_print($entity_type_id . ' entity type : ');
153       foreach ($changes as $change) {
154         drush_print(strip_tags($change), 2);
155       }
156     }
157
158     foreach (array('update', 'post_update') as $update_type) {
159       $updates = $update_type == 'update' ? $pending : $post_updates;
160       foreach ($updates as $module => $updates) {
161         if (isset($updates['start'])) {
162           drush_print($module . ' module : ');
163           if (!empty($updates['pending'])) {
164             $start += [$module => array()];
165
166             $start[$module] = array_merge($start[$module], $updates['pending']);
167             foreach ($updates['pending'] as $update) {
168               drush_print(strip_tags($update), 2);
169             }
170           }
171           drush_print();
172         }
173       }
174     }
175
176     if (!drush_confirm(dt('Do you wish to run all pending updates?'))) {
177       return drush_user_abort();
178     }
179
180     drush_update_batch($start);
181   }
182   else {
183     drush_log(dt("No database updates required"), LogLevel::SUCCESS);
184   }
185
186   return count($pending) + count($change_summary) + count($post_updates);
187 }
188
189 function _update_batch_command($id) {
190   // In D8, we expect to be in full bootstrap.
191   drush_bootstrap_to_phase(DRUSH_BOOTSTRAP_DRUPAL_FULL);
192
193   drush_batch_command($id);
194 }
195
196 /**
197  * Start the database update batch process.
198  */
199 function drush_update_batch() {
200   $start = drush_get_update_list();
201   // Resolve any update dependencies to determine the actual updates that will
202   // be run and the order they will be run in.
203   $updates = update_resolve_dependencies($start);
204
205   // Store the dependencies for each update function in an array which the
206   // batch API can pass in to the batch operation each time it is called. (We
207   // do not store the entire update dependency array here because it is
208   // potentially very large.)
209   $dependency_map = array();
210   foreach ($updates as $function => $update) {
211     $dependency_map[$function] = !empty($update['reverse_paths']) ? array_keys($update['reverse_paths']) : array();
212   }
213
214   $operations = array();
215
216   foreach ($updates as $update) {
217     if ($update['allowed']) {
218       // Set the installed version of each module so updates will start at the
219       // correct place. (The updates are already sorted, so we can simply base
220       // this on the first one we come across in the above foreach loop.)
221       if (isset($start[$update['module']])) {
222         drupal_set_installed_schema_version($update['module'], $update['number'] - 1);
223         unset($start[$update['module']]);
224       }
225       // Add this update function to the batch.
226       $function = $update['module'] . '_update_' . $update['number'];
227       $operations[] = array('drush_update_do_one', array($update['module'], $update['number'], $dependency_map[$function]));
228     }
229   }
230
231   // Apply post update hooks.
232   $post_updates = \Drupal::service('update.post_update_registry')->getPendingUpdateFunctions();
233   if ($post_updates) {
234     $operations[] = ['drush_update_cache_rebuild', []];
235     foreach ($post_updates as $function) {
236       $operations[] = ['update_invoke_post_update', [$function]];
237     }
238   }
239
240   // Lastly, perform entity definition updates, which will update storage
241   // schema if needed. If module update functions need to work with specific
242   // entity schema they should call the entity update service for the specific
243   // update themselves.
244   // @see \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface::applyEntityUpdate()
245   // @see \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface::applyFieldUpdate()
246   if (drush_get_option('entity-updates', FALSE) &&  \Drupal::entityDefinitionUpdateManager()->needsUpdates()) {
247     $operations[] = array('drush_update_entity_definitions', array());
248   }
249
250   $batch['operations'] = $operations;
251   $batch += array(
252     'title' => 'Updating',
253     'init_message' => 'Starting updates',
254     'error_message' => 'An unrecoverable error has occurred. You can find the error message below. It is advised to copy it to the clipboard for reference.',
255     'finished' => 'drush_update_finished',
256     'file' => 'includes/update.inc',
257   );
258   batch_set($batch);
259   \Drupal::service('state')->set('system.maintenance_mode', TRUE);
260   drush_backend_batch_process('updatedb-batch-process');
261   \Drupal::service('state')->set('system.maintenance_mode', FALSE);
262 }
263
264 /**
265  * Apply entity schema updates.
266  */
267 function drush_update_entity_definitions(&$context) {
268   try {
269     \Drupal::entityDefinitionUpdateManager()->applyUpdates();
270   }
271   catch (EntityStorageException $e) {
272     watchdog_exception('update', $e);
273     $variables = Error::decodeException($e);
274     unset($variables['backtrace']);
275     // The exception message is run through
276     // \Drupal\Component\Utility\SafeMarkup::checkPlain() by
277     // \Drupal\Core\Utility\Error::decodeException().
278     $ret['#abort'] = array('success' => FALSE, 'query' => t('%type: !message in %function (line %line of %file).', $variables));
279     $context['results']['core']['update_entity_definitions'] = $ret;
280     $context['results']['#abort'][] = 'update_entity_definitions';
281   }
282 }
283
284 // Copy of protected \Drupal\system\Controller\DbUpdateController::getModuleUpdates.
285 function drush_get_update_list() {
286   $return = array();
287   $updates = update_get_update_list();
288   foreach ($updates as $module => $update) {
289     $return[$module] = $update['start'];
290   }
291
292   return $return;
293 }
294
295 /**
296  * Process and display any returned update output.
297  *
298  * @see \Drupal\system\Controller\DbUpdateController::batchFinished()
299  * @see \Drupal\system\Controller\DbUpdateController::results()
300  */
301 function drush_update_finished($success, $results, $operations) {
302
303   if (!drush_get_option('cache-clear', TRUE)) {
304     drush_log(dt("Skipping cache-clear operation due to --cache-clear=0 option."), LogLevel::WARNING);
305   }
306   else {
307     drupal_flush_all_caches();
308   }
309
310   foreach ($results as $module => $updates) {
311     if ($module != '#abort') {
312       foreach ($updates as $number => $queries) {
313         foreach ($queries as $query) {
314           // If there is no message for this update, don't show anything.
315           if (empty($query['query'])) {
316             continue;
317           }
318
319           if ($query['success']) {
320             drush_log(strip_tags($query['query']));
321           }
322           else {
323             drush_set_error(dt('Failed: ') . strip_tags($query['query']));
324           }
325         }
326       }
327     }
328   }
329 }
330
331 /**
332  * Return a 2 item array with
333  *  - an array where each item is a 3 item associative array describing a pending update.
334  *  - an array listing the first update to run, keyed by module.
335  */
336 function updatedb_status() {
337   $pending = update_get_update_list();
338
339   $return = array();
340   // Ensure system module's updates run first.
341   $start['system'] = array();
342
343   foreach (\Drupal::entityDefinitionUpdateManager()->getChangeSummary() as $entity_type_id => $changes) {
344     foreach ($changes as $change) {
345       $return[] = array(
346         'module' => dt('@type entity type', array('@type' => $entity_type_id)), 'update_id' => '', 'description' => strip_tags($change));
347     }
348   }
349
350   // Print a list of pending updates for this module and get confirmation.
351   foreach ($pending as $module => $updates) {
352     if (isset($updates['start']))  {
353       foreach ($updates['pending'] as $update_id => $description) {
354         // Strip cruft from front.
355         $description = str_replace($update_id . ' -   ', '', $description);
356         $return[] = array('module' => ucfirst($module), 'update_id' => $update_id, 'description' => $description);
357       }
358       if (isset($updates['start'])) {
359         $start[$module] = $updates['start'];
360       }
361     }
362   }
363
364   return array($return, $start);
365 }
366
367 /**
368  * Apply pending entity schema updates.
369  */
370 function entity_updates_main() {
371   $change_summary = \Drupal::entityDefinitionUpdateManager()->getChangeSummary();
372   if (!empty($change_summary)) {
373     drush_print(dt('The following updates are pending:'));
374     drush_print();
375
376     foreach ($change_summary as $entity_type_id => $changes) {
377       drush_print($entity_type_id . ' entity type : ');
378       foreach ($changes as $change) {
379         drush_print(strip_tags($change), 2);
380       }
381     }
382
383     if (!drush_confirm(dt('Do you wish to run all pending updates?'))) {
384       return drush_user_abort();
385     }
386
387     $operations[] = array('drush_update_entity_definitions', array());
388
389
390     $batch['operations'] = $operations;
391     $batch += array(
392       'title' => 'Updating',
393       'init_message' => 'Starting updates',
394       'error_message' => 'An unrecoverable error has occurred. You can find the error message below. It is advised to copy it to the clipboard for reference.',
395       'finished' => 'drush_update_finished',
396       'file' => 'includes/update.inc',
397     );
398     batch_set($batch);
399     \Drupal::service('state')->set('system.maintenance_mode', TRUE);
400     drush_backend_batch_process('updatedb-batch-process');
401     \Drupal::service('state')->set('system.maintenance_mode', FALSE);
402   }
403   else {
404     drush_log(dt("No entity schema updates required"), LogLevel::SUCCESS);
405   }
406 }