update.fetch.inc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. <?php
  2. /**
  3. * @file
  4. * Code required only when fetching information about available updates.
  5. */
  6. /**
  7. * Page callback: Checks for updates and displays the update status report.
  8. *
  9. * Manually checks the update status without the use of cron.
  10. *
  11. * @see update_menu()
  12. */
  13. function update_manual_status() {
  14. _update_refresh();
  15. $batch = array(
  16. 'operations' => array(
  17. array('update_fetch_data_batch', array()),
  18. ),
  19. 'finished' => 'update_fetch_data_finished',
  20. 'title' => t('Checking available update data'),
  21. 'progress_message' => t('Trying to check available update data ...'),
  22. 'error_message' => t('Error checking available update data.'),
  23. 'file' => drupal_get_path('module', 'update') . '/update.fetch.inc',
  24. );
  25. batch_set($batch);
  26. batch_process('admin/reports/updates');
  27. }
  28. /**
  29. * Implements callback_batch_operation().
  30. *
  31. * Processes a step in batch for fetching available update data.
  32. *
  33. * @param $context
  34. * Reference to an array used for Batch API storage.
  35. */
  36. function update_fetch_data_batch(&$context) {
  37. $queue = DrupalQueue::get('update_fetch_tasks');
  38. if (empty($context['sandbox']['max'])) {
  39. $context['finished'] = 0;
  40. $context['sandbox']['max'] = $queue->numberOfItems();
  41. $context['sandbox']['progress'] = 0;
  42. $context['message'] = t('Checking available update data ...');
  43. $context['results']['updated'] = 0;
  44. $context['results']['failures'] = 0;
  45. $context['results']['processed'] = 0;
  46. }
  47. // Grab another item from the fetch queue.
  48. for ($i = 0; $i < 5; $i++) {
  49. if ($item = $queue->claimItem()) {
  50. if (_update_process_fetch_task($item->data)) {
  51. $context['results']['updated']++;
  52. $context['message'] = t('Checked available update data for %title.', array('%title' => $item->data['info']['name']));
  53. }
  54. else {
  55. $context['message'] = t('Failed to check available update data for %title.', array('%title' => $item->data['info']['name']));
  56. $context['results']['failures']++;
  57. }
  58. $context['sandbox']['progress']++;
  59. $context['results']['processed']++;
  60. $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  61. $queue->deleteItem($item);
  62. }
  63. else {
  64. // If the queue is currently empty, we're done. It's possible that
  65. // another thread might have added new fetch tasks while we were
  66. // processing this batch. In that case, the usual 'finished' math could
  67. // get confused, since we'd end up processing more tasks that we thought
  68. // we had when we started and initialized 'max' with numberOfItems(). By
  69. // forcing 'finished' to be exactly 1 here, we ensure that batch
  70. // processing is terminated.
  71. $context['finished'] = 1;
  72. return;
  73. }
  74. }
  75. }
  76. /**
  77. * Implements callback_batch_finished().
  78. *
  79. * Performs actions when all fetch tasks have been completed.
  80. *
  81. * @param $success
  82. * TRUE if the batch operation was successful; FALSE if there were errors.
  83. * @param $results
  84. * An associative array of results from the batch operation, including the key
  85. * 'updated' which holds the total number of projects we fetched available
  86. * update data for.
  87. */
  88. function update_fetch_data_finished($success, $results) {
  89. if ($success) {
  90. if (!empty($results)) {
  91. if (!empty($results['updated'])) {
  92. drupal_set_message(format_plural($results['updated'], 'Checked available update data for one project.', 'Checked available update data for @count projects.'));
  93. }
  94. if (!empty($results['failures'])) {
  95. drupal_set_message(format_plural($results['failures'], 'Failed to get available update data for one project.', 'Failed to get available update data for @count projects.'), 'error');
  96. }
  97. }
  98. }
  99. else {
  100. drupal_set_message(t('An error occurred trying to get available update data.'), 'error');
  101. }
  102. }
  103. /**
  104. * Attempts to drain the queue of tasks for release history data to fetch.
  105. */
  106. function _update_fetch_data() {
  107. $queue = DrupalQueue::get('update_fetch_tasks');
  108. $end = time() + variable_get('update_max_fetch_time', UPDATE_MAX_FETCH_TIME);
  109. while (time() < $end && ($item = $queue->claimItem())) {
  110. _update_process_fetch_task($item->data);
  111. $queue->deleteItem($item);
  112. }
  113. }
  114. /**
  115. * Processes a task to fetch available update data for a single project.
  116. *
  117. * Once the release history XML data is downloaded, it is parsed and saved into
  118. * the {cache_update} table in an entry just for that project.
  119. *
  120. * @param $project
  121. * Associative array of information about the project to fetch data for.
  122. *
  123. * @return
  124. * TRUE if we fetched parsable XML, otherwise FALSE.
  125. */
  126. function _update_process_fetch_task($project) {
  127. global $base_url;
  128. $fail = &drupal_static(__FUNCTION__, array());
  129. // This can be in the middle of a long-running batch, so REQUEST_TIME won't
  130. // necessarily be valid.
  131. $now = time();
  132. if (empty($fail)) {
  133. // If we have valid data about release history XML servers that we have
  134. // failed to fetch from on previous attempts, load that from the cache.
  135. if (($cache = _update_cache_get('fetch_failures')) && ($cache->expire > $now)) {
  136. $fail = $cache->data;
  137. }
  138. }
  139. $max_fetch_attempts = variable_get('update_max_fetch_attempts', UPDATE_MAX_FETCH_ATTEMPTS);
  140. $success = FALSE;
  141. $available = array();
  142. $site_key = drupal_hmac_base64($base_url, drupal_get_private_key());
  143. $url = _update_build_fetch_url($project, $site_key);
  144. $fetch_url_base = _update_get_fetch_url_base($project);
  145. $project_name = $project['name'];
  146. if (empty($fail[$fetch_url_base]) || $fail[$fetch_url_base] < $max_fetch_attempts) {
  147. $xml = drupal_http_request($url);
  148. if (!isset($xml->error) && isset($xml->data)) {
  149. $data = $xml->data;
  150. }
  151. }
  152. if (!empty($data)) {
  153. $available = update_parse_xml($data);
  154. // @todo: Purge release data we don't need (http://drupal.org/node/238950).
  155. if (!empty($available)) {
  156. // Only if we fetched and parsed something sane do we return success.
  157. $success = TRUE;
  158. }
  159. }
  160. else {
  161. $available['project_status'] = 'not-fetched';
  162. if (empty($fail[$fetch_url_base])) {
  163. $fail[$fetch_url_base] = 1;
  164. }
  165. else {
  166. $fail[$fetch_url_base]++;
  167. }
  168. }
  169. $frequency = variable_get('update_check_frequency', 1);
  170. $cid = 'available_releases::' . $project_name;
  171. _update_cache_set($cid, $available, $now + (60 * 60 * 24 * $frequency));
  172. // Stash the $fail data back in the DB for the next 5 minutes.
  173. _update_cache_set('fetch_failures', $fail, $now + (60 * 5));
  174. // Whether this worked or not, we did just (try to) check for updates.
  175. variable_set('update_last_check', $now);
  176. // Now that we processed the fetch task for this project, clear out the
  177. // record in {cache_update} for this task so we're willing to fetch again.
  178. _update_cache_clear('fetch_task::' . $project_name);
  179. return $success;
  180. }
  181. /**
  182. * Clears out all the cached available update data and initiates re-fetching.
  183. */
  184. function _update_refresh() {
  185. module_load_include('inc', 'update', 'update.compare');
  186. // Since we're fetching new available update data, we want to clear
  187. // our cache of both the projects we care about, and the current update
  188. // status of the site. We do *not* want to clear the cache of available
  189. // releases just yet, since that data (even if it's stale) can be useful
  190. // during update_get_projects(); for example, to modules that implement
  191. // hook_system_info_alter() such as cvs_deploy.
  192. _update_cache_clear('update_project_projects');
  193. _update_cache_clear('update_project_data');
  194. $projects = update_get_projects();
  195. // Now that we have the list of projects, we should also clear our cache of
  196. // available release data, since even if we fail to fetch new data, we need
  197. // to clear out the stale data at this point.
  198. _update_cache_clear('available_releases::', TRUE);
  199. foreach ($projects as $key => $project) {
  200. update_create_fetch_task($project);
  201. }
  202. }
  203. /**
  204. * Adds a task to the queue for fetching release history data for a project.
  205. *
  206. * We only create a new fetch task if there's no task already in the queue for
  207. * this particular project (based on 'fetch_task::' entries in the
  208. * {cache_update} table).
  209. *
  210. * @param $project
  211. * Associative array of information about a project as created by
  212. * update_get_projects(), including keys such as 'name' (short name), and the
  213. * 'info' array with data from a .info file for the project.
  214. *
  215. * @see update_get_projects()
  216. * @see update_get_available()
  217. * @see update_refresh()
  218. * @see update_fetch_data()
  219. * @see _update_process_fetch_task()
  220. */
  221. function _update_create_fetch_task($project) {
  222. $fetch_tasks = &drupal_static(__FUNCTION__, array());
  223. if (empty($fetch_tasks)) {
  224. $fetch_tasks = _update_get_cache_multiple('fetch_task');
  225. }
  226. $cid = 'fetch_task::' . $project['name'];
  227. if (empty($fetch_tasks[$cid])) {
  228. $queue = DrupalQueue::get('update_fetch_tasks');
  229. $queue->createItem($project);
  230. // Due to race conditions, it is possible that another process already
  231. // inserted a row into the {cache_update} table and the following query will
  232. // throw an exception.
  233. // @todo: Remove the need for the manual check by relying on a queue that
  234. // enforces unique items.
  235. try {
  236. db_insert('cache_update')
  237. ->fields(array(
  238. 'cid' => $cid,
  239. 'created' => REQUEST_TIME,
  240. ))
  241. ->execute();
  242. }
  243. catch (Exception $e) {
  244. // The exception can be ignored safely.
  245. }
  246. $fetch_tasks[$cid] = REQUEST_TIME;
  247. }
  248. }
  249. /**
  250. * Generates the URL to fetch information about project updates.
  251. *
  252. * This figures out the right URL to use, based on the project's .info file and
  253. * the global defaults. Appends optional query arguments when the site is
  254. * configured to report usage stats.
  255. *
  256. * @param $project
  257. * The array of project information from update_get_projects().
  258. * @param $site_key
  259. * (optional) The anonymous site key hash. Defaults to an empty string.
  260. *
  261. * @return
  262. * The URL for fetching information about updates to the specified project.
  263. *
  264. * @see update_fetch_data()
  265. * @see _update_process_fetch_task()
  266. * @see update_get_projects()
  267. */
  268. function _update_build_fetch_url($project, $site_key = '') {
  269. $name = $project['name'];
  270. $url = _update_get_fetch_url_base($project);
  271. $url .= '/' . $name . '/' . DRUPAL_CORE_COMPATIBILITY;
  272. // Only append usage information if we have a site key and the project is
  273. // enabled. We do not want to record usage statistics for disabled projects.
  274. if (!empty($site_key) && (strpos($project['project_type'], 'disabled') === FALSE)) {
  275. // Append the site key.
  276. $url .= (strpos($url, '?') !== FALSE) ? '&' : '?';
  277. $url .= 'site_key=';
  278. $url .= rawurlencode($site_key);
  279. // Append the version.
  280. if (!empty($project['info']['version'])) {
  281. $url .= '&version=';
  282. $url .= rawurlencode($project['info']['version']);
  283. }
  284. // Append the list of modules or themes enabled.
  285. $list = array_keys($project['includes']);
  286. $url .= '&list=';
  287. $url .= rawurlencode(implode(',', $list));
  288. }
  289. return $url;
  290. }
  291. /**
  292. * Returns the base of the URL to fetch available update data for a project.
  293. *
  294. * @param $project
  295. * The array of project information from update_get_projects().
  296. *
  297. * @return
  298. * The base of the URL used for fetching available update data. This does
  299. * not include the path elements to specify a particular project, version,
  300. * site_key, etc.
  301. *
  302. * @see _update_build_fetch_url()
  303. */
  304. function _update_get_fetch_url_base($project) {
  305. return isset($project['info']['project status url']) ? $project['info']['project status url'] : variable_get('update_fetch_url', UPDATE_DEFAULT_URL);
  306. }
  307. /**
  308. * Performs any notifications that should be done once cron fetches new data.
  309. *
  310. * This method checks the status of the site using the new data and, depending
  311. * on the configuration of the site, notifies administrators via e-mail if there
  312. * are new releases or missing security updates.
  313. *
  314. * @see update_requirements()
  315. */
  316. function _update_cron_notify() {
  317. module_load_install('update');
  318. $status = update_requirements('runtime');
  319. $params = array();
  320. $notify_all = (variable_get('update_notification_threshold', 'all') == 'all');
  321. foreach (array('core', 'contrib') as $report_type) {
  322. $type = 'update_' . $report_type;
  323. if (isset($status[$type]['severity'])
  324. && ($status[$type]['severity'] == REQUIREMENT_ERROR || ($notify_all && $status[$type]['reason'] == UPDATE_NOT_CURRENT))) {
  325. $params[$report_type] = $status[$type]['reason'];
  326. }
  327. }
  328. if (!empty($params)) {
  329. $notify_list = variable_get('update_notify_emails', '');
  330. if (!empty($notify_list)) {
  331. $default_language = language_default();
  332. foreach ($notify_list as $target) {
  333. if ($target_user = user_load_by_mail($target)) {
  334. $target_language = user_preferred_language($target_user);
  335. }
  336. else {
  337. $target_language = $default_language;
  338. }
  339. $message = drupal_mail('update', 'status_notify', $target, $target_language, $params);
  340. // Track when the last mail was successfully sent to avoid sending
  341. // too many e-mails.
  342. if ($message['result']) {
  343. variable_set('update_last_email_notification', REQUEST_TIME);
  344. }
  345. }
  346. }
  347. }
  348. }
  349. /**
  350. * Parses the XML of the Drupal release history info files.
  351. *
  352. * @param $raw_xml
  353. * A raw XML string of available release data for a given project.
  354. *
  355. * @return
  356. * Array of parsed data about releases for a given project, or NULL if there
  357. * was an error parsing the string.
  358. */
  359. function update_parse_xml($raw_xml) {
  360. try {
  361. $xml = new SimpleXMLElement($raw_xml);
  362. }
  363. catch (Exception $e) {
  364. // SimpleXMLElement::__construct produces an E_WARNING error message for
  365. // each error found in the XML data and throws an exception if errors
  366. // were detected. Catch any exception and return failure (NULL).
  367. return;
  368. }
  369. // If there is no valid project data, the XML is invalid, so return failure.
  370. if (!isset($xml->short_name)) {
  371. return;
  372. }
  373. $short_name = (string) $xml->short_name;
  374. $data = array();
  375. foreach ($xml as $k => $v) {
  376. $data[$k] = (string) $v;
  377. }
  378. $data['releases'] = array();
  379. if (isset($xml->releases)) {
  380. foreach ($xml->releases->children() as $release) {
  381. $version = (string) $release->version;
  382. $data['releases'][$version] = array();
  383. foreach ($release->children() as $k => $v) {
  384. $data['releases'][$version][$k] = (string) $v;
  385. }
  386. $data['releases'][$version]['terms'] = array();
  387. if ($release->terms) {
  388. foreach ($release->terms->children() as $term) {
  389. if (!isset($data['releases'][$version]['terms'][(string) $term->name])) {
  390. $data['releases'][$version]['terms'][(string) $term->name] = array();
  391. }
  392. $data['releases'][$version]['terms'][(string) $term->name][] = (string) $term->value;
  393. }
  394. }
  395. }
  396. }
  397. return $data;
  398. }