update.fetch.inc

  1. 7.x drupal-7.x/modules/update/update.fetch.inc
  2. 6.x drupal-6.x/modules/update/update.fetch.inc

Code required only when fetching information about available updates.

File

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