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