2b9d651a7490ca67f9a8ccf30ae08c33d3f92e44
[yaffs-website] / web / core / modules / update / update.module
1 <?php
2
3 /**
4  * @file
5  * Handles updates of Drupal core and contributed projects.
6  *
7  * The module checks for available updates of Drupal core and any installed
8  * contributed modules and themes. It warns site administrators if newer
9  * releases are available via the system status report (admin/reports/status),
10  * the module and theme pages, and optionally via email. It also provides the
11  * ability to install contributed modules and themes via an user interface.
12  */
13
14 use Drupal\Core\Url;
15 use Drupal\Core\Form\FormStateInterface;
16 use Drupal\Core\Routing\RouteMatchInterface;
17 use Drupal\Core\Site\Settings;
18
19 // These are internally used constants for this code, do not modify.
20
21 /**
22  * Project is missing security update(s).
23  *
24  * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
25  *   Use \Drupal\update\UpdateManagerInterface::NOT_SECURE instead.
26  *
27  * @see https://www.drupal.org/node/2831620
28  */
29 const UPDATE_NOT_SECURE = 1;
30
31 /**
32  * Current release has been unpublished and is no longer available.
33  *
34  * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
35  *   Use \Drupal\update\UpdateManagerInterface::REVOKED instead.
36  *
37  * @see https://www.drupal.org/node/2831620
38  */
39 const UPDATE_REVOKED = 2;
40
41 /**
42  * Current release is no longer supported by the project maintainer.
43  *
44  * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
45  *   Use \Drupal\update\UpdateManagerInterface::NOT_SUPPORTED instead.
46  *
47  * @see https://www.drupal.org/node/2831620
48  */
49 const UPDATE_NOT_SUPPORTED = 3;
50
51 /**
52  * Project has a new release available, but it is not a security release.
53  *
54  * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
55  *   Use \Drupal\update\UpdateManagerInterface::NOT_CURRENT instead.
56  *
57  * @see https://www.drupal.org/node/2831620
58  */
59 const UPDATE_NOT_CURRENT = 4;
60
61 /**
62  * Project is up to date.
63  *
64  * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
65  *   Use \Drupal\update\UpdateManagerInterface::CURRENT instead.
66  *
67  * @see https://www.drupal.org/node/2831620
68  */
69 const UPDATE_CURRENT = 5;
70
71 /**
72  * Project's status cannot be checked.
73  *
74  * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
75  *   Use \Drupal\update\UpdateFetcherInterface::NOT_CHECKED instead.
76  *
77  * @see https://www.drupal.org/node/2831620
78  */
79 const UPDATE_NOT_CHECKED = -1;
80
81 /**
82  * No available update data was found for project.
83  *
84  * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
85  *   Use \Drupal\update\UpdateFetcherInterface::UNKNOWN instead.
86  *
87  * @see https://www.drupal.org/node/2831620
88  */
89 const UPDATE_UNKNOWN = -2;
90
91 /**
92  * There was a failure fetching available update data for this project.
93  *
94  * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
95  *   Use \Drupal\update\UpdateFetcherInterface::NOT_FETCHED instead.
96  *
97  * @see https://www.drupal.org/node/2831620
98  */
99 const UPDATE_NOT_FETCHED = -3;
100
101 /**
102  * We need to (re)fetch available update data for this project.
103  *
104  * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0.
105  *   Use \Drupal\update\UpdateFetcherInterface::FETCH_PENDING instead.
106  *
107  * @see https://www.drupal.org/node/2831620
108  */
109 const UPDATE_FETCH_PENDING = -4;
110
111 /**
112  * Implements hook_help().
113  */
114 function update_help($route_name, RouteMatchInterface $route_match) {
115   switch ($route_name) {
116     case 'help.page.update':
117       $output = '';
118       $output .= '<h3>' . t('About') . '</h3>';
119       $output .= '<p>' . t('The Update Manager module periodically checks for new versions of your site\'s software (including contributed modules and themes), and alerts administrators to available updates. The Update Manager system is also used by some other modules to manage updates and downloads; for example, the Interface Translation module uses the Update Manager to download translations from the localization server. Note that whenever the Update Manager system is used, anonymous usage statistics are sent to Drupal.org. If desired, you may disable the Update Manager module from the <a href=":modules">Extend page</a>; if you do so, functionality that depends on the Update Manager system will not work. For more information, see the <a href=":update">online documentation for the Update Manager module</a>.', [':update' => 'https://www.drupal.org/documentation/modules/update', ':modules' => \Drupal::url('system.modules_list')]) . '</p>';
120       // Only explain the Update manager if it has not been disabled.
121       if (_update_manager_access()) {
122         $output .= '<p>' . t('The Update Manager also allows administrators to update and install modules and themes through the administration interface.') . '</p>';
123       }
124       $output .= '<h3>' . t('Uses') . '</h3>';
125       $output .= '<dl>';
126       $output .= '<dt>' . t('Checking for available updates') . '</dt>';
127       $output .= '<dd>' . t('The <a href=":update-report">Available updates report</a> displays core, contributed modules, and themes for which there are new releases available for download. On the report page, you can also check manually for updates. You can configure the frequency of update checks, which are performed during cron runs, and whether notifications are sent on the <a href=":update-settings">Update Manager settings page</a>.', [':update-report' => \Drupal::url('update.status'), ':update-settings' => \Drupal::url('update.settings')]) . '</dd>';
128       // Only explain the Update manager if it has not been disabled.
129       if (_update_manager_access()) {
130         $output .= '<dt>' . t('Performing updates through the Update page') . '</dt>';
131         $output .= '<dd>' . t('The Update Manager module allows administrators to perform updates directly from the <a href=":update-page">Update page</a>. It lists all available updates, and you can confirm whether you want to download them. If you don\'t have sufficient access rights to your web server, you could be prompted for your FTP/SSH password. Afterwards the files are transferred into your site installation, overwriting your old files. Direct links to the Update page are also displayed on the <a href=":modules_page">Extend page</a> and the <a href=":themes_page">Appearance page</a>.', [':modules_page' => \Drupal::url('system.modules_list'), ':themes_page' => \Drupal::url('system.themes_page'), ':update-page' => \Drupal::url('update.report_update')]) . '</dd>';
132         $output .= '<dt>' . t('Installing new modules and themes through the Install page') . '</dt>';
133         $output .= '<dd>' . t('You can also install new modules and themes in the same fashion, through the <a href=":install">Install page</a>, or by clicking the <em>Install new module/theme</em> links at the top of the <a href=":modules_page">Extend page</a> and the <a href=":themes_page">Appearance page</a>. In this case, you are prompted to provide either the URL to the download, or to upload a packaged release file from your local computer.', [':modules_page' => \Drupal::url('system.modules_list'), ':themes_page' => \Drupal::url('system.themes_page'), ':install' => \Drupal::url('update.report_install')]) . '</dd>';
134       }
135       $output .= '</dl>';
136       return $output;
137
138     case 'update.status':
139       return '<p>' . t('Here you can find information about available updates for your installed modules and themes. Note that each module or theme is part of a "project", which may or may not have the same name, and might include multiple modules or themes within it.') . '</p>';
140
141     case 'system.modules_list':
142       if (_update_manager_access()) {
143         $output = '<p>' . t('Regularly review and install <a href=":updates">available updates</a> to maintain a secure and current site. Always run the <a href=":update-php">update script</a> each time a module is updated.', [':update-php' => \Drupal::url('system.db_update'), ':updates' => \Drupal::url('update.status')]) . '</p>';
144       }
145       else {
146         $output = '<p>' . t('Regularly review <a href=":updates">available updates</a> to maintain a secure and current site. Always run the <a href=":update-php">update script</a> each time a module is updated.', [':update-php' => \Drupal::url('system.db_update'), ':updates' => \Drupal::url('update.status')]) . '</p>';
147       }
148       return $output;
149   }
150 }
151
152 /**
153  * Implements hook_page_top().
154  */
155 function update_page_top() {
156   /** @var \Drupal\Core\Routing\AdminContext $admin_context */
157   $admin_context = \Drupal::service('router.admin_context');
158   $route_match = \Drupal::routeMatch();
159   if ($admin_context->isAdminRoute($route_match->getRouteObject()) && \Drupal::currentUser()->hasPermission('administer site configuration')) {
160     $route_name = \Drupal::routeMatch()->getRouteName();
161     switch ($route_name) {
162       // These pages don't need additional nagging.
163       case 'update.theme_update':
164       case 'system.theme_install':
165       case 'update.module_update':
166       case 'update.module_install':
167       case 'update.status':
168       case 'update.report_update':
169       case 'update.report_install':
170       case 'update.settings':
171       case 'system.status':
172       case 'update.confirmation_page':
173         return;
174
175       // If we are on the appearance or modules list, display a detailed report
176       // of the update status.
177       case 'system.themes_page':
178       case 'system.modules_list':
179         $verbose = TRUE;
180         break;
181
182     }
183     module_load_install('update');
184     $status = update_requirements('runtime');
185     foreach (['core', 'contrib'] as $report_type) {
186       $type = 'update_' . $report_type;
187       // hook_requirements() supports render arrays therefore we need to render
188       // them before using drupal_set_message().
189       if (isset($status[$type]['description']) && is_array($status[$type]['description'])) {
190         $status[$type]['description'] = \Drupal::service('renderer')->renderPlain($status[$type]['description']);
191       }
192       if (!empty($verbose)) {
193         if (isset($status[$type]['severity'])) {
194           if ($status[$type]['severity'] == REQUIREMENT_ERROR) {
195             drupal_set_message($status[$type]['description'], 'error');
196           }
197           elseif ($status[$type]['severity'] == REQUIREMENT_WARNING) {
198             drupal_set_message($status[$type]['description'], 'warning');
199           }
200         }
201       }
202       // Otherwise, if we're on *any* admin page and there's a security
203       // update missing, print an error message about it.
204       else {
205         if (isset($status[$type])
206             && isset($status[$type]['reason'])
207             && $status[$type]['reason'] === UPDATE_NOT_SECURE) {
208           drupal_set_message($status[$type]['description'], 'error');
209         }
210       }
211     }
212   }
213 }
214
215 /**
216  * Resolves if the current user can access updater menu items.
217  *
218  * It both enforces the 'administer software updates' permission and the global
219  * kill switch for the authorize.php script.
220  *
221  * @return
222  *   TRUE if the current user can access the updater menu items; FALSE
223  *   otherwise.
224  */
225 function _update_manager_access() {
226   return Settings::get('allow_authorize_operations', TRUE) && \Drupal::currentUser()->hasPermission('administer software updates');
227 }
228
229 /**
230  * Implements hook_theme().
231  */
232 function update_theme() {
233   return [
234     'update_last_check' => [
235       'variables' => ['last' => 0],
236     ],
237     'update_report' => [
238       'variables' => ['data' => NULL],
239       'file' => 'update.report.inc',
240     ],
241     'update_project_status' => [
242       'variables' => ['project' => []],
243       'file' => 'update.report.inc',
244     ],
245     // We are using template instead of '#type' => 'table' here to keep markup
246     // out of preprocess and allow for easier changes to markup.
247     'update_version' => [
248       'variables' => ['version' => NULL, 'title' => NULL, 'attributes' => []],
249       'file' => 'update.report.inc',
250     ],
251   ];
252 }
253
254 /**
255  * Implements hook_cron().
256  */
257 function update_cron() {
258   $update_config = \Drupal::config('update.settings');
259   $frequency = $update_config->get('check.interval_days');
260   $interval = 60 * 60 * 24 * $frequency;
261   $last_check = \Drupal::state()->get('update.last_check') ?: 0;
262   if ((REQUEST_TIME - $last_check) > $interval) {
263     // If the configured update interval has elapsed, we want to invalidate
264     // the data for all projects, attempt to re-fetch, and trigger any
265     // configured notifications about the new status.
266     update_refresh();
267     update_fetch_data();
268   }
269   else {
270     // Otherwise, see if any individual projects are now stale or still
271     // missing data, and if so, try to fetch the data.
272     update_get_available(TRUE);
273   }
274   $last_email_notice = \Drupal::state()->get('update.last_email_notification') ?: 0;
275   if ((REQUEST_TIME - $last_email_notice) > $interval) {
276     // If configured time between notifications elapsed, send email about
277     // updates possibly available.
278     module_load_include('inc', 'update', 'update.fetch');
279     _update_cron_notify();
280   }
281
282   // Clear garbage from disk.
283   update_clear_update_disk_cache();
284 }
285
286 /**
287  * Implements hook_themes_installed().
288  *
289  * If themes are installed, we invalidate the information of available updates.
290  */
291 function update_themes_installed($themes) {
292   // Clear all update module data.
293   update_storage_clear();
294 }
295
296 /**
297  * Implements hook_themes_uninstalled().
298  *
299  * If themes are uninstalled, we invalidate the information of available updates.
300  */
301 function update_themes_uninstalled($themes) {
302   // Clear all update module data.
303   update_storage_clear();
304 }
305
306 /**
307  * Implements hook_form_FORM_ID_alter() for system_modules().
308  *
309  * Adds a form submission handler to the system modules form, so that if a site
310  * admin saves the form, we invalidate the information of available updates.
311  *
312  * @see _update_cache_clear()
313  */
314 function update_form_system_modules_alter(&$form, FormStateInterface $form_state) {
315   $form['#submit'][] = 'update_storage_clear_submit';
316 }
317
318 /**
319  * Form submission handler for system_modules().
320  *
321  * @see update_form_system_modules_alter()
322  */
323 function update_storage_clear_submit($form, FormStateInterface $form_state) {
324   // Clear all update module data.
325   update_storage_clear();
326 }
327
328 /**
329  * Returns a warning message when there is no data about available updates.
330  */
331 function _update_no_data() {
332   $destination = \Drupal::destination()->getAsArray();
333   return t('No update information available. <a href=":run_cron">Run cron</a> or <a href=":check_manually">check manually</a>.', [
334     ':run_cron' => \Drupal::url('system.run_cron', [], ['query' => $destination]),
335     ':check_manually' => \Drupal::url('update.manual_status', [], ['query' => $destination]),
336   ]);
337 }
338
339 /**
340  * Tries to get update information and refreshes it when necessary.
341  *
342  * In addition to checking the lifetime, this function also ensures that
343  * there are no .info.yml files for enabled modules or themes that have a newer
344  * modification timestamp than the last time we checked for available update
345  * data. If any .info.yml file was modified, it almost certainly means a new
346  * version of something was installed. Without fresh available update data, the
347  * logic in update_calculate_project_data() will be wrong and produce confusing,
348  * bogus results.
349  *
350  * @param $refresh
351  *   (optional) Boolean to indicate if this method should refresh automatically
352  *   if there's no data. Defaults to FALSE.
353  *
354  * @return
355  *   Array of data about available releases, keyed by project shortname.
356  *
357  * @see update_refresh()
358  * @see \Drupal\Update\UpdateManager::getProjects()
359  */
360 function update_get_available($refresh = FALSE) {
361   module_load_include('inc', 'update', 'update.compare');
362   $needs_refresh = FALSE;
363
364   // Grab whatever data we currently have.
365   $available = \Drupal::keyValueExpirable('update_available_releases')->getAll();
366   $projects = \Drupal::service('update.manager')->getProjects();
367   foreach ($projects as $key => $project) {
368     // If there's no data at all, we clearly need to fetch some.
369     if (empty($available[$key])) {
370       // update_create_fetch_task($project);
371       \Drupal::service('update.processor')->createFetchTask($project);
372       $needs_refresh = TRUE;
373       continue;
374     }
375
376     // See if the .info.yml file is newer than the last time we checked for
377     // data, and if so, mark this project's data as needing to be re-fetched.
378     // Any time an admin upgrades their local installation, the .info.yml file
379     // will be changed, so this is the only way we can be sure we're not showing
380     // bogus information right after they upgrade.
381     if ($project['info']['_info_file_ctime'] > $available[$key]['last_fetch']) {
382       $available[$key]['fetch_status'] = UPDATE_FETCH_PENDING;
383     }
384
385     // If we have project data but no release data, we need to fetch. This
386     // can be triggered when we fail to contact a release history server.
387     if (empty($available[$key]['releases']) && !$available[$key]['last_fetch']) {
388       $available[$key]['fetch_status'] = UPDATE_FETCH_PENDING;
389     }
390
391     // If we think this project needs to fetch, actually create the task now
392     // and remember that we think we're missing some data.
393     if (!empty($available[$key]['fetch_status']) && $available[$key]['fetch_status'] == UPDATE_FETCH_PENDING) {
394       \Drupal::service('update.processor')->createFetchTask($project);
395       $needs_refresh = TRUE;
396     }
397   }
398
399   if ($needs_refresh && $refresh) {
400     // Attempt to drain the queue of fetch tasks.
401     update_fetch_data();
402     // After processing the queue, we've (hopefully) got better data, so pull
403     // the latest data again and use that directly.
404     $available = \Drupal::keyValueExpirable('update_available_releases')->getAll();
405   }
406
407   // Check for security releases that are covered under the same security
408   // advisories as the site's current release, and override the update status
409   // data so that those releases are not flagged as needed security updates.
410   // Any security releases beyond those specific releases will still be shown
411   // as required security updates.
412
413   // @todo This is a temporary fix to allow minor-version backports of security
414   //   fixes to be shown as secure. It should not be included in the codebase of
415   //   any release or branch other than such backports. Replace this with
416   //   https://www.drupal.org/project/drupal/issues/2766491.
417   foreach (_update_equivalent_security_releases() as $equivalent_release) {
418     if (!empty($available['drupal']['releases'][$equivalent_release]['terms']['Release type'])) {
419       $security_release_key = array_search('Security update', $available['drupal']['releases'][$equivalent_release]['terms']['Release type']);
420       if ($security_release_key !== FALSE) {
421         unset($available['drupal']['releases'][$equivalent_release]['terms']['Release type'][$security_release_key]);
422       }
423     }
424   }
425   return $available;
426 }
427
428 /**
429  * Identifies equivalent security releases with a hardcoded list.
430  *
431  * Generally, only the latest minor version of Drupal 8 is supported. However,
432  * when security fixes are backported to an old branch, and the site owner
433  * updates to the release containing the backported fix, they should not
434  * see "Security update required!" again if the only other security releases
435  * are releases for the same advisories.
436  *
437  * @return string[]
438  *   A list of security release numbers that are equivalent to this release
439  *   (i.e. covered by the same advisory), for backported security fixes only.
440  *
441  * @todo This is a temporary fix to allow minor-version backports of security
442  *   fixes to be shown as secure. It should not be included in the codebase of
443  *   any release or branch other than such backports. Replace this with
444  *   https://www.drupal.org/project/drupal/issues/2766491.
445  */
446 function _update_equivalent_security_releases() {
447   switch (\Drupal::VERSION) {
448     case '8.4.5':
449       return ['8.5.0-rc1'];
450     case '8.4.6':
451       return ['8.5.1'];
452   }
453
454   return [];
455 }
456
457 /**
458  * Adds a task to the queue for fetching release history data for a project.
459  *
460  * We only create a new fetch task if there's no task already in the queue for
461  * this particular project (based on 'update_fetch_task' key-value collection).
462  *
463  * @param $project
464  *   Associative array of information about a project as created by
465  *   \Drupal\Update\UpdateManager::getProjects(), including keys such as 'name'
466  *   (short name), and the 'info' array with data from a .info.yml file for the
467  *   project.
468  *
469  * @see \Drupal\update\UpdateFetcher::createFetchTask()
470  */
471 function update_create_fetch_task($project) {
472   \Drupal::service('update.processor')->createFetchTask($project);
473 }
474
475 /**
476  * Refreshes the release data after loading the necessary include file.
477  */
478 function update_refresh() {
479   \Drupal::service('update.manager')->refreshUpdateData();
480 }
481
482 /**
483  * Attempts to fetch update data after loading the necessary include file.
484  *
485  * @see \Drupal\update\UpdateProcessor::fetchData()
486  */
487 function update_fetch_data() {
488   \Drupal::service('update.processor')->fetchData();
489 }
490
491 /**
492  * Batch callback: Performs actions when all fetch tasks have been completed.
493  *
494  * @param $success
495  *   TRUE if the batch operation was successful; FALSE if there were errors.
496  * @param $results
497  *   An associative array of results from the batch operation, including the key
498  *   'updated' which holds the total number of projects we fetched available
499  *   update data for.
500  */
501 function update_fetch_data_finished($success, $results) {
502   if ($success) {
503     if (!empty($results)) {
504       if (!empty($results['updated'])) {
505         drupal_set_message(\Drupal::translation()->formatPlural($results['updated'], 'Checked available update data for one project.', 'Checked available update data for @count projects.'));
506       }
507       if (!empty($results['failures'])) {
508         drupal_set_message(\Drupal::translation()->formatPlural($results['failures'], 'Failed to get available update data for one project.', 'Failed to get available update data for @count projects.'), 'error');
509       }
510     }
511   }
512   else {
513     drupal_set_message(t('An error occurred trying to get available update data.'), 'error');
514   }
515 }
516
517 /**
518  * Implements hook_mail().
519  *
520  * Constructs the email notification message when the site is out of date.
521  *
522  * @param $key
523  *   Unique key to indicate what message to build, always 'status_notify'.
524  * @param $message
525  *   Reference to the message array being built.
526  * @param $params
527  *   Array of parameters to indicate what kind of text to include in the message
528  *   body. This is a keyed array of message type ('core' or 'contrib') as the
529  *   keys, and the status reason constant (UPDATE_NOT_SECURE, etc) for the
530  *   values.
531  *
532  * @see \Drupal\Core\Mail\MailManagerInterface::mail()
533  * @see _update_cron_notify()
534  * @see _update_message_text()
535  */
536 function update_mail($key, &$message, $params) {
537   $langcode = $message['langcode'];
538   $language = \Drupal::languageManager()->getLanguage($langcode);
539   $message['subject'] .= t('New release(s) available for @site_name', ['@site_name' => \Drupal::config('system.site')->get('name')], ['langcode' => $langcode]);
540   foreach ($params as $msg_type => $msg_reason) {
541     $message['body'][] = _update_message_text($msg_type, $msg_reason, $langcode);
542   }
543   $message['body'][] = t('See the available updates page for more information:', [], ['langcode' => $langcode]) . "\n" . \Drupal::url('update.status', [], ['absolute' => TRUE, 'language' => $language]);
544   if (_update_manager_access()) {
545     $message['body'][] = t('You can automatically install your missing updates using the Update manager:', [], ['langcode' => $langcode]) . "\n" . \Drupal::url('update.report_update', [], ['absolute' => TRUE, 'language' => $language]);
546   }
547   $settings_url = \Drupal::url('update.settings', [], ['absolute' => TRUE]);
548   if (\Drupal::config('update.settings')->get('notification.threshold') == 'all') {
549     $message['body'][] = t('Your site is currently configured to send these emails when any updates are available. To get notified only for security updates, @url.', ['@url' => $settings_url]);
550   }
551   else {
552     $message['body'][] = t('Your site is currently configured to send these emails only when security updates are available. To get notified for any available updates, @url.', ['@url' => $settings_url]);
553   }
554 }
555
556 /**
557  * Returns the appropriate message text when site is out of date or not secure.
558  *
559  * These error messages are shared by both update_requirements() for the
560  * site-wide status report at admin/reports/status and in the body of the
561  * notification email messages generated by update_cron().
562  *
563  * @param $msg_type
564  *   String to indicate what kind of message to generate. Can be either 'core'
565  *   or 'contrib'.
566  * @param $msg_reason
567  *   Integer constant specifying why message is generated.
568  * @param $langcode
569  *   (optional) A language code to use. Defaults to NULL.
570  *
571  * @return
572  *   The properly translated error message for the given key.
573  */
574 function _update_message_text($msg_type, $msg_reason, $langcode = NULL) {
575   $text = '';
576   switch ($msg_reason) {
577     case UPDATE_NOT_SECURE:
578       if ($msg_type == 'core') {
579         $text = t('There is a security update available for your version of Drupal. To ensure the security of your server, you should update immediately!', [], ['langcode' => $langcode]);
580       }
581       else {
582         $text = t('There are security updates available for one or more of your modules or themes. To ensure the security of your server, you should update immediately!', [], ['langcode' => $langcode]);
583       }
584       break;
585
586     case UPDATE_REVOKED:
587       if ($msg_type == 'core') {
588         $text = t('Your version of Drupal has been revoked and is no longer available for download. Upgrading is strongly recommended!', [], ['langcode' => $langcode]);
589       }
590       else {
591         $text = t('The installed version of at least one of your modules or themes has been revoked and is no longer available for download. Upgrading or disabling is strongly recommended!', [], ['langcode' => $langcode]);
592       }
593       break;
594
595     case UPDATE_NOT_SUPPORTED:
596       if ($msg_type == 'core') {
597         $text = t('Your version of Drupal is no longer supported. Upgrading is strongly recommended!', [], ['langcode' => $langcode]);
598       }
599       else {
600         $text = t('The installed version of at least one of your modules or themes is no longer supported. Upgrading or disabling is strongly recommended. See the project homepage for more details.', [], ['langcode' => $langcode]);
601       }
602       break;
603
604     case UPDATE_NOT_CURRENT:
605       if ($msg_type == 'core') {
606         $text = t('There are updates available for your version of Drupal. To ensure the proper functioning of your site, you should update as soon as possible.', [], ['langcode' => $langcode]);
607       }
608       else {
609         $text = t('There are updates available for one or more of your modules or themes. To ensure the proper functioning of your site, you should update as soon as possible.', [], ['langcode' => $langcode]);
610       }
611       break;
612
613     case UPDATE_UNKNOWN:
614     case UPDATE_NOT_CHECKED:
615     case UPDATE_NOT_FETCHED:
616     case UPDATE_FETCH_PENDING:
617       if ($msg_type == 'core') {
618         $text = t('There was a problem checking <a href=":update-report">available updates</a> for Drupal.', [':update-report' => \Drupal::url('update.status')], ['langcode' => $langcode]);
619       }
620       else {
621         $text = t('There was a problem checking <a href=":update-report">available updates</a> for your modules or themes.', [':update-report' => \Drupal::url('update.status')], ['langcode' => $langcode]);
622       }
623       break;
624   }
625
626   return $text;
627 }
628
629 /**
630  * Orders projects based on their status.
631  *
632  * Callback for uasort() within update_requirements().
633  */
634 function _update_project_status_sort($a, $b) {
635   // The status constants are numerically in the right order, so we can
636   // usually subtract the two to compare in the order we want. However,
637   // negative status values should be treated as if they are huge, since we
638   // always want them at the bottom of the list.
639   $a_status = $a['status'] > 0 ? $a['status'] : (-10 * $a['status']);
640   $b_status = $b['status'] > 0 ? $b['status'] : (-10 * $b['status']);
641   return $a_status - $b_status;
642 }
643
644 /**
645  * Prepares variables for last time update data was checked templates.
646  *
647  * Default template: update-last-check.html.twig.
648  *
649  * In addition to properly formatting the given timestamp, this function also
650  * provides a "Check manually" link that refreshes the available update and
651  * redirects back to the same page.
652  *
653  * @param $variables
654  *   An associative array containing:
655  *   - last: The timestamp when the site last checked for available updates.
656  *
657  * @see theme_update_report()
658  */
659 function template_preprocess_update_last_check(&$variables) {
660   $variables['time'] = \Drupal::service('date.formatter')->formatTimeDiffSince($variables['last']);
661   $variables['link'] = \Drupal::l(t('Check manually'), new Url('update.manual_status', [], ['query' => \Drupal::destination()->getAsArray()]));
662 }
663
664 /**
665  * Implements hook_verify_update_archive().
666  *
667  * First, we ensure that the archive isn't a copy of Drupal core, which the
668  * update manager does not yet support. See https://www.drupal.org/node/606592.
669  *
670  * Then, we make sure that at least one module included in the archive file has
671  * an .info.yml file which claims that the code is compatible with the current
672  * version of Drupal core.
673  *
674  * @see \Drupal\Core\Extension\ExtensionDiscovery
675  * @see _system_rebuild_module_data()
676  */
677 function update_verify_update_archive($project, $archive_file, $directory) {
678   $errors = [];
679
680   // Make sure this isn't a tarball of Drupal core.
681   if (
682     file_exists("$directory/$project/index.php")
683     && file_exists("$directory/$project/core/install.php")
684     && file_exists("$directory/$project/core/includes/bootstrap.inc")
685     && file_exists("$directory/$project/core/modules/node/node.module")
686     && file_exists("$directory/$project/core/modules/system/system.module")
687   ) {
688     return [
689       'no-core' => t('Automatic updating of Drupal core is not supported. See the <a href=":upgrade-guide">upgrade guide</a> for information on how to update Drupal core manually.', [':upgrade-guide' => 'https://www.drupal.org/upgrade']),
690     ];
691   }
692
693   // Parse all the .info.yml files and make sure at least one is compatible with
694   // this version of Drupal core. If one is compatible, then the project as a
695   // whole is considered compatible (since, for example, the project may ship
696   // with some out-of-date modules that are not necessary for its overall
697   // functionality).
698   $compatible_project = FALSE;
699   $incompatible = [];
700   $files = file_scan_directory("$directory/$project", '/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.info.yml$/', ['key' => 'name', 'min_depth' => 0]);
701   foreach ($files as $file) {
702     // Get the .info.yml file for the module or theme this file belongs to.
703     $info = \Drupal::service('info_parser')->parse($file->uri);
704
705     // If the module or theme is incompatible with Drupal core, set an error.
706     if (empty($info['core']) || $info['core'] != \Drupal::CORE_COMPATIBILITY) {
707       $incompatible[] = !empty($info['name']) ? $info['name'] : t('Unknown');
708     }
709     else {
710       $compatible_project = TRUE;
711       break;
712     }
713   }
714
715   if (empty($files)) {
716     $errors[] = t('%archive_file does not contain any .info.yml files.', ['%archive_file' => drupal_basename($archive_file)]);
717   }
718   elseif (!$compatible_project) {
719     $errors[] = \Drupal::translation()->formatPlural(
720       count($incompatible),
721       '%archive_file contains a version of %names that is not compatible with Drupal @version.',
722       '%archive_file contains versions of modules or themes that are not compatible with Drupal @version: %names',
723       ['@version' => \Drupal::CORE_COMPATIBILITY, '%archive_file' => drupal_basename($archive_file), '%names' => implode(', ', $incompatible)]
724     );
725   }
726
727   return $errors;
728 }
729
730 /**
731  * Invalidates stored data relating to update status.
732  */
733 function update_storage_clear() {
734   \Drupal::keyValueExpirable('update')->deleteAll();
735   \Drupal::keyValueExpirable('update_available_release')->deleteAll();
736 }
737
738 /**
739  * Returns a short unique identifier for this Drupal installation.
740  *
741  * @return
742  *   An eight character string uniquely identifying this Drupal installation.
743  */
744 function _update_manager_unique_identifier() {
745   $id = &drupal_static(__FUNCTION__, '');
746   if (empty($id)) {
747     $id = substr(hash('sha256', Settings::getHashSalt()), 0, 8);
748   }
749   return $id;
750 }
751
752 /**
753  * Returns the directory where update archive files should be extracted.
754  *
755  * @param $create
756  *   (optional) Whether to attempt to create the directory if it does not
757  *   already exist. Defaults to TRUE.
758  *
759  * @return
760  *   The full path to the temporary directory where update file archives should
761  *   be extracted.
762  */
763 function _update_manager_extract_directory($create = TRUE) {
764   $directory = &drupal_static(__FUNCTION__, '');
765   if (empty($directory)) {
766     $directory = 'temporary://update-extraction-' . _update_manager_unique_identifier();
767     if ($create && !file_exists($directory)) {
768       mkdir($directory);
769     }
770   }
771   return $directory;
772 }
773
774 /**
775  * Returns the directory where update archive files should be cached.
776  *
777  * @param $create
778  *   (optional) Whether to attempt to create the directory if it does not
779  *   already exist. Defaults to TRUE.
780  *
781  * @return
782  *   The full path to the temporary directory where update file archives should
783  *   be cached.
784  */
785 function _update_manager_cache_directory($create = TRUE) {
786   $directory = &drupal_static(__FUNCTION__, '');
787   if (empty($directory)) {
788     $directory = 'temporary://update-cache-' . _update_manager_unique_identifier();
789     if ($create && !file_exists($directory)) {
790       mkdir($directory);
791     }
792   }
793   return $directory;
794 }
795
796 /**
797  * Clears the temporary files and directories based on file age from disk.
798  */
799 function update_clear_update_disk_cache() {
800   // List of update module cache directories. Do not create the directories if
801   // they do not exist.
802   $directories = [
803     _update_manager_cache_directory(FALSE),
804     _update_manager_extract_directory(FALSE),
805   ];
806
807   // Search for files and directories in base folder only without recursion.
808   foreach ($directories as $directory) {
809     file_scan_directory($directory, '/.*/', ['callback' => 'update_delete_file_if_stale', 'recurse' => FALSE]);
810   }
811 }
812
813 /**
814  * Deletes stale files and directories from the update manager disk cache.
815  *
816  * Files and directories older than 6 hours and development snapshots older than
817  * 5 minutes are considered stale. We only cache development snapshots for 5
818  * minutes since otherwise updated snapshots might not be downloaded as
819  * expected.
820  *
821  * When checking file ages, we need to use the ctime, not the mtime
822  * (modification time) since many (all?) tar implementations go out of their way
823  * to set the mtime on the files they create to the timestamps recorded in the
824  * tarball. We want to see the last time the file was changed on disk, which is
825  * left alone by tar and correctly set to the time the archive file was
826  * unpacked.
827  *
828  * @param $path
829  *   A string containing a file path or (streamwrapper) URI.
830  */
831 function update_delete_file_if_stale($path) {
832   if (file_exists($path)) {
833     $filectime = filectime($path);
834     $max_age = \Drupal::config('system.file')->get('temporary_maximum_age');
835
836     if (REQUEST_TIME - $filectime > $max_age || (preg_match('/.*-dev\.(tar\.gz|zip)/i', $path) && REQUEST_TIME - $filectime > 300)) {
837       file_unmanaged_delete_recursive($path);
838     }
839   }
840 }