Move into nested docroot

This commit is contained in:
Rob Davies 2017-02-13 15:31:17 +00:00
parent 83a0d3a149
commit c8b70abde9
13405 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,43 @@
<?php
namespace Drupal\update\Access;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Site\Settings;
/**
* Determines whether allow authorized operations is set.
*/
class UpdateManagerAccessCheck implements AccessInterface {
/**
* Settings Service.
*
* @var \Drupal\Core\Site\Settings
*/
protected $settings;
/**
* Constructs a UpdateManagerAccessCheck object.
*
* @param \Drupal\Core\Site\Settings $settings
* The read-only settings container.
*/
public function __construct(Settings $settings) {
$this->settings = $settings;
}
/**
* Checks access.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
public function access() {
// Uncacheable because the access result depends on a Settings key-value
// pair, and can therefore change at any time.
return AccessResult::allowedIf($this->settings->get('allow_authorize_operations', TRUE))->setCacheMaxAge(0);
}
}

View file

@ -0,0 +1,75 @@
<?php
namespace Drupal\update\Controller;
use Drupal\update\UpdateManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Controller\ControllerBase;
/**
* Controller routines for update routes.
*/
class UpdateController extends ControllerBase {
/**
* Update manager service.
*
* @var \Drupal\update\UpdateManagerInterface
*/
protected $updateManager;
/**
* Constructs update status data.
*
* @param \Drupal\update\UpdateManagerInterface $update_manager
* Update Manager Service.
*/
public function __construct(UpdateManagerInterface $update_manager) {
$this->updateManager = $update_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('update.manager')
);
}
/**
* Returns a page about the update status of projects.
*
* @return array
* A build array with the update status of projects.
*/
public function updateStatus() {
$build = array(
'#theme' => 'update_report'
);
if ($available = update_get_available(TRUE)) {
$this->moduleHandler()->loadInclude('update', 'compare.inc');
$build['#data'] = update_calculate_project_data($available);
}
return $build;
}
/**
* Manually checks the update status without the use of cron.
*/
public function updateStatusManually() {
$this->updateManager->refreshUpdateData();
$batch = array(
'operations' => array(
array(array($this->updateManager, 'fetchDataBatch'), array()),
),
'finished' => 'update_fetch_data_finished',
'title' => t('Checking available update data'),
'progress_message' => t('Trying to check available update data ...'),
'error_message' => t('Error checking available update data.'),
);
batch_set($batch);
return batch_process('admin/reports/updates');
}
}

View file

@ -0,0 +1,253 @@
<?php
namespace Drupal\update\Form;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\FileTransfer\Local;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Updater\Updater;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
/**
* Configure update settings for this site.
*/
class UpdateManagerInstall extends FormBase {
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The root location under which installed projects will be saved.
*
* @var string
*/
protected $root;
/**
* The site path.
*
* @var string
*/
protected $sitePath;
/**
* Constructs a new UpdateManagerInstall.
*
* @param string $root
* The root location under which installed projects will be saved.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param string $site_path
* The site path.
*/
public function __construct($root, ModuleHandlerInterface $module_handler, $site_path) {
$this->root = $root;
$this->moduleHandler = $module_handler;
$this->sitePath = $site_path;
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'update_manager_install_form';
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('update.root'),
$container->get('module_handler'),
$container->get('site.path')
);
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$this->moduleHandler->loadInclude('update', 'inc', 'update.manager');
if (!_update_manager_check_backends($form, 'install')) {
return $form;
}
$form['help_text'] = array(
'#prefix' => '<p>',
'#markup' => $this->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' => 'https://www.drupal.org/project/modules',
':theme_url' => 'https://www.drupal.org/project/themes',
':drupal_org_url' => 'https://www.drupal.org',
'%extensions' => archiver_get_extensions(),
)),
'#suffix' => '</p>',
);
$form['project_url'] = array(
'#type' => 'url',
'#title' => $this->t('Install from a URL'),
'#description' => $this->t('For example: %url', array('%url' => 'http://ftp.drupal.org/files/projects/name.tar.gz')),
);
$form['information'] = array(
'#prefix' => '<strong>',
'#markup' => $this->t('Or'),
'#suffix' => '</strong>',
);
$form['project_upload'] = array(
'#type' => 'file',
'#title' => $this->t('Upload a module or theme archive to install'),
'#description' => $this->t('For example: %filename from your local computer', array('%filename' => 'name.tar.gz')),
);
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
'#type' => 'submit',
'#button_type' => 'primary',
'#value' => $this->t('Install'),
);
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$all_files = $this->getRequest()->files->get('files', []);
if (!($form_state->getValue('project_url') xor !empty($all_files['project_upload']))) {
$form_state->setErrorByName('project_url', $this->t('You must either provide a URL or upload an archive file to install.'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$local_cache = NULL;
if ($form_state->getValue('project_url')) {
$local_cache = update_manager_file_get($form_state->getValue('project_url'));
if (!$local_cache) {
drupal_set_message($this->t('Unable to retrieve Drupal project from %url.', array('%url' => $form_state->getValue('project_url'))), 'error');
return;
}
}
elseif ($_FILES['files']['name']['project_upload']) {
$validators = array('file_validate_extensions' => array(archiver_get_extensions()));
if (!($finfo = file_save_upload('project_upload', $validators, NULL, 0, FILE_EXISTS_REPLACE))) {
// Failed to upload the file. file_save_upload() calls
// drupal_set_message() on failure.
return;
}
$local_cache = $finfo->getFileUri();
}
$directory = _update_manager_extract_directory();
try {
$archive = update_manager_archive_extract($local_cache, $directory);
}
catch (\Exception $e) {
drupal_set_message($e->getMessage(), 'error');
return;
}
$files = $archive->listContents();
if (!$files) {
drupal_set_message($this->t('Provided archive contains no files.'), 'error');
return;
}
// 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], '/\\');
$archive_errors = $this->moduleHandler->invokeAll('verify_update_archive', array($project, $local_cache, $directory));
if (!empty($archive_errors)) {
drupal_set_message(array_shift($archive_errors), 'error');
// @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');
}
}
return;
}
// Make sure the Updater registry is loaded.
drupal_get_updaters();
$project_location = $directory . '/' . $project;
try {
$updater = Updater::factory($project_location, $this->root);
}
catch (\Exception $e) {
drupal_set_message($e->getMessage(), 'error');
return;
}
try {
$project_title = Updater::getProjectTitle($project_location);
}
catch (\Exception $e) {
drupal_set_message($e->getMessage(), 'error');
return;
}
if (!$project_title) {
drupal_set_message($this->t('Unable to determine %project name.', array('%project' => $project)), 'error');
}
if ($updater->isInstalled()) {
drupal_set_message($this->t('%project is already installed.', array('%project' => $project_title)), 'error');
return;
}
$project_real_location = drupal_realpath($project_location);
$arguments = array(
'project' => $project,
'updater_name' => get_class($updater),
'local_url' => $project_real_location,
);
// This process is inherently difficult to test therefore use a state flag.
$test_authorize = FALSE;
if (drupal_valid_test_ua()) {
$test_authorize = \Drupal::state()->get('test_uploaders_via_prompt', FALSE);
}
// 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 credentials.
// Instead, we instantiate a Drupal\Core\FileTransfer\Local and invoke
// update_authorize_run_install() directly.
if (fileowner($project_real_location) == fileowner($this->sitePath) && !$test_authorize) {
$this->moduleHandler->loadInclude('update', 'inc', 'update.authorize');
$filetransfer = new Local($this->root);
$response = call_user_func_array('update_authorize_run_install', array_merge(array($filetransfer), $arguments));
if ($response instanceof Response) {
$form_state->setResponse($response);
}
}
// 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 {
// The page title must be passed here to ensure it is initially used when
// authorize.php loads for the first time with the FTP/SSH credentials
// form.
system_authorized_init('update_authorize_run_install', __DIR__ . '/../../update.authorize.inc', $arguments, $this->t('Update manager'));
$form_state->setRedirectUrl(system_authorized_get_url());
}
}
}

View file

@ -0,0 +1,340 @@
<?php
namespace Drupal\update\Form;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\State\StateInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Configure update settings for this site.
*/
class UpdateManagerUpdate extends FormBase {
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The Drupal state storage service.
*
* @var \Drupal\Core\State\StateInterface
*/
protected $state;
/**
* Constructs a new UpdateManagerUpdate object.
*
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\State\StateInterface $state
* The state service.
*/
public function __construct(ModuleHandlerInterface $module_handler, StateInterface $state) {
$this->moduleHandler = $module_handler;
$this->state = $state;
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'update_manager_update_form';
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('module_handler'),
$container->get('state')
);
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$this->moduleHandler->loadInclude('update', 'inc', 'update.manager');
$last_markup = array(
'#theme' => 'update_last_check',
'#last' => $this->state->get('update.last_check') ?: 0,
);
$form['last_check'] = array(
'#markup' => drupal_render($last_markup),
);
if (!_update_manager_check_backends($form, 'update')) {
return $form;
}
$available = update_get_available(TRUE);
if (empty($available)) {
$form['message'] = array(
'#markup' => $this->t('There was a problem getting update information. Try again later.'),
);
return $form;
}
$form['#attached']['library'][] = 'update/drupal.update.admin';
// This will be a nested array. The first key is the kind of project, which
// 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.
$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);
$this->moduleHandler->loadInclude('update', 'inc', 'update.compare');
$project_data = update_calculate_project_data($available);
foreach ($project_data as $name => $project) {
// Filter out projects which are up to date already.
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 = $this->l($project['title'], Url::fromUri($project['link']));
}
else {
$project_name = $project['title'];
}
}
elseif (!empty($project['info']['name'])) {
$project_name = $project['info']['name'];
}
else {
$project_name = $name;
}
if ($project['project_type'] == 'theme' || $project['project_type'] == 'theme-disabled') {
$project_name .= ' ' . $this->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']];
$recommended_version = '{{ release_version }} (<a href="{{ release_link }}" title="{{ project_title }}">{{ release_notes }}</a>)';
if ($recommended_release['version_major'] != $project['existing_major']) {
$recommended_version .= '<div title="{{ major_update_warning_title }}" class="update-major-version-warning">{{ major_update_warning_text }}</div>';
}
$recommended_version = array(
'#type' => 'inline_template',
'#template' => $recommended_version,
'#context' => array(
'release_version' => $recommended_release['version'],
'release_link' => $recommended_release['release_link'],
'project_title' => $this->t('Release notes for @project_title', array('@project_title' => $project['title'])),
'major_update_warning_title' => $this->t('Major upgrade warning'),
'major_update_warning_text' => $this->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.'),
'release_notes' => $this->t('Release notes'),
),
);
// Create an entry for this project.
$entry = array(
'title' => $project_name,
'installed_version' => $project['existing_version'],
'recommended_version' => array('data' => $recommended_version),
);
switch ($project['status']) {
case UPDATE_NOT_SECURE:
case UPDATE_REVOKED:
$entry['title'] .= ' ' . $this->t('(Security update)');
$entry['#weight'] = -2;
$type = 'security';
break;
case UPDATE_NOT_SUPPORTED:
$type = 'unsupported';
$entry['title'] .= ' ' . $this->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;
}
// Use the project title for the tableselect checkboxes.
$entry['title'] = array('data' => array(
'#title' => $entry['title'],
'#markup' => $entry['title'],
));
$entry['#attributes'] = array('class' => array('update-' . $type));
// Drupal core needs to be upgraded manually.
$needs_manual = $project['project_type'] == 'core';
if ($needs_manual) {
// There are no checkboxes in the 'Manual updates' table so it will be
// rendered by '#theme' => 'table', not '#theme' => 'tableselect'. Since
// the data formats are incompatible, we convert now to the format
// expected by '#theme' => 'table'.
unset($entry['#weight']);
$attributes = $entry['#attributes'];
unset($entry['#attributes']);
$entry = array(
'data' => $entry,
) + $attributes;
}
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':
// Core needs manual updates at this time.
$projects['manual'][$name] = $entry;
break;
case 'module':
case 'theme':
$projects['enabled'][$name] = $entry;
break;
case 'module-disabled':
case 'theme-disabled':
$projects['disabled'][$name] = $entry;
break;
}
}
if (empty($projects)) {
$form['message'] = array(
'#markup' => $this->t('All of your projects are up to date.'),
);
return $form;
}
$headers = array(
'title' => array(
'data' => $this->t('Name'),
'class' => array('update-project-name'),
),
'installed_version' => $this->t('Installed version'),
'recommended_version' => $this->t('Recommended version'),
);
if (!empty($projects['enabled'])) {
$form['projects'] = array(
'#type' => 'tableselect',
'#header' => $headers,
'#options' => $projects['enabled'],
);
if (!empty($projects['disabled'])) {
$form['projects']['#prefix'] = '<h2>' . $this->t('Enabled') . '</h2>';
}
}
if (!empty($projects['disabled'])) {
$form['disabled_projects'] = array(
'#type' => 'tableselect',
'#header' => $headers,
'#options' => $projects['disabled'],
'#weight' => 1,
'#prefix' => '<h2>' . $this->t('Disabled') . '</h2>',
);
}
// If either table has been printed yet, we need a submit button and to
// validate the checkboxes.
if (!empty($projects['enabled']) || !empty($projects['disabled'])) {
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Download these updates'),
);
}
if (!empty($projects['manual'])) {
$prefix = '<h2>' . $this->t('Manual updates required') . '</h2>';
$prefix .= '<p>' . $this->t('Updates of Drupal core are not supported at this time.') . '</p>';
$form['manual_updates'] = array(
'#type' => 'table',
'#header' => $headers,
'#rows' => $projects['manual'],
'#prefix' => $prefix,
'#weight' => 120,
);
}
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
if (!$form_state->isValueEmpty('projects')) {
$enabled = array_filter($form_state->getValue('projects'));
}
if (!$form_state->isValueEmpty('disabled_projects')) {
$disabled = array_filter($form_state->getValue('disabled_projects'));
}
if (empty($enabled) && empty($disabled)) {
$form_state->setErrorByName('projects', $this->t('You must select at least one project to update.'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->moduleHandler->loadInclude('update', 'inc', 'update.manager');
$projects = array();
foreach (array('projects', 'disabled_projects') as $type) {
if (!$form_state->isValueEmpty($type)) {
$projects = array_merge($projects, array_keys(array_filter($form_state->getValue($type))));
}
}
$operations = array();
foreach ($projects as $project) {
$operations[] = array(
'update_manager_batch_project_get',
array(
$project,
$form_state->getValue(array('project_downloads', $project)),
),
);
}
$batch = array(
'title' => $this->t('Downloading updates'),
'init_message' => $this->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);
}
}

View file

@ -0,0 +1,173 @@
<?php
namespace Drupal\update\Form;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\FileTransfer\Local;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\State\StateInterface;
use Drupal\Core\Updater\Updater;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
/**
* Configure update settings for this site.
*/
class UpdateReady extends FormBase {
/**
* The root location under which updated projects will be saved.
*
* @var string
*/
protected $root;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The state key value store.
*
* @var \Drupal\Core\State\StateInterface
*/
protected $state;
/**
* The Site path.
*
* @var string
*/
protected $sitePath;
/**
* Constructs a new UpdateReady object.
*
* @param string $root
* The root location under which updated projects will be saved.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The object that manages enabled modules in a Drupal installation.
* @param \Drupal\Core\State\StateInterface $state
* The state key value store.
* @param string $site_path
* The site path.
*/
public function __construct($root, ModuleHandlerInterface $module_handler, StateInterface $state, $site_path) {
$this->root = $root;
$this->moduleHandler = $module_handler;
$this->state = $state;
$this->sitePath = $site_path;
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'update_manager_update_ready_form';
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('update.root'),
$container->get('module_handler'),
$container->get('state'),
$container->get('site.path')
);
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$this->moduleHandler->loadInclude('update', 'inc', 'update.manager');
if (!_update_manager_check_backends($form, 'update')) {
return $form;
}
$form['backup'] = array(
'#prefix' => '<strong>',
'#markup' => $this->t('Back up your database and site before you continue. <a href=":backup_url">Learn how</a>.', array(':backup_url' => 'https://www.drupal.org/node/22281')),
'#suffix' => '</strong>',
);
$form['maintenance_mode'] = array(
'#title' => $this->t('Perform updates with site in maintenance mode (strongly recommended)'),
'#type' => 'checkbox',
'#default_value' => TRUE,
);
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Continue'),
);
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Store maintenance_mode setting so we can restore it when done.
$_SESSION['maintenance_mode'] = $this->state->get('system.maintenance_mode');
if ($form_state->getValue('maintenance_mode') == TRUE) {
$this->state->set('system.maintenance_mode', TRUE);
}
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']);
$project_real_location = NULL;
foreach ($projects as $project => $url) {
$project_location = $directory . '/' . $project;
$updater = Updater::factory($project_location, $this->root);
$project_real_location = drupal_realpath($project_location);
$updates[] = array(
'project' => $project,
'updater_name' => get_class($updater),
'local_url' => $project_real_location,
);
}
// 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
// credentials. Instead, we instantiate a Drupal\Core\FileTransfer\Local
// and invoke update_authorize_run_update() directly.
if (fileowner($project_real_location) == fileowner($this->sitePath)) {
$this->moduleHandler->loadInclude('update', 'inc', 'update.authorize');
$filetransfer = new Local($this->root);
$response = update_authorize_run_update($filetransfer, $updates);
if ($response instanceof Response) {
$form_state->setResponse($response);
}
}
// 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 {
// The page title must be passed here to ensure it is initially used
// when authorize.php loads for the first time with the FTP/SSH
// credentials form.
system_authorized_init('update_authorize_run_update', __DIR__ . '/../../update.authorize.inc', array($updates), $this->t('Update manager'));
$form_state->setRedirectUrl(system_authorized_get_url());
}
}
}
}

View file

@ -0,0 +1,58 @@
<?php
namespace Drupal\update\Tests;
/**
* Tests the Update Manager module upload via authorize.php functionality.
*
* @group update
*/
class FileTransferAuthorizeFormTest extends UpdateTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('update', 'update_test');
protected function setUp() {
parent::setUp();
$admin_user = $this->drupalCreateUser(array('administer modules', 'administer software updates', 'administer site configuration'));
$this->drupalLogin($admin_user);
// Create a local cache so the module is not downloaded from drupal.org.
$cache_directory = _update_manager_cache_directory(TRUE);
$validArchiveFile = __DIR__ . '/../../tests/update_test_new_module/8.x-1.0/update_test_new_module.tar.gz';
copy($validArchiveFile, $cache_directory . '/update_test_new_module.tar.gz');
}
/**
* Tests the Update Manager module upload via authorize.php functionality.
*/
public function testViaAuthorize() {
// Ensure the that we can select which file transfer backend to use.
\Drupal::state()->set('test_uploaders_via_prompt', TRUE);
// Ensure the module does not already exist.
$this->drupalGet('admin/modules');
$this->assertNoText('Update test new module');
$edit = [
// This project has been cached in the test's setUp() method.
'project_url' => 'https://ftp.drupal.org/files/projects/update_test_new_module.tar.gz',
];
$this->drupalPostForm('admin/modules/install', $edit, t('Install'));
$edit = [
'connection_settings[authorize_filetransfer_default]' => 'system_test',
'connection_settings[system_test][update_test_username]' => $this->randomMachineName(),
];
$this->drupalPostForm(NULL, $edit, t('Continue'));
$this->assertText(t('Installation was completed successfully.'));
// Ensure the module is available to install.
$this->drupalGet('admin/modules');
$this->assertText('Update test new module');
}
}

View file

@ -0,0 +1,441 @@
<?php
namespace Drupal\update\Tests;
use Drupal\Core\Url;
use Drupal\Core\Utility\ProjectInfo;
/**
* Tests how the Update Manager module handles contributed modules and themes in
* a series of functional tests using mock XML data.
*
* @group update
*/
class UpdateContribTest extends UpdateTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('update_test', 'update', 'aaa_update_test', 'bbb_update_test', 'ccc_update_test');
protected function setUp() {
parent::setUp();
$admin_user = $this->drupalCreateUser(array('administer site configuration'));
$this->drupalLogin($admin_user);
}
/**
* Tests when there is no available release data for a contrib module.
*/
function testNoReleasesAvailable() {
$system_info = array(
'#all' => array(
'version' => '8.0.0',
),
'aaa_update_test' => array(
'project' => 'aaa_update_test',
'version' => '8.x-1.0',
'hidden' => FALSE,
),
);
$this->config('update_test.settings')->set('system_info', $system_info)->save();
$this->refreshUpdateStatus(array('drupal' => '0.0', 'aaa_update_test' => 'no-releases'));
$this->drupalGet('admin/reports/updates');
// Cannot use $this->standardTests() because we need to check for the
// 'No available releases found' string.
$this->assertRaw('<h3>' . t('Drupal core') . '</h3>');
$this->assertRaw(\Drupal::l(t('Drupal'), Url::fromUri('http://example.com/project/drupal')));
$this->assertText(t('Up to date'));
$this->assertRaw('<h3>' . t('Modules') . '</h3>');
$this->assertNoText(t('Update available'));
$this->assertText(t('No available releases found'));
$this->assertNoRaw(\Drupal::l(t('AAA Update test'), Url::fromUri('http://example.com/project/aaa_update_test')));
$available = update_get_available();
$this->assertFalse(isset($available['aaa_update_test']['fetch_status']), 'Results are cached even if no releases are available.');
}
/**
* Tests the basic functionality of a contrib module on the status report.
*/
function testUpdateContribBasic() {
$project_link = \Drupal::l(t('AAA Update test'), Url::fromUri('http://example.com/project/aaa_update_test'));
$system_info = array(
'#all' => array(
'version' => '8.0.0',
),
'aaa_update_test' => array(
'project' => 'aaa_update_test',
'version' => '8.x-1.0',
'hidden' => FALSE,
),
);
$this->config('update_test.settings')->set('system_info', $system_info)->save();
$this->refreshUpdateStatus(
array(
'drupal' => '0.0',
'aaa_update_test' => '1_0',
)
);
$this->standardTests();
$this->assertText(t('Up to date'));
$this->assertRaw('<h3>' . t('Modules') . '</h3>');
$this->assertNoText(t('Update available'));
$this->assertRaw($project_link, 'Link to aaa_update_test project appears.');
// Since aaa_update_test is installed the fact it is hidden and in the
// Testing package means it should not appear.
$system_info['aaa_update_test']['hidden'] = TRUE;
$this->config('update_test.settings')->set('system_info', $system_info)->save();
$this->refreshUpdateStatus(
array(
'drupal' => '0.0',
'aaa_update_test' => '1_0',
)
);
$this->assertNoRaw($project_link, 'Link to aaa_update_test project does not appear.');
// A hidden and installed project not in the Testing package should appear.
$system_info['aaa_update_test']['package'] = 'aaa_update_test';
$this->config('update_test.settings')->set('system_info', $system_info)->save();
$this->refreshUpdateStatus(
array(
'drupal' => '0.0',
'aaa_update_test' => '1_0',
)
);
$this->assertRaw($project_link, 'Link to aaa_update_test project appears.');
}
/**
* Tests that contrib projects are ordered by project name.
*
* If a project contains multiple modules, we want to make sure that the
* available updates report is sorted by the parent project names, not by the
* names of the modules included in each project. In this test case, we have
* two contrib projects, "BBB Update test" and "CCC Update test". However, we
* have a module called "aaa_update_test" that's part of the "CCC Update test"
* project. We need to make sure that we see the "BBB" project before the
* "CCC" project, even though "CCC" includes a module that's processed first
* if you sort alphabetically by module name (which is the order we see things
* inside system_rebuild_module_data() for example).
*/
function testUpdateContribOrder() {
// We want core to be version 8.0.0.
$system_info = array(
'#all' => array(
'version' => '8.0.0',
),
// All the rest should be visible as contrib modules at version 8.x-1.0.
// aaa_update_test needs to be part of the "CCC Update test" project,
// which would throw off the report if we weren't properly sorting by
// the project names.
'aaa_update_test' => array(
'project' => 'ccc_update_test',
'version' => '8.x-1.0',
'hidden' => FALSE,
),
// This should be its own project, and listed first on the report.
'bbb_update_test' => array(
'project' => 'bbb_update_test',
'version' => '8.x-1.0',
'hidden' => FALSE,
),
// This will contain both aaa_update_test and ccc_update_test, and
// should come after the bbb_update_test project.
'ccc_update_test' => array(
'project' => 'ccc_update_test',
'version' => '8.x-1.0',
'hidden' => FALSE,
),
);
$this->config('update_test.settings')->set('system_info', $system_info)->save();
$this->refreshUpdateStatus(array('drupal' => '0.0', '#all' => '1_0'));
$this->standardTests();
// We're expecting the report to say all projects are up to date.
$this->assertText(t('Up to date'));
$this->assertNoText(t('Update available'));
// We want to see all 3 module names listed, since they'll show up either
// as project names or as modules under the "Includes" listing.
$this->assertText(t('AAA Update test'));
$this->assertText(t('BBB Update test'));
$this->assertText(t('CCC Update test'));
// We want aaa_update_test included in the ccc_update_test project, not as
// its own project on the report.
$this->assertNoRaw(\Drupal::l(t('AAA Update test'), Url::fromUri('http://example.com/project/aaa_update_test')), 'Link to aaa_update_test project does not appear.');
// The other two should be listed as projects.
$this->assertRaw(\Drupal::l(t('BBB Update test'), Url::fromUri('http://example.com/project/bbb_update_test')), 'Link to bbb_update_test project appears.');
$this->assertRaw(\Drupal::l(t('CCC Update test'), Url::fromUri('http://example.com/project/ccc_update_test')), 'Link to bbb_update_test project appears.');
// We want to make sure we see the BBB project before the CCC project.
// Instead of just searching for 'BBB Update test' or something, we want
// to use the full markup that starts the project entry itself, so that
// we're really testing that the project listings are in the right order.
$bbb_project_link = '<div class="project-update__title"><a href="http://example.com/project/bbb_update_test">BBB Update test</a>';
$ccc_project_link = '<div class="project-update__title"><a href="http://example.com/project/ccc_update_test">CCC Update test</a>';
$this->assertTrue(strpos($this->getRawContent(), $bbb_project_link) < strpos($this->getRawContent(), $ccc_project_link), "'BBB Update test' project is listed before the 'CCC Update test' project");
}
/**
* Tests that subthemes are notified about security updates for base themes.
*/
function testUpdateBaseThemeSecurityUpdate() {
// @todo https://www.drupal.org/node/2338175 base themes have to be
// installed.
// Only install the subtheme, not the base theme.
\Drupal::service('theme_handler')->install(array('update_test_subtheme'));
// Define the initial state for core and the subtheme.
$system_info = array(
// We want core to be version 8.0.0.
'#all' => array(
'version' => '8.0.0',
),
// Show the update_test_basetheme
'update_test_basetheme' => array(
'project' => 'update_test_basetheme',
'version' => '8.x-1.0',
'hidden' => FALSE,
),
// Show the update_test_subtheme
'update_test_subtheme' => array(
'project' => 'update_test_subtheme',
'version' => '8.x-1.0',
'hidden' => FALSE,
),
);
$this->config('update_test.settings')->set('system_info', $system_info)->save();
$xml_mapping = array(
'drupal' => '0.0',
'update_test_subtheme' => '1_0',
'update_test_basetheme' => '1_1-sec',
);
$this->refreshUpdateStatus($xml_mapping);
$this->assertText(t('Security update required!'));
$this->assertRaw(\Drupal::l(t('Update test base theme'), Url::fromUri('http://example.com/project/update_test_basetheme')), 'Link to the Update test base theme project appears.');
}
/**
* Tests that disabled themes are only shown when desired.
*
* @todo https://www.drupal.org/node/2338175 extensions can not be hidden and
* base themes have to be installed.
*/
function testUpdateShowDisabledThemes() {
$update_settings = $this->config('update.settings');
// Make sure all the update_test_* themes are disabled.
$extension_config = $this->config('core.extension');
foreach ($extension_config->get('theme') as $theme => $weight) {
if (preg_match('/^update_test_/', $theme)) {
$extension_config->clear("theme.$theme");
}
}
$extension_config->save();
// Define the initial state for core and the test contrib themes.
$system_info = array(
// We want core to be version 8.0.0.
'#all' => array(
'version' => '8.0.0',
),
// The update_test_basetheme should be visible and up to date.
'update_test_basetheme' => array(
'project' => 'update_test_basetheme',
'version' => '8.x-1.1',
'hidden' => FALSE,
),
// The update_test_subtheme should be visible and up to date.
'update_test_subtheme' => array(
'project' => 'update_test_subtheme',
'version' => '8.x-1.0',
'hidden' => FALSE,
),
);
// When there are contributed modules in the site's file system, the
// total number of attempts made in the test may exceed the default value
// of update_max_fetch_attempts. Therefore this variable is set very high
// to avoid test failures in those cases.
$update_settings->set('fetch.max_attempts', 99999)->save();
$this->config('update_test.settings')->set('system_info', $system_info)->save();
$xml_mapping = array(
'drupal' => '0.0',
'update_test_subtheme' => '1_0',
'update_test_basetheme' => '1_1-sec',
);
$base_theme_project_link = \Drupal::l(t('Update test base theme'), Url::fromUri('http://example.com/project/update_test_basetheme'));
$sub_theme_project_link = \Drupal::l(t('Update test subtheme'), Url::fromUri('http://example.com/project/update_test_subtheme'));
foreach (array(TRUE, FALSE) as $check_disabled) {
$update_settings->set('check.disabled_extensions', $check_disabled)->save();
$this->refreshUpdateStatus($xml_mapping);
// In neither case should we see the "Themes" heading for installed
// themes.
$this->assertNoText(t('Themes'));
if ($check_disabled) {
$this->assertText(t('Uninstalled themes'));
$this->assertRaw($base_theme_project_link, 'Link to the Update test base theme project appears.');
$this->assertRaw($sub_theme_project_link, 'Link to the Update test subtheme project appears.');
}
else {
$this->assertNoText(t('Uninstalled themes'));
$this->assertNoRaw($base_theme_project_link, 'Link to the Update test base theme project does not appear.');
$this->assertNoRaw($sub_theme_project_link, 'Link to the Update test subtheme project does not appear.');
}
}
}
/**
* Tests updates with a hidden base theme.
*/
function testUpdateHiddenBaseTheme() {
module_load_include('compare.inc', 'update');
// Install the subtheme.
\Drupal::service('theme_handler')->install(array('update_test_subtheme'));
// Add a project and initial state for base theme and subtheme.
$system_info = array(
// Hide the update_test_basetheme.
'update_test_basetheme' => array(
'project' => 'update_test_basetheme',
'hidden' => TRUE,
),
// Show the update_test_subtheme.
'update_test_subtheme' => array(
'project' => 'update_test_subtheme',
'hidden' => FALSE,
),
);
$this->config('update_test.settings')->set('system_info', $system_info)->save();
$projects = \Drupal::service('update.manager')->getProjects();
$theme_data = \Drupal::service('theme_handler')->rebuildThemeData();
$project_info = new ProjectInfo();
$project_info->processInfoList($projects, $theme_data, 'theme', TRUE);
$this->assertTrue(!empty($projects['update_test_basetheme']), 'Valid base theme (update_test_basetheme) was found.');
}
/**
* Makes sure that if we fetch from a broken URL, sane things happen.
*/
function testUpdateBrokenFetchURL() {
$system_info = array(
'#all' => array(
'version' => '8.0.0',
),
'aaa_update_test' => array(
'project' => 'aaa_update_test',
'version' => '8.x-1.0',
'hidden' => FALSE,
),
'bbb_update_test' => array(
'project' => 'bbb_update_test',
'version' => '8.x-1.0',
'hidden' => FALSE,
),
'ccc_update_test' => array(
'project' => 'ccc_update_test',
'version' => '8.x-1.0',
'hidden' => FALSE,
),
);
$this->config('update_test.settings')->set('system_info', $system_info)->save();
// Ensure that the update information is correct before testing.
$this->drupalGet('admin/reports/updates');
$xml_mapping = array(
'drupal' => '0.0',
'aaa_update_test' => '1_0',
'bbb_update_test' => 'does-not-exist',
'ccc_update_test' => '1_0',
);
$this->refreshUpdateStatus($xml_mapping);
$this->assertText(t('Up to date'));
// We're expecting the report to say most projects are up to date, so we
// hope that 'Up to date' is not unique.
$this->assertNoUniqueText(t('Up to date'));
// It should say we failed to get data, not that we're missing an update.
$this->assertNoText(t('Update available'));
// We need to check that this string is found as part of a project row, not
// just in the "Failed to get available update data" message at the top of
// the page.
$this->assertRaw('<div class="project-update__status">' . t('Failed to get available update data'));
// We should see the output messages from fetching manually.
$this->assertUniqueText(t('Checked available update data for 3 projects.'));
$this->assertUniqueText(t('Failed to get available update data for one project.'));
// The other two should be listed as projects.
$this->assertRaw(\Drupal::l(t('AAA Update test'), Url::fromUri('http://example.com/project/aaa_update_test')), 'Link to aaa_update_test project appears.');
$this->assertNoRaw(\Drupal::l(t('BBB Update test'), Url::fromUri('http://example.com/project/bbb_update_test')), 'Link to bbb_update_test project does not appear.');
$this->assertRaw(\Drupal::l(t('CCC Update test'), Url::fromUri('http://example.com/project/ccc_update_test')), 'Link to bbb_update_test project appears.');
}
/**
* Checks that hook_update_status_alter() works to change a status.
*
* We provide the same external data as if aaa_update_test 8.x-1.0 were
* installed and that was the latest release. Then we use
* hook_update_status_alter() to try to mark this as missing a security
* update, then assert if we see the appropriate warnings on the right pages.
*/
function testHookUpdateStatusAlter() {
$update_test_config = $this->config('update_test.settings');
$update_admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer software updates'));
$this->drupalLogin($update_admin_user);
$system_info = array(
'#all' => array(
'version' => '8.0.0',
),
'aaa_update_test' => array(
'project' => 'aaa_update_test',
'version' => '8.x-1.0',
'hidden' => FALSE,
),
);
$update_test_config->set('system_info', $system_info)->save();
$update_status = array(
'aaa_update_test' => array(
'status' => UPDATE_NOT_SECURE,
),
);
$update_test_config->set('update_status', $update_status)->save();
$this->refreshUpdateStatus(
array(
'drupal' => '0.0',
'aaa_update_test' => '1_0',
)
);
$this->drupalGet('admin/reports/updates');
$this->assertRaw('<h3>' . t('Modules') . '</h3>');
$this->assertText(t('Security update required!'));
$this->assertRaw(\Drupal::l(t('AAA Update test'), Url::fromUri('http://example.com/project/aaa_update_test')), 'Link to aaa_update_test project appears.');
// Visit the reports page again without the altering and make sure the
// status is back to normal.
$update_test_config->set('update_status', array())->save();
$this->drupalGet('admin/reports/updates');
$this->assertRaw('<h3>' . t('Modules') . '</h3>');
$this->assertNoText(t('Security update required!'));
$this->assertRaw(\Drupal::l(t('AAA Update test'), Url::fromUri('http://example.com/project/aaa_update_test')), 'Link to aaa_update_test project appears.');
// Turn the altering back on and visit the Update manager UI.
$update_test_config->set('update_status', $update_status)->save();
$this->drupalGet('admin/modules/update');
$this->assertText(t('Security update'));
// Turn the altering back off and visit the Update manager UI.
$update_test_config->set('update_status', array())->save();
$this->drupalGet('admin/modules/update');
$this->assertNoText(t('Security update'));
}
}

View file

@ -0,0 +1,368 @@
<?php
namespace Drupal\update\Tests;
use Drupal\Core\Url;
/**
* Tests the Update Manager module through a series of functional tests using
* mock XML data.
*
* @group update
*/
class UpdateCoreTest extends UpdateTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['update_test', 'update', 'language', 'block'];
protected function setUp() {
parent::setUp();
$admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer modules', 'administer themes'));
$this->drupalLogin($admin_user);
$this->drupalPlaceBlock('local_actions_block');
}
/**
* Sets the version to x.x.x when no project-specific mapping is defined.
*
* @param string $version
* The version.
*/
protected function setSystemInfo($version) {
$setting = array(
'#all' => array(
'version' => $version,
),
);
$this->config('update_test.settings')->set('system_info', $setting)->save();
}
/**
* Tests the Update Manager module when no updates are available.
*/
function testNoUpdatesAvailable() {
foreach (array(0, 1) as $minor_version) {
foreach (array(0, 1) as $patch_version) {
foreach (array('-alpha1', '-beta1', '') as $extra_version) {
$this->setSystemInfo("8.$minor_version.$patch_version" . $extra_version);
$this->refreshUpdateStatus(array('drupal' => "$minor_version.$patch_version" . $extra_version));
$this->standardTests();
$this->assertText(t('Up to date'));
$this->assertNoText(t('Update available'));
$this->assertNoText(t('Security update required!'));
$this->assertRaw('check.svg', 'Check icon was found.');
}
}
}
}
/**
* Tests the Update Manager module when one normal update is available.
*/
function testNormalUpdateAvailable() {
$this->setSystemInfo('8.0.0');
// Ensure that the update check requires a token.
$this->drupalGet('admin/reports/updates/check');
$this->assertResponse(403, 'Accessing admin/reports/updates/check without a CSRF token results in access denied.');
foreach (array(0, 1) as $minor_version) {
foreach (array('-alpha1', '-beta1', '') as $extra_version) {
$this->refreshUpdateStatus(array('drupal' => "$minor_version.1" . $extra_version));
$this->standardTests();
$this->drupalGet('admin/reports/updates');
$this->clickLink(t('Check manually'));
$this->assertNoText(t('Security update required!'));
$this->assertRaw(\Drupal::l("8.$minor_version.1" . $extra_version, Url::fromUri("http://example.com/drupal-8-$minor_version-1$extra_version-release")), 'Link to release appears.');
$this->assertRaw(\Drupal::l(t('Download'), Url::fromUri("http://example.com/drupal-8-$minor_version-1$extra_version.tar.gz")), 'Link to download appears.');
$this->assertRaw(\Drupal::l(t('Release notes'), Url::fromUri("http://example.com/drupal-8-$minor_version-1$extra_version-release")), 'Link to release notes appears.');
switch ($minor_version) {
case 0:
// Both stable and unstable releases are available.
// A stable release is the latest.
if ($extra_version == '') {
$this->assertNoText(t('Up to date'));
$this->assertText(t('Update available'));
$this->assertText(t('Recommended version:'));
$this->assertNoText(t('Latest version:'));
$this->assertRaw('warning.svg', 'Warning icon was found.');
}
// Only unstable releases are available.
// An unstable release is the latest.
else {
$this->assertText(t('Up to date'));
$this->assertNoText(t('Update available'));
$this->assertNoText(t('Recommended version:'));
$this->assertText(t('Latest version:'));
$this->assertRaw('check.svg', 'Check icon was found.');
}
break;
case 1:
// Both stable and unstable releases are available.
// A stable release is the latest.
if ($extra_version == '') {
$this->assertNoText(t('Up to date'));
$this->assertText(t('Update available'));
$this->assertText(t('Recommended version:'));
$this->assertNoText(t('Latest version:'));
$this->assertRaw('warning.svg', 'Warning icon was found.');
}
// Both stable and unstable releases are available.
// An unstable release is the latest.
else {
$this->assertNoText(t('Up to date'));
$this->assertText(t('Update available'));
$this->assertText(t('Recommended version:'));
$this->assertText(t('Latest version:'));
$this->assertRaw('warning.svg', 'Warning icon was found.');
}
break;
}
}
}
}
/**
* Tests the Update Manager module when a major update is available.
*/
function testMajorUpdateAvailable() {
foreach (array(0, 1) as $minor_version) {
foreach (array(0, 1) as $patch_version) {
foreach (array('-alpha1', '-beta1', '') as $extra_version) {
$this->setSystemInfo("8.$minor_version.$patch_version" . $extra_version);
$this->refreshUpdateStatus(array('drupal' => '9'));
$this->standardTests();
$this->drupalGet('admin/reports/updates');
$this->clickLink(t('Check manually'));
$this->assertNoText(t('Security update required!'));
$this->assertRaw(\Drupal::l('9.0.0', Url::fromUri("http://example.com/drupal-9-0-0-release")), 'Link to release appears.');
$this->assertRaw(\Drupal::l(t('Download'), Url::fromUri("http://example.com/drupal-9-0-0.tar.gz")), 'Link to download appears.');
$this->assertRaw(\Drupal::l(t('Release notes'), Url::fromUri("http://example.com/drupal-9-0-0-release")), 'Link to release notes appears.');
$this->assertNoText(t('Up to date'));
$this->assertText(t('Not supported!'));
$this->assertText(t('Recommended version:'));
$this->assertNoText(t('Latest version:'));
$this->assertRaw('error.svg', 'Error icon was found.');
}
}
}
}
/**
* Tests the Update Manager module when a security update is available.
*/
function testSecurityUpdateAvailable() {
foreach (array(0, 1) as $minor_version) {
$this->setSystemInfo("8.$minor_version.0");
$this->refreshUpdateStatus(array('drupal' => "$minor_version.2-sec"));
$this->standardTests();
$this->assertNoText(t('Up to date'));
$this->assertNoText(t('Update available'));
$this->assertText(t('Security update required!'));
$this->assertRaw(\Drupal::l("8.$minor_version.2", Url::fromUri("http://example.com/drupal-8-$minor_version-2-release")), 'Link to release appears.');
$this->assertRaw(\Drupal::l(t('Download'), Url::fromUri("http://example.com/drupal-8-$minor_version-2.tar.gz")), 'Link to download appears.');
$this->assertRaw(\Drupal::l(t('Release notes'), Url::fromUri("http://example.com/drupal-8-$minor_version-2-release")), 'Link to release notes appears.');
$this->assertRaw('error.svg', 'Error icon was found.');
}
}
/**
* Ensures proper results where there are date mismatches among modules.
*/
function testDatestampMismatch() {
$system_info = array(
'#all' => array(
// We need to think we're running a -dev snapshot to see dates.
'version' => '8.1.0-dev',
'datestamp' => time(),
),
'block' => array(
// This is 2001-09-09 01:46:40 GMT, so test for "2001-Sep-".
'datestamp' => '1000000000',
),
);
$this->config('update_test.settings')->set('system_info', $system_info)->save();
$this->refreshUpdateStatus(array('drupal' => 'dev'));
$this->assertNoText(t('2001-Sep-'));
$this->assertText(t('Up to date'));
$this->assertNoText(t('Update available'));
$this->assertNoText(t('Security update required!'));
}
/**
* Checks that running cron updates the list of available updates.
*/
function testModulePageRunCron() {
$this->setSystemInfo('8.0.0');
$this->config('update.settings')
->set('fetch.url', Url::fromRoute('update_test.update_test')->setAbsolute()->toString())
->save();
$this->config('update_test.settings')
->set('xml_map', array('drupal' => '0.0'))
->save();
$this->cronRun();
$this->drupalGet('admin/modules');
$this->assertNoText(t('No update information available.'));
}
/**
* Checks the messages at admin/modules when the site is up to date.
*/
function testModulePageUpToDate() {
$this->setSystemInfo('8.0.0');
// Instead of using refreshUpdateStatus(), set these manually.
$this->config('update.settings')
->set('fetch.url', Url::fromRoute('update_test.update_test')->setAbsolute()->toString())
->save();
$this->config('update_test.settings')
->set('xml_map', array('drupal' => '0.0'))
->save();
$this->drupalGet('admin/reports/updates');
$this->clickLink(t('Check manually'));
$this->assertText(t('Checked available update data for one project.'));
$this->drupalGet('admin/modules');
$this->assertNoText(t('There are updates available for your version of Drupal.'));
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
}
/**
* Checks the messages at admin/modules when an update is missing.
*/
function testModulePageRegularUpdate() {
$this->setSystemInfo('8.0.0');
// Instead of using refreshUpdateStatus(), set these manually.
$this->config('update.settings')
->set('fetch.url', Url::fromRoute('update_test.update_test')->setAbsolute()->toString())
->save();
$this->config('update_test.settings')
->set('xml_map', array('drupal' => '0.1'))
->save();
$this->drupalGet('admin/reports/updates');
$this->clickLink(t('Check manually'));
$this->assertText(t('Checked available update data for one project.'));
$this->drupalGet('admin/modules');
$this->assertText(t('There are updates available for your version of Drupal.'));
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
}
/**
* Checks the messages at admin/modules when a security update is missing.
*/
function testModulePageSecurityUpdate() {
$this->setSystemInfo('8.0.0');
// Instead of using refreshUpdateStatus(), set these manually.
$this->config('update.settings')
->set('fetch.url', Url::fromRoute('update_test.update_test')->setAbsolute()->toString())
->save();
$this->config('update_test.settings')
->set('xml_map', array('drupal' => '0.2-sec'))
->save();
$this->drupalGet('admin/reports/updates');
$this->clickLink(t('Check manually'));
$this->assertText(t('Checked available update data for one project.'));
$this->drupalGet('admin/modules');
$this->assertNoText(t('There are updates available for your version of Drupal.'));
$this->assertText(t('There is a security update available for your version of Drupal.'));
// Make sure admin/appearance warns you you're missing a security update.
$this->drupalGet('admin/appearance');
$this->assertNoText(t('There are updates available for your version of Drupal.'));
$this->assertText(t('There is a security update available for your version of Drupal.'));
// Make sure duplicate messages don't appear on Update status pages.
$this->drupalGet('admin/reports/status');
// We're expecting "There is a security update..." inside the status report
// itself, but the drupal_set_message() appears as an li so we can prefix
// with that and search for the raw HTML.
$this->assertNoRaw('<li>' . t('There is a security update available for your version of Drupal.'));
$this->drupalGet('admin/reports/updates');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
$this->drupalGet('admin/reports/updates/settings');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
}
/**
* Tests the Update Manager module when the update server returns 503 errors.
*/
function testServiceUnavailable() {
$this->refreshUpdateStatus(array(), '503-error');
// Ensure that no "Warning: SimpleXMLElement..." parse errors are found.
$this->assertNoText('SimpleXMLElement');
$this->assertUniqueText(t('Failed to get available update data for one project.'));
}
/**
* Tests that exactly one fetch task per project is created and not more.
*/
function testFetchTasks() {
$projecta = array(
'name' => 'aaa_update_test',
);
$projectb = array(
'name' => 'bbb_update_test',
);
$queue = \Drupal::queue('update_fetch_tasks');
$this->assertEqual($queue->numberOfItems(), 0, 'Queue is empty');
update_create_fetch_task($projecta);
$this->assertEqual($queue->numberOfItems(), 1, 'Queue contains one item');
update_create_fetch_task($projectb);
$this->assertEqual($queue->numberOfItems(), 2, 'Queue contains two items');
// Try to add project a again.
update_create_fetch_task($projecta);
$this->assertEqual($queue->numberOfItems(), 2, 'Queue still contains two items');
// Clear storage and try again.
update_storage_clear();
update_create_fetch_task($projecta);
$this->assertEqual($queue->numberOfItems(), 2, 'Queue contains two items');
}
/**
* Checks language module in core package at admin/reports/updates.
*/
function testLanguageModuleUpdate() {
$this->setSystemInfo('8.0.0');
// Instead of using refreshUpdateStatus(), set these manually.
$this->config('update.settings')
->set('fetch.url', Url::fromRoute('update_test.update_test')->setAbsolute()->toString())
->save();
$this->config('update_test.settings')
->set('xml_map', array('drupal' => '0.1'))
->save();
$this->drupalGet('admin/reports/updates');
$this->assertText(t('Language'));
}
/**
* Ensures that the local actions appear.
*/
public function testLocalActions() {
$admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer modules', 'administer software updates', 'administer themes'));
$this->drupalLogin($admin_user);
$this->drupalGet('admin/modules');
$this->clickLink(t('Install new module'));
$this->assertUrl('admin/modules/install');
$this->drupalGet('admin/appearance');
$this->clickLink(t('Install new theme'));
$this->assertUrl('admin/theme/install');
$this->drupalGet('admin/reports/updates');
$this->clickLink(t('Install new module or theme'));
$this->assertUrl('admin/reports/updates/install');
}
}

View file

@ -0,0 +1,47 @@
<?php
namespace Drupal\update\Tests;
/**
* Tests the update_delete_file_if_stale() function.
*
* @group update
*/
class UpdateDeleteFileIfStaleTest extends UpdateTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('update');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
}
/**
* Tests the deletion of stale files.
*/
function testUpdateDeleteFileIfStale() {
$file_name = file_unmanaged_save_data($this->randomMachineName());
$this->assertNotNull($file_name);
// During testing the file change and the stale checking occurs in the same
// request, so the beginning of request will be before the file changes and
// REQUEST_TIME - $filectime is negative. Set the maximum age to a number
// even smaller than that.
$this->config('system.file')
->set('temporary_maximum_age', -100000)
->save();
$file_path = drupal_realpath($file_name);
update_delete_file_if_stale($file_path);
$this->assertFalse(is_file($file_path));
}
}

View file

@ -0,0 +1,83 @@
<?php
namespace Drupal\update\Tests;
use Drupal\Core\DrupalKernel;
use Drupal\Core\Url;
use Drupal\simpletest\WebTestBase;
/**
* Defines some shared functions used by all update tests.
*
* The overarching methodology of these tests is we need to compare a given
* state of installed modules and themes (e.g., version, project grouping,
* timestamps, etc) against a current state of what the release history XML
* files we fetch say is available. We have dummy XML files (in the
* core/modules/update/tests directory) that describe various scenarios of
* what's available for different test projects, and we have dummy .info file
* data (specified via hook_system_info_alter() in the update_test helper
* module) describing what's currently installed. Each test case defines a set
* of projects to install, their current state (via the
* 'update_test_system_info' variable) and the desired available update data
* (via the 'update_test_xml_map' variable), and then performs a series of
* assertions that the report matches our expectations given the specific
* initial state and availability scenario.
*/
abstract class UpdateTestBase extends WebTestBase {
protected function setUp() {
parent::setUp();
// Change the root path which Update Manager uses to install and update
// projects to be inside the testing site directory. See
// \Drupal\update\UpdateRootFactory::get() for equivalent changes to the
// test child site.
$request = \Drupal::request();
$update_root = $this->container->get('update.root') . '/' . DrupalKernel::findSitePath($request);
$this->container->set('update.root', $update_root);
\Drupal::setContainer($this->container);
// Create the directories within the root path within which the Update
// Manager will install projects.
foreach (drupal_get_updaters() as $updater_info) {
$updater = $updater_info['class'];
$install_directory = $update_root . '/' . $updater::getRootDirectoryRelativePath();
if (!is_dir($install_directory)) {
mkdir($install_directory);
}
}
}
/**
* Refreshes the update status based on the desired available update scenario.
*
* @param $xml_map
* Array that maps project names to availability scenarios to fetch. The key
* '#all' is used if a project-specific mapping is not defined.
* @param $url
* (optional) A string containing the URL to fetch update data from.
* Defaults to 'update-test'.
*
* @see Drupal\update_test\Controller\UpdateTestController::updateTest()
*/
protected function refreshUpdateStatus($xml_map, $url = 'update-test') {
// Tell the Update Manager module to fetch from the URL provided by
// update_test module.
$this->config('update.settings')->set('fetch.url', Url::fromUri('base:' . $url, array('absolute' => TRUE))->toString())->save();
// Save the map for UpdateTestController::updateTest() to use.
$this->config('update_test.settings')->set('xml_map', $xml_map)->save();
// Manually check the update status.
$this->drupalGet('admin/reports/updates');
$this->clickLink(t('Check manually'));
}
/**
* Runs a series of assertions that are applicable to all update statuses.
*/
protected function standardTests() {
$this->assertRaw('<h3>' . t('Drupal core') . '</h3>');
$this->assertRaw(\Drupal::l(t('Drupal'), Url::fromUri('http://example.com/project/drupal')), 'Link to the Drupal project appears.');
$this->assertNoText(t('No available releases found'));
}
}

View file

@ -0,0 +1,195 @@
<?php
namespace Drupal\update\Tests;
use Drupal\Core\Extension\InfoParserDynamic;
use Drupal\Core\Updater\Updater;
use Drupal\Core\Url;
/**
* Tests the Update Manager module's upload and extraction functionality.
*
* @group update
*/
class UpdateUploadTest extends UpdateTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('update', 'update_test');
protected function setUp() {
parent::setUp();
$admin_user = $this->drupalCreateUser(array('administer modules', 'administer software updates', 'administer site configuration'));
$this->drupalLogin($admin_user);
}
/**
* Tests upload, extraction, and update of a module.
*/
public function testUploadModule() {
// Ensure that the update information is correct before testing.
update_get_available(TRUE);
// Images are not valid archives, so get one and try to install it. We
// need an extra variable to store the result of drupalGetTestFiles()
// since reset() takes an argument by reference and passing in a constant
// emits a notice in strict mode.
$imageTestFiles = $this->drupalGetTestFiles('image');
$invalidArchiveFile = reset($imageTestFiles);
$edit = array(
'files[project_upload]' => $invalidArchiveFile->uri,
);
// This also checks that the correct archive extensions are allowed.
$this->drupalPostForm('admin/modules/install', $edit, t('Install'));
$this->assertText(t('Only files with the following extensions are allowed: @archive_extensions.', array('@archive_extensions' => archiver_get_extensions())), 'Only valid archives can be uploaded.');
$this->assertUrl('admin/modules/install');
// Check to ensure an existing module can't be reinstalled. Also checks that
// the archive was extracted since we can't know if the module is already
// installed until after extraction.
$validArchiveFile = __DIR__ . '/../../tests/aaa_update_test.tar.gz';
$edit = array(
'files[project_upload]' => $validArchiveFile,
);
$this->drupalPostForm('admin/modules/install', $edit, t('Install'));
$this->assertText(t('@module_name is already installed.', array('@module_name' => 'AAA Update test')), 'Existing module was extracted and not reinstalled.');
$this->assertUrl('admin/modules/install');
// Ensure that a new module can be extracted and installed.
$updaters = drupal_get_updaters();
$moduleUpdater = $updaters['module']['class'];
$installedInfoFilePath = $this->container->get('update.root') . '/' . $moduleUpdater::getRootDirectoryRelativePath() . '/update_test_new_module/update_test_new_module.info.yml';
$this->assertFalse(file_exists($installedInfoFilePath), 'The new module does not exist in the filesystem before it is installed with the Update Manager.');
$validArchiveFile = __DIR__ . '/../../tests/update_test_new_module/8.x-1.0/update_test_new_module.tar.gz';
$edit = array(
'files[project_upload]' => $validArchiveFile,
);
$this->drupalPostForm('admin/modules/install', $edit, t('Install'));
// Check that submitting the form takes the user to authorize.php.
$this->assertUrl('core/authorize.php');
$this->assertTitle('Update manager | Drupal');
// Check for a success message on the page, and check that the installed
// module now exists in the expected place in the filesystem.
$this->assertRaw(t('Installed %project_name successfully', array('%project_name' => 'update_test_new_module')));
$this->assertTrue(file_exists($installedInfoFilePath), 'The new module exists in the filesystem after it is installed with the Update Manager.');
// Ensure the links are relative to the site root and not
// core/authorize.php.
$this->assertLink(t('Install another module'));
$this->assertLinkByHref(Url::fromRoute('update.module_install')->toString());
$this->assertLink(t('Enable newly added modules'));
$this->assertLinkByHref(Url::fromRoute('system.modules_list')->toString());
$this->assertLink(t('Administration pages'));
$this->assertLinkByHref(Url::fromRoute('system.admin')->toString());
// Ensure we can reach the "Install another module" link.
$this->clickLink(t('Install another module'));
$this->assertResponse(200);
$this->assertUrl('admin/modules/install');
// Check that the module has the correct version before trying to update
// it. Since the module is installed in sites/simpletest, which only the
// child site has access to, standard module API functions won't find it
// when called here. To get the version, the info file must be parsed
// directly instead.
$info_parser = new InfoParserDynamic();
$info = $info_parser->parse($installedInfoFilePath);
$this->assertEqual($info['version'], '8.x-1.0');
// Enable the module.
$this->drupalPostForm('admin/modules', array('modules[Testing][update_test_new_module][enable]' => TRUE), t('Install'));
// Define the update XML such that the new module downloaded above needs an
// update from 8.x-1.0 to 8.x-1.1.
$update_test_config = $this->config('update_test.settings');
$system_info = array(
'update_test_new_module' => array(
'project' => 'update_test_new_module',
),
);
$update_test_config->set('system_info', $system_info)->save();
$xml_mapping = array(
'update_test_new_module' => '1_1',
);
$this->refreshUpdateStatus($xml_mapping);
// Run the updates for the new module.
$this->drupalPostForm('admin/reports/updates/update', array('projects[update_test_new_module]' => TRUE), t('Download these updates'));
$this->drupalPostForm(NULL, array('maintenance_mode' => FALSE), t('Continue'));
$this->assertText(t('Update was completed successfully.'));
$this->assertRaw(t('Installed %project_name successfully', array('%project_name' => 'update_test_new_module')));
// Parse the info file again to check that the module has been updated to
// 8.x-1.1.
$info = $info_parser->parse($installedInfoFilePath);
$this->assertEqual($info['version'], '8.x-1.1');
}
/**
* Ensures that archiver extensions are properly merged in the UI.
*/
function testFileNameExtensionMerging() {
$this->drupalGet('admin/modules/install');
// Make sure the bogus extension supported by update_test.module is there.
$this->assertPattern('/file extensions are supported:.*update-test-extension/', "Found 'update-test-extension' extension.");
// Make sure it didn't clobber the first option from core.
$this->assertPattern('/file extensions are supported:.*tar/', "Found 'tar' extension.");
}
/**
* Checks the messages on update manager pages when missing a security update.
*/
function testUpdateManagerCoreSecurityUpdateMessages() {
$setting = array(
'#all' => array(
'version' => '8.0.0',
),
);
$this->config('update_test.settings')
->set('system_info', $setting)
->set('xml_map', array('drupal' => '0.2-sec'))
->save();
$this->config('update.settings')
->set('fetch.url', Url::fromRoute('update_test.update_test')->setAbsolute()->toString())
->save();
// Initialize the update status.
$this->drupalGet('admin/reports/updates');
// Now, make sure none of the Update manager pages have duplicate messages
// about core missing a security update.
$this->drupalGet('admin/modules/install');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
$this->drupalGet('admin/modules/update');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
$this->drupalGet('admin/appearance/install');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
$this->drupalGet('admin/appearance/update');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
$this->drupalGet('admin/reports/updates/install');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
$this->drupalGet('admin/reports/updates/update');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
$this->drupalGet('admin/update/ready');
$this->assertNoText(t('There is a security update available for your version of Drupal.'));
}
/**
* Tests only an *.info.yml file are detected without supporting files.
*/
public function testUpdateDirectory() {
$type = Updater::getUpdaterFromDirectory(\Drupal::root() . '/core/modules/update/tests/modules/aaa_update_test');
$this->assertEqual($type, 'Drupal\\Core\\Updater\\Module', 'Detected a Module');
$type = Updater::getUpdaterFromDirectory(\Drupal::root() . '/core/modules/update/tests/themes/update_test_basetheme');
$this->assertEqual($type, 'Drupal\\Core\\Updater\\Theme', 'Detected a Theme.');
}
}

View file

@ -0,0 +1,120 @@
<?php
namespace Drupal\update;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\RequestException;
/**
* Fetches project information from remote locations.
*/
class UpdateFetcher implements UpdateFetcherInterface {
use DependencySerializationTrait;
/**
* URL to check for updates, if a given project doesn't define its own.
*/
const UPDATE_DEFAULT_URL = 'http://updates.drupal.org/release-history';
/**
* The fetch url configured in the update settings.
*
* @var string
*/
protected $fetchUrl;
/**
* The update settings
*
* @var \Drupal\Core\Config\Config
*/
protected $updateSettings;
/**
* The HTTP client to fetch the feed data with.
*
* @var \GuzzleHttp\ClientInterface
*/
protected $httpClient;
/**
* Constructs a UpdateFetcher.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory.
* @param \GuzzleHttp\ClientInterface $http_client
* A Guzzle client object.
*/
public function __construct(ConfigFactoryInterface $config_factory, ClientInterface $http_client) {
$this->fetchUrl = $config_factory->get('update.settings')->get('fetch.url');
$this->httpClient = $http_client;
$this->updateSettings = $config_factory->get('update.settings');
}
/**
* {@inheritdoc}
*/
public function fetchProjectData(array $project, $site_key = '') {
$url = $this->buildFetchUrl($project, $site_key);
$data = '';
try {
$data = (string) $this->httpClient
->get($url, array('headers' => array('Accept' => 'text/xml')))
->getBody();
}
catch (RequestException $exception) {
watchdog_exception('update', $exception);
}
return $data;
}
/**
* {@inheritdoc}
*/
public function buildFetchUrl(array $project, $site_key = '') {
$name = $project['name'];
$url = $this->getFetchBaseUrl($project);
$url .= '/' . $name . '/' . \Drupal::CORE_COMPATIBILITY;
// Only append usage information if we have a site key and the project is
// enabled. We do not want to record usage statistics for disabled projects.
if (!empty($site_key) && (strpos($project['project_type'], 'disabled') === FALSE)) {
// Append the site key.
$url .= (strpos($url, '?') !== FALSE) ? '&' : '?';
$url .= 'site_key=';
$url .= rawurlencode($site_key);
// Append the version.
if (!empty($project['info']['version'])) {
$url .= '&version=';
$url .= rawurlencode($project['info']['version']);
}
// Append the list of modules or themes enabled.
$list = array_keys($project['includes']);
$url .= '&list=';
$url .= rawurlencode(implode(',', $list));
}
return $url;
}
/**
* {@inheritdoc}
*/
public function getFetchBaseUrl($project) {
if (isset($project['info']['project status url'])) {
$url = $project['info']['project status url'];
}
else {
$url = $this->fetchUrl;
if (empty($url)) {
$url = static::UPDATE_DEFAULT_URL;
}
}
return $url;
}
}

View file

@ -0,0 +1,60 @@
<?php
namespace Drupal\update;
/**
* Fetches project information from remote locations.
*/
interface UpdateFetcherInterface {
/**
* Returns the base of the URL to fetch available update data for a project.
*
* @param array $project
* The array of project information from
* \Drupal\Update\UpdateManager::getProjects().
*
* @return string
* The base of the URL used for fetching available update data. This does
* not include the path elements to specify a particular project, version,
* site_key, etc.
*/
public function getFetchBaseUrl($project);
/**
* Retrieves the project information.
*
* @param array $project
* The array of project information from
* \Drupal\Update\UpdateManager::getProjects().
* @param string $site_key
* (optional) The anonymous site key hash. Defaults to an empty string.
*
* @return string
* The project information fetched as string. Empty string upon failure.
*/
public function fetchProjectData(array $project, $site_key = '');
/**
* Generates the URL to fetch information about project updates.
*
* This figures out the right URL to use, based on the project's .info.yml
* file and the global defaults. Appends optional query arguments when the
* site is configured to report usage stats.
*
* @param array $project
* The array of project information from
* \Drupal\Update\UpdateManager::getProjects().
* @param string $site_key
* (optional) The anonymous site key hash. Defaults to an empty string.
*
* @return string
* The URL for fetching information about updates to the specified project.
*
* @see \Drupal\update\UpdateProcessor::fetchData()
* @see \Drupal\update\UpdateProcessor::processFetchTask()
* @see \Drupal\update\UpdateManager::getProjects()
*/
public function buildFetchUrl(array $project, $site_key = '');
}

View file

@ -0,0 +1,226 @@
<?php
namespace Drupal\update;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Utility\ProjectInfo;
/**
* Default implementation of UpdateManagerInterface.
*/
class UpdateManager implements UpdateManagerInterface {
use DependencySerializationTrait;
use StringTranslationTrait;
/**
* The update settings
*
* @var \Drupal\Core\Config\Config
*/
protected $updateSettings;
/**
* Module Handler Service.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* Update Processor Service.
*
* @var \Drupal\update\UpdateProcessorInterface
*/
protected $updateProcessor;
/**
* An array of installed and enabled projects.
*
* @var array
*/
protected $projects;
/**
* The key/value store.
*
* @var \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
*/
protected $keyValueStore;
/**
* Update available releases key/value store.
*
* @var \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
*/
protected $availableReleasesTempStore;
/**
* The theme handler.
*
* @var \Drupal\Core\Extension\ThemeHandlerInterface
*/
protected $themeHandler;
/**
* Constructs a UpdateManager.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The Module Handler service
* @param \Drupal\update\UpdateProcessorInterface $update_processor
* The Update Processor service.
* @param \Drupal\Core\StringTranslation\TranslationInterface $translation
* The translation service.
* @param \Drupal\Core\KeyValueStore\KeyValueFactoryInterface $key_value_expirable_factory
* The expirable key/value factory.
* @param \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler
* The theme handler.
*/
public function __construct(ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, UpdateProcessorInterface $update_processor, TranslationInterface $translation, KeyValueFactoryInterface $key_value_expirable_factory, ThemeHandlerInterface $theme_handler) {
$this->updateSettings = $config_factory->get('update.settings');
$this->moduleHandler = $module_handler;
$this->updateProcessor = $update_processor;
$this->stringTranslation = $translation;
$this->keyValueStore = $key_value_expirable_factory->get('update');
$this->themeHandler = $theme_handler;
$this->availableReleasesTempStore = $key_value_expirable_factory->get('update_available_releases');
$this->projects = array();
}
/**
* {@inheritdoc}
*/
public function refreshUpdateData() {
// Since we're fetching new available update data, we want to clear
// of both the projects we care about, and the current update status of the
// site. We do *not* want to clear the cache of available releases just yet,
// since that data (even if it's stale) can be useful during
// \Drupal\Update\UpdateManager::getProjects(); for example, to modules
// that implement hook_system_info_alter() such as cvs_deploy.
$this->keyValueStore->delete('update_project_projects');
$this->keyValueStore->delete('update_project_data');
$projects = $this->getProjects();
// Now that we have the list of projects, we should also clear the available
// release data, since even if we fail to fetch new data, we need to clear
// out the stale data at this point.
$this->availableReleasesTempStore->deleteAll();
foreach ($projects as $project) {
$this->updateProcessor->createFetchTask($project);
}
}
/**
* {@inheritdoc}
*/
public function getProjects() {
if (empty($this->projects)) {
// Retrieve the projects from storage, if present.
$this->projects = $this->projectStorage('update_project_projects');
if (empty($this->projects)) {
// Still empty, so we have to rebuild.
$module_data = system_rebuild_module_data();
$theme_data = $this->themeHandler->rebuildThemeData();
$project_info = new ProjectInfo();
$project_info->processInfoList($this->projects, $module_data, 'module', TRUE);
$project_info->processInfoList($this->projects, $theme_data, 'theme', TRUE);
if ($this->updateSettings->get('check.disabled_extensions')) {
$project_info->processInfoList($this->projects, $module_data, 'module', FALSE);
$project_info->processInfoList($this->projects, $theme_data, 'theme', FALSE);
}
// Allow other modules to alter projects before fetching and comparing.
$this->moduleHandler->alter('update_projects', $this->projects);
// Store the site's project data for at most 1 hour.
$this->keyValueStore->setWithExpire('update_project_projects', $this->projects, 3600);
}
}
return $this->projects;
}
/**
* {@inheritdoc}
*/
public function projectStorage($key) {
$projects = array();
// On certain paths, we should clear the data and recompute the projects for
// update status of the site to avoid presenting stale information.
$route_names = array(
'update.theme_update',
'system.modules_list',
'system.theme_install',
'update.module_update',
'update.module_install',
'update.status',
'update.report_update',
'update.report_install',
'update.settings',
'system.status',
'update.manual_status',
'update.confirmation_page',
'system.themes_page',
);
if (in_array(\Drupal::routeMatch()->getRouteName(), $route_names)) {
$this->keyValueStore->delete($key);
}
else {
$projects = $this->keyValueStore->get($key, array());
}
return $projects;
}
/**
* {@inheritdoc}
*/
public function fetchDataBatch(&$context) {
if (empty($context['sandbox']['max'])) {
$context['finished'] = 0;
$context['sandbox']['max'] = $this->updateProcessor->numberOfQueueItems();
$context['sandbox']['progress'] = 0;
$context['message'] = $this->t('Checking available update data ...');
$context['results']['updated'] = 0;
$context['results']['failures'] = 0;
$context['results']['processed'] = 0;
}
// Grab another item from the fetch queue.
for ($i = 0; $i < 5; $i++) {
if ($item = $this->updateProcessor->claimQueueItem()) {
if ($this->updateProcessor->processFetchTask($item->data)) {
$context['results']['updated']++;
$context['message'] = $this->t('Checked available update data for %title.', array('%title' => $item->data['info']['name']));
}
else {
$context['message'] = $this->t('Failed to check available update data for %title.', array('%title' => $item->data['info']['name']));
$context['results']['failures']++;
}
$context['sandbox']['progress']++;
$context['results']['processed']++;
$context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
$this->updateProcessor->deleteQueueItem($item);
}
else {
// If the queue is currently empty, we're done. It's possible that
// another thread might have added new fetch tasks while we were
// processing this batch. In that case, the usual 'finished' math could
// get confused, since we'd end up processing more tasks that we thought
// we had when we started and initialized 'max' with numberOfItems(). By
// forcing 'finished' to be exactly 1 here, we ensure that batch
// processing is terminated.
$context['finished'] = 1;
return;
}
}
}
}

View file

@ -0,0 +1,102 @@
<?php
namespace Drupal\update;
/**
* Manages project update information.
*/
interface UpdateManagerInterface {
/**
* Fetches an array of installed and enabled projects.
*
* This is only responsible for generating an array of projects (taking into
* account projects that include more than one module or theme). Other
* information like the specific version and install type (official release,
* dev snapshot, etc) is handled later in update_process_project_info() since
* that logic is only required when preparing the status report, not for
* fetching the available release data.
*
* This array is fairly expensive to construct, since it involves a lot of
* disk I/O, so we store the results. However, since this is not the data
* about available updates fetched from the network, it is acceptable to
* invalidate it somewhat quickly. If we keep this data for very long, site
* administrators are more likely to see incorrect results if they upgrade to
* a newer version of a module or theme but do not visit certain pages that
* automatically clear this data.
*
* @return array
* An associative array of currently enabled projects keyed by the
* machine-readable project short name. Each project contains:
* - name: The machine-readable project short name.
* - info: An array with values from the main .info.yml file for this
* project.
* - name: The human-readable name of the project.
* - package: The package that the project is grouped under.
* - version: The version of the project.
* - project: The Drupal.org project name.
* - datestamp: The date stamp of the project's main .info.yml file.
* - _info_file_ctime: The maximum file change time for all of the
* .info.yml
* files included in this project.
* - datestamp: The date stamp when the project was released, if known.
* - includes: An associative array containing all projects included with
* this project, keyed by the machine-readable short name with the
* human-readable name as value.
* - project_type: The type of project. Allowed values are 'module' and
* 'theme'.
* - project_status: This indicates if the project is enabled and will
* always be TRUE, as the function only returns enabled projects.
*
* @see update_process_project_info()
* @see update_calculate_project_data()
* @see \Drupal\update\UpdateManager::projectStorage()
*/
public function getProjects();
/**
* Processes a step in batch for fetching available update data.
*
* @param array $context
* Reference to an array used for Batch API storage.
*/
public function fetchDataBatch(&$context);
/**
* Clears out all the available update data and initiates re-fetching.
*/
public function refreshUpdateData();
/**
* Retrieves update storage data or empties it.
*
* Two very expensive arrays computed by this module are the list of all
* installed modules and themes (and .info.yml data, project associations,
* etc), and the current status of the site relative to the currently
* available releases. These two arrays are stored and used whenever possible.
* The data is cleared whenever the administrator visits the status report,
* available updates report, or the module or theme administration pages,
* since we should always recompute the most current values on any of those
* pages.
*
* Note: while both of these arrays are expensive to compute (in terms of disk
* I/O and some fairly heavy CPU processing), neither of these is the actual
* data about available updates that we have to fetch over the network from
* updates.drupal.org. That information is stored in the
* 'update_available_releases' collection -- it needs to persist longer than 1
* hour and never get invalidated just by visiting a page on the site.
*
* @param string $key
* The key of data to return. Valid options are 'update_project_data' and
* 'update_project_projects'.
*
* @return array
* The stored value of the $projects array generated by
* update_calculate_project_data() or
* \Drupal\Update\UpdateManager::getProjects(), or an empty array when the
* storage is cleared.
* array when the storage is cleared.
*/
public function projectStorage($key);
}

View file

@ -0,0 +1,269 @@
<?php
namespace Drupal\update;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\KeyValueStore\KeyValueFactoryInterface;
use Drupal\Core\State\StateInterface;
use Drupal\Core\PrivateKey;
use Drupal\Core\Queue\QueueFactory;
/**
* Process project update information.
*/
class UpdateProcessor implements UpdateProcessorInterface {
/**
* The update settings
*
* @var \Drupal\Core\Config\Config
*/
protected $updateSettings;
/**
* The UpdateFetcher service.
*
* @var \Drupal\update\UpdateFetcherInterface
*/
protected $updateFetcher;
/**
* The update fetch queue.
*
* @var \Drupal\Core\Queue\QueueInterface
*/
protected $fetchQueue;
/**
* Update key/value store
*
* @var \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
*/
protected $tempStore;
/**
* Update Fetch Task Store
*
* @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface
*/
protected $fetchTaskStore;
/**
* Update available releases store
*
* @var \Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface
*/
protected $availableReleasesTempStore;
/**
* Array of release history URLs that we have failed to fetch
*
* @var array
*/
protected $failed;
/**
* The state service.
*
* @var \Drupal\Core\State\StateInterface
*/
protected $stateStore;
/**
* The private key.
*
* @var \Drupal\Core\PrivateKey
*/
protected $privateKey;
/**
* Constructs a UpdateProcessor.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory.
* @param \Drupal\Core\Queue\QueueFactory $queue_factory
* The queue factory
* @param \Drupal\update\UpdateFetcherInterface $update_fetcher
* The update fetcher service
* @param \Drupal\Core\State\StateInterface $state_store
* The state service.
* @param \Drupal\Core\PrivateKey $private_key
* The private key factory service.
* @param \Drupal\Core\KeyValueStore\KeyValueFactoryInterface $key_value_factory
* The key/value factory.
* @param \Drupal\Core\KeyValueStore\KeyValueFactoryInterface $key_value_expirable_factory
* The expirable key/value factory.
*/
public function __construct(ConfigFactoryInterface $config_factory, QueueFactory $queue_factory, UpdateFetcherInterface $update_fetcher, StateInterface $state_store, PrivateKey $private_key, KeyValueFactoryInterface $key_value_factory, KeyValueFactoryInterface $key_value_expirable_factory) {
$this->updateFetcher = $update_fetcher;
$this->updateSettings = $config_factory->get('update.settings');
$this->fetchQueue = $queue_factory->get('update_fetch_tasks');
$this->tempStore = $key_value_expirable_factory->get('update');
$this->fetchTaskStore = $key_value_factory->get('update_fetch_task');
$this->availableReleasesTempStore = $key_value_expirable_factory->get('update_available_releases');
$this->stateStore = $state_store;
$this->privateKey = $private_key;
$this->fetchTasks = array();
$this->failed = array();
}
/**
* {@inheritdoc}
*/
public function createFetchTask($project) {
if (empty($this->fetchTasks)) {
$this->fetchTasks = $this->fetchTaskStore->getAll();
}
if (empty($this->fetchTasks[$project['name']])) {
$this->fetchQueue->createItem($project);
$this->fetchTaskStore->set($project['name'], $project);
$this->fetchTasks[$project['name']] = REQUEST_TIME;
}
}
/**
* {@inheritdoc}
*/
public function fetchData() {
$end = time() + $this->updateSettings->get('fetch.timeout');
while (time() < $end && ($item = $this->fetchQueue->claimItem())) {
$this->processFetchTask($item->data);
$this->fetchQueue->deleteItem($item);
}
}
/**
* {@inheritdoc}
*/
public function processFetchTask($project) {
global $base_url;
// This can be in the middle of a long-running batch, so REQUEST_TIME won't
// necessarily be valid.
$request_time_difference = time() - REQUEST_TIME;
if (empty($this->failed)) {
// If we have valid data about release history XML servers that we have
// failed to fetch from on previous attempts, load that.
$this->failed = $this->tempStore->get('fetch_failures');
}
$max_fetch_attempts = $this->updateSettings->get('fetch.max_attempts');
$success = FALSE;
$available = array();
$site_key = Crypt::hmacBase64($base_url, $this->privateKey->get());
$fetch_url_base = $this->updateFetcher->getFetchBaseUrl($project);
$project_name = $project['name'];
if (empty($this->failed[$fetch_url_base]) || $this->failed[$fetch_url_base] < $max_fetch_attempts) {
$data = $this->updateFetcher->fetchProjectData($project, $site_key);
}
if (!empty($data)) {
$available = $this->parseXml($data);
// @todo: Purge release data we don't need. See
// https://www.drupal.org/node/238950.
if (!empty($available)) {
// Only if we fetched and parsed something sane do we return success.
$success = TRUE;
}
}
else {
$available['project_status'] = 'not-fetched';
if (empty($this->failed[$fetch_url_base])) {
$this->failed[$fetch_url_base] = 1;
}
else {
$this->failed[$fetch_url_base]++;
}
}
$frequency = $this->updateSettings->get('check.interval_days');
$available['last_fetch'] = REQUEST_TIME + $request_time_difference;
$this->availableReleasesTempStore->setWithExpire($project_name, $available, $request_time_difference + (60 * 60 * 24 * $frequency));
// Stash the $this->failed data back in the DB for the next 5 minutes.
$this->tempStore->setWithExpire('fetch_failures', $this->failed, $request_time_difference + (60 * 5));
// Whether this worked or not, we did just (try to) check for updates.
$this->stateStore->set('update.last_check', REQUEST_TIME + $request_time_difference);
// Now that we processed the fetch task for this project, clear out the
// record for this task so we're willing to fetch again.
$this->fetchTaskStore->delete($project_name);
return $success;
}
/**
* Parses the XML of the Drupal release history info files.
*
* @param string $raw_xml
* A raw XML string of available release data for a given project.
*
* @return array
* Array of parsed data about releases for a given project, or NULL if there
* was an error parsing the string.
*/
protected function parseXml($raw_xml) {
try {
$xml = new \SimpleXMLElement($raw_xml);
}
catch (\Exception $e) {
// SimpleXMLElement::__construct produces an E_WARNING error message for
// each error found in the XML data and throws an exception if errors
// were detected. Catch any exception and return failure (NULL).
return NULL;
}
// If there is no valid project data, the XML is invalid, so return failure.
if (!isset($xml->short_name)) {
return NULL;
}
$data = array();
foreach ($xml as $k => $v) {
$data[$k] = (string) $v;
}
$data['releases'] = array();
if (isset($xml->releases)) {
foreach ($xml->releases->children() as $release) {
$version = (string) $release->version;
$data['releases'][$version] = array();
foreach ($release->children() as $k => $v) {
$data['releases'][$version][$k] = (string) $v;
}
$data['releases'][$version]['terms'] = array();
if ($release->terms) {
foreach ($release->terms->children() as $term) {
if (!isset($data['releases'][$version]['terms'][(string) $term->name])) {
$data['releases'][$version]['terms'][(string) $term->name] = array();
}
$data['releases'][$version]['terms'][(string) $term->name][] = (string) $term->value;
}
}
}
}
return $data;
}
/**
* {@inheritdoc}
*/
public function numberOfQueueItems() {
return $this->fetchQueue->numberOfItems();
}
/**
* {@inheritdoc}
*/
public function claimQueueItem() {
return $this->fetchQueue->claimItem();
}
/**
* {@inheritdoc}
*/
public function deleteQueueItem($item) {
return $this->fetchQueue->deleteItem($item);
}
}

View file

@ -0,0 +1,82 @@
<?php
namespace Drupal\update;
/**
* Processor of project update information.
*/
interface UpdateProcessorInterface {
/**
* Claims an item in the update fetch queue for processing.
*
* @return bool|\stdClass
* On success we return an item object. If the queue is unable to claim an
* item it returns false.
*
* @see \Drupal\Core\Queue\QueueInterface::claimItem()
*/
public function claimQueueItem();
/**
* Attempts to drain the queue of tasks for release history data to fetch.
*/
public function fetchData();
/**
* Adds a task to the queue for fetching release history data for a project.
*
* We only create a new fetch task if there's no task already in the queue for
* this particular project (based on 'update_fetch_task' key-value
* collection).
*
* @param array $project
* Associative array of information about a project as created by
* \Drupal\Update\UpdateManager::getProjects(), including keys such as
* 'name' (short name), and the 'info' array with data from a .info.yml
* file for the project.
*
* @see \Drupal\update\UpdateManager::getProjects()
* @see update_get_available()
* @see \Drupal\update\UpdateManager::refreshUpdateData()
* @see \Drupal\update\UpdateProcessor::fetchData()
* @see \Drupal\update\UpdateProcessor::processFetchTask()
*/
public function createFetchTask($project);
/**
* Processes a task to fetch available update data for a single project.
*
* Once the release history XML data is downloaded, it is parsed and saved in
* an entry just for that project.
*
* @param array $project
* Associative array of information about the project to fetch data for.
*
* @return bool
* TRUE if we fetched parsable XML, otherwise FALSE.
*/
public function processFetchTask($project);
/**
* Retrieves the number of items in the update fetch queue.
*
* @return int
* An integer estimate of the number of items in the queue.
*
* @see \Drupal\Core\Queue\QueueInterface::numberOfItems()
*/
public function numberOfQueueItems();
/**
* Deletes a finished item from the update fetch queue.
*
* @param \stdClass $item
* The item returned by \Drupal\Core\Queue\QueueInterface::claimItem().
*
* @see \Drupal\Core\Queue\QueueInterface::deleteItem()
*/
public function deleteQueueItem($item);
}

View file

@ -0,0 +1,72 @@
<?php
namespace Drupal\update;
use Drupal\Core\DrupalKernelInterface;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Gets the root path used by the Update Manager to install or update projects.
*/
class UpdateRootFactory {
/**
* The Drupal kernel.
*
* @var \Drupal\Core\DrupalKernelInterface
*/
protected $drupalKernel;
/**
* The request stack.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* Constructs an UpdateRootFactory instance.
*
* @param \Drupal\Core\DrupalKernelInterface $drupal_kernel
* The Drupal kernel.
* @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
* The request stack.
*/
public function __construct(DrupalKernelInterface $drupal_kernel, RequestStack $request_stack) {
$this->drupalKernel = $drupal_kernel;
$this->requestStack = $request_stack;
}
/**
* Gets the root path under which projects are installed or updated.
*
* The Update Manager will ensure that project files can only be copied to
* specific subdirectories of this root path.
*
* @return string
*/
public function get() {
// Normally the Update Manager's root path is the same as the app root (the
// directory in which the Drupal site is installed).
$root_path = $this->drupalKernel->getAppRoot();
// When running in a test site, change the root path to be the testing site
// directory. This ensures that it will always be writable by the webserver
// (thereby allowing the actual extraction and installation of projects by
// the Update Manager to be tested) and also ensures that new project files
// added there won't be visible to the parent site and will be properly
// cleaned up once the test finishes running. This is done here (rather
// than having the tests enable a module which overrides the update root
// factory service) to ensure that the parent site is automatically kept
// clean without relying on test authors to take any explicit steps. See
// also \Drupal\update\Tests\UpdateTestBase::setUp().
if (DRUPAL_TEST_IN_CHILD_SITE) {
$kernel = $this->drupalKernel;
$request = $this->requestStack->getCurrentRequest();
$root_path .= '/' . $kernel::findSitePath($request);
}
return $root_path;
}
}

View file

@ -0,0 +1,156 @@
<?php
namespace Drupal\update;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Egulias\EmailValidator\EmailValidator;
/**
* Configure update settings for this site.
*/
class UpdateSettingsForm extends ConfigFormBase implements ContainerInjectionInterface {
/**
* The email validator.
*
* @var \Egulias\EmailValidator\EmailValidator
*/
protected $emailValidator;
/**
* Constructs a new UpdateSettingsForm.
*
* @param \Egulias\EmailValidator\EmailValidator $email_validator
* The email validator.
*/
public function __construct(EmailValidator $email_validator) {
$this->emailValidator = $email_validator;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('email.validator')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'update_settings';
}
/**
* {@inheritdoc}
*/
protected function getEditableConfigNames() {
return ['update.settings'];
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('update.settings');
$form['update_check_frequency'] = array(
'#type' => 'radios',
'#title' => t('Check for updates'),
'#default_value' => $config->get('check.interval_days'),
'#options' => array(
'1' => t('Daily'),
'7' => t('Weekly'),
),
'#description' => t('Select how frequently you want to automatically check for new releases of your currently installed modules and themes.'),
);
$form['update_check_disabled'] = array(
'#type' => 'checkbox',
'#title' => t('Check for updates of uninstalled modules and themes'),
'#default_value' => $config->get('check.disabled_extensions'),
);
$notification_emails = $config->get('notification.emails');
$form['update_notify_emails'] = array(
'#type' => 'textarea',
'#title' => t('Email addresses to notify when updates are available'),
'#rows' => 4,
'#default_value' => implode("\n", $notification_emails),
'#description' => t('Whenever your site checks for available updates and finds new releases, it can notify a list of users via email. Put each address on a separate line. If blank, no emails will be sent.'),
);
$form['update_notification_threshold'] = array(
'#type' => 'radios',
'#title' => t('Email notification threshold'),
'#default_value' => $config->get('notification.threshold'),
'#options' => array(
'all' => t('All newer versions'),
'security' => t('Only security updates'),
),
'#description' => t('You can choose to send email only if a security update is available, or to be notified about all newer versions. If there are updates available of Drupal core or any of your installed modules and themes, your site will always print a message on the <a href=":status_report">status report</a> page, and will also display an error message on administration pages if there is a security update.', array(':status_report' => $this->url('system.status')))
);
return parent::buildForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$form_state->set('notify_emails', []);
if (!$form_state->isValueEmpty('update_notify_emails')) {
$valid = array();
$invalid = array();
foreach (explode("\n", trim($form_state->getValue('update_notify_emails'))) as $email) {
$email = trim($email);
if (!empty($email)) {
if ($this->emailValidator->isValid($email)) {
$valid[] = $email;
}
else {
$invalid[] = $email;
}
}
}
if (empty($invalid)) {
$form_state->set('notify_emails', $valid);
}
elseif (count($invalid) == 1) {
$form_state->setErrorByName('update_notify_emails', $this->t('%email is not a valid email address.', array('%email' => reset($invalid))));
}
else {
$form_state->setErrorByName('update_notify_emails', $this->t('%emails are not valid email addresses.', array('%emails' => implode(', ', $invalid))));
}
}
parent::validateForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$config = $this->config('update.settings');
// See if the update_check_disabled setting is being changed, and if so,
// invalidate all update status data.
if ($form_state->getValue('update_check_disabled') != $config->get('check.disabled_extensions')) {
update_storage_clear();
}
$config
->set('check.disabled_extensions', $form_state->getValue('update_check_disabled'))
->set('check.interval_days', $form_state->getValue('update_check_frequency'))
->set('notification.emails', $form_state->get('notify_emails'))
->set('notification.threshold', $form_state->getValue('update_notification_threshold'))
->save();
parent::submitForm($form, $form_state);
}
}