update.module 34 KB

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