update.inc 58 KB

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