update.module 35 KB

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