Projet

Général

Profil

Paste
Télécharger (37,9 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / update / update.module @ 08f5d39b

1
<?php
2

    
3
/**
4
 * @file
5
 * Handles updates of Drupal core and contributed projects.
6
 *
7
 * The module checks for available updates of Drupal core and any installed
8
 * contributed modules and themes. It warns site administrators if newer
9
 * releases are available via the system status report (admin/reports/status),
10
 * the module and theme pages, and optionally via e-mail. It also provides the
11
 * ability to install contributed modules and themes via an user interface.
12
 */
13

    
14
/**
15
 * URL to check for updates, if a given project doesn't define its own.
16
 */
17
define('UPDATE_DEFAULT_URL', 'http://updates.drupal.org/release-history');
18

    
19
// These are internally used constants for this code, do not modify.
20

    
21
/**
22
 * Project is missing security update(s).
23
 */
24
define('UPDATE_NOT_SECURE', 1);
25

    
26
/**
27
 * Current release has been unpublished and is no longer available.
28
 */
29
define('UPDATE_REVOKED', 2);
30

    
31
/**
32
 * Current release is no longer supported by the project maintainer.
33
 */
34
define('UPDATE_NOT_SUPPORTED', 3);
35

    
36
/**
37
 * Project has a new release available, but it is not a security release.
38
 */
39
define('UPDATE_NOT_CURRENT', 4);
40

    
41
/**
42
 * Project is up to date.
43
 */
44
define('UPDATE_CURRENT', 5);
45

    
46
/**
47
 * Project's status cannot be checked.
48
 */
49
define('UPDATE_NOT_CHECKED', -1);
50

    
51
/**
52
 * No available update data was found for project.
53
 */
54
define('UPDATE_UNKNOWN', -2);
55

    
56
/**
57
 * There was a failure fetching available update data for this project.
58
 */
59
define('UPDATE_NOT_FETCHED', -3);
60

    
61
/**
62
 * We need to (re)fetch available update data for this project.
63
 */
64
define('UPDATE_FETCH_PENDING', -4);
65

    
66
/**
67
 * Maximum number of attempts to fetch available update data from a given host.
68
 */
69
define('UPDATE_MAX_FETCH_ATTEMPTS', 2);
70

    
71
/**
72
 * Maximum number of seconds to try fetching available update data at a time.
73
 */
74
define('UPDATE_MAX_FETCH_TIME', 30);
75

    
76
/**
77
 * Implements hook_help().
78
 */
79
function update_help($path, $arg) {
80
  switch ($path) {
81
    case 'admin/reports/updates':
82
      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>';
83

    
84
    case 'admin/help#update':
85
      $output = '';
86
      $output .= '<h3>' . t('About') . '</h3>';
87
      $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>';
88
      // Only explain the Update manager if it has not been disabled.
89
      if (update_manager_access()) {
90
        $output .= '<p>' . t('The Update manager also allows administrators to update and install modules and themes through the administration interface.') . '</p>';
91
      }
92
      $output .= '<h3>' . t('Uses') . '</h3>';
93
      $output .= '<dl>';
94
      $output .= '<dt>' . t('Checking for available updates') . '</dt>';
95
      $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>';
96
      // Only explain the Update manager if it has not been disabled.
97
      if (update_manager_access()) {
98
        $output .= '<dt>' . t('Performing updates through the user interface') . '</dt>';
99
        $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>';
100
        $output .= '<dt>' . t('Installing new modules and themes through the user interface') . '</dt>';
101
        $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>';
102
      }
103
      $output .= '</dl>';
104
      return $output;
105
  }
106
}
107

    
108
/**
109
 * Implements hook_init().
110
 */
111
function update_init() {
112
  if (arg(0) == 'admin' && user_access('administer site configuration')) {
113
    switch ($_GET['q']) {
114
      // These pages don't need additional nagging.
115
      case 'admin/appearance/update':
116
      case 'admin/appearance/install':
117
      case 'admin/modules/update':
118
      case 'admin/modules/install':
119
      case 'admin/reports/updates':
120
      case 'admin/reports/updates/update':
121
      case 'admin/reports/updates/install':
122
      case 'admin/reports/updates/settings':
123
      case 'admin/reports/status':
124
      case 'admin/update/ready':
125
        return;
126

    
127
      // If we are on the appearance or modules list, display a detailed report
128
      // of the update status.
129
      case 'admin/appearance':
130
      case 'admin/modules':
131
        $verbose = TRUE;
132
        break;
133

    
134
    }
135
    module_load_install('update');
136
    $status = update_requirements('runtime');
137
    foreach (array('core', 'contrib') as $report_type) {
138
      $type = 'update_' . $report_type;
139
      if (!empty($verbose)) {
140
        if (isset($status[$type]['severity'])) {
141
          if ($status[$type]['severity'] == REQUIREMENT_ERROR) {
142
            drupal_set_message($status[$type]['description'], 'error', FALSE);
143
          }
144
          elseif ($status[$type]['severity'] == REQUIREMENT_WARNING) {
145
            drupal_set_message($status[$type]['description'], 'warning', FALSE);
146
          }
147
        }
148
      }
149
      // Otherwise, if we're on *any* admin page and there's a security
150
      // update missing, print an error message about it.
151
      else {
152
        if (isset($status[$type])
153
            && isset($status[$type]['reason'])
154
            && $status[$type]['reason'] === UPDATE_NOT_SECURE) {
155
          drupal_set_message($status[$type]['description'], 'error', FALSE);
156
        }
157
      }
158
    }
159
  }
160
}
161

    
162
/**
163
 * Implements hook_menu().
164
 */
165
function update_menu() {
166
  $items = array();
167

    
168
  $items['admin/reports/updates'] = array(
169
    'title' => 'Available updates',
170
    'description' => 'Get a status report about available updates for your installed modules and themes.',
171
    'page callback' => 'update_status',
172
    'access arguments' => array('administer site configuration'),
173
    'weight' => -50,
174
    'file' => 'update.report.inc',
175
  );
176
  $items['admin/reports/updates/list'] = array(
177
    'title' => 'List',
178
    'access arguments' => array('administer site configuration'),
179
    'type' => MENU_DEFAULT_LOCAL_TASK,
180
  );
181
  $items['admin/reports/updates/settings'] = array(
182
    'title' => 'Settings',
183
    'page callback' => 'drupal_get_form',
184
    'page arguments' => array('update_settings'),
185
    'access arguments' => array('administer site configuration'),
186
    'file' => 'update.settings.inc',
187
    'type' => MENU_LOCAL_TASK,
188
    'weight' => 50,
189
  );
190
  $items['admin/reports/updates/check'] = array(
191
    'title' => 'Manual update check',
192
    'page callback' => 'update_manual_status',
193
    'access arguments' => array('administer site configuration'),
194
    'type' => MENU_CALLBACK,
195
    'file' => 'update.fetch.inc',
196
  );
197

    
198
  // We want action links for updating projects at a few different locations:
199
  // both the module and theme administration pages, and on the available
200
  // updates report itself. The menu items will be mostly identical, except the
201
  // paths and titles, so we just define them in a loop. We pass in a string
202
  // indicating what context we're entering the action from, so that can
203
  // customize the appearance as needed.
204
  $paths = array(
205
    'report' => 'admin/reports/updates',
206
    'module' => 'admin/modules',
207
    'theme' => 'admin/appearance',
208
  );
209
  foreach ($paths as $context => $path) {
210
    $items[$path . '/install'] = array(
211
      'page callback' => 'drupal_get_form',
212
      'page arguments' => array('update_manager_install_form', $context),
213
      'access callback' => 'update_manager_access',
214
      'access arguments' => array(),
215
      'weight' => 25,
216
      'type' => MENU_LOCAL_ACTION,
217
      'file' => 'update.manager.inc',
218
    );
219
    $items[$path . '/update'] = array(
220
      'page callback' => 'drupal_get_form',
221
      'page arguments' => array('update_manager_update_form', $context),
222
      'access callback' => 'update_manager_access',
223
      'access arguments' => array(),
224
      'weight' => 10,
225
      'title' => 'Update',
226
      'type' => MENU_LOCAL_TASK,
227
      'file' => 'update.manager.inc',
228
    );
229
  }
230
  // Customize the titles of the action links depending on where they appear.
231
  // We use += array() to let the translation extractor find these menu titles.
232
  $items['admin/reports/updates/install'] += array('title' => 'Install new module or theme');
233
  $items['admin/modules/install'] += array('title' => 'Install new module');
234
  $items['admin/appearance/install'] += array('title' => 'Install new theme');
235

    
236
  // Menu callback used for the confirmation page after all the releases
237
  // have been downloaded, asking you to backup before installing updates.
238
  $items['admin/update/ready'] = array(
239
    'title' => 'Ready to update',
240
    'page callback' => 'drupal_get_form',
241
    'page arguments' => array('update_manager_update_ready_form'),
242
    'access callback' => 'update_manager_access',
243
    'access arguments' => array(),
244
    'type' => MENU_CALLBACK,
245
    'file' => 'update.manager.inc',
246
  );
247

    
248
  return $items;
249
}
250

    
251
/**
252
 * Access callback: Resolves if the current user can access updater menu items.
253
 *
254
 * It both enforces the 'administer software updates' permission and the global
255
 * kill switch for the authorize.php script.
256
 *
257
 * @return
258
 *   TRUE if the current user can access the updater menu items; FALSE
259
 *   otherwise.
260
 *
261
 * @see update_menu()
262
 */
263
function update_manager_access() {
264
  return variable_get('allow_authorize_operations', TRUE) && user_access('administer software updates');
265
}
266

    
267
/**
268
 * Implements hook_theme().
269
 */
270
function update_theme() {
271
  return array(
272
    'update_manager_update_form' => array(
273
      'render element' => 'form',
274
      'file' => 'update.manager.inc',
275
    ),
276
    'update_last_check' => array(
277
      'variables' => array('last' => NULL),
278
    ),
279
    'update_report' => array(
280
      'variables' => array('data' => NULL),
281
      'file' => 'update.report.inc',
282
    ),
283
    'update_version' => array(
284
      'variables' => array('version' => NULL, 'tag' => NULL, 'class' => array()),
285
      'file' => 'update.report.inc',
286
    ),
287
    'update_status_label' => array(
288
      'variables' => array('status' => NULL),
289
      'file' => 'update.report.inc',
290
    ),
291
  );
292
}
293

    
294
/**
295
 * Implements hook_cron().
296
 */
297
function update_cron() {
298
  $frequency = variable_get('update_check_frequency', 1);
299
  $interval = 60 * 60 * 24 * $frequency;
300
  if ((REQUEST_TIME - variable_get('update_last_check', 0)) > $interval) {
301
    // If the configured update interval has elapsed, we want to invalidate
302
    // the cached data for all projects, attempt to re-fetch, and trigger any
303
    // configured notifications about the new status.
304
    update_refresh();
305
    update_fetch_data();
306
  }
307
  else {
308
    // Otherwise, see if any individual projects are now stale or still
309
    // missing data, and if so, try to fetch the data.
310
    update_get_available(TRUE);
311
  }
312
  if ((REQUEST_TIME - variable_get('update_last_email_notification', 0)) > $interval) {
313
    // If configured time between notifications elapsed, send email about
314
    // updates possibly available.
315
    module_load_include('inc', 'update', 'update.fetch');
316
    _update_cron_notify();
317
  }
318

    
319
  // Clear garbage from disk.
320
  update_clear_update_disk_cache();
321
}
322

    
323
/**
324
 * Implements hook_themes_enabled().
325
 *
326
 * If themes are enabled, we invalidate the cache of available updates.
327
 */
328
function update_themes_enabled($themes) {
329
  // Clear all update module caches.
330
  _update_cache_clear();
331
}
332

    
333
/**
334
 * Implements hook_themes_disabled().
335
 *
336
 * If themes are disabled, we invalidate the cache of available updates.
337
 */
338
function update_themes_disabled($themes) {
339
  // Clear all update module caches.
340
  _update_cache_clear();
341
}
342

    
343
/**
344
 * Implements hook_form_FORM_ID_alter() for system_modules().
345
 *
346
 * Adds a form submission handler to the system modules form, so that if a site
347
 * admin saves the form, we invalidate the cache of available updates.
348
 *
349
 * @see _update_cache_clear()
350
 */
351
function update_form_system_modules_alter(&$form, $form_state) {
352
  $form['#submit'][] = 'update_cache_clear_submit';
353
}
354

    
355
/**
356
 * Form submission handler for system_modules().
357
 *
358
 * @see update_form_system_modules_alter()
359
 */
360
function update_cache_clear_submit($form, &$form_state) {
361
  // Clear all update module caches.
362
  _update_cache_clear();
363
}
364

    
365
/**
366
 * Returns a warning message when there is no data about available updates.
367
 */
368
function _update_no_data() {
369
  $destination = drupal_get_destination();
370
  return t('No update information available. <a href="@run_cron">Run cron</a> or <a href="@check_manually">check manually</a>.', array(
371
    '@run_cron' => url('admin/reports/status/run-cron', array('query' => $destination)),
372
    '@check_manually' => url('admin/reports/updates/check', array('query' => $destination)),
373
  ));
374
}
375

    
376
/**
377
 * Tries to get update information from cache and refreshes it when necessary.
378
 *
379
 * In addition to checking the cache lifetime, this function also ensures that
380
 * there are no .info files for enabled modules or themes that have a newer
381
 * modification timestamp than the last time we checked for available update
382
 * data. If any .info file was modified, it almost certainly means a new version
383
 * of something was installed. Without fresh available update data, the logic in
384
 * update_calculate_project_data() will be wrong and produce confusing, bogus
385
 * results.
386
 *
387
 * @param $refresh
388
 *   (optional) Boolean to indicate if this method should refresh the cache
389
 *   automatically if there's no data. Defaults to FALSE.
390
 *
391
 * @return
392
 *   Array of data about available releases, keyed by project shortname.
393
 *
394
 * @see update_refresh()
395
 * @see update_get_projects()
396
 */
397
function update_get_available($refresh = FALSE) {
398
  module_load_include('inc', 'update', 'update.compare');
399
  $needs_refresh = FALSE;
400

    
401
  // Grab whatever data we currently have cached in the DB.
402
  $available = _update_get_cached_available_releases();
403
  $num_avail = count($available);
404

    
405
  $projects = update_get_projects();
406
  foreach ($projects as $key => $project) {
407
    // If there's no data at all, we clearly need to fetch some.
408
    if (empty($available[$key])) {
409
      update_create_fetch_task($project);
410
      $needs_refresh = TRUE;
411
      continue;
412
    }
413

    
414
    // See if the .info file is newer than the last time we checked for data,
415
    // and if so, mark this project's data as needing to be re-fetched. Any
416
    // time an admin upgrades their local installation, the .info file will
417
    // be changed, so this is the only way we can be sure we're not showing
418
    // bogus information right after they upgrade.
419
    if ($project['info']['_info_file_ctime'] > $available[$key]['last_fetch']) {
420
      $available[$key]['fetch_status'] = UPDATE_FETCH_PENDING;
421
    }
422

    
423
    // If we have project data but no release data, we need to fetch. This
424
    // can be triggered when we fail to contact a release history server.
425
    if (empty($available[$key]['releases'])) {
426
      $available[$key]['fetch_status'] = UPDATE_FETCH_PENDING;
427
    }
428

    
429
    // If we think this project needs to fetch, actually create the task now
430
    // and remember that we think we're missing some data.
431
    if (!empty($available[$key]['fetch_status']) && $available[$key]['fetch_status'] == UPDATE_FETCH_PENDING) {
432
      update_create_fetch_task($project);
433
      $needs_refresh = TRUE;
434
    }
435
  }
436

    
437
  if ($needs_refresh && $refresh) {
438
    // Attempt to drain the queue of fetch tasks.
439
    update_fetch_data();
440
    // After processing the queue, we've (hopefully) got better data, so pull
441
    // the latest from the cache again and use that directly.
442
    $available = _update_get_cached_available_releases();
443
  }
444

    
445
  return $available;
446
}
447

    
448
/**
449
 * Creates a new fetch task after loading the necessary include file.
450
 *
451
 * @param $project
452
 *   Associative array of information about a project. See update_get_projects()
453
 *   for the keys used.
454
 *
455
 * @see _update_create_fetch_task()
456
 */
457
function update_create_fetch_task($project) {
458
  module_load_include('inc', 'update', 'update.fetch');
459
  return _update_create_fetch_task($project);
460
}
461

    
462
/**
463
 * Refreshes the release data after loading the necessary include file.
464
 *
465
 * @see _update_refresh()
466
 */
467
function update_refresh() {
468
  module_load_include('inc', 'update', 'update.fetch');
469
  return _update_refresh();
470
}
471

    
472
/**
473
 * Attempts to fetch update data after loading the necessary include file.
474
 *
475
 * @see _update_fetch_data()
476
 */
477
function update_fetch_data() {
478
  module_load_include('inc', 'update', 'update.fetch');
479
  return _update_fetch_data();
480
}
481

    
482
/**
483
 * Returns all currently cached data about available releases for all projects.
484
 *
485
 * @return
486
 *   Array of data about available releases, keyed by project shortname.
487
 */
488
function _update_get_cached_available_releases() {
489
  $data = array();
490
  $cache_items = _update_get_cache_multiple('available_releases');
491
  foreach ($cache_items as $cid => $cache) {
492
    $cache->data['last_fetch'] = $cache->created;
493
    if ($cache->expire < REQUEST_TIME) {
494
      $cache->data['fetch_status'] = UPDATE_FETCH_PENDING;
495
    }
496
    // The project shortname is embedded in the cache ID, even if there's no
497
    // data for this project in the DB at all, so use that for the indexes in
498
    // the array.
499
    $parts = explode('::', $cid, 2);
500
    $data[$parts[1]] = $cache->data;
501
  }
502
  return $data;
503
}
504

    
505
/**
506
 * Implements hook_mail().
507
 *
508
 * Constructs the e-mail notification message when the site is out of date.
509
 *
510
 * @param $key
511
 *   Unique key to indicate what message to build, always 'status_notify'.
512
 * @param $message
513
 *   Reference to the message array being built.
514
 * @param $params
515
 *   Array of parameters to indicate what kind of text to include in the message
516
 *   body. This is a keyed array of message type ('core' or 'contrib') as the
517
 *   keys, and the status reason constant (UPDATE_NOT_SECURE, etc) for the
518
 *   values.
519
 *
520
 * @see drupal_mail()
521
 * @see _update_cron_notify()
522
 * @see _update_message_text()
523
 */
524
function update_mail($key, &$message, $params) {
525
  $language = $message['language'];
526
  $langcode = $language->language;
527
  $message['subject'] .= t('New release(s) available for !site_name', array('!site_name' => variable_get('site_name', 'Drupal')), array('langcode' => $langcode));
528
  foreach ($params as $msg_type => $msg_reason) {
529
    $message['body'][] = _update_message_text($msg_type, $msg_reason, FALSE, $language);
530
  }
531
  $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));
532
  if (update_manager_access()) {
533
    $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));
534
  }
535
  $settings_url = url('admin/reports/updates/settings', array('absolute' => TRUE));
536
  if (variable_get('update_notification_threshold', 'all') == 'all') {
537
    $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));
538
  }
539
  else {
540
    $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));
541
  }
542
}
543

    
544
/**
545
 * Returns the appropriate message text when site is out of date or not secure.
546
 *
547
 * These error messages are shared by both update_requirements() for the
548
 * site-wide status report at admin/reports/status and in the body of the
549
 * notification e-mail messages generated by update_cron().
550
 *
551
 * @param $msg_type
552
 *   String to indicate what kind of message to generate. Can be either 'core'
553
 *   or 'contrib'.
554
 * @param $msg_reason
555
 *   Integer constant specifying why message is generated.
556
 * @param $report_link
557
 *   (optional) Boolean that controls if a link to the updates report should be
558
 *   added. Defaults to FALSE.
559
 * @param $language
560
 *   (optional) A language object to use. Defaults to NULL.
561
 *
562
 * @return
563
 *   The properly translated error message for the given key.
564
 */
565
function _update_message_text($msg_type, $msg_reason, $report_link = FALSE, $language = NULL) {
566
  $langcode = isset($language) ? $language->language : NULL;
567
  $text = '';
568
  switch ($msg_reason) {
569
    case UPDATE_NOT_SECURE:
570
      if ($msg_type == 'core') {
571
        $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));
572
      }
573
      else {
574
        $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));
575
      }
576
      break;
577

    
578
    case UPDATE_REVOKED:
579
      if ($msg_type == 'core') {
580
        $text = t('Your version of Drupal has been revoked and is no longer available for download. Upgrading is strongly recommended!', array(), array('langcode' => $langcode));
581
      }
582
      else {
583
        $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));
584
      }
585
      break;
586

    
587
    case UPDATE_NOT_SUPPORTED:
588
      if ($msg_type == 'core') {
589
        $text = t('Your version of Drupal is no longer supported. Upgrading is strongly recommended!', array(), array('langcode' => $langcode));
590
      }
591
      else {
592
        $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));
593
      }
594
      break;
595

    
596
    case UPDATE_NOT_CURRENT:
597
      if ($msg_type == 'core') {
598
        $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));
599
      }
600
      else {
601
        $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));
602
      }
603
      break;
604

    
605
    case UPDATE_UNKNOWN:
606
    case UPDATE_NOT_CHECKED:
607
    case UPDATE_NOT_FETCHED:
608
    case UPDATE_FETCH_PENDING:
609
      if ($msg_type == 'core') {
610
        $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));
611
      }
612
      else {
613
        $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));
614
      }
615
      break;
616
  }
617

    
618
  if ($report_link) {
619
    if (update_manager_access()) {
620
      $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));
621
    }
622
    else {
623
      $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));
624
    }
625
  }
626

    
627
  return $text;
628
}
629

    
630
/**
631
 * Orders projects based on their status.
632
 *
633
 * Callback for uasort() within update_requirements().
634
 */
635
function _update_project_status_sort($a, $b) {
636
  // The status constants are numerically in the right order, so we can
637
  // usually subtract the two to compare in the order we want. However,
638
  // negative status values should be treated as if they are huge, since we
639
  // always want them at the bottom of the list.
640
  $a_status = $a['status'] > 0 ? $a['status'] : (-10 * $a['status']);
641
  $b_status = $b['status'] > 0 ? $b['status'] : (-10 * $b['status']);
642
  return $a_status - $b_status;
643
}
644

    
645
/**
646
 * Returns HTML for the last time we checked for update data.
647
 *
648
 * In addition to properly formatting the given timestamp, this function also
649
 * provides a "Check manually" link that refreshes the available update and
650
 * redirects back to the same page.
651
 *
652
 * @param $variables
653
 *   An associative array containing:
654
 *   - last: The timestamp when the site last checked for available updates.
655
 *
656
 * @see theme_update_report()
657
 * @see theme_update_available_updates_form()
658
 * @ingroup themeable
659
 */
660
function theme_update_last_check($variables) {
661
  $last = $variables['last'];
662
  $output = '<div class="update checked">';
663
  $output .= $last ? t('Last checked: @time ago', array('@time' => format_interval(REQUEST_TIME - $last))) : t('Last checked: never');
664
  $output .= ' <span class="check-manually">(' . l(t('Check manually'), 'admin/reports/updates/check', array('query' => drupal_get_destination())) . ')</span>';
665
  $output .= "</div>\n";
666
  return $output;
667
}
668

    
669
/**
670
 * Implements hook_verify_update_archive().
671
 *
672
 * First, we ensure that the archive isn't a copy of Drupal core, which the
673
 * update manager does not yet support. See http://drupal.org/node/606592
674
 *
675
 * Then, we make sure that at least one module included in the archive file has
676
 * an .info file which claims that the code is compatible with the current
677
 * version of Drupal core.
678
 *
679
 * @see drupal_system_listing()
680
 * @see _system_rebuild_module_data()
681
 */
682
function update_verify_update_archive($project, $archive_file, $directory) {
683
  $errors = array();
684

    
685
  // Make sure this isn't a tarball of Drupal core.
686
  if (
687
    file_exists("$directory/$project/index.php")
688
    && file_exists("$directory/$project/update.php")
689
    && file_exists("$directory/$project/includes/bootstrap.inc")
690
    && file_exists("$directory/$project/modules/node/node.module")
691
    && file_exists("$directory/$project/modules/system/system.module")
692
  ) {
693
    return array(
694
      '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')),
695
    );
696
  }
697

    
698
  // Parse all the .info files and make sure at least one is compatible with
699
  // this version of Drupal core. If one is compatible, then the project as a
700
  // whole is considered compatible (since, for example, the project may ship
701
  // with some out-of-date modules that are not necessary for its overall
702
  // functionality).
703
  $compatible_project = FALSE;
704
  $incompatible = array();
705
  $files = file_scan_directory("$directory/$project", '/^' . DRUPAL_PHP_FUNCTION_PATTERN . '\.info$/', array('key' => 'name', 'min_depth' => 0));
706
  foreach ($files as $key => $file) {
707
    // Get the .info file for the module or theme this file belongs to.
708
    $info = drupal_parse_info_file($file->uri);
709

    
710
    // If the module or theme is incompatible with Drupal core, set an error.
711
    if (empty($info['core']) || $info['core'] != DRUPAL_CORE_COMPATIBILITY) {
712
      $incompatible[] = !empty($info['name']) ? $info['name'] : t('Unknown');
713
    }
714
    else {
715
      $compatible_project = TRUE;
716
      break;
717
    }
718
  }
719

    
720
  if (empty($files)) {
721
    $errors[] = t('%archive_file does not contain any .info files.', array('%archive_file' => drupal_basename($archive_file)));
722
  }
723
  elseif (!$compatible_project) {
724
    $errors[] = format_plural(
725
      count($incompatible),
726
      '%archive_file contains a version of %names that is not compatible with Drupal !version.',
727
      '%archive_file contains versions of modules or themes that are not compatible with Drupal !version: %names',
728
      array('!version' => DRUPAL_CORE_COMPATIBILITY, '%archive_file' => drupal_basename($archive_file), '%names' => implode(', ', $incompatible))
729
    );
730
  }
731

    
732
  return $errors;
733
}
734

    
735
/**
736
 * @defgroup update_status_cache Private update status cache system
737
 * @{
738
 * Functions to manage the update status cache.
739
 *
740
 * We specifically do NOT use the core cache API for saving the fetched data
741
 * about available updates. It is vitally important that this cache is only
742
 * cleared when we're populating it after successfully fetching new available
743
 * update data. Usage of the core cache API results in all sorts of potential
744
 * problems that would result in attempting to fetch available update data all
745
 * the time, including if a site has a "minimum cache lifetime" (which is both a
746
 * minimum and a maximum) defined, or if a site uses memcache or another
747
 * pluggable cache system that assumes volatile caches.
748
 *
749
 * The Update Manager module still uses the {cache_update} table, but instead of
750
 * using cache_set(), cache_get(), and cache_clear_all(), there are private
751
 * helper functions that implement these same basic tasks but ensure that the
752
 * cache is not prematurely cleared, and that the data is always stored in the
753
 * database, even if memcache or another cache backend is in use.
754
 */
755

    
756
/**
757
 * Stores data in the private update status cache table.
758
 *
759
 * @param $cid
760
 *   The cache ID to save the data with.
761
 * @param $data
762
 *   The data to store.
763
 * @param $expire
764
 *   One of the following values:
765
 *   - CACHE_PERMANENT: Indicates that the item should never be removed except
766
 *     by explicitly using _update_cache_clear().
767
 *   - A Unix timestamp: Indicates that the item should be kept at least until
768
 *     the given time, after which it will be invalidated.
769
 *
770
 * @see _update_cache_get()
771
 */
772
function _update_cache_set($cid, $data, $expire) {
773
  $fields = array(
774
    'created' => REQUEST_TIME,
775
    'expire' => $expire,
776
  );
777
  if (!is_string($data)) {
778
    $fields['data'] = serialize($data);
779
    $fields['serialized'] = 1;
780
  }
781
  else {
782
    $fields['data'] = $data;
783
    $fields['serialized'] = 0;
784
  }
785
  db_merge('cache_update')
786
    ->key(array('cid' => $cid))
787
    ->fields($fields)
788
    ->execute();
789
}
790

    
791
/**
792
 * Retrieves data from the private update status cache table.
793
 *
794
 * @param $cid
795
 *   The cache ID to retrieve.
796
 *
797
 * @return
798
 *   An array of data for the given cache ID, or NULL if the ID was not found.
799
 *
800
 * @see _update_cache_set()
801
 */
802
function _update_cache_get($cid) {
803
  $cache = db_query("SELECT data, created, expire, serialized FROM {cache_update} WHERE cid = :cid", array(':cid' => $cid))->fetchObject();
804
  if (isset($cache->data)) {
805
    if ($cache->serialized) {
806
      $cache->data = unserialize($cache->data);
807
    }
808
  }
809
  return $cache;
810
}
811

    
812
/**
813
 * Returns an array of cache items with a given cache ID prefix.
814
 *
815
 * @param string $cid_prefix
816
 *   The cache ID prefix.
817
 *
818
 * @return
819
 *   Associative array of cache items, keyed by cache ID.
820
 */
821
function _update_get_cache_multiple($cid_prefix) {
822
  $data = array();
823
  $result = db_select('cache_update')
824
    ->fields('cache_update', array('cid', 'data', 'created', 'expire', 'serialized'))
825
    ->condition('cache_update.cid', $cid_prefix . '::%', 'LIKE')
826
    ->execute();
827
  foreach ($result as $cache) {
828
    if ($cache) {
829
      if ($cache->serialized) {
830
        $cache->data = unserialize($cache->data);
831
      }
832
      $data[$cache->cid] = $cache;
833
    }
834
  }
835
  return $data;
836
}
837

    
838
/**
839
 * Invalidates cached data relating to update status.
840
 *
841
 * @param $cid
842
 *   (optional) Cache ID of the record to clear from the private update module
843
 *   cache. If empty, all records will be cleared from the table except fetch
844
 *   tasks. Defaults to NULL.
845
 * @param $wildcard
846
 *   (optional) If TRUE, cache IDs starting with $cid are deleted in addition to
847
 *   the exact cache ID specified by $cid. Defaults to FALSE.
848
 */
849
function _update_cache_clear($cid = NULL, $wildcard = FALSE) {
850
  if (empty($cid)) {
851
    db_delete('cache_update')
852
      // Clear everything except fetch task information because these are used
853
      // to ensure that the fetch task queue items are not added multiple times.
854
      ->condition('cid', 'fetch_task::%', 'NOT LIKE')
855
      ->execute();
856
  }
857
  else {
858
    $query = db_delete('cache_update');
859
    if ($wildcard) {
860
      $query->condition('cid', $cid . '%', 'LIKE');
861
    }
862
    else {
863
      $query->condition('cid', $cid);
864
    }
865
    $query->execute();
866
  }
867
}
868

    
869
/**
870
 * Implements hook_flush_caches().
871
 *
872
 * Called from update.php (among others) to flush the caches. Since we're
873
 * running update.php, we are likely to install a new version of something, in
874
 * which case, we want to check for available update data again. However,
875
 * because we have our own caching system, we need to directly clear the
876
 * database table ourselves at this point and return nothing, for example, on
877
 * sites that use memcache where cache_clear_all() won't know how to purge this
878
 * data.
879
 *
880
 * However, we only want to do this from update.php, since otherwise, we'd lose
881
 * all the available update data on every cron run. So, we specifically check if
882
 * the site is in MAINTENANCE_MODE == 'update' (which indicates update.php is
883
 * running, not update module... alas for overloaded names).
884
 */
885
function update_flush_caches() {
886
  if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
887
    _update_cache_clear();
888
  }
889
  return array();
890
}
891

    
892
/**
893
 * @} End of "defgroup update_status_cache".
894
 */
895

    
896
/**
897
 * Returns a short unique identifier for this Drupal installation.
898
 *
899
 * @return
900
 *   An eight character string uniquely identifying this Drupal installation.
901
 */
902
function _update_manager_unique_identifier() {
903
  $id = &drupal_static(__FUNCTION__, '');
904
  if (empty($id)) {
905
    $id = substr(hash('sha256', drupal_get_hash_salt()), 0, 8);
906
  }
907
  return $id;
908
}
909

    
910
/**
911
 * Returns the directory where update archive files should be extracted.
912
 *
913
 * @param $create
914
 *   (optional) Whether to attempt to create the directory if it does not
915
 *   already exist. Defaults to TRUE.
916
 *
917
 * @return
918
 *   The full path to the temporary directory where update file archives should
919
 *   be extracted.
920
 */
921
function _update_manager_extract_directory($create = TRUE) {
922
  $directory = &drupal_static(__FUNCTION__, '');
923
  if (empty($directory)) {
924
    $directory = 'temporary://update-extraction-' . _update_manager_unique_identifier();
925
    if ($create && !file_exists($directory)) {
926
      mkdir($directory);
927
    }
928
  }
929
  return $directory;
930
}
931

    
932
/**
933
 * Returns the directory where update archive files should be cached.
934
 *
935
 * @param $create
936
 *   (optional) Whether to attempt to create the directory if it does not
937
 *   already exist. Defaults to TRUE.
938
 *
939
 * @return
940
 *   The full path to the temporary directory where update file archives should
941
 *   be cached.
942
 */
943
function _update_manager_cache_directory($create = TRUE) {
944
  $directory = &drupal_static(__FUNCTION__, '');
945
  if (empty($directory)) {
946
    $directory = 'temporary://update-cache-' . _update_manager_unique_identifier();
947
    if ($create && !file_exists($directory)) {
948
      mkdir($directory);
949
    }
950
  }
951
  return $directory;
952
}
953

    
954
/**
955
 * Clears the temporary files and directories based on file age from disk.
956
 */
957
function update_clear_update_disk_cache() {
958
  // List of update module cache directories. Do not create the directories if
959
  // they do not exist.
960
  $directories = array(
961
    _update_manager_cache_directory(FALSE),
962
    _update_manager_extract_directory(FALSE),
963
  );
964

    
965
  // Search for files and directories in base folder only without recursion.
966
  foreach ($directories as $directory) {
967
    file_scan_directory($directory, '/.*/', array('callback' => 'update_delete_file_if_stale', 'recurse' => FALSE));
968
  }
969
}
970

    
971
/**
972
 * Deletes stale files and directories from the update manager disk cache.
973
 *
974
 * Files and directories older than 6 hours and development snapshots older than
975
 * 5 minutes are considered stale. We only cache development snapshots for 5
976
 * minutes since otherwise updated snapshots might not be downloaded as
977
 * expected.
978
 *
979
 * When checking file ages, we need to use the ctime, not the mtime
980
 * (modification time) since many (all?) tar implementations go out of their way
981
 * to set the mtime on the files they create to the timestamps recorded in the
982
 * tarball. We want to see the last time the file was changed on disk, which is
983
 * left alone by tar and correctly set to the time the archive file was
984
 * unpacked.
985
 *
986
 * @param $path
987
 *   A string containing a file path or (streamwrapper) URI.
988
 */
989
function update_delete_file_if_stale($path) {
990
  if (file_exists($path)) {
991
    $filectime = filectime($path);
992
    if (REQUEST_TIME - $filectime > DRUPAL_MAXIMUM_TEMP_FILE_AGE || (preg_match('/.*-dev\.(tar\.gz|zip)/i', $path) && REQUEST_TIME - $filectime > 300)) {
993
      file_unmanaged_delete_recursive($path);
994
    }
995
  }
996
}