update.authorize.inc 13.2 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5 6 7 8 9 10
 * Callbacks and related functions invoked by authorize.php to update projects.
 *
 * We use the Batch API to actually update each individual project on the site.
 * All of the code in this file is run at a low bootstrap level (modules are not
 * loaded), so these functions cannot assume access to the rest of the code of
 * the Update Manager module.
11 12
 */

13
use Drupal\Core\Updater\UpdaterException;
14
use Drupal\Core\Url;
15

16
/**
17 18 19 20
 * Updates existing projects when invoked by authorize.php.
 *
 * Callback for system_authorized_init() in
 * update_manager_update_ready_form_submit().
21 22 23 24 25 26 27
 *
 * @param $filetransfer
 *   The FileTransfer object created by authorize.php for use during this
 *   operation.
 * @param $projects
 *   A nested array of projects to install into the live webroot, keyed by
 *   project name. Each subarray contains the following keys:
28 29
 *   - project: The canonical project short name.
 *   - updater_name: The name of the Drupal\Core\Updater\Updater class to use
30
 *     for this project.
31
 *   - local_url: The locally installed location of new code to update with.
32 33 34 35 36
 *
 * @return \Symfony\Component\HttpFoundation\Response|null
 *   The result of processing the batch that updates the projects. If this is
 *   an instance of \Symfony\Component\HttpFoundation\Response the calling code
 *   should use that response for the current page request.
37 38
 */
function update_authorize_run_update($filetransfer, $projects) {
39
  $operations = [];
40
  foreach ($projects as $project_info) {
41
    $operations[] = [
42
      'update_authorize_batch_copy_project',
43
      [
44 45 46 47
        $project_info['project'],
        $project_info['updater_name'],
        $project_info['local_url'],
        $filetransfer,
48 49
      ],
    ];
50 51
  }

52
  $batch = [
53 54 55 56
    'init_message' => t('Preparing to update your site'),
    'operations' => $operations,
    'finished' => 'update_authorize_update_batch_finished',
    'file' => drupal_get_path('module', 'update') . '/update.authorize.inc',
57
  ];
58
  batch_set($batch);
59

60 61 62 63 64
  // Since authorize.php has its own method for setting the page title, set it
  // manually here rather than passing it in to batch_set() as would normally
  // be done.
  $_SESSION['authorize_page_title'] = t('Installing updates');

65
  // Invoke the batch via authorize.php.
66
  return system_authorized_batch_process();
67 68 69
}

/**
70 71 72 73
 * Installs a new project when invoked by authorize.php.
 *
 * Callback for system_authorized_init() in
 * update_manager_install_form_submit().
74 75 76 77 78
 *
 * @param FileTransfer $filetransfer
 *   The FileTransfer object created by authorize.php for use during this
 *   operation.
 * @param string $project
79 80
 *   The canonical project short name; i.e., the name of the module, theme, or
 *   profile.
81
 * @param string $updater_name
82 83
 *   The name of the Drupal\Core\Updater\Updater class to use for installing
 *   this project.
84 85 86
 * @param string $local_url
 *   The URL to the locally installed temp directory where the project has
 *   already been downloaded and extracted into.
87 88 89 90 91
 *
 * @return \Symfony\Component\HttpFoundation\Response|null
 *   The result of processing the batch that installs the project. If this is
 *   an instance of \Symfony\Component\HttpFoundation\Response the calling code
 *   should use that response for the current page request.
92 93
 */
function update_authorize_run_install($filetransfer, $project, $updater_name, $local_url) {
94
  $operations[] = [
95
    'update_authorize_batch_copy_project',
96
    [
97 98 99 100
      $project,
      $updater_name,
      $local_url,
      $filetransfer,
101 102
    ],
  ];
103 104

  // @todo Instantiate our Updater to set the human-readable title?
105
  $batch = [
106 107 108 109 110
    'init_message' => t('Preparing to install'),
    'operations' => $operations,
    // @todo Use a different finished callback for different messages?
    'finished' => 'update_authorize_install_batch_finished',
    'file' => drupal_get_path('module', 'update') . '/update.authorize.inc',
111
  ];
112 113
  batch_set($batch);

114 115 116
  // Since authorize.php has its own method for setting the page title, set it
  // manually here rather than passing it in to batch_set() as would normally
  // be done.
117
  $_SESSION['authorize_page_title'] = t('Installing %project', ['%project' => $project]);
118

119
  // Invoke the batch via authorize.php.
120
  return system_authorized_batch_process();
121 122 123
}

/**
124 125 126
 * Implements callback_batch_operation().
 *
 * Copies project to its proper place when authorized to do so.
127 128
 *
 * @param string $project
129
 *   The canonical short name of the project being installed.
130
 * @param string $updater_name
131 132
 *   The name of the Drupal\Core\Updater\Updater class to use for installing
 *   this project.
133 134 135 136 137
 * @param string $local_url
 *   The URL to the locally installed temp directory where the project has
 *   already been downloaded and extracted into.
 * @param FileTransfer $filetransfer
 *   The FileTransfer object to use for performing this operation.
138
 * @param array $context
139
 *   Reference to an array used for Batch API storage.
140 141 142 143 144
 */
function update_authorize_batch_copy_project($project, $updater_name, $local_url, $filetransfer, &$context) {

  // Initialize some variables in the Batch API $context array.
  if (!isset($context['results']['log'])) {
145
    $context['results']['log'] = [];
146 147
  }
  if (!isset($context['results']['log'][$project])) {
148
    $context['results']['log'][$project] = [];
149 150 151
  }

  if (!isset($context['results']['tasks'])) {
152
    $context['results']['tasks'] = [];
153 154
  }

155 156 157 158 159 160 161
  // The batch API uses a session, and since all the arguments are serialized
  // and unserialized between requests, although the FileTransfer object itself
  // will be reconstructed, the connection pointer itself will be lost. However,
  // the FileTransfer object will still have the connection variable, even
  // though the connection itself is now gone. So, although it's ugly, we have
  // to unset the connection variable at this point so that the FileTransfer
  // object will re-initiate the actual connection.
162 163 164
  unset($filetransfer->connection);

  if (!empty($context['results']['log'][$project]['#abort'])) {
165
    $context['finished'] = 1;
166 167 168
    return;
  }

169
  $updater = new $updater_name($local_url, \Drupal::getContainer()->get('update.root'));
170 171 172 173 174 175 176 177 178 179

  try {
    if ($updater->isInstalled()) {
      // This is an update.
      $tasks = $updater->update($filetransfer);
    }
    else {
      $tasks = $updater->install($filetransfer);
    }
  }
180 181
  catch (UpdaterException $e) {
    _update_batch_create_message($context['results']['log'][$project], t('Error installing / updating'), FALSE);
182 183 184 185 186
    _update_batch_create_message($context['results']['log'][$project], $e->getMessage(), FALSE);
    $context['results']['log'][$project]['#abort'] = TRUE;
    return;
  }

187
  _update_batch_create_message($context['results']['log'][$project], t('Installed %project_name successfully', ['%project_name' => $project]));
188 189 190
  if (!empty($tasks)) {
    $context['results']['tasks'] += $tasks;
  }
191 192 193 194 195 196 197

  // This particular operation is now complete, even though the batch might
  // have other operations to perform.
  $context['finished'] = 1;
}

/**
198
 * Batch callback: Performs actions when the authorized update batch is done.
199 200 201
 *
 * This processes the results and stashes them into SESSION such that
 * authorize.php will render a report. Also responsible for putting the site
202
 * back online and clearing the update status storage after a successful update.
203 204 205 206 207
 *
 * @param $success
 *   TRUE if the batch operation was successful; FALSE if there were errors.
 * @param $results
 *   An associative array of results from the batch operation.
208 209
 */
function update_authorize_update_batch_finished($success, $results) {
210
  foreach ($results['log'] as $messages) {
211 212 213 214
    if (!empty($messages['#abort'])) {
      $success = FALSE;
    }
  }
215
  $offline = \Drupal::state()->get('system.maintenance_mode');
216
  if ($success) {
217 218
    // Now that the update completed, we need to clear the available update data
    // and recompute our status, so prevent show bogus results.
219 220
    _update_authorize_clear_update_status();

221 222
    // Take the site out of maintenance mode if it was previously that way.
    if ($offline && isset($_SESSION['maintenance_mode']) && $_SESSION['maintenance_mode'] == FALSE) {
223
      \Drupal::state()->set('system.maintenance_mode', FALSE);
224
      $page_message = [
225 226
        'message' => t('Update was completed successfully. Your site has been taken out of maintenance mode.'),
        'type' => 'status',
227
      ];
228 229
    }
    else {
230
      $page_message = [
231 232
        'message' => t('Update was completed successfully.'),
        'type' => 'status',
233
      ];
234 235 236
    }
  }
  elseif (!$offline) {
237
    $page_message = [
238 239
      'message' => t('Update failed! See the log below for more information.'),
      'type' => 'error',
240
    ];
241 242
  }
  else {
243
    $page_message = [
244 245
      'message' => t('Update failed! See the log below for more information. Your site is still in maintenance mode.'),
      'type' => 'error',
246
    ];
247
  }
248 249
  // Since we're doing an update of existing code, always add a task for
  // running update.php.
250
  $url = Url::fromRoute('system.db_update');
251
  $results['tasks'][] = t('Your modules have been downloaded and updated.');
252 253
  $results['tasks'][] = [
    '#type' => 'link',
254
    '#url' => $url,
255 256 257 258 259 260 261 262 263
    '#title' => t('Run database updates'),
    // Since this is being called outsite of the primary front controller,
    // the base_url needs to be set explicitly to ensure that links are
    // relative to the site root.
    // @todo Simplify with https://www.drupal.org/node/2548095
    '#options' => [
      'absolute' => TRUE,
      'base_url' => $GLOBALS['base_url'],
    ],
264
    '#access' => $url->access(\Drupal::currentUser())
265
  ];
266

267 268 269
  // Unset the variable since it is no longer needed.
  unset($_SESSION['maintenance_mode']);

270 271 272 273 274
  // Set all these values into the SESSION so authorize.php can display them.
  $_SESSION['authorize_results']['success'] = $success;
  $_SESSION['authorize_results']['page_message'] = $page_message;
  $_SESSION['authorize_results']['messages'] = $results['log'];
  $_SESSION['authorize_results']['tasks'] = $results['tasks'];
275
  $_SESSION['authorize_page_title'] = t('Update manager');
276 277 278
}

/**
279 280 281
 * Implements callback_batch_finished().
 *
 * Performs actions when the authorized install batch is done.
282 283 284 285
 *
 * This processes the results and stashes them into SESSION such that
 * authorize.php will render a report. Also responsible for putting the site
 * back online after a successful install if necessary.
286 287 288 289 290
 *
 * @param $success
 *   TRUE if the batch operation was a success; FALSE if there were errors.
 * @param $results
 *   An associative array of results from the batch operation.
291 292
 */
function update_authorize_install_batch_finished($success, $results) {
293
  foreach ($results['log'] as $messages) {
294 295 296 297
    if (!empty($messages['#abort'])) {
      $success = FALSE;
    }
  }
298
  $offline = \Drupal::state()->get('system.maintenance_mode');
299 300 301
  if ($success) {
    // Take the site out of maintenance mode if it was previously that way.
    if ($offline && isset($_SESSION['maintenance_mode']) && $_SESSION['maintenance_mode'] == FALSE) {
302
      \Drupal::state()->set('system.maintenance_mode', FALSE);
303
      $page_message = [
304 305
        'message' => t('Installation was completed successfully. Your site has been taken out of maintenance mode.'),
        'type' => 'status',
306
      ];
307 308
    }
    else {
309
      $page_message = [
310 311
        'message' => t('Installation was completed successfully.'),
        'type' => 'status',
312
      ];
313
    }
314 315
  }
  elseif (!$success && !$offline) {
316
    $page_message = [
317 318
      'message' => t('Installation failed! See the log below for more information.'),
      'type' => 'error',
319
    ];
320 321
  }
  else {
322
    $page_message = [
323 324
      'message' => t('Installation failed! See the log below for more information. Your site is still in maintenance mode.'),
      'type' => 'error',
325
    ];
326 327
  }

328 329 330
  // Unset the variable since it is no longer needed.
  unset($_SESSION['maintenance_mode']);

331 332 333 334 335
  // Set all these values into the SESSION so authorize.php can display them.
  $_SESSION['authorize_results']['success'] = $success;
  $_SESSION['authorize_results']['page_message'] = $page_message;
  $_SESSION['authorize_results']['messages'] = $results['log'];
  $_SESSION['authorize_results']['tasks'] = $results['tasks'];
336
  $_SESSION['authorize_page_title'] = t('Update manager');
337 338 339
}

/**
340
 * Creates a structure of log messages.
341 342
 *
 * @param array $project_results
343
 *   An associative array of results from the batch operation.
344
 * @param string $message
345
 *   A string containing a log message.
346
 * @param bool $success
347 348
 *   (optional) TRUE if the operation the message is about was a success, FALSE
 *   if there were errors. Defaults to TRUE.
349 350
 */
function _update_batch_create_message(&$project_results, $message, $success = TRUE) {
351
  $project_results[] = ['message' => $message, 'success' => $success];
352 353 354
}

/**
355
 * Clears available update status data.
356
 *
357
 * Since this function is run at such a low bootstrap level, the Update Manager
358 359
 * module is not loaded. So, we can't just call update_storage_clear(). However,
 * the key-value backend is available, so we just call that.
360
 *
361 362
 * Note that we do not want to delete  items related to currently pending fetch
 * attempts.
363 364
 *
 * @see update_authorize_update_batch_finished()
365
 * @see update_storage_clear()
366 367
 */
function _update_authorize_clear_update_status() {
368 369
  \Drupal::keyValueExpirable('update')->deleteAll();
  \Drupal::keyValueExpirable('update_available_release')->deleteAll();
370
}