update.module 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  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 e-mail. It also provides the
  10. * ability to install contributed modules and themes via an user interface.
  11. */
  12. /**
  13. * URL to check for updates, if a given project doesn't define its own.
  14. */
  15. define('UPDATE_DEFAULT_URL', 'http://updates.drupal.org/release-history');
  16. // These are internally used constants for this code, do not modify.
  17. /**
  18. * Project is missing security update(s).
  19. */
  20. define('UPDATE_NOT_SECURE', 1);
  21. /**
  22. * Current release has been unpublished and is no longer available.
  23. */
  24. define('UPDATE_REVOKED', 2);
  25. /**
  26. * Current release is no longer supported by the project maintainer.
  27. */
  28. define('UPDATE_NOT_SUPPORTED', 3);
  29. /**
  30. * Project has a new release available, but it is not a security release.
  31. */
  32. define('UPDATE_NOT_CURRENT', 4);
  33. /**
  34. * Project is up to date.
  35. */
  36. define('UPDATE_CURRENT', 5);
  37. /**
  38. * Project's status cannot be checked.
  39. */
  40. define('UPDATE_NOT_CHECKED', -1);
  41. /**
  42. * No available update data was found for project.
  43. */
  44. define('UPDATE_UNKNOWN', -2);
  45. /**
  46. * There was a failure fetching available update data for this project.
  47. */
  48. define('UPDATE_NOT_FETCHED', -3);
  49. /**
  50. * We need to (re)fetch available update data for this project.
  51. */
  52. define('UPDATE_FETCH_PENDING', -4);
  53. /**
  54. * Maximum number of attempts to fetch available update data from a given host.
  55. */
  56. define('UPDATE_MAX_FETCH_ATTEMPTS', 2);
  57. /**
  58. * Maximum number of seconds to try fetching available update data at a time.
  59. */
  60. define('UPDATE_MAX_FETCH_TIME', 5);
  61. /**
  62. * Implements hook_help().
  63. */
  64. function update_help($path, $arg) {
  65. switch ($path) {
  66. case 'admin/reports/updates':
  67. 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>';
  68. case 'admin/help#update':
  69. $output = '';
  70. $output .= '<h3>' . t('About') . '</h3>';
  71. $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. In order to provide update information, anonymous usage statistics are sent to Drupal.org. If desired, you may disable the Update manager module from the <a href='@modules'>Module administration page</a>. For more information, see the online handbook entry for <a href='@update'>Update manager module</a>.", array('@update' => 'http://drupal.org/documentation/modules/update', '@modules' => url('admin/modules'))) . '</p>';
  72. // Only explain the Update manager if it has not been disabled.
  73. if (update_manager_access()) {
  74. $output .= '<p>' . t('The Update manager also allows administrators to update and install modules and themes through the administration interface.') . '</p>';
  75. }
  76. $output .= '<h3>' . t('Uses') . '</h3>';
  77. $output .= '<dl>';
  78. $output .= '<dt>' . t('Checking for available updates') . '</dt>';
  79. $output .= '<dd>' . t('A report of <a href="@update-report">available updates</a> will alert you when new releases are available for download. You may configure options for the frequency for checking updates (which are performed during <a href="@cron">cron</a> runs) and e-mail notifications at the <a href="@update-settings">Update manager settings</a> page.', array('@update-report' => url('admin/reports/updates'), '@cron' => 'http://drupal.org/cron', '@update-settings' => url('admin/reports/updates/settings'))) . '</dd>';
  80. // Only explain the Update manager if it has not been disabled.
  81. if (update_manager_access()) {
  82. $output .= '<dt>' . t('Performing updates through the user interface') . '</dt>';
  83. $output .= '<dd>' . t('The Update manager module allows administrators to perform updates directly through the administration interface. At the top of the <a href="@modules_page">modules</a> and <a href="@themes_page">themes</a> pages you will see a link to update to new releases. This will direct you to the <a href="@update-page">update page</a> where you see a listing of all the missing updates and confirm which ones you want to upgrade. From there, you are prompted for your FTP/SSH password, which then transfers the files into your Drupal installation, overwriting your old files. More detailed instructions can be found in the <a href="@update">online handbook</a>.', array('@modules_page' => url('admin/modules'), '@themes_page' => url('admin/appearance'), '@update-page' => url('admin/reports/updates/update'), '@update' => 'http://drupal.org/documentation/modules/update')) . '</dd>';
  84. $output .= '<dt>' . t('Installing new modules and themes through the user interface') . '</dt>';
  85. $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> link at the top of the <a href="@modules_page">modules</a> and <a href="@themes_page">themes</a> pages. 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.', array('@modules_page' => url('admin/modules'), '@themes_page' => url('admin/appearance'), '@install' => url('admin/reports/updates/install'))) . '</dd>';
  86. }
  87. $output .= '</dl>';
  88. return $output;
  89. }
  90. }
  91. /**
  92. * Implements hook_init().
  93. */
  94. function update_init() {
  95. if (arg(0) == 'admin' && user_access('administer site configuration')) {
  96. switch ($_GET['q']) {
  97. // These pages don't need additional nagging.
  98. case 'admin/appearance/update':
  99. case 'admin/appearance/install':
  100. case 'admin/modules/update':
  101. case 'admin/modules/install':
  102. case 'admin/reports/updates':
  103. case 'admin/reports/updates/update':
  104. case 'admin/reports/updates/install':
  105. case 'admin/reports/updates/settings':
  106. case 'admin/reports/status':
  107. case 'admin/update/ready':
  108. return;
  109. // If we are on the appearance or modules list, display a detailed report
  110. // of the update status.
  111. case 'admin/appearance':
  112. case 'admin/modules':
  113. $verbose = TRUE;
  114. break;
  115. }
  116. module_load_install('update');
  117. $status = update_requirements('runtime');
  118. foreach (array('core', 'contrib') as $report_type) {
  119. $type = 'update_' . $report_type;
  120. if (!empty($verbose)) {
  121. if (isset($status[$type]['severity'])) {
  122. if ($status[$type]['severity'] == REQUIREMENT_ERROR) {
  123. drupal_set_message($status[$type]['description'], 'error', FALSE);
  124. }
  125. elseif ($status[$type]['severity'] == REQUIREMENT_WARNING) {
  126. drupal_set_message($status[$type]['description'], 'warning', FALSE);
  127. }
  128. }
  129. }
  130. // Otherwise, if we're on *any* admin page and there's a security
  131. // update missing, print an error message about it.
  132. else {
  133. if (isset($status[$type])
  134. && isset($status[$type]['reason'])
  135. && $status[$type]['reason'] === UPDATE_NOT_SECURE) {
  136. drupal_set_message($status[$type]['description'], 'error', FALSE);
  137. }
  138. }
  139. }
  140. }
  141. }
  142. /**
  143. * Implements hook_menu().
  144. */
  145. function update_menu() {
  146. $items = array();
  147. $items['admin/reports/updates'] = array(
  148. 'title' => 'Available updates',
  149. 'description' => 'Get a status report about available updates for your installed modules and themes.',
  150. 'page callback' => 'update_status',
  151. 'access arguments' => array('administer site configuration'),
  152. 'weight' => -50,
  153. 'file' => 'update.report.inc',
  154. );
  155. $items['admin/reports/updates/list'] = array(
  156. 'title' => 'List',
  157. 'access arguments' => array('administer site configuration'),
  158. 'type' => MENU_DEFAULT_LOCAL_TASK,
  159. );
  160. $items['admin/reports/updates/settings'] = array(
  161. 'title' => 'Settings',
  162. 'page callback' => 'drupal_get_form',
  163. 'page arguments' => array('update_settings'),
  164. 'access arguments' => array('administer site configuration'),
  165. 'file' => 'update.settings.inc',
  166. 'type' => MENU_LOCAL_TASK,
  167. 'weight' => 50,
  168. );
  169. $items['admin/reports/updates/check'] = array(
  170. 'title' => 'Manual update check',
  171. 'page callback' => 'update_manual_status',
  172. 'access arguments' => array('administer site configuration'),
  173. 'type' => MENU_CALLBACK,
  174. 'file' => 'update.fetch.inc',
  175. );
  176. // We want action links for updating projects at a few different locations:
  177. // both the module and theme administration pages, and on the available
  178. // updates report itself. The menu items will be mostly identical, except the
  179. // paths and titles, so we just define them in a loop. We pass in a string
  180. // indicating what context we're entering the action from, so that can
  181. // customize the appearance as needed.
  182. $paths = array(
  183. 'report' => 'admin/reports/updates',
  184. 'module' => 'admin/modules',
  185. 'theme' => 'admin/appearance',
  186. );
  187. foreach ($paths as $context => $path) {
  188. $items[$path . '/install'] = array(
  189. 'page callback' => 'drupal_get_form',
  190. 'page arguments' => array('update_manager_install_form', $context),
  191. 'access callback' => 'update_manager_access',
  192. 'access arguments' => array(),
  193. 'weight' => 25,
  194. 'type' => MENU_LOCAL_ACTION,
  195. 'file' => 'update.manager.inc',
  196. );
  197. $items[$path . '/update'] = array(
  198. 'page callback' => 'drupal_get_form',
  199. 'page arguments' => array('update_manager_update_form', $context),
  200. 'access callback' => 'update_manager_access',
  201. 'access arguments' => array(),
  202. 'weight' => 10,
  203. 'title' => 'Update',
  204. 'type' => MENU_LOCAL_TASK,
  205. 'file' => 'update.manager.inc',
  206. );
  207. }
  208. // Customize the titles of the action links depending on where they appear.
  209. // We use += array() to let the translation extractor find these menu titles.
  210. $items['admin/reports/updates/install'] += array('title' => 'Install new module or theme');
  211. $items['admin/modules/install'] += array('title' => 'Install new module');
  212. $items['admin/appearance/install'] += array('title' => 'Install new theme');
  213. // Menu callback used for the confirmation page after all the releases
  214. // have been downloaded, asking you to backup before installing updates.
  215. $items['admin/update/ready'] = array(
  216. 'title' => 'Ready to update',
  217. 'page callback' => 'drupal_get_form',
  218. 'page arguments' => array('update_manager_update_ready_form'),
  219. 'access callback' => 'update_manager_access',
  220. 'access arguments' => array(),
  221. 'type' => MENU_CALLBACK,
  222. 'file' => 'update.manager.inc',
  223. );
  224. return $items;
  225. }
  226. /**
  227. * Access callback: Resolves if the current user can access updater menu items.
  228. *
  229. * It both enforces the 'administer software updates' permission and the global
  230. * kill switch for the authorize.php script.
  231. *
  232. * @return
  233. * TRUE if the current user can access the updater menu items; FALSE
  234. * otherwise.
  235. *
  236. * @see update_menu()
  237. */
  238. function update_manager_access() {
  239. return variable_get('allow_authorize_operations', TRUE) && user_access('administer software updates');
  240. }
  241. /**
  242. * Implements hook_theme().
  243. */
  244. function update_theme() {
  245. return array(
  246. 'update_manager_update_form' => array(
  247. 'render element' => 'form',
  248. 'file' => 'update.manager.inc',
  249. ),
  250. 'update_last_check' => array(
  251. 'variables' => array('last' => NULL),
  252. ),
  253. 'update_report' => array(
  254. 'variables' => array('data' => NULL),
  255. ),
  256. 'update_version' => array(
  257. 'variables' => array('version' => NULL, 'tag' => NULL, 'class' => array()),
  258. ),
  259. 'update_status_label' => array(
  260. 'variables' => array('status' => NULL),
  261. ),
  262. );
  263. }
  264. /**
  265. * Implements hook_cron().
  266. */
  267. function update_cron() {
  268. $frequency = variable_get('update_check_frequency', 1);
  269. $interval = 60 * 60 * 24 * $frequency;
  270. if ((REQUEST_TIME - variable_get('update_last_check', 0)) > $interval) {
  271. // If the configured update interval has elapsed, we want to invalidate
  272. // the cached data for all projects, attempt to re-fetch, and trigger any
  273. // configured notifications about the new status.
  274. update_refresh();
  275. update_fetch_data();
  276. }
  277. else {
  278. // Otherwise, see if any individual projects are now stale or still
  279. // missing data, and if so, try to fetch the data.
  280. update_get_available(TRUE);
  281. }
  282. if ((REQUEST_TIME - variable_get('update_last_email_notification', 0)) > $interval) {
  283. // If configured time between notifications elapsed, send email about
  284. // updates possibly available.
  285. module_load_include('inc', 'update', 'update.fetch');
  286. _update_cron_notify();
  287. }
  288. // Clear garbage from disk.
  289. update_clear_update_disk_cache();
  290. }
  291. /**
  292. * Implements hook_themes_enabled().
  293. *
  294. * If themes are enabled, we invalidate the cache of available updates.
  295. */
  296. function update_themes_enabled($themes) {
  297. // Clear all update module caches.
  298. _update_cache_clear();
  299. }
  300. /**
  301. * Implements hook_themes_disabled().
  302. *
  303. * If themes are disabled, we invalidate the cache of available updates.
  304. */
  305. function update_themes_disabled($themes) {
  306. // Clear all update module caches.
  307. _update_cache_clear();
  308. }
  309. /**
  310. * Implements hook_form_FORM_ID_alter() for system_modules().
  311. *
  312. * Adds a form submission handler to the system modules form, so that if a site
  313. * admin saves the form, we invalidate the cache of available updates.
  314. *
  315. * @see _update_cache_clear()
  316. */
  317. function update_form_system_modules_alter(&$form, $form_state) {
  318. $form['#submit'][] = 'update_cache_clear_submit';
  319. }
  320. /**
  321. * Form submission handler for system_modules().
  322. *
  323. * @see update_form_system_modules_alter()
  324. */
  325. function update_cache_clear_submit($form, &$form_state) {
  326. // Clear all update module caches.
  327. _update_cache_clear();
  328. }
  329. /**
  330. * Returns a warning message when there is no data about available updates.
  331. */
  332. function _update_no_data() {
  333. $destination = drupal_get_destination();
  334. return t('No update information available. <a href="@run_cron">Run cron</a> or <a href="@check_manually">check manually</a>.', array(
  335. '@run_cron' => url('admin/reports/status/run-cron', array('query' => $destination)),
  336. '@check_manually' => url('admin/reports/updates/check', array('query' => $destination)),
  337. ));
  338. }
  339. /**
  340. * Tries to get update information from cache and refreshes it when necessary.
  341. *
  342. * In addition to checking the cache lifetime, this function also ensures that
  343. * there are no .info files for enabled modules or themes that have a newer
  344. * modification timestamp than the last time we checked for available update
  345. * data. If any .info file was modified, it almost certainly means a new version
  346. * of something was installed. Without fresh available update data, the logic in
  347. * update_calculate_project_data() will be wrong and produce confusing, bogus
  348. * results.
  349. *
  350. * @param $refresh
  351. * (optional) Boolean to indicate if this method should refresh the cache
  352. * automatically if there's no data. Defaults to FALSE.
  353. *
  354. * @return
  355. * Array of data about available releases, keyed by project shortname.
  356. *
  357. * @see update_refresh()
  358. * @see update_get_projects()
  359. */
  360. function update_get_available($refresh = FALSE) {
  361. module_load_include('inc', 'update', 'update.compare');
  362. $needs_refresh = FALSE;
  363. // Grab whatever data we currently have cached in the DB.
  364. $available = _update_get_cached_available_releases();
  365. $num_avail = count($available);
  366. $projects = update_get_projects();
  367. foreach ($projects as $key => $project) {
  368. // If there's no data at all, we clearly need to fetch some.
  369. if (empty($available[$key])) {
  370. update_create_fetch_task($project);
  371. $needs_refresh = TRUE;
  372. continue;
  373. }
  374. // See if the .info file is newer than the last time we checked for data,
  375. // and if so, mark this project's data as needing to be re-fetched. Any
  376. // time an admin upgrades their local installation, the .info file will
  377. // be changed, so this is the only way we can be sure we're not showing
  378. // bogus information right after they upgrade.
  379. if ($project['info']['_info_file_ctime'] > $available[$key]['last_fetch']) {
  380. $available[$key]['fetch_status'] = UPDATE_FETCH_PENDING;
  381. }
  382. // If we have project data but no release data, we need to fetch. This
  383. // can be triggered when we fail to contact a release history server.
  384. if (empty($available[$key]['releases'])) {
  385. $available[$key]['fetch_status'] = UPDATE_FETCH_PENDING;
  386. }
  387. // If we think this project needs to fetch, actually create the task now
  388. // and remember that we think we're missing some data.
  389. if (!empty($available[$key]['fetch_status']) && $available[$key]['fetch_status'] == UPDATE_FETCH_PENDING) {
  390. update_create_fetch_task($project);
  391. $needs_refresh = TRUE;
  392. }
  393. }
  394. if ($needs_refresh && $refresh) {
  395. // Attempt to drain the queue of fetch tasks.
  396. update_fetch_data();
  397. // After processing the queue, we've (hopefully) got better data, so pull
  398. // the latest from the cache again and use that directly.
  399. $available = _update_get_cached_available_releases();
  400. }
  401. return $available;
  402. }
  403. /**
  404. * Creates a new fetch task after loading the necessary include file.
  405. *
  406. * @param $project
  407. * Associative array of information about a project. See update_get_projects()
  408. * for the keys used.
  409. *
  410. * @see _update_create_fetch_task()
  411. */
  412. function update_create_fetch_task($project) {
  413. module_load_include('inc', 'update', 'update.fetch');
  414. return _update_create_fetch_task($project);
  415. }
  416. /**
  417. * Refreshes the release data after loading the necessary include file.
  418. *
  419. * @see _update_refresh()
  420. */
  421. function update_refresh() {
  422. module_load_include('inc', 'update', 'update.fetch');
  423. return _update_refresh();
  424. }
  425. /**
  426. * Attempts to fetch update data after loading the necessary include file.
  427. *
  428. * @see _update_fetch_data()
  429. */
  430. function update_fetch_data() {
  431. module_load_include('inc', 'update', 'update.fetch');
  432. return _update_fetch_data();
  433. }
  434. /**
  435. * Returns all currently cached data about available releases for all projects.
  436. *
  437. * @return
  438. * Array of data about available releases, keyed by project shortname.
  439. */
  440. function _update_get_cached_available_releases() {
  441. $data = array();
  442. $cache_items = _update_get_cache_multiple('available_releases');
  443. foreach ($cache_items as $cid => $cache) {
  444. $cache->data['last_fetch'] = $cache->created;
  445. if ($cache->expire < REQUEST_TIME) {
  446. $cache->data['fetch_status'] = UPDATE_FETCH_PENDING;
  447. }
  448. // The project shortname is embedded in the cache ID, even if there's no
  449. // data for this project in the DB at all, so use that for the indexes in
  450. // the array.
  451. $parts = explode('::', $cid, 2);
  452. $data[$parts[1]] = $cache->data;
  453. }
  454. return $data;
  455. }
  456. /**
  457. * Implements hook_mail().
  458. *
  459. * Constructs the e-mail notification message when the site is out of date.
  460. *
  461. * @param $key
  462. * Unique key to indicate what message to build, always 'status_notify'.
  463. * @param $message
  464. * Reference to the message array being built.
  465. * @param $params
  466. * Array of parameters to indicate what kind of text to include in the message
  467. * body. This is a keyed array of message type ('core' or 'contrib') as the
  468. * keys, and the status reason constant (UPDATE_NOT_SECURE, etc) for the
  469. * values.
  470. *
  471. * @see drupal_mail()
  472. * @see _update_cron_notify()
  473. * @see _update_message_text()
  474. */
  475. function update_mail($key, &$message, $params) {
  476. $language = $message['language'];
  477. $langcode = $language->language;
  478. $message['subject'] .= t('New release(s) available for !site_name', array('!site_name' => variable_get('site_name', 'Drupal')), array('langcode' => $langcode));
  479. foreach ($params as $msg_type => $msg_reason) {
  480. $message['body'][] = _update_message_text($msg_type, $msg_reason, FALSE, $language);
  481. }
  482. $message['body'][] = t('See the available updates page for more information:', array(), array('langcode' => $langcode)) . "\n" . url('admin/reports/updates', array('absolute' => TRUE, 'language' => $language));
  483. if (update_manager_access()) {
  484. $message['body'][] = t('You can automatically install your missing updates using the Update manager:', array(), array('langcode' => $langcode)) . "\n" . url('admin/reports/updates/update', array('absolute' => TRUE, 'language' => $language));
  485. }
  486. $settings_url = url('admin/reports/updates/settings', array('absolute' => TRUE));
  487. if (variable_get('update_notification_threshold', 'all') == 'all') {
  488. $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.', array('!url' => $settings_url));
  489. }
  490. else {
  491. $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.', array('!url' => $settings_url));
  492. }
  493. }
  494. /**
  495. * Returns the appropriate message text when site is out of date or not secure.
  496. *
  497. * These error messages are shared by both update_requirements() for the
  498. * site-wide status report at admin/reports/status and in the body of the
  499. * notification e-mail messages generated by update_cron().
  500. *
  501. * @param $msg_type
  502. * String to indicate what kind of message to generate. Can be either 'core'
  503. * or 'contrib'.
  504. * @param $msg_reason
  505. * Integer constant specifying why message is generated.
  506. * @param $report_link
  507. * (optional) Boolean that controls if a link to the updates report should be
  508. * added. Defaults to FALSE.
  509. * @param $language
  510. * (optional) A language object to use. Defaults to NULL.
  511. *
  512. * @return
  513. * The properly translated error message for the given key.
  514. */
  515. function _update_message_text($msg_type, $msg_reason, $report_link = FALSE, $language = NULL) {
  516. $langcode = isset($language) ? $language->language : NULL;
  517. $text = '';
  518. switch ($msg_reason) {
  519. case UPDATE_NOT_SECURE:
  520. if ($msg_type == 'core') {
  521. $text = t('There is a security update available for your version of Drupal. To ensure the security of your server, you should update immediately!', array(), array('langcode' => $langcode));
  522. }
  523. else {
  524. $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!', array(), array('langcode' => $langcode));
  525. }
  526. break;
  527. case UPDATE_REVOKED:
  528. if ($msg_type == 'core') {
  529. $text = t('Your version of Drupal has been revoked and is no longer available for download. Upgrading is strongly recommended!', array(), array('langcode' => $langcode));
  530. }
  531. else {
  532. $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!', array(), array('langcode' => $langcode));
  533. }
  534. break;
  535. case UPDATE_NOT_SUPPORTED:
  536. if ($msg_type == 'core') {
  537. $text = t('Your version of Drupal is no longer supported. Upgrading is strongly recommended!', array(), array('langcode' => $langcode));
  538. }
  539. else {
  540. $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.', array(), array('langcode' => $langcode));
  541. }
  542. break;
  543. case UPDATE_NOT_CURRENT:
  544. if ($msg_type == 'core') {
  545. $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.', array(), array('langcode' => $langcode));
  546. }
  547. else {
  548. $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.', array(), array('langcode' => $langcode));
  549. }
  550. break;
  551. case UPDATE_UNKNOWN:
  552. case UPDATE_NOT_CHECKED:
  553. case UPDATE_NOT_FETCHED:
  554. case UPDATE_FETCH_PENDING:
  555. if ($msg_type == 'core') {
  556. $text = t('There was a problem checking <a href="@update-report">available updates</a> for Drupal.', array('@update-report' => url('admin/reports/updates')), array('langcode' => $langcode));
  557. }
  558. else {
  559. $text = t('There was a problem checking <a href="@update-report">available updates</a> for your modules or themes.', array('@update-report' => url('admin/reports/updates')), array('langcode' => $langcode));
  560. }
  561. break;
  562. }
  563. if ($report_link) {
  564. if (update_manager_access()) {
  565. $text .= ' ' . t('See the <a href="@available_updates">available updates</a> page for more information and to install your missing updates.', array('@available_updates' => url('admin/reports/updates/update', array('language' => $language))), array('langcode' => $langcode));
  566. }
  567. else {
  568. $text .= ' ' . t('See the <a href="@available_updates">available updates</a> page for more information.', array('@available_updates' => url('admin/reports/updates', array('language' => $language))), array('langcode' => $langcode));
  569. }
  570. }
  571. return $text;
  572. }
  573. /**
  574. * Orders projects based on their status.
  575. *
  576. * Callback for uasort() within update_requirements().
  577. */
  578. function _update_project_status_sort($a, $b) {
  579. // The status constants are numerically in the right order, so we can
  580. // usually subtract the two to compare in the order we want. However,
  581. // negative status values should be treated as if they are huge, since we
  582. // always want them at the bottom of the list.
  583. $a_status = $a['status'] > 0 ? $a['status'] : (-10 * $a['status']);
  584. $b_status = $b['status'] > 0 ? $b['status'] : (-10 * $b['status']);
  585. return $a_status - $b_status;
  586. }
  587. /**
  588. * Returns HTML for the last time we checked for update data.
  589. *
  590. * In addition to properly formatting the given timestamp, this function also
  591. * provides a "Check manually" link that refreshes the available update and
  592. * redirects back to the same page.
  593. *
  594. * @param $variables
  595. * An associative array containing:
  596. * - last: The timestamp when the site last checked for available updates.
  597. *
  598. * @see theme_update_report()
  599. * @see theme_update_available_updates_form()
  600. * @ingroup themeable
  601. */
  602. function theme_update_last_check($variables) {
  603. $last = $variables['last'];
  604. $output = '<div class="update checked">';
  605. $output .= $last ? t('Last checked: @time ago', array('@time' => format_interval(REQUEST_TIME - $last))) : t('Last checked: never');
  606. $output .= ' <span class="check-manually">(' . l(t('Check manually'), 'admin/reports/updates/check', array('query' => drupal_get_destination())) . ')</span>';
  607. $output .= "</div>\n";
  608. return $output;
  609. }
  610. /**
  611. * Implements hook_verify_update_archive().
  612. *
  613. * First, we ensure that the archive isn't a copy of Drupal core, which the
  614. * update manager does not yet support. See http://drupal.org/node/606592
  615. *
  616. * Then, we make sure that at least one module included in the archive file has
  617. * an .info file which claims that the code is compatible with the current
  618. * version of Drupal core.
  619. *
  620. * @see drupal_system_listing()
  621. * @see _system_rebuild_module_data()
  622. */
  623. function update_verify_update_archive($project, $archive_file, $directory) {
  624. $errors = array();
  625. // Make sure this isn't a tarball of Drupal core.
  626. if (
  627. file_exists("$directory/$project/index.php")
  628. && file_exists("$directory/$project/update.php")
  629. && file_exists("$directory/$project/includes/bootstrap.inc")
  630. && file_exists("$directory/$project/modules/node/node.module")
  631. && file_exists("$directory/$project/modules/system/system.module")
  632. ) {
  633. return array(
  634. '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.', array('@upgrade-guide' => 'http://drupal.org/upgrade')),
  635. );
  636. }
  637. // Parse all the .info files and make sure at least one is compatible with
  638. // this version of Drupal core. If one is compatible, then the project as a
  639. // whole is considered compatible (since, for example, the project may ship
  640. // with some out-of-date modules that are not necessary for its overall
  641. // functionality).
  642. $compatible_project = FALSE;
  643. $incompatible = array();
  644. $files = file_scan_directory("$directory/$project", '/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.info$/', array('key' => 'name', 'min_depth' => 0));
  645. foreach ($files as $key => $file) {
  646. // Get the .info file for the module or theme this file belongs to.
  647. $info = drupal_parse_info_file($file->uri);
  648. // If the module or theme is incompatible with Drupal core, set an error.
  649. if (empty($info['core']) || $info['core'] != DRUPAL_CORE_COMPATIBILITY) {
  650. $incompatible[] = !empty($info['name']) ? $info['name'] : t('Unknown');
  651. }
  652. else {
  653. $compatible_project = TRUE;
  654. break;
  655. }
  656. }
  657. if (empty($files)) {
  658. $errors[] = t('%archive_file does not contain any .info files.', array('%archive_file' => drupal_basename($archive_file)));
  659. }
  660. elseif (!$compatible_project) {
  661. $errors[] = format_plural(
  662. count($incompatible),
  663. '%archive_file contains a version of %names that is not compatible with Drupal !version.',
  664. '%archive_file contains versions of modules or themes that are not compatible with Drupal !version: %names',
  665. array('!version' => DRUPAL_CORE_COMPATIBILITY, '%archive_file' => drupal_basename($archive_file), '%names' => implode(', ', $incompatible))
  666. );
  667. }
  668. return $errors;
  669. }
  670. /**
  671. * @defgroup update_status_cache Private update status cache system
  672. * @{
  673. * Functions to manage the update status cache.
  674. *
  675. * We specifically do NOT use the core cache API for saving the fetched data
  676. * about available updates. It is vitally important that this cache is only
  677. * cleared when we're populating it after successfully fetching new available
  678. * update data. Usage of the core cache API results in all sorts of potential
  679. * problems that would result in attempting to fetch available update data all
  680. * the time, including if a site has a "minimum cache lifetime" (which is both a
  681. * minimum and a maximum) defined, or if a site uses memcache or another
  682. * pluggable cache system that assumes volatile caches.
  683. *
  684. * The Update Manager module still uses the {cache_update} table, but instead of
  685. * using cache_set(), cache_get(), and cache_clear_all(), there are private
  686. * helper functions that implement these same basic tasks but ensure that the
  687. * cache is not prematurely cleared, and that the data is always stored in the
  688. * database, even if memcache or another cache backend is in use.
  689. */
  690. /**
  691. * Stores data in the private update status cache table.
  692. *
  693. * @param $cid
  694. * The cache ID to save the data with.
  695. * @param $data
  696. * The data to store.
  697. * @param $expire
  698. * One of the following values:
  699. * - CACHE_PERMANENT: Indicates that the item should never be removed except
  700. * by explicitly using _update_cache_clear().
  701. * - A Unix timestamp: Indicates that the item should be kept at least until
  702. * the given time, after which it will be invalidated.
  703. *
  704. * @see _update_cache_get()
  705. */
  706. function _update_cache_set($cid, $data, $expire) {
  707. $fields = array(
  708. 'created' => REQUEST_TIME,
  709. 'expire' => $expire,
  710. );
  711. if (!is_string($data)) {
  712. $fields['data'] = serialize($data);
  713. $fields['serialized'] = 1;
  714. }
  715. else {
  716. $fields['data'] = $data;
  717. $fields['serialized'] = 0;
  718. }
  719. db_merge('cache_update')
  720. ->key(array('cid' => $cid))
  721. ->fields($fields)
  722. ->execute();
  723. }
  724. /**
  725. * Retrieves data from the private update status cache table.
  726. *
  727. * @param $cid
  728. * The cache ID to retrieve.
  729. *
  730. * @return
  731. * An array of data for the given cache ID, or NULL if the ID was not found.
  732. *
  733. * @see _update_cache_set()
  734. */
  735. function _update_cache_get($cid) {
  736. $cache = db_query("SELECT data, created, expire, serialized FROM {cache_update} WHERE cid = :cid", array(':cid' => $cid))->fetchObject();
  737. if (isset($cache->data)) {
  738. if ($cache->serialized) {
  739. $cache->data = unserialize($cache->data);
  740. }
  741. }
  742. return $cache;
  743. }
  744. /**
  745. * Returns an array of cache items with a given cache ID prefix.
  746. *
  747. * @param string $cid_prefix
  748. * The cache ID prefix.
  749. *
  750. * @return
  751. * Associative array of cache items, keyed by cache ID.
  752. */
  753. function _update_get_cache_multiple($cid_prefix) {
  754. $data = array();
  755. $result = db_select('cache_update')
  756. ->fields('cache_update', array('cid', 'data', 'created', 'expire', 'serialized'))
  757. ->condition('cache_update.cid', $cid_prefix . '::%', 'LIKE')
  758. ->execute();
  759. foreach ($result as $cache) {
  760. if ($cache) {
  761. if ($cache->serialized) {
  762. $cache->data = unserialize($cache->data);
  763. }
  764. $data[$cache->cid] = $cache;
  765. }
  766. }
  767. return $data;
  768. }
  769. /**
  770. * Invalidates cached data relating to update status.
  771. *
  772. * @param $cid
  773. * (optional) Cache ID of the record to clear from the private update module
  774. * cache. If empty, all records will be cleared from the table except fetch
  775. * tasks. Defaults to NULL.
  776. * @param $wildcard
  777. * (optional) If TRUE, cache IDs starting with $cid are deleted in addition to
  778. * the exact cache ID specified by $cid. Defaults to FALSE.
  779. */
  780. function _update_cache_clear($cid = NULL, $wildcard = FALSE) {
  781. if (empty($cid)) {
  782. db_delete('cache_update')
  783. // Clear everything except fetch task information because these are used
  784. // to ensure that the fetch task queue items are not added multiple times.
  785. ->condition('cid', 'fetch_task::%', 'NOT LIKE')
  786. ->execute();
  787. }
  788. else {
  789. $query = db_delete('cache_update');
  790. if ($wildcard) {
  791. $query->condition('cid', $cid . '%', 'LIKE');
  792. }
  793. else {
  794. $query->condition('cid', $cid);
  795. }
  796. $query->execute();
  797. }
  798. }
  799. /**
  800. * Implements hook_flush_caches().
  801. *
  802. * Called from update.php (among others) to flush the caches. Since we're
  803. * running update.php, we are likely to install a new version of something, in
  804. * which case, we want to check for available update data again. However,
  805. * because we have our own caching system, we need to directly clear the
  806. * database table ourselves at this point and return nothing, for example, on
  807. * sites that use memcache where cache_clear_all() won't know how to purge this
  808. * data.
  809. *
  810. * However, we only want to do this from update.php, since otherwise, we'd lose
  811. * all the available update data on every cron run. So, we specifically check if
  812. * the site is in MAINTENANCE_MODE == 'update' (which indicates update.php is
  813. * running, not update module... alas for overloaded names).
  814. */
  815. function update_flush_caches() {
  816. if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
  817. _update_cache_clear();
  818. }
  819. return array();
  820. }
  821. /**
  822. * @} End of "defgroup update_status_cache".
  823. */
  824. /**
  825. * Returns a short unique identifier for this Drupal installation.
  826. *
  827. * @return
  828. * An eight character string uniquely identifying this Drupal installation.
  829. */
  830. function _update_manager_unique_identifier() {
  831. $id = &drupal_static(__FUNCTION__, '');
  832. if (empty($id)) {
  833. $id = substr(hash('sha256', drupal_get_hash_salt()), 0, 8);
  834. }
  835. return $id;
  836. }
  837. /**
  838. * Returns the directory where update archive files should be extracted.
  839. *
  840. * @param $create
  841. * (optional) Whether to attempt to create the directory if it does not
  842. * already exist. Defaults to TRUE.
  843. *
  844. * @return
  845. * The full path to the temporary directory where update file archives should
  846. * be extracted.
  847. */
  848. function _update_manager_extract_directory($create = TRUE) {
  849. $directory = &drupal_static(__FUNCTION__, '');
  850. if (empty($directory)) {
  851. $directory = 'temporary://update-extraction-' . _update_manager_unique_identifier();
  852. if ($create && !file_exists($directory)) {
  853. mkdir($directory);
  854. }
  855. }
  856. return $directory;
  857. }
  858. /**
  859. * Returns the directory where update archive files should be cached.
  860. *
  861. * @param $create
  862. * (optional) Whether to attempt to create the directory if it does not
  863. * already exist. Defaults to TRUE.
  864. *
  865. * @return
  866. * The full path to the temporary directory where update file archives should
  867. * be cached.
  868. */
  869. function _update_manager_cache_directory($create = TRUE) {
  870. $directory = &drupal_static(__FUNCTION__, '');
  871. if (empty($directory)) {
  872. $directory = 'temporary://update-cache-' . _update_manager_unique_identifier();
  873. if ($create && !file_exists($directory)) {
  874. mkdir($directory);
  875. }
  876. }
  877. return $directory;
  878. }
  879. /**
  880. * Clears the temporary files and directories based on file age from disk.
  881. */
  882. function update_clear_update_disk_cache() {
  883. // List of update module cache directories. Do not create the directories if
  884. // they do not exist.
  885. $directories = array(
  886. _update_manager_cache_directory(FALSE),
  887. _update_manager_extract_directory(FALSE),
  888. );
  889. // Search for files and directories in base folder only without recursion.
  890. foreach ($directories as $directory) {
  891. file_scan_directory($directory, '/.*/', array('callback' => 'update_delete_file_if_stale', 'recurse' => FALSE));
  892. }
  893. }
  894. /**
  895. * Deletes stale files and directories from the update manager disk cache.
  896. *
  897. * Files and directories older than 6 hours and development snapshots older than
  898. * 5 minutes are considered stale. We only cache development snapshots for 5
  899. * minutes since otherwise updated snapshots might not be downloaded as
  900. * expected.
  901. *
  902. * When checking file ages, we need to use the ctime, not the mtime
  903. * (modification time) since many (all?) tar implementations go out of their way
  904. * to set the mtime on the files they create to the timestamps recorded in the
  905. * tarball. We want to see the last time the file was changed on disk, which is
  906. * left alone by tar and correctly set to the time the archive file was
  907. * unpacked.
  908. *
  909. * @param $path
  910. * A string containing a file path or (streamwrapper) URI.
  911. */
  912. function update_delete_file_if_stale($path) {
  913. if (file_exists($path)) {
  914. $filectime = filectime($path);
  915. if (REQUEST_TIME - $filectime > DRUPAL_MAXIMUM_TEMP_FILE_AGE || (preg_match('/.*-dev\.(tar\.gz|zip)/i', $path) && REQUEST_TIME - $filectime > 300)) {
  916. file_unmanaged_delete_recursive($path);
  917. }
  918. }
  919. }