Projet

Général

Profil

Paste
Télécharger (57,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / includes / update.inc @ 7c856df4

1 85ad3d82 Assos Assos
<?php
2
3
/**
4
 * @file
5
 * Drupal database update API.
6
 *
7
 * This file contains functions to perform database updates for a Drupal
8
 * installation. It is included and used extensively by update.php.
9
 */
10
11
/**
12
 * Minimum schema version of Drupal 6 required for upgrade to Drupal 7.
13
 *
14
 * Upgrades from Drupal 6 to Drupal 7 require that Drupal 6 be running
15
 * the most recent version, or the upgrade could fail. We can't easily
16
 * check the Drupal 6 version once the update process has begun, so instead
17
 * we check the schema version of system.module in the system table.
18
 */
19
define('REQUIRED_D6_SCHEMA_VERSION', '6055');
20
21
/**
22
 * Disable any items in the {system} table that are not core compatible.
23
 */
24
function update_fix_compatibility() {
25
  $incompatible = array();
26
  $result = db_query("SELECT name, type, status FROM {system} WHERE status = 1 AND type IN ('module','theme')");
27
  foreach ($result as $row) {
28
    if (update_check_incompatibility($row->name, $row->type)) {
29
      $incompatible[] = $row->name;
30
    }
31
  }
32
  if (!empty($incompatible)) {
33
    db_update('system')
34
      ->fields(array('status' => 0))
35
      ->condition('name', $incompatible, 'IN')
36
      ->execute();
37
  }
38
}
39
40
/**
41
 * Tests the compatibility of a module or theme.
42
 */
43
function update_check_incompatibility($name, $type = 'module') {
44
  static $themes, $modules;
45
46
  // Store values of expensive functions for future use.
47
  if (empty($themes) || empty($modules)) {
48
    // We need to do a full rebuild here to make sure the database reflects any
49
    // code changes that were made in the filesystem before the update script
50
    // was initiated.
51
    $themes = system_rebuild_theme_data();
52
    $modules = system_rebuild_module_data();
53
  }
54
55
  if ($type == 'module' && isset($modules[$name])) {
56
    $file = $modules[$name];
57
  }
58
  elseif ($type == 'theme' && isset($themes[$name])) {
59
    $file = $themes[$name];
60
  }
61
  if (!isset($file)
62
      || !isset($file->info['core'])
63
      || $file->info['core'] != DRUPAL_CORE_COMPATIBILITY
64
      || version_compare(phpversion(), $file->info['php']) < 0) {
65
    return TRUE;
66
  }
67
  return FALSE;
68
}
69
70
/**
71
 * Performs extra steps required to bootstrap when using a Drupal 6 database.
72
 *
73
 * Users who still have a Drupal 6 database (and are in the process of
74
 * updating to Drupal 7) need extra help before a full bootstrap can be
75
 * achieved. This function does the necessary preliminary work that allows
76
 * the bootstrap to be successful.
77
 *
78
 * No access check has been performed when this function is called, so no
79
 * irreversible changes to the database are made here.
80
 */
81
function update_prepare_d7_bootstrap() {
82
  // Allow the bootstrap to proceed even if a Drupal 6 settings.php file is
83
  // still being used.
84
  include_once DRUPAL_ROOT . '/includes/install.inc';
85
  drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION);
86
  global $databases, $db_url, $db_prefix, $update_rewrite_settings;
87
  if (empty($databases) && !empty($db_url)) {
88
    $databases = update_parse_db_url($db_url, $db_prefix);
89
    // Record the fact that the settings.php file will need to be rewritten.
90
    $update_rewrite_settings = TRUE;
91
    $settings_file = conf_path() . '/settings.php';
92
    $writable = drupal_verify_install_file($settings_file, FILE_EXIST|FILE_READABLE|FILE_WRITABLE);
93
    $requirements = array(
94
      'settings file' => array(
95
        'title' => 'Settings file',
96
        'value' => $writable ? 'The settings file is writable.' : 'The settings file is not writable.',
97
        'severity' => $writable ? REQUIREMENT_OK : REQUIREMENT_ERROR,
98
        'description' => $writable ? '' : 'Drupal requires write permissions to <em>' . $settings_file . '</em> during the update process. If you are unsure how to grant file permissions, consult the <a href="http://drupal.org/server-permissions">online handbook</a>.',
99
      ),
100
    );
101
    update_extra_requirements($requirements);
102
  }
103
104
  // The new {blocked_ips} table is used in Drupal 7 to store a list of
105
  // banned IP addresses. If this table doesn't exist then we are still
106
  // running on a Drupal 6 database, so we suppress the unavoidable errors
107
  // that occur by creating a static list.
108
  $GLOBALS['conf']['blocked_ips'] = array();
109
110
  // Check that PDO is available and that the correct PDO database driver is
111
  // loaded. Bootstrapping to DRUPAL_BOOTSTRAP_DATABASE will result in a fatal
112
  // error otherwise.
113
  $message = '';
114
  $pdo_link = 'http://drupal.org/requirements/pdo';
115
  // Check that PDO is loaded.
116
  if (!extension_loaded('pdo')) {
117
    $message = '<h2>PDO is required!</h2><p>Drupal 7 requires PHP ' . DRUPAL_MINIMUM_PHP . ' or higher with the PHP Data Objects (PDO) extension enabled.</p>';
118
  }
119
  // The PDO::ATTR_DEFAULT_FETCH_MODE constant is not available in the PECL
120
  // version of PDO.
121
  elseif (!defined('PDO::ATTR_DEFAULT_FETCH_MODE')) {
122
    $message = '<h2>The wrong version of PDO is installed!</h2><p>Drupal 7 requires the PHP Data Objects (PDO) extension from PHP core to be enabled. This system has the older PECL version installed.';
123
    $pdo_link = 'http://drupal.org/requirements/pdo#pecl';
124
  }
125
  // Check that the correct driver is loaded for the database being updated.
126
  // If we have no driver information (for example, if someone tried to create
127
  // the Drupal 7 $databases array themselves but did not do it correctly),
128
  // this message will be confusing, so do not perform the check; instead, just
129
  // let the database connection fail in the code that follows.
130
  elseif (isset($databases['default']['default']['driver']) && !in_array($databases['default']['default']['driver'], PDO::getAvailableDrivers())) {
131
    $message = '<h2>A PDO database driver is required!</h2><p>You need to enable the PDO_' . strtoupper($databases['default']['default']['driver']) . ' database driver for PHP ' . DRUPAL_MINIMUM_PHP . ' or higher so that Drupal 7 can access the database.</p>';
132
  }
133
  if ($message) {
134
    print $message . '<p>See the <a href="' . $pdo_link . '">system requirements page</a> for more information.</p>';
135
    exit();
136
  }
137
138
  // Allow the database system to work even if the registry has not been
139
  // created yet.
140
  drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
141
142
  // If the site has not updated to Drupal 7 yet, check to make sure that it is
143
  // running an up-to-date version of Drupal 6 before proceeding. Note this has
144
  // to happen AFTER the database bootstraps because of
145
  // drupal_get_installed_schema_version().
146
  $system_schema = drupal_get_installed_schema_version('system');
147
  if ($system_schema < 7000) {
148
    $has_required_schema = $system_schema >= REQUIRED_D6_SCHEMA_VERSION;
149
    $requirements = array(
150
      'drupal 6 version' => array(
151
        'title' => 'Drupal 6 version',
152
        'value' => $has_required_schema ? 'You are running a current version of Drupal 6.' : 'You are not running a current version of Drupal 6',
153
        'severity' => $has_required_schema ? REQUIREMENT_OK : REQUIREMENT_ERROR,
154
        'description' => $has_required_schema ? '' : 'Please update your Drupal 6 installation to the most recent version before attempting to upgrade to Drupal 7',
155
      ),
156
    );
157
158
    // Make sure that the database environment is properly set up.
159
    try {
160
      db_run_tasks(db_driver());
161
    }
162
    catch (DatabaseTaskException $e) {
163
      $requirements['database tasks'] = array(
164
        'title' => 'Database environment',
165
        'value' => 'There is a problem with your database environment',
166
        'severity' => REQUIREMENT_ERROR,
167
        'description' => $e->getMessage(),
168
      );
169
    }
170
171
    update_extra_requirements($requirements);
172
173
    // Allow a D6 session to work, since the upgrade has not been performed yet.
174
    $d6_session_name = update_get_d6_session_name();
175
    if (!empty($_COOKIE[$d6_session_name])) {
176
      // Set the current sid to the one found in the D6 cookie.
177
      $sid = $_COOKIE[$d6_session_name];
178
      $_COOKIE[session_name()] = $sid;
179
      session_id($sid);
180
    }
181
182
    // Upgrading from D6 to D7.{0,1,2,3,4,8,...} is different than upgrading
183
    // from D6 to D7.{5,6,7} which should be considered broken. To be able to
184
    // properly handle this difference in node_update_7012 we need to keep track
185
    // of whether a D6 > D7 upgrade or a D7 > D7 update is running.
186
    // Since variable_set() is not available here, the D6 status is being saved
187
    // in a local variable to be able to store it later.
188
    $update_d6 = TRUE;
189
  }
190
191
  // Create the registry tables.
192
  if (!db_table_exists('registry')) {
193
    $schema['registry'] = array(
194
      'fields' => array(
195
        'name'   => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''),
196
        'type'   => array('type' => 'varchar', 'length' => 9, 'not null' => TRUE, 'default' => ''),
197
        'filename'   => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''),
198
        'module'   => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''),
199
        'weight'   => array('type' => 'int', 'not null' => TRUE, 'default' => 0),
200
      ),
201
      'primary key' => array('name', 'type'),
202
      'indexes' => array(
203
        'hook' => array('type', 'weight', 'module'),
204
      ),
205
    );
206
    db_create_table('registry', $schema['registry']);
207
  }
208
  if (!db_table_exists('registry_file')) {
209
    $schema['registry_file'] = array(
210
      'fields' => array(
211
        'filename'   => array('type' => 'varchar', 'length' => 255, 'not null' => TRUE),
212
        'hash'   => array('type' => 'varchar', 'length' => 64, 'not null' => TRUE),
213
      ),
214
      'primary key' => array('filename'),
215
    );
216
    db_create_table('registry_file', $schema['registry_file']);
217
  }
218
219
  // Older versions of Drupal 6 do not include the semaphore table, which is
220
  // required to bootstrap, so we add it now so that we can bootstrap and
221
  // provide a reasonable error message.
222
  if (!db_table_exists('semaphore')) {
223
    $semaphore = array(
224
      'description' => 'Table for holding semaphores, locks, flags, etc. that cannot be stored as Drupal variables since they must not be cached.',
225
      'fields' => array(
226
        'name' => array(
227
          'description' => 'Primary Key: Unique name.',
228
          'type' => 'varchar',
229
          'length' => 255,
230
          'not null' => TRUE,
231
          'default' => ''
232
        ),
233
        'value' => array(
234
          'description' => 'A value for the semaphore.',
235
          'type' => 'varchar',
236
          'length' => 255,
237
          'not null' => TRUE,
238
          'default' => ''
239
        ),
240
        'expire' => array(
241
          'description' => 'A Unix timestamp with microseconds indicating when the semaphore should expire.',
242
          'type' => 'float',
243
          'size' => 'big',
244
          'not null' => TRUE
245
        ),
246
      ),
247
      'indexes' => array(
248
        'value' => array('value'),
249
        'expire' => array('expire'),
250
      ),
251
      'primary key' => array('name'),
252
    );
253
    db_create_table('semaphore', $semaphore);
254
  }
255
256
  // The new cache_bootstrap bin is required to bootstrap to
257
  // DRUPAL_BOOTSTRAP_SESSION, so create it here rather than in
258
  // update_fix_d7_requirements().
259
  if (!db_table_exists('cache_bootstrap')) {
260
    $cache_bootstrap = array(
261
      'description' => 'Cache table for data required to bootstrap Drupal, may be routed to a shared memory cache.',
262
      'fields' => array(
263
        'cid' => array(
264
          'description' => 'Primary Key: Unique cache ID.',
265
          'type' => 'varchar',
266
          'length' => 255,
267
          'not null' => TRUE,
268
          'default' => '',
269
        ),
270
        'data' => array(
271
          'description' => 'A collection of data to cache.',
272
          'type' => 'blob',
273
          'not null' => FALSE,
274
          'size' => 'big',
275
        ),
276
        'expire' => array(
277
          'description' => 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.',
278
          'type' => 'int',
279
          'not null' => TRUE,
280
          'default' => 0,
281
        ),
282
        'created' => array(
283
          'description' => 'A Unix timestamp indicating when the cache entry was created.',
284
          'type' => 'int',
285
          'not null' => TRUE,
286
          'default' => 0,
287
        ),
288
        'serialized' => array(
289
          'description' => 'A flag to indicate whether content is serialized (1) or not (0).',
290
          'type' => 'int',
291
          'size' => 'small',
292
          'not null' => TRUE,
293
          'default' => 0,
294
        ),
295
      ),
296
      'indexes' => array(
297
        'expire' => array('expire'),
298
      ),
299
      'primary key' => array('cid'),
300
    );
301
    db_create_table('cache_bootstrap', $cache_bootstrap);
302
  }
303
304
  // Set a valid timezone for 6 -> 7 upgrade process.
305
  drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES);
306
  $timezone_offset = variable_get('date_default_timezone', 0);
307
  if (is_numeric($timezone_offset)) {
308
    // Save the original offset.
309
    variable_set('date_temporary_timezone', $timezone_offset);
310
    // Set the timezone for this request only.
311
    $GLOBALS['conf']['date_default_timezone'] = 'UTC';
312
  }
313
314
  // This allows update functions to tell if an upgrade from D6 is running.
315
  if (!empty($update_d6)) {
316
    variable_set('update_d6', TRUE);
317
  }
318
}
319
320
/**
321
 * A helper function that modules can use to assist with the transformation
322
 * from numeric block deltas to string block deltas during the 6.x -> 7.x
323
 * upgrade.
324
 *
325
 * @todo This function should be removed in 8.x.
326
 *
327
 * @param $sandbox
328
 *   An array holding data for the batch process.
329
 * @param $renamed_deltas
330
 *   An associative array.  Keys are module names, values an associative array
331
 *   mapping the old block deltas to the new block deltas for the module.
332
 *   Example:
333
 *   @code
334
 *     $renamed_deltas = array(
335
 *       'mymodule' =>
336
 *         array(
337
 *           0 => 'mymodule-block-1',
338
 *           1 => 'mymodule-block-2',
339
 *         ),
340
 *     );
341
 *   @endcode
342
 * @param $moved_deltas
343
 *   An associative array. Keys are source module names, values an associative
344
 *   array mapping the (possibly renamed) block name to the new module name.
345
 *   Example:
346
 *   @code
347
 *     $moved_deltas = array(
348
 *       'user' =>
349
 *         array(
350
 *           'navigation' => 'system',
351
 *         ),
352
 *     );
353
 *   @endcode
354
 */
355
function update_fix_d7_block_deltas(&$sandbox, $renamed_deltas, $moved_deltas) {
356
  // Loop through each block and make changes to the block tables.
357
  // Only run this the first time through the batch update.
358
  if (!isset($sandbox['progress'])) {
359
    // Determine whether to use the old or new block table names.
360
    $block_tables = db_table_exists('blocks') ? array('blocks', 'blocks_roles') : array('block', 'block_role');
361
    foreach ($block_tables as $table) {
362
      foreach ($renamed_deltas as $module => $deltas) {
363
        foreach ($deltas as $old_delta => $new_delta) {
364
          // Only do the update if the old block actually exists.
365
          $block_exists = db_query("SELECT COUNT(*) FROM {" . $table . "} WHERE module = :module AND delta = :delta", array(
366
              ':module' => $module,
367
              ':delta' => $old_delta,
368
            ))
369
            ->fetchField();
370
          if ($block_exists) {
371
            // Delete any existing blocks with the new module+delta.
372
            db_delete($table)
373
              ->condition('module', $module)
374
              ->condition('delta', $new_delta)
375
              ->execute();
376
            // Rename the old block to the new module+delta.
377
            db_update($table)
378
              ->fields(array('delta' => $new_delta))
379
              ->condition('module', $module)
380
              ->condition('delta', $old_delta)
381
              ->execute();
382
          }
383
        }
384
      }
385
      foreach ($moved_deltas as $old_module => $deltas) {
386
        foreach ($deltas as $delta => $new_module) {
387
          // Only do the update if the old block actually exists.
388
          $block_exists = db_query("SELECT COUNT(*) FROM {" . $table . "} WHERE module = :module AND delta = :delta", array(
389
              ':module' => $old_module,
390
              ':delta' => $delta,
391
            ))
392
            ->fetchField();
393
          if ($block_exists) {
394
            // Delete any existing blocks with the new module+delta.
395
            db_delete($table)
396
              ->condition('module', $new_module)
397
              ->condition('delta', $delta)
398
              ->execute();
399
            // Rename the old block to the new module+delta.
400
            db_update($table)
401
              ->fields(array('module' => $new_module))
402
              ->condition('module', $old_module)
403
              ->condition('delta', $delta)
404
              ->execute();
405
          }
406
        }
407
      }
408
    }
409
410
    // Initialize batch update information.
411
    $sandbox['progress'] = 0;
412
    $sandbox['last_user_processed'] = -1;
413
    $sandbox['max'] = db_query("SELECT COUNT(*) FROM {users} WHERE data LIKE :block", array(
414
        ':block' => '%' . db_like(serialize('block')) . '%',
415
      ))
416
      ->fetchField();
417
  }
418
  // Now do the batch update of the user-specific block visibility settings.
419
  $limit = 100;
420
  $result = db_select('users', 'u')
421
    ->fields('u', array('uid', 'data'))
422
    ->condition('uid', $sandbox['last_user_processed'], '>')
423
    ->condition('data', '%' . db_like(serialize('block')) . '%', 'LIKE')
424
    ->orderBy('uid', 'ASC')
425
    ->range(0, $limit)
426
    ->execute();
427
  foreach ($result as $row) {
428
    $data = unserialize($row->data);
429
    $user_needs_update = FALSE;
430
    foreach ($renamed_deltas as $module => $deltas) {
431
      foreach ($deltas as $old_delta => $new_delta) {
432
        if (isset($data['block'][$module][$old_delta])) {
433
          // Transfer the old block visibility settings to the newly-renamed
434
          // block, and mark this user for a database update.
435
          $data['block'][$module][$new_delta] = $data['block'][$module][$old_delta];
436
          unset($data['block'][$module][$old_delta]);
437
          $user_needs_update = TRUE;
438
        }
439
      }
440
    }
441
    foreach ($moved_deltas as $old_module => $deltas) {
442
      foreach ($deltas as $delta => $new_module) {
443
        if (isset($data['block'][$old_module][$delta])) {
444
          // Transfer the old block visibility settings to the moved
445
          // block, and mark this user for a database update.
446
          $data['block'][$new_module][$delta] = $data['block'][$old_module][$delta];
447
          unset($data['block'][$old_module][$delta]);
448
          $user_needs_update = TRUE;
449
        }
450
      }
451
    }
452
    // Update the current user.
453
    if ($user_needs_update) {
454
      db_update('users')
455
        ->fields(array('data' => serialize($data)))
456
        ->condition('uid', $row->uid)
457
        ->execute();
458
    }
459
    // Update our progress information for the batch update.
460
    $sandbox['progress']++;
461
    $sandbox['last_user_processed'] = $row->uid;
462
  }
463
  // Indicate our current progress to the batch update system.
464
  if ($sandbox['progress'] < $sandbox['max']) {
465
    $sandbox['#finished'] = $sandbox['progress'] / $sandbox['max'];
466
  }
467
}
468
469
/**
470
 * Perform Drupal 6.x to 7.x updates that are required for update.php
471
 * to function properly.
472
 *
473
 * This function runs when update.php is run the first time for 7.x,
474
 * even before updates are selected or performed. It is important
475
 * that if updates are not ultimately performed that no changes are
476
 * made which make it impossible to continue using the prior version.
477
 */
478
function update_fix_d7_requirements() {
479
  global $conf;
480
481
  // Rewrite the settings.php file if necessary, see
482
  // update_prepare_d7_bootstrap().
483
  global $update_rewrite_settings, $db_url, $db_prefix;
484
  if (!empty($update_rewrite_settings)) {
485
    $databases = update_parse_db_url($db_url, $db_prefix);
486
    $salt = drupal_hash_base64(drupal_random_bytes(55));
487
    file_put_contents(conf_path() . '/settings.php', "\n" . '$databases = ' . var_export($databases, TRUE) . ";\n\$drupal_hash_salt = '$salt';", FILE_APPEND);
488
  }
489
  if (drupal_get_installed_schema_version('system') < 7000 && !variable_get('update_d7_requirements', FALSE)) {
490
    // Change 6.x system table field values to 7.x equivalent.
491
    // Change field values.
492
    db_change_field('system', 'schema_version', 'schema_version', array(
493
     'type' => 'int',
494
     'size' => 'small',
495
     'not null' => TRUE,
496
     'default' => -1)
497
    );
498
    db_change_field('system', 'status', 'status', array(
499
      'type' => 'int', 'not null' => TRUE, 'default' => 0));
500
    db_change_field('system', 'weight', 'weight', array(
501
      'type' => 'int', 'not null' => TRUE, 'default' => 0));
502
    db_change_field('system', 'bootstrap', 'bootstrap', array(
503
      'type' => 'int', 'not null' => TRUE, 'default' => 0));
504
    // Drop and recreate 6.x indexes.
505
    db_drop_index('system', 'bootstrap');
506
    db_add_index('system', 'bootstrap', array(
507
      'status', 'bootstrap', array('type', 12), 'weight', 'name'));
508
509
    db_drop_index('system' ,'modules');
510
    db_add_index('system', 'modules', array(array(
511
      'type', 12), 'status', 'weight', 'name'));
512
513
    db_drop_index('system', 'type_name');
514
    db_add_index('system', 'type_name', array(array('type', 12), 'name'));
515
    // Add 7.x indexes.
516
    db_add_index('system', 'system_list', array('weight', 'name'));
517
518
    // Add the cache_path table.
519
    if (db_table_exists('cache_path')) {
520
      db_drop_table('cache_path');
521
    }
522
    require_once('./modules/system/system.install');
523
    $schema['cache_path'] = system_schema_cache_7054();
524
    $schema['cache_path']['description'] = 'Cache table used for path alias lookups.';
525
    db_create_table('cache_path', $schema['cache_path']);
526
527
    // system_update_7042() renames columns, but these are needed to bootstrap.
528
    // Add empty columns for now.
529
    db_add_field('url_alias', 'source', array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''));
530
    db_add_field('url_alias', 'alias', array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''));
531
532
    // Add new columns to {menu_router}.
533
    db_add_field('menu_router', 'delivery_callback', array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''));
534
    db_add_field('menu_router', 'context', array(
535
      'description' => 'Only for local tasks (tabs) - the context of a local task to control its placement.',
536
      'type' => 'int',
537
      'not null' => TRUE,
538
      'default' => 0,
539
    ));
540
    db_drop_index('menu_router', 'tab_parent');
541
    db_add_index('menu_router', 'tab_parent', array(array('tab_parent', 64), 'weight', 'title'));
542
    db_add_field('menu_router', 'theme_callback', array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''));
543
    db_add_field('menu_router', 'theme_arguments', array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => ''));
544
545
    // Add the role_permission table.
546
    $schema['role_permission'] = array(
547
      'fields' => array(
548
        'rid' => array(
549
        'type' => 'int',
550
        'unsigned' => TRUE,
551
        'not null' => TRUE,
552
      ),
553
      'permission' => array(
554
        'type' => 'varchar',
555
        'length' => 128,
556
        'not null' => TRUE,
557
        'default' => '',
558
      ),
559
    ),
560
    'primary key' => array('rid', 'permission'),
561
    'indexes' => array(
562
      'permission' => array('permission'),
563
      ),
564
    );
565
    db_create_table('role_permission', $schema['role_permission']);
566
567
    // Drops and recreates semaphore value index.
568
    db_drop_index('semaphore', 'value');
569
    db_add_index('semaphore', 'value', array('value'));
570
571
    $schema['date_format_type'] = array(
572
      'description' => 'Stores configured date format types.',
573
      'fields' => array(
574
        'type' => array(
575
          'description' => 'The date format type, e.g. medium.',
576
          'type' => 'varchar',
577
          'length' => 64,
578
          'not null' => TRUE,
579
        ),
580
        'title' => array(
581
          'description' => 'The human readable name of the format type.',
582
          'type' => 'varchar',
583
          'length' => 255,
584
          'not null' => TRUE,
585
        ),
586
        'locked' => array(
587
          'description' => 'Whether or not this is a system provided format.',
588
          'type' => 'int',
589
          'size' => 'tiny',
590
          'default' => 0,
591
          'not null' => TRUE,
592
        ),
593
      ),
594
      'primary key' => array('type'),
595
    );
596
597
    $schema['date_formats'] = array(
598
      'description' => 'Stores configured date formats.',
599
      'fields' => array(
600
        'dfid' => array(
601
          'description' => 'The date format identifier.',
602
          'type' => 'serial',
603
          'not null' => TRUE,
604
          'unsigned' => TRUE,
605
        ),
606
        'format' => array(
607
          'description' => 'The date format string.',
608
          'type' => 'varchar',
609
          'length' => 100,
610
          'not null' => TRUE,
611
        ),
612
        'type' => array(
613
          'description' => 'The date format type, e.g. medium.',
614
          'type' => 'varchar',
615
          'length' => 64,
616
          'not null' => TRUE,
617
        ),
618
        'locked' => array(
619
          'description' => 'Whether or not this format can be modified.',
620
          'type' => 'int',
621
          'size' => 'tiny',
622
          'default' => 0,
623
          'not null' => TRUE,
624
        ),
625
      ),
626
      'primary key' => array('dfid'),
627
      'unique keys' => array('formats' => array('format', 'type')),
628
    );
629
630
    $schema['date_format_locale'] = array(
631
      'description' => 'Stores configured date formats for each locale.',
632
      'fields' => array(
633
        'format' => array(
634
          'description' => 'The date format string.',
635
          'type' => 'varchar',
636
          'length' => 100,
637
          'not null' => TRUE,
638
        ),
639
        'type' => array(
640
          'description' => 'The date format type, e.g. medium.',
641
          'type' => 'varchar',
642
          'length' => 64,
643
          'not null' => TRUE,
644
        ),
645
        'language' => array(
646
          'description' => 'A {languages}.language for this format to be used with.',
647
          'type' => 'varchar',
648
          'length' => 12,
649
          'not null' => TRUE,
650
        ),
651
      ),
652
      'primary key' => array('type', 'language'),
653
    );
654
655
    db_create_table('date_format_type', $schema['date_format_type']);
656
    // Sites that have the Drupal 6 Date module installed already have the
657
    // following tables.
658
    if (db_table_exists('date_formats')) {
659
      db_rename_table('date_formats', 'd6_date_formats');
660
    }
661
    db_create_table('date_formats', $schema['date_formats']);
662
    if (db_table_exists('date_format_locale')) {
663
      db_rename_table('date_format_locale', 'd6_date_format_locale');
664
    }
665
    db_create_table('date_format_locale', $schema['date_format_locale']);
666
667
    // Add the queue table.
668
    $schema['queue'] = array(
669
      'description' => 'Stores items in queues.',
670
      'fields' => array(
671
        'item_id' => array(
672
          'type' => 'serial',
673
          'unsigned' => TRUE,
674
          'not null' => TRUE,
675
          'description' => 'Primary Key: Unique item ID.',
676
        ),
677
        'name' => array(
678
          'type' => 'varchar',
679
          'length' => 255,
680
          'not null' => TRUE,
681
          'default' => '',
682
          'description' => 'The queue name.',
683
        ),
684
        'data' => array(
685
          'type' => 'blob',
686
          'not null' => FALSE,
687
          'size' => 'big',
688
          'serialize' => TRUE,
689
          'description' => 'The arbitrary data for the item.',
690
        ),
691
        'expire' => array(
692
          'type' => 'int',
693
          'not null' => TRUE,
694
          'default' => 0,
695
          'description' => 'Timestamp when the claim lease expires on the item.',
696
        ),
697
        'created' => array(
698
          'type' => 'int',
699
          'not null' => TRUE,
700
          'default' => 0,
701
          'description' => 'Timestamp when the item was created.',
702
        ),
703
      ),
704
      'primary key' => array('item_id'),
705
      'indexes' => array(
706
        'name_created' => array('name', 'created'),
707
        'expire' => array('expire'),
708
      ),
709
    );
710
    // Check for queue table that may remain from D5 or D6, if found
711
    //drop it.
712
    if (db_table_exists('queue')) {
713
      db_drop_table('queue');
714
    }
715
716
    db_create_table('queue', $schema['queue']);
717
718
    // Create the sequences table.
719
    $schema['sequences'] = array(
720
      'description' => 'Stores IDs.',
721
      'fields' => array(
722
        'value' => array(
723
          'description' => 'The value of the sequence.',
724
          'type' => 'serial',
725
          'unsigned' => TRUE,
726
          'not null' => TRUE,
727
        ),
728
       ),
729
      'primary key' => array('value'),
730
    );
731
    // Check for sequences table that may remain from D5 or D6, if found
732
    //drop it.
733
    if (db_table_exists('sequences')) {
734
      db_drop_table('sequences');
735
    }
736
    db_create_table('sequences', $schema['sequences']);
737
    // Initialize the table with the maximum current increment of the tables
738
    // that will rely on it for their ids.
739
    $max_aid = db_query('SELECT MAX(aid) FROM {actions_aid}')->fetchField();
740
    $max_uid = db_query('SELECT MAX(uid) FROM {users}')->fetchField();
741
    $max_batch_id = db_query('SELECT MAX(bid) FROM {batch}')->fetchField();
742
    db_insert('sequences')->fields(array('value' => max($max_aid, $max_uid, $max_batch_id)))->execute();
743
744
    // Add column for locale context.
745
    if (db_table_exists('locales_source')) {
746
      db_add_field('locales_source', 'context', array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '', 'description' => 'The context this string applies to.'));
747
    }
748
749
    // Rename 'site_offline_message' variable to 'maintenance_mode_message'
750
    // and 'site_offline' variable to 'maintenance_mode'.
751
    // Old variable is removed in update for system.module, see
752
    // system_update_7072().
753
    if ($message = variable_get('site_offline_message', NULL)) {
754
      variable_set('maintenance_mode_message', $message);
755
    }
756
    // Old variable is removed in update for system.module, see
757
    // system_update_7069().
758
    $site_offline = variable_get('site_offline', -1);
759
    if ($site_offline != -1) {
760
      variable_set('maintenance_mode', $site_offline);
761
    }
762
763
    // Add ssid column and index.
764
    db_add_field('sessions', 'ssid', array('description' => "Secure session ID. The value is generated by Drupal's session handlers.", 'type' => 'varchar', 'length' => 128, 'not null' => TRUE, 'default' => ''));
765
    db_add_index('sessions', 'ssid', array('ssid'));
766
    // Drop existing primary key.
767
    db_drop_primary_key('sessions');
768
    // Add new primary key.
769
    db_add_primary_key('sessions', array('sid', 'ssid'));
770
771
    // Allow longer javascript file names.
772
    if (db_table_exists('languages')) {
773
      db_change_field('languages', 'javascript', 'javascript', array('type' => 'varchar', 'length' => 64, 'not null' => TRUE, 'default' => ''));
774
    }
775
776
    // Rename action description to label.
777
    db_change_field('actions', 'description', 'label', array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'default' => '0'));
778
779
    variable_set('update_d7_requirements', TRUE);
780
  }
781
782
  update_fix_d7_install_profile();
783
}
784
785
/**
786
 * Register the currently installed profile in the system table.
787
 *
788
 * Installation profiles are now treated as modules by Drupal, and have an
789
 * upgrade path based on their schema version in the system table.
790
 *
791
 * The installation profile will be set to schema_version 0, as it has already
792
 * been installed. Any other hook_update_N functions provided by the
793
 * installation profile will be run by update.php.
794
 */
795
function update_fix_d7_install_profile() {
796
  $profile = drupal_get_profile();
797
798
  $results = db_select('system', 's')
799
    ->fields('s', array('name', 'schema_version'))
800
    ->condition('name', $profile)
801
    ->condition('type', 'module')
802
    ->execute()
803
    ->fetchAll();
804
805
  if (empty($results)) {
806
    $filename = 'profiles/' . $profile . '/' . $profile . '.profile';
807
808
    // Read profile info file
809
    $info = drupal_parse_info_file(dirname($filename) . '/' . $profile . '.info');
810
811
    // Merge in defaults.
812
    $info = $info + array(
813
      'dependencies' => array(),
814
      'description' => '',
815
      'package' => 'Other',
816
      'version' => NULL,
817
      'php' => DRUPAL_MINIMUM_PHP,
818
      'files' => array(),
819
    );
820
821
    $values = array(
822
      'filename' => $filename,
823
      'name' => $profile,
824
      'info' => serialize($info),
825
      'schema_version' => 0,
826
      'type' => 'module',
827
      'status' => 1,
828
      'owner' => '',
829
    );
830
831
    // Installation profile hooks are always executed last by the module system
832
    $values['weight'] = 1000;
833
834
    // Initializing the system table entry for the installation profile
835
    db_insert('system')
836
      ->fields(array_keys($values))
837
      ->values($values)
838
      ->execute();
839
840
    // Reset the cached schema version.
841
    drupal_get_installed_schema_version($profile, TRUE);
842
843
    // Load the updates again to make sure the installation profile updates
844
    // are loaded.
845
    drupal_load_updates();
846
  }
847
}
848
849
/**
850
 * Parse pre-Drupal 7 database connection URLs and return D7 compatible array.
851
 *
852
 * @return
853
 *   Drupal 7 DBTNG compatible array of database connection information.
854
 */
855
function update_parse_db_url($db_url, $db_prefix) {
856
  $databases = array();
857
  if (!is_array($db_url)) {
858
    $db_url = array('default' => $db_url);
859
  }
860
  foreach ($db_url as $database => $url) {
861
    $url = parse_url($url);
862
    $databases[$database]['default'] = array(
863
      // MySQLi uses the mysql driver.
864
      'driver' => $url['scheme'] == 'mysqli' ? 'mysql' : $url['scheme'],
865
      // Remove the leading slash to get the database name.
866
      'database' => substr(urldecode($url['path']), 1),
867
      'username' => urldecode($url['user']),
868
      'password' => isset($url['pass']) ? urldecode($url['pass']) : '',
869
      'host' => urldecode($url['host']),
870
      'port' => isset($url['port']) ? urldecode($url['port']) : '',
871
    );
872
    if (isset($db_prefix)) {
873
      $databases[$database]['default']['prefix'] = $db_prefix;
874
    }
875
  }
876
  return $databases;
877
}
878
879
/**
880
 * Constructs a session name compatible with a D6 environment.
881
 *
882
 * @return
883
 *   D6-compatible session name string.
884
 *
885
 * @see drupal_settings_initialize()
886
 */
887
function update_get_d6_session_name() {
888
  global $base_url, $cookie_domain;
889
  $cookie_secure = ini_get('session.cookie_secure');
890
891
  // If a custom cookie domain is set in settings.php, that variable forms
892
  // the basis of the session name. Re-compute the D7 hashing method to find
893
  // out if $cookie_domain was used as the session name.
894
  if (($cookie_secure ? 'SSESS' : 'SESS') . substr(hash('sha256', $cookie_domain), 0, 32) == session_name()) {
895
    $session_name = $cookie_domain;
896
  }
897
  else {
898
    // Otherwise use $base_url as session name, without the protocol
899
    // to use the same session identifiers across HTTP and HTTPS.
900
    list( , $session_name) = explode('://', $base_url, 2);
901
  }
902
903
  if ($cookie_secure) {
904
    $session_name .= 'SSL';
905
  }
906
907
  return 'SESS' . md5($session_name);
908
}
909
910
/**
911 582db59d Assos Assos
 * Implements callback_batch_operation().
912
 *
913 85ad3d82 Assos Assos
 * Performs one update and stores the results for display on the results page.
914
 *
915
 * If an update function completes successfully, it should return a message
916
 * as a string indicating success, for example:
917
 * @code
918
 * return t('New index added successfully.');
919
 * @endcode
920
 *
921
 * Alternatively, it may return nothing. In that case, no message
922
 * will be displayed at all.
923
 *
924
 * If it fails for whatever reason, it should throw an instance of
925
 * DrupalUpdateException with an appropriate error message, for example:
926
 * @code
927
 * throw new DrupalUpdateException(t('Description of what went wrong'));
928
 * @endcode
929
 *
930
 * If an exception is thrown, the current update and all updates that depend on
931
 * it will be aborted. The schema version will not be updated in this case, and
932
 * all the aborted updates will continue to appear on update.php as updates
933
 * that have not yet been run.
934
 *
935
 * If an update function needs to be re-run as part of a batch process, it
936
 * should accept the $sandbox array by reference as its first parameter
937
 * and set the #finished property to the percentage completed that it is, as a
938
 * fraction of 1.
939
 *
940
 * @param $module
941
 *   The module whose update will be run.
942
 * @param $number
943
 *   The update number to run.
944
 * @param $dependency_map
945
 *   An array whose keys are the names of all update functions that will be
946
 *   performed during this batch process, and whose values are arrays of other
947
 *   update functions that each one depends on.
948
 * @param $context
949
 *   The batch context array.
950
 *
951
 * @see update_resolve_dependencies()
952
 */
953
function update_do_one($module, $number, $dependency_map, &$context) {
954
  $function = $module . '_update_' . $number;
955
956
  // If this update was aborted in a previous step, or has a dependency that
957
  // was aborted in a previous step, go no further.
958
  if (!empty($context['results']['#abort']) && array_intersect($context['results']['#abort'], array_merge($dependency_map, array($function)))) {
959
    return;
960
  }
961
962
  $ret = array();
963
  if (function_exists($function)) {
964
    try {
965
      $ret['results']['query'] = $function($context['sandbox']);
966
      $ret['results']['success'] = TRUE;
967
    }
968
    // @TODO We may want to do different error handling for different
969
    // exception types, but for now we'll just log the exception and
970
    // return the message for printing.
971
    catch (Exception $e) {
972
      watchdog_exception('update', $e);
973
974
      require_once DRUPAL_ROOT . '/includes/errors.inc';
975
      $variables = _drupal_decode_exception($e);
976
      // The exception message is run through check_plain() by _drupal_decode_exception().
977
      $ret['#abort'] = array('success' => FALSE, 'query' => t('%type: !message in %function (line %line of %file).', $variables));
978
    }
979
  }
980
981
  if (isset($context['sandbox']['#finished'])) {
982
    $context['finished'] = $context['sandbox']['#finished'];
983
    unset($context['sandbox']['#finished']);
984
  }
985
986
  if (!isset($context['results'][$module])) {
987
    $context['results'][$module] = array();
988
  }
989
  if (!isset($context['results'][$module][$number])) {
990
    $context['results'][$module][$number] = array();
991
  }
992
  $context['results'][$module][$number] = array_merge($context['results'][$module][$number], $ret);
993
994
  if (!empty($ret['#abort'])) {
995
    // Record this function in the list of updates that were aborted.
996
    $context['results']['#abort'][] = $function;
997
  }
998
999
  // Record the schema update if it was completed successfully.
1000
  if ($context['finished'] == 1 && empty($ret['#abort'])) {
1001
    drupal_set_installed_schema_version($module, $number);
1002
  }
1003
1004
  $context['message'] = 'Updating ' . check_plain($module) . ' module';
1005
}
1006
1007
/**
1008
 * @class Exception class used to throw error if a module update fails.
1009
 */
1010
class DrupalUpdateException extends Exception { }
1011
1012
/**
1013
 * Starts the database update batch process.
1014
 *
1015
 * @param $start
1016
 *   An array whose keys contain the names of modules to be updated during the
1017
 *   current batch process, and whose values contain the number of the first
1018
 *   requested update for that module. The actual updates that are run (and the
1019
 *   order they are run in) will depend on the results of passing this data
1020
 *   through the update dependency system.
1021
 * @param $redirect
1022
 *   Path to redirect to when the batch has finished processing.
1023
 * @param $url
1024
 *   URL of the batch processing page (should only be used for separate
1025
 *   scripts like update.php).
1026
 * @param $batch
1027
 *   Optional parameters to pass into the batch API.
1028
 * @param $redirect_callback
1029
 *   (optional) Specify a function to be called to redirect to the progressive
1030
 *   processing page.
1031
 *
1032
 * @see update_resolve_dependencies()
1033
 */
1034
function update_batch($start, $redirect = NULL, $url = NULL, $batch = array(), $redirect_callback = 'drupal_goto') {
1035
  // During the update, bring the site offline so that schema changes do not
1036
  // affect visiting users.
1037
  $_SESSION['maintenance_mode'] = variable_get('maintenance_mode', FALSE);
1038
  if ($_SESSION['maintenance_mode'] == FALSE) {
1039
    variable_set('maintenance_mode', TRUE);
1040
  }
1041
1042
  // Resolve any update dependencies to determine the actual updates that will
1043
  // be run and the order they will be run in.
1044
  $updates = update_resolve_dependencies($start);
1045
1046
  // Store the dependencies for each update function in an array which the
1047
  // batch API can pass in to the batch operation each time it is called. (We
1048
  // do not store the entire update dependency array here because it is
1049
  // potentially very large.)
1050
  $dependency_map = array();
1051
  foreach ($updates as $function => $update) {
1052
    $dependency_map[$function] = !empty($update['reverse_paths']) ? array_keys($update['reverse_paths']) : array();
1053
  }
1054
1055
  $operations = array();
1056
  foreach ($updates as $update) {
1057
    if ($update['allowed']) {
1058
      // Set the installed version of each module so updates will start at the
1059
      // correct place. (The updates are already sorted, so we can simply base
1060
      // this on the first one we come across in the above foreach loop.)
1061
      if (isset($start[$update['module']])) {
1062
        drupal_set_installed_schema_version($update['module'], $update['number'] - 1);
1063
        unset($start[$update['module']]);
1064
      }
1065
      // Add this update function to the batch.
1066
      $function = $update['module'] . '_update_' . $update['number'];
1067
      $operations[] = array('update_do_one', array($update['module'], $update['number'], $dependency_map[$function]));
1068
    }
1069
  }
1070
  $batch['operations'] = $operations;
1071
  $batch += array(
1072
    'title' => 'Updating',
1073
    'init_message' => 'Starting updates',
1074
    'error_message' => 'An unrecoverable error has occurred. You can find the error message below. It is advised to copy it to the clipboard for reference.',
1075
    'finished' => 'update_finished',
1076
    'file' => 'includes/update.inc',
1077
  );
1078
  batch_set($batch);
1079
  batch_process($redirect, $url, $redirect_callback);
1080
}
1081
1082
/**
1083 582db59d Assos Assos
 * Implements callback_batch_finished().
1084
 *
1085 85ad3d82 Assos Assos
 * Finishes the update process and stores the results for eventual display.
1086
 *
1087
 * After the updates run, all caches are flushed. The update results are
1088
 * stored into the session (for example, to be displayed on the update results
1089
 * page in update.php). Additionally, if the site was off-line, now that the
1090
 * update process is completed, the site is set back online.
1091
 *
1092
 * @param $success
1093
 *   Indicate that the batch API tasks were all completed successfully.
1094
 * @param $results
1095
 *   An array of all the results that were updated in update_do_one().
1096
 * @param $operations
1097
 *   A list of all the operations that had not been completed by the batch API.
1098
 *
1099
 * @see update_batch()
1100
 */
1101
function update_finished($success, $results, $operations) {
1102
  // Remove the D6 upgrade flag variable so that subsequent update runs do not
1103
  // get the wrong context.
1104
  variable_del('update_d6');
1105
1106
  // Clear the caches in case the data has been updated.
1107
  drupal_flush_all_caches();
1108
1109
  $_SESSION['update_results'] = $results;
1110
  $_SESSION['update_success'] = $success;
1111
  $_SESSION['updates_remaining'] = $operations;
1112
1113
  // Now that the update is done, we can put the site back online if it was
1114
  // previously in maintenance mode.
1115
  if (isset($_SESSION['maintenance_mode']) && $_SESSION['maintenance_mode'] == FALSE) {
1116
    variable_set('maintenance_mode', FALSE);
1117
    unset($_SESSION['maintenance_mode']);
1118
  }
1119
}
1120
1121
/**
1122
 * Returns a list of all the pending database updates.
1123
 *
1124
 * @return
1125
 *   An associative array keyed by module name which contains all information
1126
 *   about database updates that need to be run, and any updates that are not
1127
 *   going to proceed due to missing requirements. The system module will
1128
 *   always be listed first.
1129
 *
1130
 *   The subarray for each module can contain the following keys:
1131
 *   - start: The starting update that is to be processed. If this does not
1132
 *       exist then do not process any updates for this module as there are
1133
 *       other requirements that need to be resolved.
1134
 *   - warning: Any warnings about why this module can not be updated.
1135
 *   - pending: An array of all the pending updates for the module including
1136
 *       the update number and the description from source code comment for
1137
 *       each update function. This array is keyed by the update number.
1138
 */
1139
function update_get_update_list() {
1140
  // Make sure that the system module is first in the list of updates.
1141
  $ret = array('system' => array());
1142
1143
  $modules = drupal_get_installed_schema_version(NULL, FALSE, TRUE);
1144
  foreach ($modules as $module => $schema_version) {
1145
    // Skip uninstalled and incompatible modules.
1146
    if ($schema_version == SCHEMA_UNINSTALLED || update_check_incompatibility($module)) {
1147
      continue;
1148
    }
1149
    // Otherwise, get the list of updates defined by this module.
1150
    $updates = drupal_get_schema_versions($module);
1151
    if ($updates !== FALSE) {
1152
      // module_invoke returns NULL for nonexisting hooks, so if no updates
1153
      // are removed, it will == 0.
1154
      $last_removed = module_invoke($module, 'update_last_removed');
1155
      if ($schema_version < $last_removed) {
1156
        $ret[$module]['warning'] = '<em>' . $module . '</em> module can not be updated. Its schema version is ' . $schema_version . '. Updates up to and including ' . $last_removed . ' have been removed in this release. In order to update <em>' . $module . '</em> module, you will first <a href="http://drupal.org/upgrade">need to upgrade</a> to the last version in which these updates were available.';
1157
        continue;
1158
      }
1159
1160
      $updates = drupal_map_assoc($updates);
1161
      foreach (array_keys($updates) as $update) {
1162
        if ($update > $schema_version) {
1163
          // The description for an update comes from its Doxygen.
1164
          $func = new ReflectionFunction($module . '_update_' . $update);
1165
          $description = str_replace(array("\n", '*', '/'), '', $func->getDocComment());
1166
          $ret[$module]['pending'][$update] = "$update - $description";
1167
          if (!isset($ret[$module]['start'])) {
1168
            $ret[$module]['start'] = $update;
1169
          }
1170
        }
1171
      }
1172
      if (!isset($ret[$module]['start']) && isset($ret[$module]['pending'])) {
1173
        $ret[$module]['start'] = $schema_version;
1174
      }
1175
    }
1176
  }
1177
1178
  if (empty($ret['system'])) {
1179
    unset($ret['system']);
1180
  }
1181
  return $ret;
1182
}
1183
1184
/**
1185
 * Resolves dependencies in a set of module updates, and orders them correctly.
1186
 *
1187
 * This function receives a list of requested module updates and determines an
1188
 * appropriate order to run them in such that all update dependencies are met.
1189
 * Any updates whose dependencies cannot be met are included in the returned
1190
 * array but have the key 'allowed' set to FALSE; the calling function should
1191
 * take responsibility for ensuring that these updates are ultimately not
1192
 * performed.
1193
 *
1194
 * In addition, the returned array also includes detailed information about the
1195
 * dependency chain for each update, as provided by the depth-first search
1196
 * algorithm in drupal_depth_first_search().
1197
 *
1198
 * @param $starting_updates
1199
 *   An array whose keys contain the names of modules with updates to be run
1200
 *   and whose values contain the number of the first requested update for that
1201
 *   module.
1202
 *
1203
 * @return
1204
 *   An array whose keys are the names of all update functions within the
1205
 *   provided modules that would need to be run in order to fulfill the
1206
 *   request, arranged in the order in which the update functions should be
1207
 *   run. (This includes the provided starting update for each module and all
1208
 *   subsequent updates that are available.) The values are themselves arrays
1209
 *   containing all the keys provided by the drupal_depth_first_search()
1210
 *   algorithm, which encode detailed information about the dependency chain
1211
 *   for this update function (for example: 'paths', 'reverse_paths', 'weight',
1212
 *   and 'component'), as well as the following additional keys:
1213
 *   - 'allowed': A boolean which is TRUE when the update function's
1214
 *     dependencies are met, and FALSE otherwise. Calling functions should
1215
 *     inspect this value before running the update.
1216
 *   - 'missing_dependencies': An array containing the names of any other
1217
 *     update functions that are required by this one but that are unavailable
1218
 *     to be run. This array will be empty when 'allowed' is TRUE.
1219
 *   - 'module': The name of the module that this update function belongs to.
1220
 *   - 'number': The number of this update function within that module.
1221
 *
1222
 * @see drupal_depth_first_search()
1223
 */
1224
function update_resolve_dependencies($starting_updates) {
1225
  // Obtain a dependency graph for the requested update functions.
1226
  $update_functions = update_get_update_function_list($starting_updates);
1227
  $graph = update_build_dependency_graph($update_functions);
1228
1229
  // Perform the depth-first search and sort the results.
1230
  require_once DRUPAL_ROOT . '/includes/graph.inc';
1231
  drupal_depth_first_search($graph);
1232
  uasort($graph, 'drupal_sort_weight');
1233
1234
  foreach ($graph as $function => &$data) {
1235
    $module = $data['module'];
1236
    $number = $data['number'];
1237
    // If the update function is missing and has not yet been performed, mark
1238
    // it and everything that ultimately depends on it as disallowed.
1239
    if (update_is_missing($module, $number, $update_functions) && !update_already_performed($module, $number)) {
1240
      $data['allowed'] = FALSE;
1241
      foreach (array_keys($data['paths']) as $dependent) {
1242
        $graph[$dependent]['allowed'] = FALSE;
1243
        $graph[$dependent]['missing_dependencies'][] = $function;
1244
      }
1245
    }
1246
    elseif (!isset($data['allowed'])) {
1247
      $data['allowed'] = TRUE;
1248
      $data['missing_dependencies'] = array();
1249
    }
1250
    // Now that we have finished processing this function, remove it from the
1251
    // graph if it was not part of the original list. This ensures that we
1252
    // never try to run any updates that were not specifically requested.
1253
    if (!isset($update_functions[$module][$number])) {
1254
      unset($graph[$function]);
1255
    }
1256
  }
1257
1258
  return $graph;
1259
}
1260
1261
/**
1262
 * Returns an organized list of update functions for a set of modules.
1263
 *
1264
 * @param $starting_updates
1265
 *   An array whose keys contain the names of modules and whose values contain
1266
 *   the number of the first requested update for that module.
1267
 *
1268
 * @return
1269
 *   An array containing all the update functions that should be run for each
1270
 *   module, including the provided starting update and all subsequent updates
1271
 *   that are available. The keys of the array contain the module names, and
1272
 *   each value is an ordered array of update functions, keyed by the update
1273
 *   number.
1274
 *
1275
 * @see update_resolve_dependencies()
1276
 */
1277
function update_get_update_function_list($starting_updates) {
1278
  // Go through each module and find all updates that we need (including the
1279
  // first update that was requested and any updates that run after it).
1280
  $update_functions = array();
1281
  foreach ($starting_updates as $module => $version) {
1282
    $update_functions[$module] = array();
1283
    $updates = drupal_get_schema_versions($module);
1284
    if ($updates !== FALSE) {
1285
      $max_version = max($updates);
1286
      if ($version <= $max_version) {
1287
        foreach ($updates as $update) {
1288
          if ($update >= $version) {
1289
            $update_functions[$module][$update] = $module . '_update_' . $update;
1290
          }
1291
        }
1292
      }
1293
    }
1294
  }
1295
  return $update_functions;
1296
}
1297
1298
/**
1299
 * Constructs a graph which encodes the dependencies between module updates.
1300
 *
1301
 * This function returns an associative array which contains a "directed graph"
1302
 * representation of the dependencies between a provided list of update
1303
 * functions, as well as any outside update functions that they directly depend
1304
 * on but that were not in the provided list. The vertices of the graph
1305
 * represent the update functions themselves, and each edge represents a
1306
 * requirement that the first update function needs to run before the second.
1307
 * For example, consider this graph:
1308
 *
1309
 * system_update_7000 ---> system_update_7001 ---> system_update_7002
1310
 *
1311
 * Visually, this indicates that system_update_7000() must run before
1312
 * system_update_7001(), which in turn must run before system_update_7002().
1313
 *
1314
 * The function takes into account standard dependencies within each module, as
1315
 * shown above (i.e., the fact that each module's updates must run in numerical
1316
 * order), but also finds any cross-module dependencies that are defined by
1317
 * modules which implement hook_update_dependencies(), and builds them into the
1318
 * graph as well.
1319
 *
1320
 * @param $update_functions
1321
 *   An organized array of update functions, in the format returned by
1322
 *   update_get_update_function_list().
1323
 *
1324
 * @return
1325
 *   A multidimensional array representing the dependency graph, suitable for
1326
 *   passing in to drupal_depth_first_search(), but with extra information
1327
 *   about each update function also included. Each array key contains the name
1328
 *   of an update function, including all update functions from the provided
1329
 *   list as well as any outside update functions which they directly depend
1330
 *   on. Each value is an associative array containing the following keys:
1331
 *   - 'edges': A representation of any other update functions that immediately
1332
 *     depend on this one. See drupal_depth_first_search() for more details on
1333
 *     the format.
1334
 *   - 'module': The name of the module that this update function belongs to.
1335
 *   - 'number': The number of this update function within that module.
1336
 *
1337
 * @see drupal_depth_first_search()
1338
 * @see update_resolve_dependencies()
1339
 */
1340
function update_build_dependency_graph($update_functions) {
1341
  // Initialize an array that will define a directed graph representing the
1342
  // dependencies between update functions.
1343
  $graph = array();
1344
1345
  // Go through each update function and build an initial list of dependencies.
1346
  foreach ($update_functions as $module => $functions) {
1347
    $previous_function = NULL;
1348
    foreach ($functions as $number => $function) {
1349
      // Add an edge to the directed graph representing the fact that each
1350
      // update function in a given module must run after the update that
1351
      // numerically precedes it.
1352
      if ($previous_function) {
1353
        $graph[$previous_function]['edges'][$function] = TRUE;
1354
      }
1355
      $previous_function = $function;
1356
1357
      // Define the module and update number associated with this function.
1358
      $graph[$function]['module'] = $module;
1359
      $graph[$function]['number'] = $number;
1360
    }
1361
  }
1362
1363
  // Now add any explicit update dependencies declared by modules.
1364
  $update_dependencies = update_retrieve_dependencies();
1365
  foreach ($graph as $function => $data) {
1366
    if (!empty($update_dependencies[$data['module']][$data['number']])) {
1367
      foreach ($update_dependencies[$data['module']][$data['number']] as $module => $number) {
1368
        $dependency = $module . '_update_' . $number;
1369
        $graph[$dependency]['edges'][$function] = TRUE;
1370
        $graph[$dependency]['module'] = $module;
1371
        $graph[$dependency]['number'] = $number;
1372
      }
1373
    }
1374
  }
1375
1376
  return $graph;
1377
}
1378
1379
/**
1380
 * Determines if a module update is missing or unavailable.
1381
 *
1382
 * @param $module
1383
 *   The name of the module.
1384
 * @param $number
1385
 *   The number of the update within that module.
1386
 * @param $update_functions
1387
 *   An organized array of update functions, in the format returned by
1388
 *   update_get_update_function_list(). This should represent all module
1389
 *   updates that are requested to run at the time this function is called.
1390
 *
1391
 * @return
1392
 *   TRUE if the provided module update is not installed or is not in the
1393
 *   provided list of updates to run; FALSE otherwise.
1394
 */
1395
function update_is_missing($module, $number, $update_functions) {
1396
  return !isset($update_functions[$module][$number]) || !function_exists($update_functions[$module][$number]);
1397
}
1398
1399
/**
1400
 * Determines if a module update has already been performed.
1401
 *
1402
 * @param $module
1403
 *   The name of the module.
1404
 * @param $number
1405
 *   The number of the update within that module.
1406
 *
1407
 * @return
1408
 *   TRUE if the database schema indicates that the update has already been
1409
 *   performed; FALSE otherwise.
1410
 */
1411
function update_already_performed($module, $number) {
1412
  return $number <= drupal_get_installed_schema_version($module);
1413
}
1414
1415
/**
1416
 * Invokes hook_update_dependencies() in all installed modules.
1417
 *
1418
 * This function is similar to module_invoke_all(), with the main difference
1419
 * that it does not require that a module be enabled to invoke its hook, only
1420
 * that it be installed. This allows the update system to properly perform
1421
 * updates even on modules that are currently disabled.
1422
 *
1423
 * @return
1424
 *   An array of return values obtained by merging the results of the
1425
 *   hook_update_dependencies() implementations in all installed modules.
1426
 *
1427
 * @see module_invoke_all()
1428
 * @see hook_update_dependencies()
1429
 */
1430
function update_retrieve_dependencies() {
1431
  $return = array();
1432
  // Get a list of installed modules, arranged so that we invoke their hooks in
1433
  // the same order that module_invoke_all() does.
1434
  $modules = db_query("SELECT name FROM {system} WHERE type = 'module' AND schema_version <> :schema ORDER BY weight ASC, name ASC", array(':schema' => SCHEMA_UNINSTALLED))->fetchCol();
1435
  foreach ($modules as $module) {
1436
    $function = $module . '_update_dependencies';
1437
    if (function_exists($function)) {
1438
      $result = $function();
1439
      // Each implementation of hook_update_dependencies() returns a
1440
      // multidimensional, associative array containing some keys that
1441
      // represent module names (which are strings) and other keys that
1442
      // represent update function numbers (which are integers). We cannot use
1443
      // array_merge_recursive() to properly merge these results, since it
1444
      // treats strings and integers differently. Therefore, we have to
1445
      // explicitly loop through the expected array structure here and perform
1446
      // the merge manually.
1447
      if (isset($result) && is_array($result)) {
1448
        foreach ($result as $module => $module_data) {
1449
          foreach ($module_data as $update => $update_data) {
1450
            foreach ($update_data as $module_dependency => $update_dependency) {
1451
              // If there are redundant dependencies declared for the same
1452
              // update function (so that it is declared to depend on more than
1453
              // one update from a particular module), record the dependency on
1454
              // the highest numbered update here, since that automatically
1455
              // implies the previous ones. For example, if one module's
1456
              // implementation of hook_update_dependencies() required this
1457
              // ordering:
1458
              //
1459
              // system_update_7001 ---> user_update_7000
1460
              //
1461
              // but another module's implementation of the hook required this
1462
              // one:
1463
              //
1464
              // system_update_7002 ---> user_update_7000
1465
              //
1466
              // we record the second one, since system_update_7001() is always
1467
              // guaranteed to run before system_update_7002() anyway (within
1468
              // an individual module, updates are always run in numerical
1469
              // order).
1470
              if (!isset($return[$module][$update][$module_dependency]) || $update_dependency > $return[$module][$update][$module_dependency]) {
1471
                $return[$module][$update][$module_dependency] = $update_dependency;
1472
              }
1473
            }
1474
          }
1475
        }
1476
      }
1477
    }
1478
  }
1479
1480
  return $return;
1481
}