update.module 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  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 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. * Resolves if the current user can access updater menu items.
  198. *
  199. * It both enforces the 'administer software updates' permission and the global
  200. * kill switch for the authorize.php script.
  201. *
  202. * @return
  203. * TRUE if the current user can access the updater menu items; FALSE
  204. * otherwise.
  205. */
  206. function _update_manager_access() {
  207. return Settings::get('allow_authorize_operations', TRUE) && \Drupal::currentUser()->hasPermission('administer software updates');
  208. }
  209. /**
  210. * Implements hook_theme().
  211. */
  212. function update_theme() {
  213. return [
  214. 'update_last_check' => [
  215. 'variables' => ['last' => 0],
  216. ],
  217. 'update_report' => [
  218. 'variables' => ['data' => NULL],
  219. 'file' => 'update.report.inc',
  220. ],
  221. 'update_project_status' => [
  222. 'variables' => ['project' => []],
  223. 'file' => 'update.report.inc',
  224. ],
  225. // We are using template instead of '#type' => 'table' here to keep markup
  226. // out of preprocess and allow for easier changes to markup.
  227. 'update_version' => [
  228. 'variables' => ['version' => NULL, 'title' => NULL, 'attributes' => []],
  229. 'file' => 'update.report.inc',
  230. ],
  231. ];
  232. }
  233. /**
  234. * Implements hook_cron().
  235. */
  236. function update_cron() {
  237. $update_config = \Drupal::config('update.settings');
  238. $frequency = $update_config->get('check.interval_days');
  239. $interval = 60 * 60 * 24 * $frequency;
  240. $last_check = \Drupal::state()->get('update.last_check') ?: 0;
  241. if ((REQUEST_TIME - $last_check) > $interval) {
  242. // If the configured update interval has elapsed, we want to invalidate
  243. // the data for all projects, attempt to re-fetch, and trigger any
  244. // configured notifications about the new status.
  245. update_refresh();
  246. update_fetch_data();
  247. }
  248. else {
  249. // Otherwise, see if any individual projects are now stale or still
  250. // missing data, and if so, try to fetch the data.
  251. update_get_available(TRUE);
  252. }
  253. $last_email_notice = \Drupal::state()->get('update.last_email_notification') ?: 0;
  254. if ((REQUEST_TIME - $last_email_notice) > $interval) {
  255. // If configured time between notifications elapsed, send email about
  256. // updates possibly available.
  257. module_load_include('inc', 'update', 'update.fetch');
  258. _update_cron_notify();
  259. }
  260. // Clear garbage from disk.
  261. update_clear_update_disk_cache();
  262. }
  263. /**
  264. * Implements hook_themes_installed().
  265. *
  266. * If themes are installed, we invalidate the information of available updates.
  267. */
  268. function update_themes_installed($themes) {
  269. // Clear all update module data.
  270. update_storage_clear();
  271. }
  272. /**
  273. * Implements hook_themes_uninstalled().
  274. *
  275. * If themes are uninstalled, we invalidate the information of available updates.
  276. */
  277. function update_themes_uninstalled($themes) {
  278. // Clear all update module data.
  279. update_storage_clear();
  280. }
  281. /**
  282. * Implements hook_form_FORM_ID_alter() for system_modules().
  283. *
  284. * Adds a form submission handler to the system modules form, so that if a site
  285. * admin saves the form, we invalidate the information of available updates.
  286. *
  287. * @see _update_cache_clear()
  288. */
  289. function update_form_system_modules_alter(&$form, FormStateInterface $form_state) {
  290. $form['#submit'][] = 'update_storage_clear_submit';
  291. }
  292. /**
  293. * Form submission handler for system_modules().
  294. *
  295. * @see update_form_system_modules_alter()
  296. */
  297. function update_storage_clear_submit($form, FormStateInterface $form_state) {
  298. // Clear all update module data.
  299. update_storage_clear();
  300. }
  301. /**
  302. * Returns a warning message when there is no data about available updates.
  303. */
  304. function _update_no_data() {
  305. $destination = \Drupal::destination()->getAsArray();
  306. return t('No update information available. <a href=":run_cron">Run cron</a> or <a href=":check_manually">check manually</a>.', [
  307. ':run_cron' => \Drupal::url('system.run_cron', [], ['query' => $destination]),
  308. ':check_manually' => \Drupal::url('update.manual_status', [], ['query' => $destination]),
  309. ]);
  310. }
  311. /**
  312. * Tries to get update information and refreshes it when necessary.
  313. *
  314. * In addition to checking the lifetime, this function also ensures that
  315. * there are no .info.yml files for enabled modules or themes that have a newer
  316. * modification timestamp than the last time we checked for available update
  317. * data. If any .info.yml file was modified, it almost certainly means a new
  318. * version of something was installed. Without fresh available update data, the
  319. * logic in update_calculate_project_data() will be wrong and produce confusing,
  320. * bogus results.
  321. *
  322. * @param $refresh
  323. * (optional) Boolean to indicate if this method should refresh automatically
  324. * if there's no data. Defaults to FALSE.
  325. *
  326. * @return
  327. * Array of data about available releases, keyed by project shortname.
  328. *
  329. * @see update_refresh()
  330. * @see \Drupal\Update\UpdateManager::getProjects()
  331. */
  332. function update_get_available($refresh = FALSE) {
  333. module_load_include('inc', 'update', 'update.compare');
  334. $needs_refresh = FALSE;
  335. // Grab whatever data we currently have.
  336. $available = \Drupal::keyValueExpirable('update_available_releases')->getAll();
  337. $projects = \Drupal::service('update.manager')->getProjects();
  338. foreach ($projects as $key => $project) {
  339. // If there's no data at all, we clearly need to fetch some.
  340. if (empty($available[$key])) {
  341. // update_create_fetch_task($project);
  342. \Drupal::service('update.processor')->createFetchTask($project);
  343. $needs_refresh = TRUE;
  344. continue;
  345. }
  346. // See if the .info.yml file is newer than the last time we checked for
  347. // data, and if so, mark this project's data as needing to be re-fetched.
  348. // Any time an admin upgrades their local installation, the .info.yml file
  349. // will be changed, so this is the only way we can be sure we're not showing
  350. // bogus information right after they upgrade.
  351. if ($project['info']['_info_file_ctime'] > $available[$key]['last_fetch']) {
  352. $available[$key]['fetch_status'] = UPDATE_FETCH_PENDING;
  353. }
  354. // If we have project data but no release data, we need to fetch. This
  355. // can be triggered when we fail to contact a release history server.
  356. if (empty($available[$key]['releases']) && !$available[$key]['last_fetch']) {
  357. $available[$key]['fetch_status'] = UPDATE_FETCH_PENDING;
  358. }
  359. // If we think this project needs to fetch, actually create the task now
  360. // and remember that we think we're missing some data.
  361. if (!empty($available[$key]['fetch_status']) && $available[$key]['fetch_status'] == UPDATE_FETCH_PENDING) {
  362. \Drupal::service('update.processor')->createFetchTask($project);
  363. $needs_refresh = TRUE;
  364. }
  365. }
  366. if ($needs_refresh && $refresh) {
  367. // Attempt to drain the queue of fetch tasks.
  368. update_fetch_data();
  369. // After processing the queue, we've (hopefully) got better data, so pull
  370. // the latest data again and use that directly.
  371. $available = \Drupal::keyValueExpirable('update_available_releases')->getAll();
  372. }
  373. return $available;
  374. }
  375. /**
  376. * Adds a task to the queue for fetching release history data for a project.
  377. *
  378. * We only create a new fetch task if there's no task already in the queue for
  379. * this particular project (based on 'update_fetch_task' key-value collection).
  380. *
  381. * @param $project
  382. * Associative array of information about a project as created by
  383. * \Drupal\Update\UpdateManager::getProjects(), including keys such as 'name'
  384. * (short name), and the 'info' array with data from a .info.yml file for the
  385. * project.
  386. *
  387. * @see \Drupal\update\UpdateFetcher::createFetchTask()
  388. */
  389. function update_create_fetch_task($project) {
  390. \Drupal::service('update.processor')->createFetchTask($project);
  391. }
  392. /**
  393. * Refreshes the release data after loading the necessary include file.
  394. */
  395. function update_refresh() {
  396. \Drupal::service('update.manager')->refreshUpdateData();
  397. }
  398. /**
  399. * Attempts to fetch update data after loading the necessary include file.
  400. *
  401. * @see \Drupal\update\UpdateProcessor::fetchData()
  402. */
  403. function update_fetch_data() {
  404. \Drupal::service('update.processor')->fetchData();
  405. }
  406. /**
  407. * Batch callback: Performs actions when all fetch tasks have been completed.
  408. *
  409. * @param $success
  410. * TRUE if the batch operation was successful; FALSE if there were errors.
  411. * @param $results
  412. * An associative array of results from the batch operation, including the key
  413. * 'updated' which holds the total number of projects we fetched available
  414. * update data for.
  415. */
  416. function update_fetch_data_finished($success, $results) {
  417. if ($success) {
  418. if (!empty($results)) {
  419. if (!empty($results['updated'])) {
  420. drupal_set_message(\Drupal::translation()->formatPlural($results['updated'], 'Checked available update data for one project.', 'Checked available update data for @count projects.'));
  421. }
  422. if (!empty($results['failures'])) {
  423. 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');
  424. }
  425. }
  426. }
  427. else {
  428. drupal_set_message(t('An error occurred trying to get available update data.'), 'error');
  429. }
  430. }
  431. /**
  432. * Implements hook_mail().
  433. *
  434. * Constructs the email notification message when the site is out of date.
  435. *
  436. * @param $key
  437. * Unique key to indicate what message to build, always 'status_notify'.
  438. * @param $message
  439. * Reference to the message array being built.
  440. * @param $params
  441. * Array of parameters to indicate what kind of text to include in the message
  442. * body. This is a keyed array of message type ('core' or 'contrib') as the
  443. * keys, and the status reason constant (UPDATE_NOT_SECURE, etc) for the
  444. * values.
  445. *
  446. * @see \Drupal\Core\Mail\MailManagerInterface::mail()
  447. * @see _update_cron_notify()
  448. * @see _update_message_text()
  449. */
  450. function update_mail($key, &$message, $params) {
  451. $langcode = $message['langcode'];
  452. $language = \Drupal::languageManager()->getLanguage($langcode);
  453. $message['subject'] .= t('New release(s) available for @site_name', ['@site_name' => \Drupal::config('system.site')->get('name')], ['langcode' => $langcode]);
  454. foreach ($params as $msg_type => $msg_reason) {
  455. $message['body'][] = _update_message_text($msg_type, $msg_reason, $langcode);
  456. }
  457. $message['body'][] = t('See the available updates page for more information:', [], ['langcode' => $langcode]) . "\n" . \Drupal::url('update.status', [], ['absolute' => TRUE, 'language' => $language]);
  458. if (_update_manager_access()) {
  459. $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]);
  460. }
  461. $settings_url = \Drupal::url('update.settings', [], ['absolute' => TRUE]);
  462. if (\Drupal::config('update.settings')->get('notification.threshold') == 'all') {
  463. $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]);
  464. }
  465. else {
  466. $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]);
  467. }
  468. }
  469. /**
  470. * Returns the appropriate message text when site is out of date or not secure.
  471. *
  472. * These error messages are shared by both update_requirements() for the
  473. * site-wide status report at admin/reports/status and in the body of the
  474. * notification email messages generated by update_cron().
  475. *
  476. * @param $msg_type
  477. * String to indicate what kind of message to generate. Can be either 'core'
  478. * or 'contrib'.
  479. * @param $msg_reason
  480. * Integer constant specifying why message is generated.
  481. * @param $langcode
  482. * (optional) A language code to use. Defaults to NULL.
  483. *
  484. * @return
  485. * The properly translated error message for the given key.
  486. */
  487. function _update_message_text($msg_type, $msg_reason, $langcode = NULL) {
  488. $text = '';
  489. switch ($msg_reason) {
  490. case UPDATE_NOT_SECURE:
  491. if ($msg_type == 'core') {
  492. $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]);
  493. }
  494. else {
  495. $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]);
  496. }
  497. break;
  498. case UPDATE_REVOKED:
  499. if ($msg_type == 'core') {
  500. $text = t('Your version of Drupal has been revoked and is no longer available for download. Upgrading is strongly recommended!', [], ['langcode' => $langcode]);
  501. }
  502. else {
  503. $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]);
  504. }
  505. break;
  506. case UPDATE_NOT_SUPPORTED:
  507. if ($msg_type == 'core') {
  508. $text = t('Your version of Drupal is no longer supported. Upgrading is strongly recommended!', [], ['langcode' => $langcode]);
  509. }
  510. else {
  511. $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]);
  512. }
  513. break;
  514. case UPDATE_NOT_CURRENT:
  515. if ($msg_type == 'core') {
  516. $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]);
  517. }
  518. else {
  519. $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]);
  520. }
  521. break;
  522. case UPDATE_UNKNOWN:
  523. case UPDATE_NOT_CHECKED:
  524. case UPDATE_NOT_FETCHED:
  525. case UPDATE_FETCH_PENDING:
  526. if ($msg_type == 'core') {
  527. $text = t('There was a problem checking <a href=":update-report">available updates</a> for Drupal.', [':update-report' => \Drupal::url('update.status')], ['langcode' => $langcode]);
  528. }
  529. else {
  530. $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]);
  531. }
  532. break;
  533. }
  534. return $text;
  535. }
  536. /**
  537. * Orders projects based on their status.
  538. *
  539. * Callback for uasort() within update_requirements().
  540. */
  541. function _update_project_status_sort($a, $b) {
  542. // The status constants are numerically in the right order, so we can
  543. // usually subtract the two to compare in the order we want. However,
  544. // negative status values should be treated as if they are huge, since we
  545. // always want them at the bottom of the list.
  546. $a_status = $a['status'] > 0 ? $a['status'] : (-10 * $a['status']);
  547. $b_status = $b['status'] > 0 ? $b['status'] : (-10 * $b['status']);
  548. return $a_status - $b_status;
  549. }
  550. /**
  551. * Prepares variables for last time update data was checked templates.
  552. *
  553. * Default template: update-last-check.html.twig.
  554. *
  555. * In addition to properly formatting the given timestamp, this function also
  556. * provides a "Check manually" link that refreshes the available update and
  557. * redirects back to the same page.
  558. *
  559. * @param $variables
  560. * An associative array containing:
  561. * - last: The timestamp when the site last checked for available updates.
  562. *
  563. * @see theme_update_report()
  564. */
  565. function template_preprocess_update_last_check(&$variables) {
  566. $variables['time'] = \Drupal::service('date.formatter')->formatTimeDiffSince($variables['last']);
  567. $variables['link'] = \Drupal::l(t('Check manually'), new Url('update.manual_status', [], ['query' => \Drupal::destination()->getAsArray()]));
  568. }
  569. /**
  570. * Implements hook_verify_update_archive().
  571. *
  572. * First, we ensure that the archive isn't a copy of Drupal core, which the
  573. * update manager does not yet support. See https://www.drupal.org/node/606592.
  574. *
  575. * Then, we make sure that at least one module included in the archive file has
  576. * an .info.yml file which claims that the code is compatible with the current
  577. * version of Drupal core.
  578. *
  579. * @see \Drupal\Core\Extension\ExtensionDiscovery
  580. * @see _system_rebuild_module_data()
  581. */
  582. function update_verify_update_archive($project, $archive_file, $directory) {
  583. $errors = [];
  584. // Make sure this isn't a tarball of Drupal core.
  585. if (
  586. file_exists("$directory/$project/index.php")
  587. && file_exists("$directory/$project/core/install.php")
  588. && file_exists("$directory/$project/core/includes/bootstrap.inc")
  589. && file_exists("$directory/$project/core/modules/node/node.module")
  590. && file_exists("$directory/$project/core/modules/system/system.module")
  591. ) {
  592. return [
  593. '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']),
  594. ];
  595. }
  596. // Parse all the .info.yml files and make sure at least one is compatible with
  597. // this version of Drupal core. If one is compatible, then the project as a
  598. // whole is considered compatible (since, for example, the project may ship
  599. // with some out-of-date modules that are not necessary for its overall
  600. // functionality).
  601. $compatible_project = FALSE;
  602. $incompatible = [];
  603. $files = file_scan_directory("$directory/$project", '/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.info.yml$/', ['key' => 'name', 'min_depth' => 0]);
  604. foreach ($files as $file) {
  605. // Get the .info.yml file for the module or theme this file belongs to.
  606. $info = \Drupal::service('info_parser')->parse($file->uri);
  607. // If the module or theme is incompatible with Drupal core, set an error.
  608. if (empty($info['core']) || $info['core'] != \Drupal::CORE_COMPATIBILITY) {
  609. $incompatible[] = !empty($info['name']) ? $info['name'] : t('Unknown');
  610. }
  611. else {
  612. $compatible_project = TRUE;
  613. break;
  614. }
  615. }
  616. if (empty($files)) {
  617. $errors[] = t('%archive_file does not contain any .info.yml files.', ['%archive_file' => drupal_basename($archive_file)]);
  618. }
  619. elseif (!$compatible_project) {
  620. $errors[] = \Drupal::translation()->formatPlural(
  621. count($incompatible),
  622. '%archive_file contains a version of %names that is not compatible with Drupal @version.',
  623. '%archive_file contains versions of modules or themes that are not compatible with Drupal @version: %names',
  624. ['@version' => \Drupal::CORE_COMPATIBILITY, '%archive_file' => drupal_basename($archive_file), '%names' => implode(', ', $incompatible)]
  625. );
  626. }
  627. return $errors;
  628. }
  629. /**
  630. * Invalidates stored data relating to update status.
  631. */
  632. function update_storage_clear() {
  633. \Drupal::keyValueExpirable('update')->deleteAll();
  634. \Drupal::keyValueExpirable('update_available_release')->deleteAll();
  635. }
  636. /**
  637. * Returns a short unique identifier for this Drupal installation.
  638. *
  639. * @return
  640. * An eight character string uniquely identifying this Drupal installation.
  641. */
  642. function _update_manager_unique_identifier() {
  643. $id = &drupal_static(__FUNCTION__, '');
  644. if (empty($id)) {
  645. $id = substr(hash('sha256', Settings::getHashSalt()), 0, 8);
  646. }
  647. return $id;
  648. }
  649. /**
  650. * Returns the directory where update archive files should be extracted.
  651. *
  652. * @param $create
  653. * (optional) Whether to attempt to create the directory if it does not
  654. * already exist. Defaults to TRUE.
  655. *
  656. * @return
  657. * The full path to the temporary directory where update file archives should
  658. * be extracted.
  659. */
  660. function _update_manager_extract_directory($create = TRUE) {
  661. $directory = &drupal_static(__FUNCTION__, '');
  662. if (empty($directory)) {
  663. $directory = 'temporary://update-extraction-' . _update_manager_unique_identifier();
  664. if ($create && !file_exists($directory)) {
  665. mkdir($directory);
  666. }
  667. }
  668. return $directory;
  669. }
  670. /**
  671. * Returns the directory where update archive files should be cached.
  672. *
  673. * @param $create
  674. * (optional) Whether to attempt to create the directory if it does not
  675. * already exist. Defaults to TRUE.
  676. *
  677. * @return
  678. * The full path to the temporary directory where update file archives should
  679. * be cached.
  680. */
  681. function _update_manager_cache_directory($create = TRUE) {
  682. $directory = &drupal_static(__FUNCTION__, '');
  683. if (empty($directory)) {
  684. $directory = 'temporary://update-cache-' . _update_manager_unique_identifier();
  685. if ($create && !file_exists($directory)) {
  686. mkdir($directory);
  687. }
  688. }
  689. return $directory;
  690. }
  691. /**
  692. * Clears the temporary files and directories based on file age from disk.
  693. */
  694. function update_clear_update_disk_cache() {
  695. // List of update module cache directories. Do not create the directories if
  696. // they do not exist.
  697. $directories = [
  698. _update_manager_cache_directory(FALSE),
  699. _update_manager_extract_directory(FALSE),
  700. ];
  701. // Search for files and directories in base folder only without recursion.
  702. foreach ($directories as $directory) {
  703. file_scan_directory($directory, '/.*/', ['callback' => 'update_delete_file_if_stale', 'recurse' => FALSE]);
  704. }
  705. }
  706. /**
  707. * Deletes stale files and directories from the update manager disk cache.
  708. *
  709. * Files and directories older than 6 hours and development snapshots older than
  710. * 5 minutes are considered stale. We only cache development snapshots for 5
  711. * minutes since otherwise updated snapshots might not be downloaded as
  712. * expected.
  713. *
  714. * When checking file ages, we need to use the ctime, not the mtime
  715. * (modification time) since many (all?) tar implementations go out of their way
  716. * to set the mtime on the files they create to the timestamps recorded in the
  717. * tarball. We want to see the last time the file was changed on disk, which is
  718. * left alone by tar and correctly set to the time the archive file was
  719. * unpacked.
  720. *
  721. * @param $path
  722. * A string containing a file path or (streamwrapper) URI.
  723. */
  724. function update_delete_file_if_stale($path) {
  725. if (file_exists($path)) {
  726. $filectime = filectime($path);
  727. $max_age = \Drupal::config('system.file')->get('temporary_maximum_age');
  728. if (REQUEST_TIME - $filectime > $max_age || (preg_match('/.*-dev\.(tar\.gz|zip)/i', $path) && REQUEST_TIME - $filectime > 300)) {
  729. file_unmanaged_delete_recursive($path);
  730. }
  731. }
  732. }