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

/**
 * @file
5 6
 * Administrative screens and processing functions of the Update Manager module.
 *
7 8 9
 * This allows site administrators with the 'administer software updates'
 * permission to either upgrade existing projects, or download and install new
 * ones, so long as the killswitch setting ('allow_authorize_operations') is
10
 * not FALSE.
11 12 13 14
 *
 * To install new code, the administrator is prompted for either the URL of an
 * archive file, or to directly upload the archive file. The archive is loaded
 * into a temporary location, extracted, and verified. If everything is
15 16 17 18
 * successful, the user is redirected to authorize.php to type in file transfer
 * credentials and authorize the installation to proceed with elevated
 * privileges, such that the extracted files can be copied out of the temporary
 * location and into the live web root.
19 20
 *
 * Updating existing code is a more elaborate process. The first step is a
21 22 23 24 25 26 27 28
 * selection form where the user is presented with a table of installed projects
 * that are missing newer releases. The user selects which projects they wish to
 * update, and presses the "Download updates" button to continue. This sets up a
 * batch to fetch all the selected releases, and redirects to
 * admin/update/download to display the batch progress bar as it runs. Each
 * batch operation is responsible for downloading a single file, extracting the
 * archive, and verifying the contents. If there are any errors, the user is
 * redirected back to the first page with the error messages. If all downloads
29
 * were extracted and verified, the user is instead redirected to
30 31 32 33 34 35 36
 * admin/update/ready, a landing page which reminds them to backup their
 * database and asks if they want to put the site offline during the update.
 * Once the user presses the "Install updates" button, they are redirected to
 * authorize.php to supply their web root file access credentials. The
 * authorized operation (which lives in update.authorize.inc) sets up a batch to
 * copy each extracted update from the temporary location into the live web
 * root.
37
 */
38

39
use Drupal\Core\Url;
40
use Drupal\Core\File\Exception\FileException;
41
use Symfony\Component\HttpFoundation\RedirectResponse;
42

43
/**
44 45 46 47 48 49
 * Batch callback: Performs actions when the download batch is completed.
 *
 * @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.
50 51
 */
function update_manager_download_batch_finished($success, $results) {
52
  if (!empty($results['errors'])) {
53
    $item_list = [
54 55 56
      '#theme' => 'item_list',
      '#title' => t('Downloading updates failed:'),
      '#items' => $results['errors'],
57
    ];
58
    \Drupal::messenger()->addError(\Drupal::service('renderer')->render($item_list));
59 60
  }
  elseif ($success) {
61
    \Drupal::messenger()->addStatus(t('Updates downloaded successfully.'));
62
    $_SESSION['update_manager_update_projects'] = $results['projects'];
63
    return new RedirectResponse(Url::fromRoute('update.confirmation_page', [], ['absolute' => TRUE])->toString());
64 65
  }
  else {
66 67
    // Ideally we're catching all Exceptions, so they should never see this,
    // but just in case, we have to tell them something.
68
    \Drupal::messenger()->addError(t('Fatal error trying to download.'));
69 70 71
  }
}

72 73 74 75 76 77
/**
 * Checks for file transfer backends and prepares a form fragment about them.
 *
 * @param array $form
 *   Reference to the form array we're building.
 * @param string $operation
78 79
 *   The update manager operation we're in the middle of. Can be either 'update'
 *   or 'install'. Use to provide operation-specific interface text.
80 81
 *
 * @return
82
 *   TRUE if the update manager should continue to the next step in the
83 84 85 86 87 88 89 90 91 92 93 94 95
 *   workflow, or FALSE if we've hit a fatal configuration and must halt the
 *   workflow.
 */
function _update_manager_check_backends(&$form, $operation) {
  // If file transfers will be performed locally, we do not need to display any
  // warnings or notices to the user and should automatically continue the
  // workflow, since we won't be using a FileTransfer backend that requires
  // user input or a specific server configuration.
  if (update_manager_local_transfers_allowed()) {
    return TRUE;
  }

  // Otherwise, show the available backends.
96
  $form['available_backends'] = [
97 98
    '#prefix' => '<p>',
    '#suffix' => '</p>',
99
  ];
100 101 102 103

  $available_backends = drupal_get_filetransfer_info();
  if (empty($available_backends)) {
    if ($operation == 'update') {
104
      $form['available_backends']['#markup'] = t('Your server does not support updating modules and themes from this interface. Instead, update modules and themes by uploading the new versions directly to the server, as documented in <a href=":doc_url">Extending Drupal 8</a>.', [':doc_url' => 'https://www.drupal.org/docs/8/extending-drupal-8/overview']);
105 106
    }
    else {
107
      $form['available_backends']['#markup'] = t('Your server does not support installing modules and themes from this interface. Instead, install modules and themes by uploading them directly to the server, as documented in <a href=":doc_url">Extending Drupal 8</a>.', [':doc_url' => 'https://www.drupal.org/docs/8/extending-drupal-8/overview']);
108 109 110 111
    }
    return FALSE;
  }

112
  $backend_names = [];
113 114 115 116
  foreach ($available_backends as $backend) {
    $backend_names[] = $backend['title'];
  }
  if ($operation == 'update') {
117
    $form['available_backends']['#markup'] = \Drupal::translation()->formatPlural(
118
      count($available_backends),
119 120
      'Updating modules and themes requires <strong>@backends access</strong> to your server. See <a href=":doc_url">Extending Drupal 8</a> for other update methods.',
      'Updating modules and themes requires access to your server via one of the following methods: <strong>@backends</strong>. See <a href=":doc_url">Extending Drupal 8</a> for other update methods.',
121
      [
122
        '@backends' => implode(', ', $backend_names),
123
        ':doc_url' => 'https://www.drupal.org/docs/8/extending-drupal-8/overview',
124
      ]);
125 126
  }
  else {
127
    $form['available_backends']['#markup'] = \Drupal::translation()->formatPlural(
128
      count($available_backends),
129 130
      'Installing modules and themes requires <strong>@backends access</strong> to your server. See <a href=":doc_url">Extending Drupal 8</a> for other installation methods.',
      'Installing modules and themes requires access to your server via one of the following methods: <strong>@backends</strong>. See <a href=":doc_url">Extending Drupal 8</a> for other installation methods.',
131
      [
132
        '@backends' => implode(', ', $backend_names),
133
        ':doc_url' => 'https://www.drupal.org/docs/8/extending-drupal-8/overview',
134
      ]);
135 136 137 138
  }
  return TRUE;
}

139
/**
140
 * Unpacks a downloaded archive file.
141 142 143 144
 *
 * @param string $file
 *   The filename of the archive you wish to extract.
 * @param string $directory
145
 *   The directory you wish to extract the archive into.
146
 *
147
 * @return \Drupal\Core\Archiver\ArchiverInterface
148
 *   The Archiver object used to extract the archive.
149 150
 *
 * @throws Exception
151 152
 */
function update_manager_archive_extract($file, $directory) {
153 154 155 156
  /** @var \Drupal\Core\Archiver\ArchiverInterface $archiver */
  $archiver = \Drupal::service('plugin.manager.archiver')->getInstance([
    'filepath' => $file,
  ]);
157
  if (!$archiver) {
158
    throw new Exception(t('Cannot extract %file, not a valid archive.', ['%file' => $file]));
159
  }
160 161 162 163 164

  // Remove the directory if it exists, otherwise it might contain a mixture of
  // old files mixed with the new files (e.g. in cases where files were removed
  // from a later release).
  $files = $archiver->listContents();
165 166 167 168 169 170

  // Unfortunately, we can only use the directory name to determine the project
  // name. Some archivers list the first file as the directory (i.e., MODULE/)
  // and others list an actual file (i.e., MODULE/README.TXT).
  $project = strtok($files[0], '/\\');

171 172
  $extract_location = $directory . '/' . $project;
  if (file_exists($extract_location)) {
173 174 175 176 177 178
    try {
      \Drupal::service('file_system')->deleteRecursive($extract_location);
    }
    catch (FileException $e) {
      // Ignore failed deletes.
    }
179 180
  }

181 182
  $archiver->extract($directory);
  return $archiver;
183 184 185
}

/**
186
 * Verifies an archive after it has been downloaded and extracted.
187 188 189 190 191 192 193 194 195 196
 *
 * This function is responsible for invoking hook_verify_update_archive().
 *
 * @param string $project
 *   The short name of the project to download.
 * @param string $archive_file
 *   The filename of the unextracted archive.
 * @param string $directory
 *   The directory that the archive was extracted into.
 *
197
 * @return array
198 199
 *   An array of error messages to display if the archive was invalid. If there
 *   are no errors, it will be an empty array.
200 201
 */
function update_manager_archive_verify($project, $archive_file, $directory) {
202
  return \Drupal::moduleHandler()->invokeAll('verify_update_archive', [$project, $archive_file, $directory]);
203 204 205
}

/**
206
 * Copies a file from the specified URL to the temporary directory for updates.
207
 *
208
 * Returns the local path if the file has already been downloaded.
209 210 211 212 213 214 215 216 217
 *
 * @param $url
 *   The URL of the file on the server.
 *
 * @return string
 *   Path to local file.
 */
function update_manager_file_get($url) {
  $parsed_url = parse_url($url);
218
  $remote_schemes = ['http', 'https', 'ftp', 'ftps', 'smb', 'nfs'];
219
  if (!isset($parsed_url['scheme']) || !in_array($parsed_url['scheme'], $remote_schemes)) {
220
    // This is a local file, just return the path.
221
    return \Drupal::service('file_system')->realpath($url);
222 223 224
  }

  // Check the cache and download the file if needed.
225
  $cache_directory = _update_manager_cache_directory();
226
  $local = $cache_directory . '/' . \Drupal::service('file_system')->basename($parsed_url['path']);
227

228 229
  if (!file_exists($local) || update_delete_file_if_stale($local)) {
    return system_retrieve_file($url, $local, FALSE, FILE_EXISTS_REPLACE);
230 231 232 233 234 235 236
  }
  else {
    return $local;
  }
}

/**
237 238 239
 * Implements callback_batch_operation().
 *
 * Downloads, unpacks, and verifies a project.
240
 *
241 242 243
 * This function assumes that the provided URL points to a file archive of some
 * sort. The URL can have any scheme that we have a file stream wrapper to
 * support. The file is downloaded to a local cache.
244 245 246 247 248
 *
 * @param string $project
 *   The short name of the project to download.
 * @param string $url
 *   The URL to download a specific project release archive file.
249
 * @param array $context
250
 *   Reference to an array used for Batch API storage.
251 252 253 254 255 256 257
 *
 * @see update_manager_download_page()
 */
function update_manager_batch_project_get($project, $url, &$context) {
  // This is here to show the user that we are in the process of downloading.
  if (!isset($context['sandbox']['started'])) {
    $context['sandbox']['started'] = TRUE;
258
    $context['message'] = t('Downloading %project', ['%project' => $project]);
259 260 261 262 263 264
    $context['finished'] = 0;
    return;
  }

  // Actually try to download the file.
  if (!($local_cache = update_manager_file_get($url))) {
265
    $context['results']['errors'][$project] = t('Failed to download %project from %url', ['%project' => $project, '%url' => $url]);
266 267 268 269 270 271 272 273 274
    return;
  }

  // Extract it.
  $extract_directory = _update_manager_extract_directory();
  try {
    update_manager_archive_extract($local_cache, $extract_directory);
  }
  catch (Exception $e) {
275
    $context['results']['errors'][$project] = $e->getMessage();
276 277 278 279
    return;
  }

  // Verify it.
280 281 282 283 284 285 286
  $archive_errors = update_manager_archive_verify($project, $local_cache, $extract_directory);
  if (!empty($archive_errors)) {
    // We just need to make sure our array keys don't collide, so use the
    // numeric keys from the $archive_errors array.
    foreach ($archive_errors as $key => $error) {
      $context['results']['errors']["$project-$key"] = $error;
    }
287 288 289 290
    return;
  }

  // Yay, success.
291
  $context['results']['projects'][$project] = $url;
292 293 294
  $context['finished'] = 1;
}

295 296 297 298
/**
 * Determines if file transfers will be performed locally.
 *
 * If the server is configured such that webserver-created files have the same
299 300
 * owner as the configuration directory (e.g., sites/default) where new code
 * will eventually be installed, the update manager can transfer files entirely
301 302 303 304 305 306 307 308 309 310 311 312 313 314
 * locally, without changing their ownership (in other words, without prompting
 * the user for FTP, SSH or other credentials).
 *
 * This server configuration is an inherent security weakness because it allows
 * a malicious webserver process to append arbitrary PHP code and then execute
 * it. However, it is supported here because it is a common configuration on
 * shared hosting, and there is nothing Drupal can do to prevent it.
 *
 * @return
 *   TRUE if local file transfers are allowed on this server, or FALSE if not.
 *
 * @see install_check_requirements()
 */
function update_manager_local_transfers_allowed() {
315
  $file_system = \Drupal::service('file_system');
316 317 318
  // Compare the owner of a webserver-created temporary file to the owner of
  // the configuration directory to determine if local transfers will be
  // allowed.
319
  $temporary_file = \Drupal::service('file_system')->tempnam('temporary://', 'update_');
320 321
  $site_path = \Drupal::service('site.path');
  $local_transfers_allowed = fileowner($temporary_file) === fileowner($site_path);
322 323 324

  // Clean up. If this fails, we can ignore it (since this is just a temporary
  // file anyway).
325
  @$file_system->unlink($temporary_file);
326 327 328

  return $local_transfers_allowed;
}