first commit
This commit is contained in:
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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 = [
|
||||
'#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 = [
|
||||
'operations' => [
|
||||
[[$this->updateManager, 'fetchDataBatch'], []],
|
||||
],
|
||||
'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');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\update\Form;
|
||||
|
||||
use Drupal\Core\Archiver\ArchiverManager;
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use Drupal\Core\File\FileSystemInterface;
|
||||
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.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
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;
|
||||
|
||||
/**
|
||||
* The archiver plugin manager service.
|
||||
*
|
||||
* @var \Drupal\Core\Archiver\ArchiverManager
|
||||
*/
|
||||
protected $archiverManager;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @param \Drupal\Core\Archiver\ArchiverManager $archiver_manager
|
||||
* The archiver plugin manager service.
|
||||
*/
|
||||
public function __construct($root, ModuleHandlerInterface $module_handler, $site_path, ArchiverManager $archiver_manager) {
|
||||
$this->root = $root;
|
||||
$this->moduleHandler = $module_handler;
|
||||
$this->sitePath = $site_path;
|
||||
$this->archiverManager = $archiver_manager;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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'),
|
||||
$container->get('plugin.manager.archiver')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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'] = [
|
||||
'#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.', [
|
||||
':module_url' => 'https://www.drupal.org/project/modules',
|
||||
':theme_url' => 'https://www.drupal.org/project/themes',
|
||||
':drupal_org_url' => 'https://www.drupal.org',
|
||||
'%extensions' => $this->archiverManager->getExtensions(),
|
||||
]),
|
||||
'#suffix' => '</p>',
|
||||
];
|
||||
|
||||
$form['project_url'] = [
|
||||
'#type' => 'url',
|
||||
'#title' => $this->t('Install from a URL'),
|
||||
'#description' => $this->t('For example: %url', ['%url' => 'https://ftp.drupal.org/files/projects/name.tar.gz']),
|
||||
];
|
||||
|
||||
$form['information'] = [
|
||||
'#prefix' => '<strong>',
|
||||
'#markup' => $this->t('Or'),
|
||||
'#suffix' => '</strong>',
|
||||
];
|
||||
|
||||
$form['project_upload'] = [
|
||||
'#type' => 'file',
|
||||
'#title' => $this->t('Upload a module or theme archive to install'),
|
||||
'#description' => $this->t('For example: %filename from your local computer', ['%filename' => 'name.tar.gz']),
|
||||
];
|
||||
|
||||
$form['actions'] = ['#type' => 'actions'];
|
||||
$form['actions']['submit'] = [
|
||||
'#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;
|
||||
$all_files = $this->getRequest()->files->get('files', []);
|
||||
if ($form_state->getValue('project_url')) {
|
||||
$local_cache = update_manager_file_get($form_state->getValue('project_url'));
|
||||
if (!$local_cache) {
|
||||
$this->messenger()->addError($this->t('Unable to retrieve Drupal project from %url.', ['%url' => $form_state->getValue('project_url')]));
|
||||
return;
|
||||
}
|
||||
}
|
||||
elseif (!empty($all_files['project_upload'])) {
|
||||
$validators = ['file_validate_extensions' => [$this->archiverManager->getExtensions()]];
|
||||
if (!($finfo = file_save_upload('project_upload', $validators, NULL, 0, FileSystemInterface::EXISTS_REPLACE))) {
|
||||
// Failed to upload the file. file_save_upload() calls
|
||||
// \Drupal\Core\Messenger\MessengerInterface::addError() on failure.
|
||||
return;
|
||||
}
|
||||
$local_cache = $finfo->getFileUri();
|
||||
}
|
||||
|
||||
$directory = _update_manager_extract_directory();
|
||||
try {
|
||||
$archive = update_manager_archive_extract($local_cache, $directory);
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
$this->messenger()->addError($e->getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
$files = $archive->listContents();
|
||||
if (!$files) {
|
||||
$this->messenger()->addError($this->t('Provided archive contains no files.'));
|
||||
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', [$project, $local_cache, $directory]);
|
||||
if (!empty($archive_errors)) {
|
||||
$this->messenger()->addError(array_shift($archive_errors));
|
||||
// @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) {
|
||||
$this->messenger()->addError($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) {
|
||||
$this->messenger()->addError($e->getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$project_title = Updater::getProjectTitle($project_location);
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
$this->messenger()->addError($e->getMessage());
|
||||
return;
|
||||
}
|
||||
|
||||
if (!$project_title) {
|
||||
$this->messenger()->addError($this->t('Unable to determine %project name.', ['%project' => $project]));
|
||||
}
|
||||
|
||||
if ($updater->isInstalled()) {
|
||||
$this->messenger()->addError($this->t('%project is already installed.', ['%project' => $project_title]));
|
||||
return;
|
||||
}
|
||||
|
||||
$project_real_location = \Drupal::service('file_system')->realpath($project_location);
|
||||
$arguments = [
|
||||
'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, \Drupal::service('file_system'));
|
||||
$response = call_user_func_array('update_authorize_run_install', array_merge([$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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\update\Form;
|
||||
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use Drupal\Core\Form\FormBase;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Link;
|
||||
use Drupal\Core\State\StateInterface;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\update\UpdateFetcherInterface;
|
||||
use Drupal\update\UpdateManagerInterface;
|
||||
use Drupal\update\ModuleVersion;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Configure update settings for this site.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
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 = [
|
||||
'#theme' => 'update_last_check',
|
||||
'#last' => $this->state->get('update.last_check') ?: 0,
|
||||
];
|
||||
$form['last_check'] = [
|
||||
'#markup' => \Drupal::service('renderer')->render($last_markup),
|
||||
];
|
||||
|
||||
if (!_update_manager_check_backends($form, 'update')) {
|
||||
return $form;
|
||||
}
|
||||
|
||||
$available = update_get_available(TRUE);
|
||||
if (empty($available)) {
|
||||
$form['message'] = [
|
||||
'#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 = [];
|
||||
|
||||
// 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'] = ['#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'] == UpdateManagerInterface::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 = Link::fromTextAndUrl($project['title'], Url::fromUri($project['link']))->toString();
|
||||
}
|
||||
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>)';
|
||||
$recommended_version_parser = ModuleVersion::createFromVersionString($recommended_release['version']);
|
||||
if ($recommended_version_parser->getMajorVersion() != $project['existing_major']) {
|
||||
$recommended_version .= '<div title="{{ major_update_warning_title }}" class="update-major-version-warning">{{ major_update_warning_text }}</div>';
|
||||
}
|
||||
|
||||
$recommended_version = [
|
||||
'#type' => 'inline_template',
|
||||
'#template' => $recommended_version,
|
||||
'#context' => [
|
||||
'release_version' => $recommended_release['version'],
|
||||
'release_link' => $recommended_release['release_link'],
|
||||
'project_title' => $this->t('Release notes for @project_title', ['@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 = [
|
||||
'title' => $project_name,
|
||||
'installed_version' => $project['existing_version'],
|
||||
'recommended_version' => ['data' => $recommended_version],
|
||||
];
|
||||
|
||||
switch ($project['status']) {
|
||||
case UpdateManagerInterface::NOT_SECURE:
|
||||
case UpdateManagerInterface::REVOKED:
|
||||
$entry['title'] .= ' ' . $this->t('(Security update)');
|
||||
$entry['#weight'] = -2;
|
||||
$type = 'security';
|
||||
break;
|
||||
|
||||
case UpdateManagerInterface::NOT_SUPPORTED:
|
||||
$type = 'unsupported';
|
||||
$entry['title'] .= ' ' . $this->t('(Unsupported)');
|
||||
$entry['#weight'] = -1;
|
||||
break;
|
||||
|
||||
case UpdateFetcherInterface::UNKNOWN:
|
||||
case UpdateFetcherInterface::NOT_FETCHED:
|
||||
case UpdateFetcherInterface::NOT_CHECKED:
|
||||
case UpdateManagerInterface::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'] = [
|
||||
'data' => [
|
||||
'#title' => $entry['title'],
|
||||
'#markup' => $entry['title'],
|
||||
],
|
||||
];
|
||||
$entry['#attributes'] = ['class' => ['update-' . $type]];
|
||||
|
||||
// Drupal core needs to be upgraded manually.
|
||||
$needs_manual = $project['project_type'] == 'core';
|
||||
|
||||
// If the recommended release for a contributed project is not compatible
|
||||
// with the currently installed version of core, list that project in a
|
||||
// separate table. To determine if the release is compatible, we inspect
|
||||
// the 'core_compatible' key from the release info array. If it's not
|
||||
// defined, it means we can't determine compatibility requirements (or
|
||||
// we're looking at core), so we assume it is compatible.
|
||||
$compatible = $recommended_release['core_compatible'] ?? TRUE;
|
||||
|
||||
if ($needs_manual) {
|
||||
$this->removeCheckboxFromRow($entry);
|
||||
$projects['manual'][$name] = $entry;
|
||||
}
|
||||
elseif (!$compatible) {
|
||||
$this->removeCheckboxFromRow($entry);
|
||||
// If the release has a core_compatibility_message, inject it.
|
||||
if (!empty($recommended_release['core_compatibility_message'])) {
|
||||
// @todo In https://www.drupal.org/project/drupal/issues/3121769
|
||||
// refactor this into something theme-friendly so we don't have a
|
||||
// classless <div> here.
|
||||
$entry['data']['recommended_version']['data']['#template'] .= ' <div>{{ core_compatibility_message }}</div>';
|
||||
$entry['data']['recommended_version']['data']['#context']['core_compatibility_message'] = $recommended_release['core_compatibility_message'];
|
||||
}
|
||||
$projects['not-compatible'][$name] = $entry;
|
||||
}
|
||||
else {
|
||||
$form['project_downloads'][$name] = [
|
||||
'#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 'module':
|
||||
case 'theme':
|
||||
$projects['enabled'][$name] = $entry;
|
||||
break;
|
||||
|
||||
case 'module-disabled':
|
||||
case 'theme-disabled':
|
||||
$projects['disabled'][$name] = $entry;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($projects)) {
|
||||
$form['message'] = [
|
||||
'#markup' => $this->t('All of your projects are up to date.'),
|
||||
];
|
||||
return $form;
|
||||
}
|
||||
|
||||
$headers = [
|
||||
'title' => [
|
||||
'data' => $this->t('Name'),
|
||||
'class' => ['update-project-name'],
|
||||
],
|
||||
'installed_version' => $this->t('Installed version'),
|
||||
'recommended_version' => $this->t('Recommended version'),
|
||||
];
|
||||
|
||||
if (!empty($projects['enabled'])) {
|
||||
$form['projects'] = [
|
||||
'#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'] = [
|
||||
'#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'] = ['#type' => 'actions'];
|
||||
$form['actions']['submit'] = [
|
||||
'#type' => 'submit',
|
||||
'#value' => $this->t('Download these updates'),
|
||||
];
|
||||
}
|
||||
|
||||
if (!empty($projects['manual'])) {
|
||||
$prefix = '<h2>' . $this->t('Manual updates required') . '</h2>';
|
||||
$prefix .= '<p>' . $this->t('Automatic updates of Drupal core are not supported at this time.') . '</p>';
|
||||
$form['manual_updates'] = [
|
||||
'#type' => 'table',
|
||||
'#header' => $headers,
|
||||
'#rows' => $projects['manual'],
|
||||
'#prefix' => $prefix,
|
||||
'#weight' => 120,
|
||||
];
|
||||
}
|
||||
|
||||
if (!empty($projects['not-compatible'])) {
|
||||
$form['not_compatible'] = [
|
||||
'#type' => 'table',
|
||||
'#header' => $headers,
|
||||
'#rows' => $projects['not-compatible'],
|
||||
'#prefix' => '<h2>' . $this->t('Not compatible') . '</h2>',
|
||||
'#weight' => 150,
|
||||
];
|
||||
}
|
||||
|
||||
return $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares a row entry for use in a regular table, not a 'tableselect'.
|
||||
*
|
||||
* There are no checkboxes in the 'Manual updates' or 'Not compatible' tables,
|
||||
* so they will be rendered by '#theme' => 'table', not 'tableselect'. Since
|
||||
* the data formats are incompatible, this method converts to the format
|
||||
* expected by '#theme' => 'table'. Generally, rows end up in the main tables
|
||||
* that have a checkbox to allow the site admin to select which missing
|
||||
* updates to install. This method is only used for the special case tables
|
||||
* that have no such checkbox.
|
||||
*
|
||||
* @todo In https://www.drupal.org/project/drupal/issues/3121775 refactor
|
||||
* self::buildForm() so that we don't need this method at all.
|
||||
*
|
||||
* @param array[] $row
|
||||
* The render array for a table row.
|
||||
*/
|
||||
protected function removeCheckboxFromRow(array &$row) {
|
||||
unset($row['#weight']);
|
||||
$attributes = $row['#attributes'];
|
||||
unset($row['#attributes']);
|
||||
$row = [
|
||||
'data' => $row,
|
||||
] + $attributes;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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 = [];
|
||||
foreach (['projects', 'disabled_projects'] as $type) {
|
||||
if (!$form_state->isValueEmpty($type)) {
|
||||
$projects = array_merge($projects, array_keys(array_filter($form_state->getValue($type))));
|
||||
}
|
||||
}
|
||||
$operations = [];
|
||||
foreach ($projects as $project) {
|
||||
$operations[] = [
|
||||
'update_manager_batch_project_get',
|
||||
[
|
||||
$project,
|
||||
$form_state->getValue(['project_downloads', $project]),
|
||||
],
|
||||
];
|
||||
}
|
||||
$batch = [
|
||||
'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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
<?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.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
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'] = [
|
||||
'#prefix' => '<strong>',
|
||||
'#markup' => $this->t('Back up your database and site before you continue. <a href=":backup_url">Learn how</a>.', [':backup_url' => 'https://www.drupal.org/node/22281']),
|
||||
'#suffix' => '</strong>',
|
||||
];
|
||||
|
||||
$form['maintenance_mode'] = [
|
||||
'#title' => $this->t('Perform updates with site in maintenance mode (strongly recommended)'),
|
||||
'#type' => 'checkbox',
|
||||
'#default_value' => TRUE,
|
||||
];
|
||||
|
||||
$form['actions'] = ['#type' => 'actions'];
|
||||
$form['actions']['submit'] = [
|
||||
'#type' => 'submit',
|
||||
'#value' => $this->t('Continue'),
|
||||
];
|
||||
|
||||
return $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitForm(array &$form, FormStateInterface $form_state) {
|
||||
$session = $this->getRequest()->getSession();
|
||||
// Store maintenance_mode setting so we can restore it when done.
|
||||
$session->set('maintenance_mode', $this->state->get('system.maintenance_mode'));
|
||||
if ($form_state->getValue('maintenance_mode') == TRUE) {
|
||||
$this->state->set('system.maintenance_mode', TRUE);
|
||||
}
|
||||
|
||||
$projects = $session->remove('update_manager_update_projects');
|
||||
if ($projects) {
|
||||
// Make sure the Updater registry is loaded.
|
||||
drupal_get_updaters();
|
||||
|
||||
$updates = [];
|
||||
$directory = _update_manager_extract_directory();
|
||||
|
||||
$project_real_location = NULL;
|
||||
foreach ($projects as $project => $url) {
|
||||
$project_location = $directory . '/' . $project;
|
||||
$updater = Updater::factory($project_location, $this->root);
|
||||
$project_real_location = \Drupal::service('file_system')->realpath($project_location);
|
||||
$updates[] = [
|
||||
'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, \Drupal::service('file_system'));
|
||||
$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', [$updates], $this->t('Update manager'));
|
||||
$form_state->setRedirectUrl(system_authorized_get_url());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\update;
|
||||
|
||||
/**
|
||||
* Provides a module version value object.
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
* @see https://www.drupal.org/drupalorg/docs/apis/update-status-xml.
|
||||
*/
|
||||
final class ModuleVersion {
|
||||
|
||||
/**
|
||||
* The '8.x-' prefix is used on contrib module version numbers.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
const CORE_PREFIX = '8.x-';
|
||||
|
||||
/**
|
||||
* The major version.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $majorVersion;
|
||||
|
||||
/**
|
||||
* The version extra string.
|
||||
*
|
||||
* For example, if the module version is '2.0.3-alpha1', then the version
|
||||
* extra string is 'alpha1'.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $versionExtra;
|
||||
|
||||
/**
|
||||
* Constructs a module version object from a version string.
|
||||
*
|
||||
* @param string $version_string
|
||||
* The version string.
|
||||
*
|
||||
* @return \Drupal\update\ModuleVersion
|
||||
* The module version instance.
|
||||
*/
|
||||
public static function createFromVersionString($version_string) {
|
||||
$original_version = $version_string;
|
||||
if (strpos($version_string, static::CORE_PREFIX) === 0 && $version_string !== '8.x-dev') {
|
||||
$version_string = preg_replace('/8\.x-/', '', $version_string, 1);
|
||||
}
|
||||
else {
|
||||
// Ensure the version string has no unsupported core prefixes.
|
||||
$dot_x_position = strpos($version_string, '.x-');
|
||||
if ($dot_x_position === 1 || $dot_x_position === 2) {
|
||||
$after_core_prefix = explode('.x-', $version_string)[1];
|
||||
if ($after_core_prefix !== 'dev') {
|
||||
throw new \UnexpectedValueException("Unexpected version core prefix in $version_string. The only core prefix expected in \Drupal\update\ModuleVersion is: 8.x-");
|
||||
}
|
||||
}
|
||||
}
|
||||
$version_parts = explode('.', $version_string);
|
||||
$major_version = $version_parts[0];
|
||||
$version_parts_count = count($version_parts);
|
||||
$last_part_split = explode('-', $version_parts[count($version_parts) - 1]);
|
||||
$version_extra = count($last_part_split) === 1 ? NULL : $last_part_split[1];
|
||||
if ($version_parts_count > 3 || $version_parts_count < 2
|
||||
|| !is_numeric($major_version)
|
||||
|| ($version_parts_count === 3 && !is_numeric($version_parts[1]))
|
||||
// The only case where a non-numeric version part other the extra part is
|
||||
// allowed is in development versions like 8.x-1.x-dev, 1.2.x-dev or
|
||||
// 1.x-dev.
|
||||
|| (!is_numeric($last_part_split[0]) && $last_part_split !== 'x' && $version_extra !== 'dev')) {
|
||||
throw new \UnexpectedValueException("Unexpected version number in: $original_version");
|
||||
}
|
||||
return new static($major_version, $version_extra);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a ModuleVersion object.
|
||||
*
|
||||
* @param string $major_version
|
||||
* The major version.
|
||||
* @param string|null $version_extra
|
||||
* The extra version string.
|
||||
*/
|
||||
private function __construct($major_version, $version_extra) {
|
||||
$this->majorVersion = $major_version;
|
||||
$this->versionExtra = $version_extra;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a module version object from a support branch.
|
||||
*
|
||||
* This can be used to determine the major version of the branch.
|
||||
* ::getVersionExtra() will always return NULL for branches.
|
||||
*
|
||||
* @param string $branch
|
||||
* The support branch.
|
||||
*
|
||||
* @return \Drupal\update\ModuleVersion
|
||||
* The module version instance.
|
||||
*/
|
||||
public static function createFromSupportBranch($branch) {
|
||||
if (substr($branch, -1) !== '.') {
|
||||
throw new \UnexpectedValueException("Invalid support branch: $branch");
|
||||
}
|
||||
return static::createFromVersionString($branch . '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the major version.
|
||||
*
|
||||
* @return string
|
||||
* The major version.
|
||||
*/
|
||||
public function getMajorVersion() {
|
||||
return $this->majorVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the version extra string at the end of the version number.
|
||||
*
|
||||
* @return string|null
|
||||
* The version extra string if available, or otherwise NULL.
|
||||
*/
|
||||
public function getVersionExtra() {
|
||||
return $this->versionExtra;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\update;
|
||||
|
||||
use Composer\Semver\Semver;
|
||||
use Composer\Semver\VersionParser;
|
||||
use Drupal\Core\StringTranslation\StringTranslationTrait;
|
||||
|
||||
/**
|
||||
* Utility class to set core compatibility messages for project releases.
|
||||
*
|
||||
* @internal
|
||||
* This class implements logic used by update_calculate_project_status(). It
|
||||
* should not be called directly.
|
||||
*/
|
||||
final class ProjectCoreCompatibility {
|
||||
|
||||
use StringTranslationTrait;
|
||||
|
||||
/**
|
||||
* The currently installed version of Drupal core.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $existingCoreVersion;
|
||||
|
||||
/**
|
||||
* Cache of core versions that are available for updates.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected $possibleCoreUpdateVersions;
|
||||
|
||||
/**
|
||||
* Cache of core compatibility messages per core version constraint.
|
||||
*
|
||||
* Keys are core version constraint strings, values are human-readable
|
||||
* messages about the versions of core that version constraint maps to.
|
||||
*
|
||||
* This list is cached since many project releases will use the same core
|
||||
* compatibility constraint.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected $compatibilityMessages = [];
|
||||
|
||||
/**
|
||||
* Constructs a ProjectCoreCompatibility object.
|
||||
*
|
||||
* @param array $core_data
|
||||
* The project data for Drupal core as returned by
|
||||
* \Drupal\update\UpdateManagerInterface::getProjects() and then processed
|
||||
* by update_process_project_info() and
|
||||
* update_calculate_project_update_status().
|
||||
* @param array $core_releases
|
||||
* The Drupal core available releases.
|
||||
*
|
||||
* @see \Drupal\update\UpdateManagerInterface::getProjects()
|
||||
* @see update_process_project_info()
|
||||
* @see update_calculate_project_update_status()
|
||||
*/
|
||||
public function __construct(array $core_data, array $core_releases) {
|
||||
if (isset($core_data['existing_version'])) {
|
||||
$this->existingCoreVersion = $core_data['existing_version'];
|
||||
$this->possibleCoreUpdateVersions = $this->getPossibleCoreUpdateVersions($core_releases);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the core versions that should be considered for compatibility ranges.
|
||||
*
|
||||
* @param array $core_releases
|
||||
* The Drupal core available releases.
|
||||
*
|
||||
* @return string[]
|
||||
* The core version numbers that are possible to update the site to.
|
||||
*/
|
||||
protected function getPossibleCoreUpdateVersions(array $core_releases) {
|
||||
if (!isset($core_releases[$this->existingCoreVersion])) {
|
||||
// If we can't determine the existing version of core then we can't
|
||||
// calculate the core compatibility of a given release based on core
|
||||
// versions after the existing version.
|
||||
return [];
|
||||
}
|
||||
$core_release_versions = array_keys($core_releases);
|
||||
$possible_core_update_versions = Semver::satisfiedBy($core_release_versions, '>= ' . $this->existingCoreVersion);
|
||||
$possible_core_update_versions = Semver::sort($possible_core_update_versions);
|
||||
$possible_core_update_versions = array_filter($possible_core_update_versions, function ($version) {
|
||||
return VersionParser::parseStability($version) === 'stable';
|
||||
});
|
||||
return $possible_core_update_versions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets core compatibility messages for project releases.
|
||||
*
|
||||
* @param array &$project_data
|
||||
* The project data as returned by
|
||||
* \Drupal\update\UpdateManagerInterface::getProjects() and then processed
|
||||
* by update_process_project_info() and
|
||||
* update_calculate_project_update_status(). If set, the following keys are
|
||||
* used in this method:
|
||||
* - recommended (string): A project version number.
|
||||
* - latest_version (string): A project version number.
|
||||
* - also (string[]): Project version numbers.
|
||||
* - releases (array[]): An array where the keys are project version numbers
|
||||
* and the values are arrays of project release information.
|
||||
* - security updates (array[]): An array of project release information.
|
||||
*
|
||||
* @see \Drupal\update\UpdateManagerInterface::getProjects()
|
||||
* @see update_process_project_info()
|
||||
* @see update_calculate_project_update_status()
|
||||
*/
|
||||
public function setReleaseMessage(array &$project_data) {
|
||||
if (empty($this->possibleCoreUpdateVersions)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the various releases that will need to have core compatibility
|
||||
// messages added to them.
|
||||
$releases_to_set = [];
|
||||
$versions = [];
|
||||
if (!empty($project_data['recommended'])) {
|
||||
$versions[] = $project_data['recommended'];
|
||||
}
|
||||
if (!empty($project_data['latest_version'])) {
|
||||
$versions[] = $project_data['latest_version'];
|
||||
}
|
||||
if (!empty($project_data['also'])) {
|
||||
$versions = array_merge($versions, $project_data['also']);
|
||||
}
|
||||
foreach ($versions as $version) {
|
||||
if (isset($project_data['releases'][$version])) {
|
||||
$releases_to_set[] = &$project_data['releases'][$version];
|
||||
}
|
||||
}
|
||||
if (!empty($project_data['security updates'])) {
|
||||
foreach ($project_data['security updates'] as &$security_update) {
|
||||
$releases_to_set[] = &$security_update;
|
||||
}
|
||||
}
|
||||
foreach ($releases_to_set as &$release) {
|
||||
if (!empty($release['core_compatibility'])) {
|
||||
$release['core_compatible'] = $this->isCoreCompatible($release['core_compatibility']);
|
||||
$release['core_compatibility_message'] = $this->createMessageFromCoreCompatibility($release['core_compatibility']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a release is compatible with the currently installed core.
|
||||
*
|
||||
* @param string $core_compatibility_constraint
|
||||
* A semantic version constraint.
|
||||
*
|
||||
* @return bool
|
||||
* TRUE if the given constraint is satisfied by the currently installed
|
||||
* version of Drupal core, otherwise FALSE.
|
||||
*/
|
||||
protected function isCoreCompatible($core_compatibility_constraint) {
|
||||
return Semver::satisfies($this->existingCoreVersion, $core_compatibility_constraint);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates core a compatibility message from a semantic version constraint.
|
||||
*
|
||||
* @param string $core_compatibility_constraint
|
||||
* A semantic version constraint.
|
||||
*
|
||||
* @return string
|
||||
* The core compatibility message.
|
||||
*/
|
||||
protected function createMessageFromCoreCompatibility($core_compatibility_constraint) {
|
||||
if (!isset($this->compatibilityMessages[$core_compatibility_constraint])) {
|
||||
$core_compatibility_ranges = $this->getCompatibilityRanges($core_compatibility_constraint);
|
||||
$range_messages = [];
|
||||
foreach ($core_compatibility_ranges as $core_compatibility_range) {
|
||||
if (count($core_compatibility_range) === 2) {
|
||||
$range_messages[] = $this->t('@low_version_number to @high_version_number', ['@low_version_number' => $core_compatibility_range[0], '@high_version_number' => $core_compatibility_range[1]]);
|
||||
}
|
||||
else {
|
||||
$range_messages[] = $core_compatibility_range[0];
|
||||
}
|
||||
}
|
||||
$this->compatibilityMessages[$core_compatibility_constraint] = $this->t('Requires Drupal core:') . ' ' . implode(', ', $range_messages);
|
||||
}
|
||||
return $this->compatibilityMessages[$core_compatibility_constraint];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the compatibility ranges for a semantic version constraint.
|
||||
*
|
||||
* @param string $core_compatibility_constraint
|
||||
* A semantic version constraint.
|
||||
*
|
||||
* @return array[]
|
||||
* An array compatibility ranges. If a range array has 2 elements then this
|
||||
* denotes a range of compatibility between and including the 2 versions. If
|
||||
* the range has 1 element then it denotes compatibility with a single
|
||||
* version.
|
||||
*/
|
||||
protected function getCompatibilityRanges($core_compatibility_constraint) {
|
||||
$compatibility_ranges = [];
|
||||
foreach ($this->possibleCoreUpdateVersions as $possible_core_update_version) {
|
||||
if (Semver::satisfies($possible_core_update_version, $core_compatibility_constraint)) {
|
||||
if (empty($range)) {
|
||||
$range[] = $possible_core_update_version;
|
||||
}
|
||||
else {
|
||||
$range[1] = $possible_core_update_version;
|
||||
}
|
||||
}
|
||||
else {
|
||||
// If core version does not satisfy the constraint and there is a non
|
||||
// empty range, add it to the list of ranges.
|
||||
if (!empty($range)) {
|
||||
$compatibility_ranges[] = $range;
|
||||
// Start a new range.
|
||||
$range = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!empty($range)) {
|
||||
$compatibility_ranges[] = $range;
|
||||
}
|
||||
return $compatibility_ranges;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\update;
|
||||
|
||||
/**
|
||||
* Calculates a project's security coverage information.
|
||||
*
|
||||
* @internal
|
||||
* This class implements logic to determine security coverage for Drupal core
|
||||
* according to Drupal core security policy. It should not be called directly.
|
||||
*/
|
||||
final class ProjectSecurityData {
|
||||
|
||||
/**
|
||||
* The number of minor versions of Drupal core that receive security coverage.
|
||||
*
|
||||
* For example, if this value is 2 and the existing version is 9.0.1, the
|
||||
* 9.0.x branch will receive security coverage until the release of version
|
||||
* 9.2.0.
|
||||
*
|
||||
* @todo In https://www.drupal.org/node/2998285 determine if we want this
|
||||
* policy to be expressed in the updates.drupal.org feed, instead of relying
|
||||
* on a hard-coded constant.
|
||||
*
|
||||
* @see https://www.drupal.org/core/release-cycle-overview
|
||||
*/
|
||||
const CORE_MINORS_WITH_SECURITY_COVERAGE = 2;
|
||||
|
||||
/**
|
||||
* Define constants for versions with security coverage end dates.
|
||||
*
|
||||
* Two types of constants are supported:
|
||||
* - SECURITY_COVERAGE_END_DATE_[VERSION_MAJOR]_[VERSION_MINOR]: A date in
|
||||
* 'Y-m-d' or 'Y-m' format.
|
||||
* - SECURITY_COVERAGE_ENDING_WARN_DATE_[VERSION_MAJOR]_[VERSION_MINOR]: A
|
||||
* date in 'Y-m-d' format.
|
||||
*
|
||||
* @see \Drupal\update\ProjectSecurityRequirement::getDateEndRequirement()
|
||||
*/
|
||||
const SECURITY_COVERAGE_END_DATE_8_8 = '2020-12-02';
|
||||
|
||||
const SECURITY_COVERAGE_ENDING_WARN_DATE_8_8 = '2020-06-02';
|
||||
|
||||
const SECURITY_COVERAGE_END_DATE_8_9 = '2021-11';
|
||||
|
||||
/**
|
||||
* The existing (currently installed) version of the project.
|
||||
*
|
||||
* Because this class only handles the Drupal core project, values will be
|
||||
* semantic version numbers such as 8.8.0, 8.8.0-alpha1, or 9.0.0.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $existingVersion;
|
||||
|
||||
/**
|
||||
* Releases as returned by update_get_available().
|
||||
*
|
||||
* @var array
|
||||
*
|
||||
* Each release item in the array has metadata about that release. This class
|
||||
* uses the keys:
|
||||
* - status (string): The status of the release.
|
||||
* - version (string): The version number of the release.
|
||||
*
|
||||
* @see update_get_available()
|
||||
*/
|
||||
protected $releases;
|
||||
|
||||
/**
|
||||
* Constructs a ProjectSecurityData object.
|
||||
*
|
||||
* @param string $existing_version
|
||||
* The existing (currently installed) version of the project.
|
||||
* @param array $releases
|
||||
* Project releases as returned by update_get_available().
|
||||
*/
|
||||
private function __construct($existing_version = NULL, array $releases = []) {
|
||||
$this->existingVersion = $existing_version;
|
||||
$this->releases = $releases;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a ProjectSecurityData object from project data and releases.
|
||||
*
|
||||
* @param array $project_data
|
||||
* Project data from Drupal\update\UpdateManagerInterface::getProjects() and
|
||||
* processed by update_process_project_info().
|
||||
* @param array $releases
|
||||
* Project releases as returned by update_get_available().
|
||||
*
|
||||
* @return static
|
||||
*/
|
||||
public static function createFromProjectDataAndReleases(array $project_data, array $releases) {
|
||||
if (!($project_data['project_type'] === 'core' && $project_data['name'] === 'drupal')) {
|
||||
// Only Drupal core has an explicit coverage range.
|
||||
return new static();
|
||||
}
|
||||
return new static($project_data['existing_version'], $releases);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the security coverage information for a project.
|
||||
*
|
||||
* Currently only Drupal core is supported.
|
||||
*
|
||||
* @return array
|
||||
* The security coverage information, or an empty array if no security
|
||||
* information is available for the project. If security coverage is based
|
||||
* on release of a specific version, the array will have the following
|
||||
* keys:
|
||||
* - security_coverage_end_version (string): The minor version the existing
|
||||
* version will receive security coverage until.
|
||||
* - additional_minors_coverage (int): The number of additional minor
|
||||
* versions the existing version will receive security coverage.
|
||||
* If the security coverage is based on a specific date, the array will have
|
||||
* the following keys:
|
||||
* - security_coverage_end_date (string): The month or date security
|
||||
* coverage will end for the existing version. It can be in either
|
||||
* 'YYYY-MM' or 'YYYY-MM-DD' format.
|
||||
* - (optional) security_coverage_ending_warn_date (string): The date, in
|
||||
* the format 'YYYY-MM-DD', after which a warning should be displayed
|
||||
* about upgrading to another version.
|
||||
*/
|
||||
public function getCoverageInfo() {
|
||||
if (empty($this->releases[$this->existingVersion])) {
|
||||
// If the existing version does not have a release, we cannot get the
|
||||
// security coverage information.
|
||||
return [];
|
||||
}
|
||||
$info = [];
|
||||
$existing_release_version = ModuleVersion::createFromVersionString($this->existingVersion);
|
||||
|
||||
// Check if the installed version has a specific end date defined.
|
||||
$version_suffix = $existing_release_version->getMajorVersion() . '_' . $this->getSemanticMinorVersion($this->existingVersion);
|
||||
if (defined("self::SECURITY_COVERAGE_END_DATE_$version_suffix")) {
|
||||
$info['security_coverage_end_date'] = constant("self::SECURITY_COVERAGE_END_DATE_$version_suffix");
|
||||
$info['security_coverage_ending_warn_date'] =
|
||||
defined("self::SECURITY_COVERAGE_ENDING_WARN_DATE_$version_suffix")
|
||||
? constant("self::SECURITY_COVERAGE_ENDING_WARN_DATE_$version_suffix")
|
||||
: NULL;
|
||||
}
|
||||
elseif ($security_coverage_until_version = $this->getSecurityCoverageUntilVersion()) {
|
||||
$info['security_coverage_end_version'] = $security_coverage_until_version;
|
||||
$info['additional_minors_coverage'] = $this->getAdditionalSecurityCoveredMinors($security_coverage_until_version);
|
||||
}
|
||||
return $info;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the release the current minor will receive security coverage until.
|
||||
*
|
||||
* For the sake of example, assume that the currently installed version of
|
||||
* Drupal is 8.7.11 and that static::CORE_MINORS_WITH_SECURITY_COVERAGE is 2.
|
||||
* When Drupal 8.9.0 is released, the supported minor versions will be 8.8
|
||||
* and 8.9. At that point, Drupal 8.7 will no longer have security coverage.
|
||||
* Therefore, this function would return "8.9.0".
|
||||
*
|
||||
* @todo In https://www.drupal.org/node/2998285 determine how we will know
|
||||
* what the final minor release of a particular major version will be. This
|
||||
* method should not return a version beyond that minor.
|
||||
*
|
||||
* @return string|null
|
||||
* The version the existing version will receive security coverage until or
|
||||
* NULL if this cannot be determined.
|
||||
*/
|
||||
private function getSecurityCoverageUntilVersion() {
|
||||
$existing_release_version = ModuleVersion::createFromVersionString($this->existingVersion);
|
||||
if (!empty($existing_release_version->getVersionExtra())) {
|
||||
// Only full releases receive security coverage.
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return $existing_release_version->getMajorVersion() . '.'
|
||||
. ($this->getSemanticMinorVersion($this->existingVersion) + static::CORE_MINORS_WITH_SECURITY_COVERAGE)
|
||||
. '.0';
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the number of additional minor releases with security coverage.
|
||||
*
|
||||
* This function compares the currently installed (existing) version of
|
||||
* the project with two things:
|
||||
* - The latest available official release of that project.
|
||||
* - The target minor release where security coverage for the current release
|
||||
* should expire. This target release is determined by
|
||||
* getSecurityCoverageUntilVersion().
|
||||
*
|
||||
* For the sake of example, assume that the currently installed version of
|
||||
* Drupal is 8.7.11 and that static::CORE_MINORS_WITH_SECURITY_COVERAGE is 2.
|
||||
*
|
||||
* Before the release of Drupal 8.8.0, this function would return 2.
|
||||
*
|
||||
* After the release of Drupal 8.8.0 and before the release of 8.9.0, this
|
||||
* function would return 1 to indicate that the next minor version release
|
||||
* will end security coverage for 8.7.
|
||||
*
|
||||
* When Drupal 8.9.0 is released, this function would return 0 to indicate
|
||||
* that security coverage is over for 8.7.
|
||||
*
|
||||
* If the currently installed version is 9.0.0, and there is no 9.1.0 release
|
||||
* yet, the function would return 2. Once 9.1.0 is out, it would return 1.
|
||||
* When 9.2.0 is released, it would again return 0.
|
||||
*
|
||||
* Note: callers should not test this function's return value with empty()
|
||||
* since 0 is a valid return value that has different meaning than NULL.
|
||||
*
|
||||
* @param string $security_covered_version
|
||||
* The version until which the existing version receives security coverage.
|
||||
*
|
||||
* @return int|null
|
||||
* The number of additional minor releases that receive security coverage,
|
||||
* or NULL if this cannot be determined.
|
||||
*
|
||||
* @see \Drupal\update\ProjectSecurityData\getSecurityCoverageUntilVersion()
|
||||
*/
|
||||
private function getAdditionalSecurityCoveredMinors($security_covered_version) {
|
||||
$security_covered_version_major = ModuleVersion::createFromVersionString($security_covered_version)->getMajorVersion();
|
||||
$security_covered_version_minor = $this->getSemanticMinorVersion($security_covered_version);
|
||||
foreach ($this->releases as $release) {
|
||||
$release_version = ModuleVersion::createFromVersionString($release['version']);
|
||||
if ($release_version->getMajorVersion() === $security_covered_version_major && $release['status'] === 'published' && !$release_version->getVersionExtra()) {
|
||||
// The releases are ordered with the most recent releases first.
|
||||
// Therefore, if we have found a published, official release with the
|
||||
// same major version as $security_covered_version, then this release
|
||||
// can be used to determine the latest minor.
|
||||
$latest_minor = $this->getSemanticMinorVersion($release['version']);
|
||||
break;
|
||||
}
|
||||
}
|
||||
// If $latest_minor is set, we know that $security_covered_version_minor and
|
||||
// $latest_minor have the same major version. Therefore, we can subtract to
|
||||
// determine the number of additional minor releases with security coverage.
|
||||
return isset($latest_minor) ? $security_covered_version_minor - $latest_minor : NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the minor version for a semantic version string.
|
||||
*
|
||||
* @param string $version
|
||||
* The semantic version string.
|
||||
*
|
||||
* @return int
|
||||
* The minor version as an integer.
|
||||
*/
|
||||
private function getSemanticMinorVersion($version) {
|
||||
return (int) (explode('.', $version)[1]);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\update;
|
||||
|
||||
use Drupal\Core\StringTranslation\StringTranslationTrait;
|
||||
use Drupal\Core\Url;
|
||||
|
||||
/**
|
||||
* Class for generating a project's security requirement.
|
||||
*
|
||||
* @see update_requirements()
|
||||
*
|
||||
* @internal
|
||||
* This class implements logic to determine security coverage for Drupal core
|
||||
* according to Drupal core security policy. It should not be called directly.
|
||||
*/
|
||||
final class ProjectSecurityRequirement {
|
||||
|
||||
use StringTranslationTrait;
|
||||
|
||||
/**
|
||||
* The project title.
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
protected $projectTitle;
|
||||
|
||||
/**
|
||||
* Security coverage information for the project.
|
||||
*
|
||||
* @var array
|
||||
*
|
||||
* @see \Drupal\update\ProjectSecurityData::getCoverageInfo()
|
||||
*/
|
||||
private $securityCoverageInfo;
|
||||
|
||||
/**
|
||||
* The next version after the installed version in the format [MAJOR].[MINOR].
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
private $nextMajorMinorVersion;
|
||||
|
||||
/**
|
||||
* The existing (currently installed) version in the format [MAJOR].[MINOR].
|
||||
*
|
||||
* @var string|null
|
||||
*/
|
||||
private $existingMajorMinorVersion;
|
||||
|
||||
/**
|
||||
* Constructs a ProjectSecurityRequirement object.
|
||||
*
|
||||
* @param string|null $project_title
|
||||
* The project title.
|
||||
* @param array $security_coverage_info
|
||||
* Security coverage information as set by
|
||||
* \Drupal\update\ProjectSecurityData::getCoverageInfo().
|
||||
* @param string|null $existing_major_minor_version
|
||||
* The existing (currently installed) version in the format [MAJOR].[MINOR].
|
||||
* @param string|null $next_major_minor_version
|
||||
* The next version after the installed version in the format
|
||||
* [MAJOR].[MINOR].
|
||||
*/
|
||||
private function __construct($project_title = NULL, array $security_coverage_info = [], $existing_major_minor_version = NULL, $next_major_minor_version = NULL) {
|
||||
$this->projectTitle = $project_title;
|
||||
$this->securityCoverageInfo = $security_coverage_info;
|
||||
$this->existingMajorMinorVersion = $existing_major_minor_version;
|
||||
$this->nextMajorMinorVersion = $next_major_minor_version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a ProjectSecurityRequirement object from project data.
|
||||
*
|
||||
* @param array $project_data
|
||||
* Project data from Drupal\update\UpdateManagerInterface::getProjects().
|
||||
* The 'security_coverage_info' key should be set by
|
||||
* calling \Drupal\update\ProjectSecurityData::getCoverageInfo() before
|
||||
* calling this method. The following keys are used in this method:
|
||||
* - existing_version (string): The version of the project that is installed
|
||||
* on the site.
|
||||
* - project_type (string): The type of project.
|
||||
* - name (string): The project machine name.
|
||||
* - title (string): The project title.
|
||||
* @param array $security_coverage_info
|
||||
* The security coverage information as returned by
|
||||
* \Drupal\update\ProjectSecurityData::getCoverageInfo().
|
||||
*
|
||||
* @return static
|
||||
*
|
||||
* @see \Drupal\update\UpdateManagerInterface::getProjects()
|
||||
* @see \Drupal\update\ProjectSecurityData::getCoverageInfo()
|
||||
* @see update_process_project_info()
|
||||
*/
|
||||
public static function createFromProjectDataAndSecurityCoverageInfo(array $project_data, array $security_coverage_info) {
|
||||
if ($project_data['project_type'] !== 'core' || $project_data['name'] !== 'drupal' || empty($security_coverage_info)) {
|
||||
return new static();
|
||||
}
|
||||
if (isset($project_data['existing_version'])) {
|
||||
list($major, $minor) = explode('.', $project_data['existing_version']);
|
||||
$existing_version = "$major.$minor";
|
||||
$next_version = "$major." . ((int) $minor + 1);
|
||||
return new static($project_data['title'], $security_coverage_info, $existing_version, $next_version);
|
||||
}
|
||||
return new static($project_data['title'], $security_coverage_info);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the security coverage requirement, if any.
|
||||
*
|
||||
* @return array
|
||||
* Requirements array as specified by hook_requirements(), or an empty array
|
||||
* if no requirements can be determined.
|
||||
*/
|
||||
public function getRequirement() {
|
||||
if (isset($this->securityCoverageInfo['security_coverage_end_version'])) {
|
||||
$requirement = $this->getVersionEndRequirement();
|
||||
}
|
||||
elseif (isset($this->securityCoverageInfo['security_coverage_end_date'])) {
|
||||
$requirement = $this->getDateEndRequirement();
|
||||
}
|
||||
else {
|
||||
return [];
|
||||
}
|
||||
$requirement['title'] = $this->t('Drupal core security coverage');
|
||||
return $requirement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the requirements based on security coverage until a specific version.
|
||||
*
|
||||
* @return array
|
||||
* Requirements array as specified by hook_requirements().
|
||||
*/
|
||||
private function getVersionEndRequirement() {
|
||||
$requirement = [];
|
||||
if ($security_coverage_message = $this->getVersionEndCoverageMessage()) {
|
||||
$requirement['description'] = $security_coverage_message;
|
||||
if ($this->securityCoverageInfo['additional_minors_coverage'] > 0) {
|
||||
$requirement['value'] = $this->t(
|
||||
'Covered until @end_version',
|
||||
['@end_version' => $this->securityCoverageInfo['security_coverage_end_version']]
|
||||
);
|
||||
$requirement['severity'] = $this->securityCoverageInfo['additional_minors_coverage'] > 1 ? REQUIREMENT_INFO : REQUIREMENT_WARNING;
|
||||
}
|
||||
else {
|
||||
$requirement['value'] = $this->t('Coverage has ended');
|
||||
$requirement['severity'] = REQUIREMENT_ERROR;
|
||||
}
|
||||
}
|
||||
return $requirement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the message for additional minor version security coverage.
|
||||
*
|
||||
* @return array[]
|
||||
* A render array containing security coverage message.
|
||||
*
|
||||
* @see \Drupal\update\ProjectSecurityData::getCoverageInfo()
|
||||
*/
|
||||
private function getVersionEndCoverageMessage() {
|
||||
if ($this->securityCoverageInfo['additional_minors_coverage'] > 0) {
|
||||
// If the installed minor version will receive security coverage until
|
||||
// newer minor versions are released, inform the user.
|
||||
if ($this->securityCoverageInfo['additional_minors_coverage'] === 1) {
|
||||
// If the installed minor version will only receive security coverage
|
||||
// for 1 newer minor core version, encourage the site owner to update
|
||||
// soon.
|
||||
$message['coverage_message'] = [
|
||||
'#markup' => $this->t(
|
||||
'<a href=":update_status_report">Update to @next_minor or higher</a> soon to continue receiving security updates.',
|
||||
[
|
||||
':update_status_report' => Url::fromRoute('update.status')->toString(),
|
||||
'@next_minor' => $this->nextMajorMinorVersion,
|
||||
]
|
||||
),
|
||||
'#suffix' => ' ',
|
||||
];
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Because the current minor version no longer has security coverage,
|
||||
// advise the site owner to update.
|
||||
$message['coverage_message'] = [
|
||||
'#markup' => $this->getVersionNoSecurityCoverageMessage(),
|
||||
'#suffix' => ' ',
|
||||
];
|
||||
}
|
||||
$message['release_cycle_link'] = [
|
||||
'#markup' => $this->getReleaseCycleLink(),
|
||||
];
|
||||
return $message;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the security coverage requirement based on an end date.
|
||||
*
|
||||
* @return array
|
||||
* Requirements array as specified by hook_requirements().
|
||||
*/
|
||||
private function getDateEndRequirement() {
|
||||
$requirement = [];
|
||||
/** @var \Drupal\Component\Datetime\Time $time */
|
||||
$time = \Drupal::service('datetime.time');
|
||||
/** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
|
||||
$date_formatter = \Drupal::service('date.formatter');
|
||||
// 'security_coverage_end_date' will either be in format 'Y-m-d' or 'Y-m'.
|
||||
if (substr_count($this->securityCoverageInfo['security_coverage_end_date'], '-') === 2) {
|
||||
$date_format = 'Y-m-d';
|
||||
$full_security_coverage_end_date = $this->securityCoverageInfo['security_coverage_end_date'];
|
||||
}
|
||||
else {
|
||||
$date_format = 'Y-m';
|
||||
// If the date does not include a day, use '15'. When calling
|
||||
// \DateTime::createFromFormat() the current day will be used if one is
|
||||
// not provided. This may cause the month to be wrong at the beginning or
|
||||
// end of the month. '15' will never be displayed because we are using the
|
||||
// 'Y-m' format.
|
||||
$full_security_coverage_end_date = $this->securityCoverageInfo['security_coverage_end_date'] . '-15';
|
||||
}
|
||||
|
||||
$comparable_request_date = $date_formatter->format($time->getRequestTime(), 'custom', $date_format);
|
||||
if ($this->securityCoverageInfo['security_coverage_end_date'] <= $comparable_request_date) {
|
||||
// Security coverage is over.
|
||||
$requirement['value'] = $this->t('Coverage has ended');
|
||||
$requirement['severity'] = REQUIREMENT_ERROR;
|
||||
$requirement['description']['coverage_message'] = [
|
||||
'#markup' => $this->getVersionNoSecurityCoverageMessage(),
|
||||
'#suffix' => ' ',
|
||||
];
|
||||
}
|
||||
else {
|
||||
$security_coverage_end_timestamp = \DateTime::createFromFormat('Y-m-d', $full_security_coverage_end_date)->getTimestamp();
|
||||
$output_date_format = $date_format === 'Y-m-d' ? 'Y-M-d' : 'Y-M';
|
||||
$formatted_end_date = $date_formatter
|
||||
->format($security_coverage_end_timestamp, 'custom', $output_date_format);
|
||||
$translation_arguments = ['@date' => $formatted_end_date];
|
||||
$requirement['value'] = $this->t('Covered until @date', $translation_arguments);
|
||||
$requirement['severity'] = REQUIREMENT_INFO;
|
||||
// 'security_coverage_ending_warn_date' will always be in the format
|
||||
// 'Y-m-d'.
|
||||
$request_date = $date_formatter->format($time->getRequestTime(), 'custom', 'Y-m-d');
|
||||
if (!empty($this->securityCoverageInfo['security_coverage_ending_warn_date']) && $this->securityCoverageInfo['security_coverage_ending_warn_date'] <= $request_date) {
|
||||
$requirement['description']['coverage_message'] = [
|
||||
'#markup' => $this->t('Update to a supported minor version soon to continue receiving security updates.'),
|
||||
'#suffix' => ' ',
|
||||
];
|
||||
$requirement['severity'] = REQUIREMENT_WARNING;
|
||||
}
|
||||
}
|
||||
$requirement['description']['release_cycle_link'] = ['#markup' => $this->getReleaseCycleLink()];
|
||||
return $requirement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the formatted message for a project with no security coverage.
|
||||
*
|
||||
* @return string
|
||||
* The message for a version with no security coverage.
|
||||
*/
|
||||
private function getVersionNoSecurityCoverageMessage() {
|
||||
return $this->t(
|
||||
'<a href=":update_status_report">Update to a supported minor</a> as soon as possible to continue receiving security updates.',
|
||||
[':update_status_report' => Url::fromRoute('update.status')->toString()]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a link the release cycle page on drupal.org.
|
||||
*
|
||||
* @return string
|
||||
* A link to the release cycle page on drupal.org.
|
||||
*/
|
||||
private function getReleaseCycleLink() {
|
||||
return $this->t(
|
||||
'Visit the <a href=":url">release cycle overview</a> for more information on supported releases.',
|
||||
[':url' => 'https://www.drupal.org/core/release-cycle-overview']
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\update\Tests;
|
||||
|
||||
@trigger_error(__NAMESPACE__ . '\UpdateTestBase is deprecated in Drupal 8.4.0 and will be removed before Drupal 9.0.0. Instead, use \Drupal\Tests\update\Functional\UpdateTestBase', E_USER_DEPRECATED);
|
||||
|
||||
use Drupal\Core\DrupalKernel;
|
||||
use Drupal\Core\Link;
|
||||
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.
|
||||
*
|
||||
* @deprecated in drupal:8.?.? and is removed from drupal:9.0.0.
|
||||
* Use \Drupal\Tests\update\Functional\UpdateTestBase instead.
|
||||
*/
|
||||
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, ['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(Link::fromTextAndUrl(t('Drupal'), Url::fromUri('http://example.com/project/drupal'))->toString(), 'Link to the Drupal project appears.');
|
||||
$this->assertNoText(t('No available releases found'));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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, ['headers' => ['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 . '/current';
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\update;
|
||||
|
||||
/**
|
||||
* Fetches project information from remote locations.
|
||||
*/
|
||||
interface UpdateFetcherInterface {
|
||||
|
||||
/**
|
||||
* Project's status cannot be checked.
|
||||
*/
|
||||
const NOT_CHECKED = -1;
|
||||
|
||||
/**
|
||||
* No available update data was found for project.
|
||||
*/
|
||||
const UNKNOWN = -2;
|
||||
|
||||
/**
|
||||
* There was a failure fetching available update data for this project.
|
||||
*/
|
||||
const NOT_FETCHED = -3;
|
||||
|
||||
/**
|
||||
* We need to (re)fetch available update data for this project.
|
||||
*/
|
||||
const FETCH_PENDING = -4;
|
||||
|
||||
/**
|
||||
* 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 = '');
|
||||
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\update;
|
||||
|
||||
use Drupal\Core\Config\ConfigFactoryInterface;
|
||||
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
|
||||
use Drupal\Core\Extension\ModuleExtensionList;
|
||||
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;
|
||||
|
||||
/**
|
||||
* The module extension list.
|
||||
*
|
||||
* @var \Drupal\Core\Extension\ModuleExtensionList
|
||||
*/
|
||||
protected $moduleExtensionList;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @param \Drupal\Core\Extension\ModuleExtensionList|null $extension_list_module
|
||||
* The module extension list. This is left optional for BC reasons, but the
|
||||
* optional usage is deprecated and will become required in Drupal 9.0.0.
|
||||
*/
|
||||
public function __construct(ConfigFactoryInterface $config_factory, ModuleHandlerInterface $module_handler, UpdateProcessorInterface $update_processor, TranslationInterface $translation, KeyValueFactoryInterface $key_value_expirable_factory, ThemeHandlerInterface $theme_handler, ModuleExtensionList $extension_list_module = NULL) {
|
||||
$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 = [];
|
||||
if ($extension_list_module === NULL) {
|
||||
@trigger_error('Invoking the UpdateManager constructor without the module extension list parameter is deprecated in Drupal 8.8.0 and will no longer be supported in Drupal 9.0.0. The extension list parameter is now required in the ConfigImporter constructor. See https://www.drupal.org/node/2943918', E_USER_DEPRECATED);
|
||||
$extension_list_module = \Drupal::service('extension.list.module');
|
||||
}
|
||||
$this->moduleExtensionList = $extension_list_module;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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 = $this->moduleExtensionList->reset()->getList();
|
||||
$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 = [];
|
||||
|
||||
// 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 = [
|
||||
'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, []);
|
||||
}
|
||||
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.', ['%title' => $item->data['info']['name']]);
|
||||
}
|
||||
else {
|
||||
$context['message'] = $this->t('Failed to check available update data for %title.', ['%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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\update;
|
||||
|
||||
/**
|
||||
* Manages project update information.
|
||||
*/
|
||||
interface UpdateManagerInterface {
|
||||
|
||||
/**
|
||||
* Project is missing security update(s).
|
||||
*/
|
||||
const NOT_SECURE = 1;
|
||||
|
||||
/**
|
||||
* Current release has been unpublished and is no longer available.
|
||||
*/
|
||||
const REVOKED = 2;
|
||||
|
||||
/**
|
||||
* Current release is no longer supported by the project maintainer.
|
||||
*/
|
||||
const NOT_SUPPORTED = 3;
|
||||
|
||||
/**
|
||||
* Project has a new release available, but it is not a security release.
|
||||
*/
|
||||
const NOT_CURRENT = 4;
|
||||
|
||||
/**
|
||||
* Project is up to date.
|
||||
*/
|
||||
const CURRENT = 5;
|
||||
|
||||
/**
|
||||
* 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);
|
||||
|
||||
}
|
||||
@@ -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 = [];
|
||||
$this->failed = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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 = [];
|
||||
$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 = [];
|
||||
foreach ($xml as $k => $v) {
|
||||
$data[$k] = (string) $v;
|
||||
}
|
||||
$data['releases'] = [];
|
||||
if (isset($xml->releases)) {
|
||||
foreach ($xml->releases->children() as $release) {
|
||||
$version = (string) $release->version;
|
||||
$data['releases'][$version] = [];
|
||||
foreach ($release->children() as $k => $v) {
|
||||
$data['releases'][$version][$k] = (string) $v;
|
||||
}
|
||||
$data['releases'][$version]['terms'] = [];
|
||||
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] = [];
|
||||
}
|
||||
$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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\update;
|
||||
|
||||
/**
|
||||
* Processor of project update information.
|
||||
*/
|
||||
interface UpdateProcessorInterface {
|
||||
|
||||
/**
|
||||
* Claims an item in the update fetch queue for processing.
|
||||
*
|
||||
* @return bool|object
|
||||
* 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 object $item
|
||||
* The item returned by \Drupal\Core\Queue\QueueInterface::claimItem().
|
||||
*
|
||||
* @see \Drupal\Core\Queue\QueueInterface::deleteItem()
|
||||
*/
|
||||
public function deleteQueueItem($item);
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\update;
|
||||
|
||||
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
|
||||
use Drupal\Core\Url;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Drupal\Core\Form\ConfigFormBase;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
|
||||
/**
|
||||
* Configure update settings for this site.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
class UpdateSettingsForm extends ConfigFormBase implements ContainerInjectionInterface {
|
||||
|
||||
/**
|
||||
* The email validator.
|
||||
*
|
||||
* @var \Drupal\Component\Utility\EmailValidatorInterface
|
||||
*/
|
||||
protected $emailValidator;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function create(ContainerInterface $container) {
|
||||
$instance = parent::create($container);
|
||||
$instance->emailValidator = $container->get('email.validator');
|
||||
return $instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@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'] = [
|
||||
'#type' => 'radios',
|
||||
'#title' => t('Check for updates'),
|
||||
'#default_value' => $config->get('check.interval_days'),
|
||||
'#options' => [
|
||||
'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'] = [
|
||||
'#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'] = [
|
||||
'#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'] = [
|
||||
'#type' => 'radios',
|
||||
'#title' => t('Email notification threshold'),
|
||||
'#default_value' => $config->get('notification.threshold'),
|
||||
'#options' => [
|
||||
'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.', [':status_report' => Url::fromRoute('system.status')->toString()]),
|
||||
];
|
||||
|
||||
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 = [];
|
||||
$invalid = [];
|
||||
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.', ['%email' => reset($invalid)]));
|
||||
}
|
||||
else {
|
||||
$form_state->setErrorByName('update_notify_emails', $this->t('%emails are not valid email addresses.', ['%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);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user