Projet

Général

Profil

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

root / drupal7 / modules / update / update.module @ 4444412d

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
    ),
282
    'update_version' => array(
283
      'variables' => array('version' => NULL, 'tag' => NULL, 'class' => array()),
284
    ),
285
    'update_status_label' => array(
286
      'variables' => array('status' => NULL),
287
    ),
288
  );
289
}
290

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

    
316
  // Clear garbage from disk.
317
  update_clear_update_disk_cache();
318
}
319

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

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

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

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

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

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

    
398
  // Grab whatever data we currently have cached in the DB.
399
  $available = _update_get_cached_available_releases();
400
  $num_avail = count($available);
401

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

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

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

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

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

    
442
  return $available;
443
}
444

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

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

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

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

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

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

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

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

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

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

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

    
624
  return $text;
625
}
626

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

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

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

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

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

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

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

    
729
  return $errors;
730
}
731

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

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

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

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

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

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

    
889
/**
890
 * @} End of "defgroup update_status_cache".
891
 */
892

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

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

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

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

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

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