update.manager.inc 34.6 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 29 30 31 32 33 34 35 36
 * 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
 * were extacted and verified, the user is instead redirected to
 * 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\Component\Utility\String;
40
use Drupal\Core\Updater\Updater;
41
use Drupal\Core\FileTransfer\Local;
42
use Symfony\Component\HttpFoundation\RedirectResponse;
43

44
/**
45
 * @defgroup update_manager_update Update Manager module: update
46
 * @{
47
 * Update Manager module functionality for updating existing code.
48 49
 *
 * Provides a user interface to update existing code.
50 51 52
 */

/**
53
 * Form constructor for the update form of the Update Manager module.
54 55 56 57 58
 *
 * This presents a table with all projects that have available updates with
 * checkboxes to select which ones to upgrade.
 *
 * @param $context
59 60 61 62 63 64
 *   String representing the context from which we're trying to update.
 *   Allowed values are 'module', 'theme', and 'report'.
 *
 * @see update_manager_update_form_validate()
 * @see update_manager_update_form_submit()
 * @see update_menu()
65
 *
66 67 68
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0. Use
 *   \Drupal\update\Form\UpdateForm::reportUpdate() or
 *   \Drupal\update\Form\UpdateForm::moduleUpdate().
69 70
 */
function update_manager_update_form($form, $form_state = array(), $context) {
71 72 73 74
  if (!_update_manager_check_backends($form, 'update')) {
    return $form;
  }

75 76 77 78 79
  $form['#theme'] = 'update_manager_update_form';

  $available = update_get_available(TRUE);
  if (empty($available)) {
    $form['message'] = array(
80
      '#markup' => t('There was a problem getting update information. Try again later.'),
81 82 83 84
    );
    return $form;
  }

85
  $form['#attached']['library'][] = 'update/drupal.update.admin';
86 87

  // This will be a nested array. The first key is the kind of project, which
88 89 90 91
  // can be either 'enabled', 'disabled', 'manual' (projects which require
  // manual updates, such as core). Then, each subarray is an array of
  // projects of that type, indexed by project short name, and containing an
  // array of data for cells in that project's row in the appropriate table.
92 93 94 95 96 97 98 99 100
  $projects = array();

  // This stores the actual download link we're going to update from for each
  // project in the form, regardless of if it's enabled or disabled.
  $form['project_downloads'] = array('#tree' => TRUE);

  module_load_include('inc', 'update', 'update.compare');
  $project_data = update_calculate_project_data($available);
  foreach ($project_data as $name => $project) {
101
    // Filter out projects which are up to date already.
102 103 104 105 106 107 108 109 110
    if ($project['status'] == UPDATE_CURRENT) {
      continue;
    }
    // The project name to display can vary based on the info we have.
    if (!empty($project['title'])) {
      if (!empty($project['link'])) {
        $project_name = l($project['title'], $project['link']);
      }
      else {
111
        $project_name = String::checkPlain($project['title']);
112 113 114
      }
    }
    elseif (!empty($project['info']['name'])) {
115
      $project_name = String::checkPlain($project['info']['name']);
116 117
    }
    else {
118
      $project_name = String::checkPlain($name);
119 120 121 122 123 124 125 126 127 128 129 130
    }
    if ($project['project_type'] == 'theme' || $project['project_type'] == 'theme-disabled') {
      $project_name .= ' ' . t('(Theme)');
    }

    if (empty($project['recommended'])) {
      // If we don't know what to recommend they upgrade to, we should skip
      // the project entirely.
      continue;
    }

    $recommended_release = $project['releases'][$project['recommended']];
131
    $recommended_version = $recommended_release['version'] . ' ' . l(t('(Release notes)'), $recommended_release['release_link'], array('attributes' => array('title' => t('Release notes for @project_title', array('@project_title' => $project['title'])))));
132 133 134 135 136 137 138 139 140 141 142 143 144 145
    if ($recommended_release['version_major'] != $project['existing_major']) {
      $recommended_version .= '<div title="Major upgrade warning" class="update-major-version-warning">' . t('This update is a major version update which means that it may not be backwards compatible with your currently running version.  It is recommended that you read the release notes and proceed at your own risk.') . '</div>';
    }

    // Create an entry for this project.
    $entry = array(
      'title' => $project_name,
      'installed_version' => $project['existing_version'],
      'recommended_version' => $recommended_version,
    );

    switch ($project['status']) {
      case UPDATE_NOT_SECURE:
      case UPDATE_REVOKED:
146
        $entry['title'] .= ' ' . t('(Security update)');
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
        $entry['#weight'] = -2;
        $type = 'security';
        break;

      case UPDATE_NOT_SUPPORTED:
        $type = 'unsupported';
        $entry['title'] .= ' ' . t('(Unsupported)');
        $entry['#weight'] = -1;
        break;

      case UPDATE_UNKNOWN:
      case UPDATE_NOT_FETCHED:
      case UPDATE_NOT_CHECKED:
      case UPDATE_NOT_CURRENT:
        $type = 'recommended';
        break;

      default:
        // Jump out of the switch and onto the next project in foreach.
        continue 2;
    }

169 170 171 172 173
    // Use the project title for the tableselect checkboxes.
    $entry['title'] = array('data' => array(
      '#title' => $entry['title'],
      '#markup' => $entry['title'],
    ));
174 175
    $entry['#attributes'] = array('class' => array('update-' . $type));

176 177
    // Drupal core needs to be upgraded manually.
    $needs_manual = $project['project_type'] == 'core';
178 179

    if ($needs_manual) {
180
      // There are no checkboxes in the 'Manual updates' table so it will be
181
      // rendered by _theme('table'), not _theme('tableselect'). Since the data
182
      // formats are incompatible, we convert now to the format expected by
183
      // _theme('table').
184
      unset($entry['#weight']);
185 186 187 188 189
      $attributes = $entry['#attributes'];
      unset($entry['#attributes']);
      $entry = array(
        'data' => $entry,
      ) + $attributes;
190 191 192 193 194 195 196 197 198 199 200 201
    }
    else {
      $form['project_downloads'][$name] = array(
        '#type' => 'value',
        '#value' => $recommended_release['download_link'],
      );
    }

    // Based on what kind of project this is, save the entry into the
    // appropriate subarray.
    switch ($project['project_type']) {
      case 'core':
202 203
        // Core needs manual updates at this time.
        $projects['manual'][$name] = $entry;
204
        break;
205

206 207
      case 'module':
      case 'theme':
208
        $projects['enabled'][$name] = $entry;
209 210 211 212
        break;

      case 'module-disabled':
      case 'theme-disabled':
213
        $projects['disabled'][$name] = $entry;
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
        break;
    }
  }

  if (empty($projects)) {
    $form['message'] = array(
      '#markup' => t('All of your projects are up to date.'),
    );
    return $form;
  }

  $headers = array(
    'title' => array(
      'data' => t('Name'),
      'class' => array('update-project-name'),
    ),
    'installed_version' => t('Installed version'),
    'recommended_version' => t('Recommended version'),
  );

  if (!empty($projects['enabled'])) {
    $form['projects'] = array(
      '#type' => 'tableselect',
      '#header' => $headers,
      '#options' => $projects['enabled'],
    );
240 241
    if (!empty($projects['disabled'])) {
      $form['projects']['#prefix'] = '<h2>' . t('Enabled') . '</h2>';
242 243 244 245 246 247 248 249 250
    }
  }

  if (!empty($projects['disabled'])) {
    $form['disabled_projects'] = array(
      '#type' => 'tableselect',
      '#header' => $headers,
      '#options' => $projects['disabled'],
      '#weight' => 1,
251
      '#prefix' => '<h2>' . t('Disabled') . '</h2>',
252 253 254 255 256 257
    );
  }

  // If either table has been printed yet, we need a submit button and to
  // validate the checkboxes.
  if (!empty($projects['enabled']) || !empty($projects['disabled'])) {
258 259
    $form['actions'] = array('#type' => 'actions');
    $form['actions']['submit'] = array(
260 261 262 263 264 265
      '#type' => 'submit',
      '#value' => t('Download these updates'),
    );
    $form['#validate'][] = 'update_manager_update_form_validate';
  }

266 267 268
  if (!empty($projects['manual'])) {
    $prefix = '<h2>' . t('Manual updates required') . '</h2>';
    $prefix .= '<p>' . t('Updates of Drupal core are not supported at this time.') . '</p>';
269
    $form['manual_updates'] = array(
270
      '#type' => 'table',
271 272
      '#header' => $headers,
      '#rows' => $projects['manual'],
273
      '#prefix' => $prefix,
274
      '#weight' => 120,
275 276 277 278 279 280 281
    );
  }

  return $form;
}

/**
282
 * Returns HTML for the first page in the process of updating projects.
283 284
 *
 * @param $variables
285 286
 *   An associative array containing:
 *   - form: A render element representing the form.
287 288 289 290 291
 *
 * @ingroup themeable
 */
function theme_update_manager_update_form($variables) {
  $form = $variables['form'];
292
  $last = \Drupal::state()->get('update.last_check') ?: 0;
293 294 295 296 297
  $update_last_check = array(
    '#theme' => 'update_last_check',
    '#last' => $last,
  );
  $output = drupal_render($update_last_check);
298 299 300 301 302
  $output .= drupal_render_children($form);
  return $output;
}

/**
303 304 305 306 307
 * Form validation handler for update_manager_update_form().
 *
 * Ensures that at least one project is selected.
 *
 * @see update_manager_update_form_submit()
308 309 310 311 312 313 314 315 316
 */
function update_manager_update_form_validate($form, &$form_state) {
  if (!empty($form_state['values']['projects'])) {
    $enabled = array_filter($form_state['values']['projects']);
  }
  if (!empty($form_state['values']['disabled_projects'])) {
    $disabled = array_filter($form_state['values']['disabled_projects']);
  }
  if (empty($enabled) && empty($disabled)) {
317
    form_set_error('projects', $form_state, t('You must select at least one project to update.'));
318 319 320 321
  }
}

/**
322
 * Form submission handler for update_manager_update_form().
323
 *
324
 * Sets up a batch that downloads, extracts, and verifies the selected releases.
325
 *
326
 * @see update_manager_update_form_validate()
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
 */
function update_manager_update_form_submit($form, &$form_state) {
  $projects = array();
  foreach (array('projects', 'disabled_projects') as $type) {
    if (!empty($form_state['values'][$type])) {
      $projects = array_merge($projects, array_keys(array_filter($form_state['values'][$type])));
    }
  }
  $operations = array();
  foreach ($projects as $project) {
    $operations[] = array(
      'update_manager_batch_project_get',
      array(
        $project,
        $form_state['values']['project_downloads'][$project],
      ),
    );
  }
  $batch = array(
    'title' => t('Downloading updates'),
    'init_message' => t('Preparing to download selected updates'),
    'operations' => $operations,
    'finished' => 'update_manager_download_batch_finished',
    'file' => drupal_get_path('module', 'update') . '/update.manager.inc',
  );
  batch_set($batch);
}

/**
356 357 358 359 360 361
 * 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.
362 363
 */
function update_manager_download_batch_finished($success, $results) {
364
  if (!empty($results['errors'])) {
365 366 367 368
    $item_list = array(
      '#theme' => 'item_list',
      '#title' => t('Downloading updates failed:'),
      '#items' => $results['errors'],
369
    );
370
    drupal_set_message(drupal_render($item_list), 'error');
371 372
  }
  elseif ($success) {
373
    drupal_set_message(t('Updates downloaded successfully.'));
374
    $_SESSION['update_manager_update_projects'] = $results['projects'];
375
    return new RedirectResponse(url('admin/update/ready', array('absolute' => TRUE)));
376 377
  }
  else {
378 379 380
    // Ideally we're catching all Exceptions, so they should never see this,
    // but just in case, we have to tell them something.
    drupal_set_message(t('Fatal error trying to download.'), 'error');
381 382 383
  }
}

384
/**
385 386
 * Form constructor for the update ready form.
 *
387
 * Build the form when the site is ready to update (after downloading).
388 389
 *
 * This form is an intermediary step in the automated update workflow. It is
390 391 392 393 394 395 396 397 398
 * presented to the site administrator after all the required updates have been
 * downloaded and verified. The point of this page is to encourage the user to
 * backup their site, give them the opportunity to put the site offline, and
 * then ask them to confirm that the update should continue. After this step,
 * the user is redirected to authorize.php to enter their file transfer
 * credentials and attempt to complete the update.
 *
 * @see update_manager_update_ready_form_submit()
 * @see update_menu()
399
 */
400
function update_manager_update_ready_form($form, &$form_state) {
401 402 403 404
  if (!_update_manager_check_backends($form, 'update')) {
    return $form;
  }

405 406 407 408
  $form['backup'] = array(
    '#prefix' => '<strong>',
    '#markup' => t('Back up your database and site before you continue. <a href="@backup_url">Learn how</a>.', array('@backup_url' => url('http://drupal.org/node/22281'))),
    '#suffix' => '</strong>',
409 410
  );

411
  $form['maintenance_mode'] = array(
412
    '#title' => t('Perform updates with site in maintenance mode (strongly recommended)'),
413 414 415 416
    '#type' => 'checkbox',
    '#default_value' => TRUE,
  );

417 418
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
419
    '#type' => 'submit',
420
    '#value' => t('Continue'),
421 422 423 424 425
  );

  return $form;
}

426
/**
427
 * Form submission handler for update_manager_update_ready_form().
428 429
 *
 * If the site administrator requested that the site is put offline during the
430 431 432 433
 * update, do so now. Otherwise, pull information about all the required updates
 * out of the SESSION, figure out what Drupal\Core\Updater\Updater class is
 * needed for each one, generate an array of update operations to perform, and
 * hand it all off to system_authorized_init(), then redirect to authorize.php.
434
 *
435 436 437
 * @see update_authorize_run_update()
 * @see system_authorized_init()
 * @see system_authorized_get_url()
438
 */
439
function update_manager_update_ready_form_submit($form, &$form_state) {
440
  // Store maintenance_mode setting so we can restore it when done.
441
  $_SESSION['maintenance_mode'] = \Drupal::state()->get('system.maintenance_mode');
442
  if ($form_state['values']['maintenance_mode'] == TRUE) {
443
    \Drupal::state()->set('system.maintenance_mode', TRUE);
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
  }

  if (!empty($_SESSION['update_manager_update_projects'])) {
    // Make sure the Updater registry is loaded.
    drupal_get_updaters();

    $updates = array();
    $directory = _update_manager_extract_directory();

    $projects = $_SESSION['update_manager_update_projects'];
    unset($_SESSION['update_manager_update_projects']);

    foreach ($projects as $project => $url) {
      $project_location = $directory . '/' . $project;
      $updater = Updater::factory($project_location);
459
      $project_real_location = drupal_realpath($project_location);
460 461 462
      $updates[] = array(
        'project' => $project,
        'updater_name' => get_class($updater),
463
        'local_url' => $project_real_location,
464 465 466
      );
    }

467 468 469
    // If the owner of the last directory we extracted is the same as the
    // owner of our configuration directory (e.g. sites/default) where we're
    // trying to install the code, there's no need to prompt for FTP/SSH
470 471
    // credentials. Instead, we instantiate a Drupal\Core\FileTransfer\Local and
    // invoke update_authorize_run_update() directly.
472 473
    if (fileowner($project_real_location) == fileowner(conf_path())) {
      module_load_include('inc', 'update', 'update.authorize');
474
      $filetransfer = new Local(DRUPAL_ROOT);
475 476 477 478 479 480
      update_authorize_run_update($filetransfer, $updates);
    }
    // Otherwise, go through the regular workflow to prompt for FTP/SSH
    // credentials and invoke update_authorize_run_update() indirectly with
    // whatever FileTransfer object authorize.php creates for us.
    else {
481
      system_authorized_init('update_authorize_run_update', drupal_get_path('module', 'update') . '/update.authorize.inc', array($updates), t('Update manager'));
482
      $form_state['redirect'] = system_authorized_get_url();
483
    }
484 485 486 487 488 489 490 491
  }
}

/**
 * @} End of "defgroup update_manager_update".
 */

/**
492
 * @defgroup update_manager_install Update Manager module: install
493
 * @{
494
 * Update Manager module functionality for installing new code.
495 496
 *
 * Provides a user interface to install new code.
497 498
 */

499
/**
500
 * Form constructor for the install form of the Update Manager module.
501 502 503 504 505
 *
 * This presents a place to enter a URL or upload an archive file to use to
 * install a new module or theme.
 *
 * @param $context
506 507 508 509 510 511
 *   String representing the context from which we're trying to install.
 *   Allowed values are 'module', 'theme', and 'report'.
 *
 * @see update_manager_install_form_validate()
 * @see update_manager_install_form_submit()
 * @see update_menu()
512
 *
513 514 515
 * @deprecated in Drupal 8.x-dev, will be removed before Drupal 8.0. Use
 *   \Drupal\update\Form\UpdateForm::reportInstall() or
 *   \Drupal\update\Form\UpdateForm::moduleInstall().
516 517
 */
function update_manager_install_form($form, &$form_state, $context) {
518 519 520
  if (!_update_manager_check_backends($form, 'install')) {
    return $form;
  }
521

522 523
  $form['help_text'] = array(
    '#prefix' => '<p>',
524 525 526 527 528 529
    '#markup' => t('You can find <a href="@module_url">modules</a> and <a href="@theme_url">themes</a> on <a href="@drupal_org_url">drupal.org</a>. The following file extensions are supported: %extensions.', array(
      '@module_url' => 'http://drupal.org/project/modules',
      '@theme_url' => 'http://drupal.org/project/themes',
      '@drupal_org_url' => 'http://drupal.org',
      '%extensions' => archiver_get_extensions(),
    )),
530 531 532
    '#suffix' => '</p>',
  );

533
  $form['project_url'] = array(
534
    '#type' => 'url',
535 536
    '#title' => t('Install from a URL'),
    '#description' => t('For example: %url', array('%url' => 'http://ftp.drupal.org/files/projects/name.tar.gz')),
537 538 539 540 541 542 543 544 545 546
  );

  $form['information'] = array(
    '#prefix' => '<strong>',
    '#markup' => t('Or'),
    '#suffix' => '</strong>',
  );

  $form['project_upload'] = array(
    '#type' => 'file',
547 548
    '#title' => t('Upload a module or theme archive to install'),
    '#description' => t('For example: %filename from your local computer', array('%filename' => 'name.tar.gz')),
549 550
  );

551 552
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
553 554 555 556 557 558 559
    '#type' => 'submit',
    '#value' => t('Install'),
  );

  return $form;
}

560 561 562 563 564 565
/**
 * 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
566 567
 *   The update manager operation we're in the middle of. Can be either 'update'
 *   or 'install'. Use to provide operation-specific interface text.
568 569
 *
 * @return
570
 *   TRUE if the update manager should continue to the next step in the
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
 *   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.
  $form['available_backends'] = array(
    '#prefix' => '<p>',
    '#suffix' => '</p>',
  );

  $available_backends = drupal_get_filetransfer_info();
  if (empty($available_backends)) {
    if ($operation == 'update') {
      $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 described in the <a href="@handbook_url">handbook</a>.', array('@handbook_url' => 'http://drupal.org/getting-started/install-contrib'));
    }
    else {
      $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 described in the <a href="@handbook_url">handbook</a>.', array('@handbook_url' => 'http://drupal.org/getting-started/install-contrib'));
    }
    return FALSE;
  }

  $backend_names = array();
  foreach ($available_backends as $backend) {
    $backend_names[] = $backend['title'];
  }
  if ($operation == 'update') {
    $form['available_backends']['#markup'] = format_plural(
      count($available_backends),
      'Updating modules and themes requires <strong>@backends access</strong> to your server. See the <a href="@handbook_url">handbook</a> for other update methods.',
      'Updating modules and themes requires access to your server via one of the following methods: <strong>@backends</strong>. See the <a href="@handbook_url">handbook</a> for other update methods.',
      array(
        '@backends' => implode(', ', $backend_names),
        '@handbook_url' => 'http://drupal.org/getting-started/install-contrib',
      ));
  }
  else {
    $form['available_backends']['#markup'] = format_plural(
      count($available_backends),
      'Installing modules and themes requires <strong>@backends access</strong> to your server. See the <a href="@handbook_url">handbook</a> for other installation methods.',
      'Installing modules and themes requires access to your server via one of the following methods: <strong>@backends</strong>. See the <a href="@handbook_url">handbook</a> for other installation methods.',
      array(
        '@backends' => implode(', ', $backend_names),
        '@handbook_url' => 'http://drupal.org/getting-started/install-contrib',
      ));
  }
  return TRUE;
}

627
/**
628 629 630
 * Form validation handler for update_manager_install_form().
 *
 * @see update_manager_install_form_submit()
631 632
 */
function update_manager_install_form_validate($form, &$form_state) {
633 634
  $uploaded_file = \Drupal::request()->files->get('files[project_upload]', NULL, TRUE);
  if (!($form_state['values']['project_url'] XOR !empty($uploaded_file))) {
635
    form_set_error('project_url', $form_state, t('You must either provide a URL or upload an archive file to install.'));
636 637 638 639
  }
}

/**
640
 * Form submission handler for update_manager_install_form().
641 642 643 644
 *
 * Either downloads the file specified in the URL to a temporary cache, or
 * uploads the file attached to the form, then attempts to extract the archive
 * into a temporary location and verify it. Instantiate the appropriate
645 646 647 648
 * Drupal\Core\Updater\Updater class for this project and make sure it is not
 * already installed in the live webroot. If everything is successful, setup an
 * operation to run via authorize.php which will copy the extracted files from
 * the temporary location into the live site.
649
 *
650
 * @see update_manager_install_form_validate()
651 652 653
 * @see update_authorize_run_install()
 * @see system_authorized_init()
 * @see system_authorized_get_url()
654 655 656 657 658 659
 */
function update_manager_install_form_submit($form, &$form_state) {
  if ($form_state['values']['project_url']) {
    $field = 'project_url';
    $local_cache = update_manager_file_get($form_state['values']['project_url']);
    if (!$local_cache) {
660
      drupal_set_message(t('Unable to retrieve Drupal project from %url.', array('%url' => $form_state['values']['project_url'])), 'error');
661 662 663 664
      return;
    }
  }
  elseif ($_FILES['files']['name']['project_upload']) {
665
    $validators = array('file_validate_extensions' => array(archiver_get_extensions()));
666
    $field = 'project_upload';
667 668 669
    if (!($finfo = file_save_upload($field, $validators, NULL, 0, FILE_EXISTS_REPLACE))) {
      // Failed to upload the file. file_save_upload() calls
      // drupal_set_message() on failure.
670 671
      return;
    }
672
    $local_cache = $finfo->getFileUri();
673
  }
674

675 676 677 678 679
  $directory = _update_manager_extract_directory();
  try {
    $archive = update_manager_archive_extract($local_cache, $directory);
  }
  catch (Exception $e) {
680
    drupal_set_message($e->getMessage(), 'error');
681 682 683
    return;
  }

684
  $files = $archive->listContents();
685
  if (!$files) {
686
    drupal_set_message(t('Provided archive contains no files.'), 'error');
687 688
    return;
  }
689 690 691 692 693

  // 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], '/\\');
694

695 696
  $archive_errors = update_manager_archive_verify($project, $local_cache, $directory);
  if (!empty($archive_errors)) {
697
    drupal_set_message(array_shift($archive_errors), 'error');
698 699 700 701 702 703 704
    // @todo: Fix me in D8: We need a way to set multiple errors on the same
    // form element and have all of them appear!
    if (!empty($archive_errors)) {
      foreach ($archive_errors as $error) {
        drupal_set_message($error, 'error');
      }
    }
705 706 707 708 709 710 711
    return;
  }

  // Make sure the Updater registry is loaded.
  drupal_get_updaters();

  $project_location = $directory . '/' . $project;
712 713 714 715
  try {
    $updater = Updater::factory($project_location);
  }
  catch (Exception $e) {
716
    drupal_set_message($e->getMessage(), 'error');
717 718 719 720 721 722 723
    return;
  }

  try {
    $project_title = Updater::getProjectTitle($project_location);
  }
  catch (Exception $e) {
724
    drupal_set_message($e->getMessage(), 'error');
725 726
    return;
  }
727 728

  if (!$project_title) {
729
    drupal_set_message(t('Unable to determine %project name.', array('%project' => $project)), 'error');
730
  }
731

732
  if ($updater->isInstalled()) {
733
    drupal_set_message(t('%project is already installed.', array('%project' => $project_title)), 'error');
734 735
    return;
  }
736

737
  $project_real_location = drupal_realpath($project_location);
738 739 740
  $arguments = array(
    'project' => $project,
    'updater_name' => get_class($updater),
741
    'local_url' => $project_real_location,
742 743
  );

744 745 746
  // If the owner of the directory we extracted is the same as the
  // owner of our configuration directory (e.g. sites/default) where we're
  // trying to install the code, there's no need to prompt for FTP/SSH
747 748
  // credentials. Instead, we instantiate a Drupal\Core\FileTransfer\Local and
  // invoke update_authorize_run_install() directly.
749 750
  if (fileowner($project_real_location) == fileowner(conf_path())) {
    module_load_include('inc', 'update', 'update.authorize');
751
    $filetransfer = new Local(DRUPAL_ROOT);
752 753 754 755 756 757
    call_user_func_array('update_authorize_run_install', array_merge(array($filetransfer), $arguments));
  }
  // Otherwise, go through the regular workflow to prompt for FTP/SSH
  // credentials and invoke update_authorize_run_install() indirectly with
  // whatever FileTransfer object authorize.php creates for us.
  else {
758
    system_authorized_init('update_authorize_run_install', drupal_get_path('module', 'update') . '/update.authorize.inc', $arguments, t('Update manager'));
759
    $form_state['redirect'] = system_authorized_get_url();
760
  }
761 762 763 764 765 766 767
}

/**
 * @} End of "defgroup update_manager_install".
 */

/**
768
 * @defgroup update_manager_file Update Manager module: file management
769
 * @{
770
 * Update Manager module file management functions.
771
 *
772 773
 * These functions are used by the update manager to copy, extract, and verify
 * archive files.
774 775 776
 */

/**
777
 * Unpacks a downloaded archive file.
778 779 780 781
 *
 * @param string $file
 *   The filename of the archive you wish to extract.
 * @param string $directory
782
 *   The directory you wish to extract the archive into.
783
 *
784 785
 * @return Archiver
 *   The Archiver object used to extract the archive.
786 787
 *
 * @throws Exception
788 789
 */
function update_manager_archive_extract($file, $directory) {
790 791 792
  $archiver = archiver_get_archiver($file);
  if (!$archiver) {
    throw new Exception(t('Cannot extract %file, not a valid archive.', array ('%file' => $file)));
793
  }
794 795 796 797 798

  // 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();
799 800 801 802 803 804

  // 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], '/\\');

805 806 807 808 809
  $extract_location = $directory . '/' . $project;
  if (file_exists($extract_location)) {
    file_unmanaged_delete_recursive($extract_location);
  }

810 811
  $archiver->extract($directory);
  return $archiver;
812 813 814
}

/**
815
 * Verifies an archive after it has been downloaded and extracted.
816 817 818 819 820 821 822 823 824 825
 *
 * 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.
 *
826
 * @return array
827 828
 *   An array of error messages to display if the archive was invalid. If there
 *   are no errors, it will be an empty array.
829 830
 */
function update_manager_archive_verify($project, $archive_file, $directory) {
831
  return \Drupal::moduleHandler()->invokeAll('verify_update_archive', array($project, $archive_file, $directory));
832 833 834
}

/**
835
 * Copies a file from the specified URL to the temporary directory for updates.
836
 *
837
 * Returns the local path if the file has already been downloaded.
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
 *
 * @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);
  $remote_schemes = array('http', 'https', 'ftp', 'ftps', 'smb', 'nfs');
  if (!in_array($parsed_url['scheme'], $remote_schemes)) {
    // This is a local file, just return the path.
    return drupal_realpath($url);
  }

  // Check the cache and download the file if needed.
854
  $cache_directory = _update_manager_cache_directory();
855
  $local = $cache_directory . '/' . drupal_basename($parsed_url['path']);
856

857 858
  if (!file_exists($local) || update_delete_file_if_stale($local)) {
    return system_retrieve_file($url, $local, FALSE, FILE_EXISTS_REPLACE);
859 860 861 862 863 864 865
  }
  else {
    return $local;
  }
}

/**
866
 * Batch callback: Downloads, unpacks, and verifies a project.
867
 *
868 869 870
 * 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.
871 872 873 874 875
 *
 * @param string $project
 *   The short name of the project to download.
 * @param string $url
 *   The URL to download a specific project release archive file.
876
 * @param array $context
877
 *   Reference to an array used for Batch API storage.
878 879 880 881 882 883 884 885 886 887 888 889 890 891
 *
 * @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;
    $context['message'] = t('Downloading %project', array('%project' => $project));
    $context['finished'] = 0;
    return;
  }

  // Actually try to download the file.
  if (!($local_cache = update_manager_file_get($url))) {
892
    $context['results']['errors'][$project] = t('Failed to download %project from %url', array('%project' => $project, '%url' => $url));
893 894 895 896 897 898 899 900 901
    return;
  }

  // Extract it.
  $extract_directory = _update_manager_extract_directory();
  try {
    update_manager_archive_extract($local_cache, $extract_directory);
  }
  catch (Exception $e) {
902
    $context['results']['errors'][$project] = $e->getMessage();
903 904 905 906
    return;
  }

  // Verify it.
907 908 909 910 911 912 913
  $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;
    }
914 915 916 917
    return;
  }

  // Yay, success.
918
  $context['results']['projects'][$project] = $url;
919 920 921
  $context['finished'] = 1;
}

922 923 924 925
/**
 * Determines if file transfers will be performed locally.
 *
 * If the server is configured such that webserver-created files have the same
926 927
 * owner as the configuration directory (e.g., sites/default) where new code
 * will eventually be installed, the update manager can transfer files entirely
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
 * 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 update_manager_update_ready_form_submit()
 * @see update_manager_install_form_submit()
 * @see install_check_requirements()
 */
function update_manager_local_transfers_allowed() {
  // Compare the owner of a webserver-created temporary file to the owner of
  // the configuration directory to determine if local transfers will be
  // allowed.
  $temporary_file = drupal_tempnam('temporary://', 'update_');
  $local_transfers_allowed = fileowner($temporary_file) === fileowner(conf_path());

  // Clean up. If this fails, we can ignore it (since this is just a temporary
  // file anyway).
  @drupal_unlink($temporary_file);

  return $local_transfers_allowed;
}

957 958 959
/**
 * @} End of "defgroup update_manager_file".
 */