update.inc 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477
  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. $results = db_select('system', 's')
  752. ->fields('s', array('name', 'schema_version'))
  753. ->condition('name', $profile)
  754. ->condition('type', 'module')
  755. ->execute()
  756. ->fetchAll();
  757. if (empty($results)) {
  758. $filename = 'profiles/' . $profile . '/' . $profile . '.profile';
  759. // Read profile info file
  760. $info = drupal_parse_info_file(dirname($filename) . '/' . $profile . '.info');
  761. // Merge in defaults.
  762. $info = $info + array(
  763. 'dependencies' => array(),
  764. 'description' => '',
  765. 'package' => 'Other',
  766. 'version' => NULL,
  767. 'php' => DRUPAL_MINIMUM_PHP,
  768. 'files' => array(),
  769. );
  770. $values = array(
  771. 'filename' => $filename,
  772. 'name' => $profile,
  773. 'info' => serialize($info),
  774. 'schema_version' => 0,
  775. 'type' => 'module',
  776. 'status' => 1,
  777. 'owner' => '',
  778. );
  779. // Installation profile hooks are always executed last by the module system
  780. $values['weight'] = 1000;
  781. // Initializing the system table entry for the installation profile
  782. db_insert('system')
  783. ->fields(array_keys($values))
  784. ->values($values)
  785. ->execute();
  786. // Reset the cached schema version.
  787. drupal_get_installed_schema_version($profile, TRUE);
  788. // Load the updates again to make sure the installation profile updates
  789. // are loaded.
  790. drupal_load_updates();
  791. }
  792. }
  793. /**
  794. * Parse pre-Drupal 7 database connection URLs and return D7 compatible array.
  795. *
  796. * @return
  797. * Drupal 7 DBTNG compatible array of database connection information.
  798. */
  799. function update_parse_db_url($db_url, $db_prefix) {
  800. $databases = array();
  801. if (!is_array($db_url)) {
  802. $db_url = array('default' => $db_url);
  803. }
  804. foreach ($db_url as $database => $url) {
  805. $url = parse_url($url);
  806. $databases[$database]['default'] = array(
  807. // MySQLi uses the mysql driver.
  808. 'driver' => $url['scheme'] == 'mysqli' ? 'mysql' : $url['scheme'],
  809. // Remove the leading slash to get the database name.
  810. 'database' => substr(urldecode($url['path']), 1),
  811. 'username' => urldecode($url['user']),
  812. 'password' => isset($url['pass']) ? urldecode($url['pass']) : '',
  813. 'host' => urldecode($url['host']),
  814. 'port' => isset($url['port']) ? urldecode($url['port']) : '',
  815. );
  816. if (isset($db_prefix)) {
  817. $databases[$database]['default']['prefix'] = $db_prefix;
  818. }
  819. }
  820. return $databases;
  821. }
  822. /**
  823. * Constructs a session name compatible with a D6 environment.
  824. *
  825. * @return
  826. * D6-compatible session name string.
  827. *
  828. * @see drupal_settings_initialize()
  829. */
  830. function update_get_d6_session_name() {
  831. global $base_url, $cookie_domain;
  832. $cookie_secure = ini_get('session.cookie_secure');
  833. // If a custom cookie domain is set in settings.php, that variable forms
  834. // the basis of the session name. Re-compute the D7 hashing method to find
  835. // out if $cookie_domain was used as the session name.
  836. if (($cookie_secure ? 'SSESS' : 'SESS') . substr(hash('sha256', $cookie_domain), 0, 32) == session_name()) {
  837. $session_name = $cookie_domain;
  838. }
  839. else {
  840. // Otherwise use $base_url as session name, without the protocol
  841. // to use the same session identifiers across HTTP and HTTPS.
  842. list( , $session_name) = explode('://', $base_url, 2);
  843. }
  844. if ($cookie_secure) {
  845. $session_name .= 'SSL';
  846. }
  847. return 'SESS' . md5($session_name);
  848. }
  849. /**
  850. * Performs one update and stores the results for display on the results page.
  851. *
  852. * If an update function completes successfully, it should return a message
  853. * as a string indicating success, for example:
  854. * @code
  855. * return t('New index added successfully.');
  856. * @endcode
  857. *
  858. * Alternatively, it may return nothing. In that case, no message
  859. * will be displayed at all.
  860. *
  861. * If it fails for whatever reason, it should throw an instance of
  862. * DrupalUpdateException with an appropriate error message, for example:
  863. * @code
  864. * throw new DrupalUpdateException(t('Description of what went wrong'));
  865. * @endcode
  866. *
  867. * If an exception is thrown, the current update and all updates that depend on
  868. * it will be aborted. The schema version will not be updated in this case, and
  869. * all the aborted updates will continue to appear on update.php as updates
  870. * that have not yet been run.
  871. *
  872. * If an update function needs to be re-run as part of a batch process, it
  873. * should accept the $sandbox array by reference as its first parameter
  874. * and set the #finished property to the percentage completed that it is, as a
  875. * fraction of 1.
  876. *
  877. * @param $module
  878. * The module whose update will be run.
  879. * @param $number
  880. * The update number to run.
  881. * @param $dependency_map
  882. * An array whose keys are the names of all update functions that will be
  883. * performed during this batch process, and whose values are arrays of other
  884. * update functions that each one depends on.
  885. * @param $context
  886. * The batch context array.
  887. *
  888. * @see update_resolve_dependencies()
  889. */
  890. function update_do_one($module, $number, $dependency_map, &$context) {
  891. $function = $module . '_update_' . $number;
  892. // If this update was aborted in a previous step, or has a dependency that
  893. // was aborted in a previous step, go no further.
  894. if (!empty($context['results']['#abort']) && array_intersect($context['results']['#abort'], array_merge($dependency_map, array($function)))) {
  895. return;
  896. }
  897. $ret = array();
  898. if (function_exists($function)) {
  899. try {
  900. $ret['results']['query'] = $function($context['sandbox']);
  901. $ret['results']['success'] = TRUE;
  902. }
  903. // @TODO We may want to do different error handling for different
  904. // exception types, but for now we'll just log the exception and
  905. // return the message for printing.
  906. catch (Exception $e) {
  907. watchdog_exception('update', $e);
  908. require_once DRUPAL_ROOT . '/includes/errors.inc';
  909. $variables = _drupal_decode_exception($e);
  910. // The exception message is run through check_plain() by _drupal_decode_exception().
  911. $ret['#abort'] = array('success' => FALSE, 'query' => t('%type: !message in %function (line %line of %file).', $variables));
  912. }
  913. }
  914. if (isset($context['sandbox']['#finished'])) {
  915. $context['finished'] = $context['sandbox']['#finished'];
  916. unset($context['sandbox']['#finished']);
  917. }
  918. if (!isset($context['results'][$module])) {
  919. $context['results'][$module] = array();
  920. }
  921. if (!isset($context['results'][$module][$number])) {
  922. $context['results'][$module][$number] = array();
  923. }
  924. $context['results'][$module][$number] = array_merge($context['results'][$module][$number], $ret);
  925. if (!empty($ret['#abort'])) {
  926. // Record this function in the list of updates that were aborted.
  927. $context['results']['#abort'][] = $function;
  928. }
  929. // Record the schema update if it was completed successfully.
  930. if ($context['finished'] == 1 && empty($ret['#abort'])) {
  931. drupal_set_installed_schema_version($module, $number);
  932. }
  933. $context['message'] = 'Updating ' . check_plain($module) . ' module';
  934. }
  935. /**
  936. * @class Exception class used to throw error if a module update fails.
  937. */
  938. class DrupalUpdateException extends Exception { }
  939. /**
  940. * Starts the database update batch process.
  941. *
  942. * @param $start
  943. * An array whose keys contain the names of modules to be updated during the
  944. * current batch process, and whose values contain the number of the first
  945. * requested update for that module. The actual updates that are run (and the
  946. * order they are run in) will depend on the results of passing this data
  947. * through the update dependency system.
  948. * @param $redirect
  949. * Path to redirect to when the batch has finished processing.
  950. * @param $url
  951. * URL of the batch processing page (should only be used for separate
  952. * scripts like update.php).
  953. * @param $batch
  954. * Optional parameters to pass into the batch API.
  955. * @param $redirect_callback
  956. * (optional) Specify a function to be called to redirect to the progressive
  957. * processing page.
  958. *
  959. * @see update_resolve_dependencies()
  960. */
  961. function update_batch($start, $redirect = NULL, $url = NULL, $batch = array(), $redirect_callback = 'drupal_goto') {
  962. // During the update, bring the site offline so that schema changes do not
  963. // affect visiting users.
  964. $_SESSION['maintenance_mode'] = variable_get('maintenance_mode', FALSE);
  965. if ($_SESSION['maintenance_mode'] == FALSE) {
  966. variable_set('maintenance_mode', TRUE);
  967. }
  968. // Resolve any update dependencies to determine the actual updates that will
  969. // be run and the order they will be run in.
  970. $updates = update_resolve_dependencies($start);
  971. // Store the dependencies for each update function in an array which the
  972. // batch API can pass in to the batch operation each time it is called. (We
  973. // do not store the entire update dependency array here because it is
  974. // potentially very large.)
  975. $dependency_map = array();
  976. foreach ($updates as $function => $update) {
  977. $dependency_map[$function] = !empty($update['reverse_paths']) ? array_keys($update['reverse_paths']) : array();
  978. }
  979. $operations = array();
  980. foreach ($updates as $update) {
  981. if ($update['allowed']) {
  982. // Set the installed version of each module so updates will start at the
  983. // correct place. (The updates are already sorted, so we can simply base
  984. // this on the first one we come across in the above foreach loop.)
  985. if (isset($start[$update['module']])) {
  986. drupal_set_installed_schema_version($update['module'], $update['number'] - 1);
  987. unset($start[$update['module']]);
  988. }
  989. // Add this update function to the batch.
  990. $function = $update['module'] . '_update_' . $update['number'];
  991. $operations[] = array('update_do_one', array($update['module'], $update['number'], $dependency_map[$function]));
  992. }
  993. }
  994. $batch['operations'] = $operations;
  995. $batch += array(
  996. 'title' => 'Updating',
  997. 'init_message' => 'Starting updates',
  998. '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.',
  999. 'finished' => 'update_finished',
  1000. 'file' => 'includes/update.inc',
  1001. );
  1002. batch_set($batch);
  1003. batch_process($redirect, $url, $redirect_callback);
  1004. }
  1005. /**
  1006. * Finishes the update process and stores the results for eventual display.
  1007. *
  1008. * After the updates run, all caches are flushed. The update results are
  1009. * stored into the session (for example, to be displayed on the update results
  1010. * page in update.php). Additionally, if the site was off-line, now that the
  1011. * update process is completed, the site is set back online.
  1012. *
  1013. * @param $success
  1014. * Indicate that the batch API tasks were all completed successfully.
  1015. * @param $results
  1016. * An array of all the results that were updated in update_do_one().
  1017. * @param $operations
  1018. * A list of all the operations that had not been completed by the batch API.
  1019. *
  1020. * @see update_batch()
  1021. */
  1022. function update_finished($success, $results, $operations) {
  1023. // Remove the D6 upgrade flag variable so that subsequent update runs do not
  1024. // get the wrong context.
  1025. variable_del('update_d6');
  1026. // Clear the caches in case the data has been updated.
  1027. drupal_flush_all_caches();
  1028. $_SESSION['update_results'] = $results;
  1029. $_SESSION['update_success'] = $success;
  1030. $_SESSION['updates_remaining'] = $operations;
  1031. // Now that the update is done, we can put the site back online if it was
  1032. // previously in maintenance mode.
  1033. if (isset($_SESSION['maintenance_mode']) && $_SESSION['maintenance_mode'] == FALSE) {
  1034. variable_set('maintenance_mode', FALSE);
  1035. unset($_SESSION['maintenance_mode']);
  1036. }
  1037. }
  1038. /**
  1039. * Returns a list of all the pending database updates.
  1040. *
  1041. * @return
  1042. * An associative array keyed by module name which contains all information
  1043. * about database updates that need to be run, and any updates that are not
  1044. * going to proceed due to missing requirements. The system module will
  1045. * always be listed first.
  1046. *
  1047. * The subarray for each module can contain the following keys:
  1048. * - start: The starting update that is to be processed. If this does not
  1049. * exist then do not process any updates for this module as there are
  1050. * other requirements that need to be resolved.
  1051. * - warning: Any warnings about why this module can not be updated.
  1052. * - pending: An array of all the pending updates for the module including
  1053. * the update number and the description from source code comment for
  1054. * each update function. This array is keyed by the update number.
  1055. */
  1056. function update_get_update_list() {
  1057. // Make sure that the system module is first in the list of updates.
  1058. $ret = array('system' => array());
  1059. $modules = drupal_get_installed_schema_version(NULL, FALSE, TRUE);
  1060. foreach ($modules as $module => $schema_version) {
  1061. // Skip uninstalled and incompatible modules.
  1062. if ($schema_version == SCHEMA_UNINSTALLED || update_check_incompatibility($module)) {
  1063. continue;
  1064. }
  1065. // Otherwise, get the list of updates defined by this module.
  1066. $updates = drupal_get_schema_versions($module);
  1067. if ($updates !== FALSE) {
  1068. // module_invoke returns NULL for nonexisting hooks, so if no updates
  1069. // are removed, it will == 0.
  1070. $last_removed = module_invoke($module, 'update_last_removed');
  1071. if ($schema_version < $last_removed) {
  1072. $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.';
  1073. continue;
  1074. }
  1075. $updates = drupal_map_assoc($updates);
  1076. foreach (array_keys($updates) as $update) {
  1077. if ($update > $schema_version) {
  1078. // The description for an update comes from its Doxygen.
  1079. $func = new ReflectionFunction($module . '_update_' . $update);
  1080. $description = str_replace(array("\n", '*', '/'), '', $func->getDocComment());
  1081. $ret[$module]['pending'][$update] = "$update - $description";
  1082. if (!isset($ret[$module]['start'])) {
  1083. $ret[$module]['start'] = $update;
  1084. }
  1085. }
  1086. }
  1087. if (!isset($ret[$module]['start']) && isset($ret[$module]['pending'])) {
  1088. $ret[$module]['start'] = $schema_version;
  1089. }
  1090. }
  1091. }
  1092. if (empty($ret['system'])) {
  1093. unset($ret['system']);
  1094. }
  1095. return $ret;
  1096. }
  1097. /**
  1098. * Resolves dependencies in a set of module updates, and orders them correctly.
  1099. *
  1100. * This function receives a list of requested module updates and determines an
  1101. * appropriate order to run them in such that all update dependencies are met.
  1102. * Any updates whose dependencies cannot be met are included in the returned
  1103. * array but have the key 'allowed' set to FALSE; the calling function should
  1104. * take responsibility for ensuring that these updates are ultimately not
  1105. * performed.
  1106. *
  1107. * In addition, the returned array also includes detailed information about the
  1108. * dependency chain for each update, as provided by the depth-first search
  1109. * algorithm in drupal_depth_first_search().
  1110. *
  1111. * @param $starting_updates
  1112. * An array whose keys contain the names of modules with updates to be run
  1113. * and whose values contain the number of the first requested update for that
  1114. * module.
  1115. *
  1116. * @return
  1117. * An array whose keys are the names of all update functions within the
  1118. * provided modules that would need to be run in order to fulfill the
  1119. * request, arranged in the order in which the update functions should be
  1120. * run. (This includes the provided starting update for each module and all
  1121. * subsequent updates that are available.) The values are themselves arrays
  1122. * containing all the keys provided by the drupal_depth_first_search()
  1123. * algorithm, which encode detailed information about the dependency chain
  1124. * for this update function (for example: 'paths', 'reverse_paths', 'weight',
  1125. * and 'component'), as well as the following additional keys:
  1126. * - 'allowed': A boolean which is TRUE when the update function's
  1127. * dependencies are met, and FALSE otherwise. Calling functions should
  1128. * inspect this value before running the update.
  1129. * - 'missing_dependencies': An array containing the names of any other
  1130. * update functions that are required by this one but that are unavailable
  1131. * to be run. This array will be empty when 'allowed' is TRUE.
  1132. * - 'module': The name of the module that this update function belongs to.
  1133. * - 'number': The number of this update function within that module.
  1134. *
  1135. * @see drupal_depth_first_search()
  1136. */
  1137. function update_resolve_dependencies($starting_updates) {
  1138. // Obtain a dependency graph for the requested update functions.
  1139. $update_functions = update_get_update_function_list($starting_updates);
  1140. $graph = update_build_dependency_graph($update_functions);
  1141. // Perform the depth-first search and sort the results.
  1142. require_once DRUPAL_ROOT . '/includes/graph.inc';
  1143. drupal_depth_first_search($graph);
  1144. uasort($graph, 'drupal_sort_weight');
  1145. foreach ($graph as $function => &$data) {
  1146. $module = $data['module'];
  1147. $number = $data['number'];
  1148. // If the update function is missing and has not yet been performed, mark
  1149. // it and everything that ultimately depends on it as disallowed.
  1150. if (update_is_missing($module, $number, $update_functions) && !update_already_performed($module, $number)) {
  1151. $data['allowed'] = FALSE;
  1152. foreach (array_keys($data['paths']) as $dependent) {
  1153. $graph[$dependent]['allowed'] = FALSE;
  1154. $graph[$dependent]['missing_dependencies'][] = $function;
  1155. }
  1156. }
  1157. elseif (!isset($data['allowed'])) {
  1158. $data['allowed'] = TRUE;
  1159. $data['missing_dependencies'] = array();
  1160. }
  1161. // Now that we have finished processing this function, remove it from the
  1162. // graph if it was not part of the original list. This ensures that we
  1163. // never try to run any updates that were not specifically requested.
  1164. if (!isset($update_functions[$module][$number])) {
  1165. unset($graph[$function]);
  1166. }
  1167. }
  1168. return $graph;
  1169. }
  1170. /**
  1171. * Returns an organized list of update functions for a set of modules.
  1172. *
  1173. * @param $starting_updates
  1174. * An array whose keys contain the names of modules and whose values contain
  1175. * the number of the first requested update for that module.
  1176. *
  1177. * @return
  1178. * An array containing all the update functions that should be run for each
  1179. * module, including the provided starting update and all subsequent updates
  1180. * that are available. The keys of the array contain the module names, and
  1181. * each value is an ordered array of update functions, keyed by the update
  1182. * number.
  1183. *
  1184. * @see update_resolve_dependencies()
  1185. */
  1186. function update_get_update_function_list($starting_updates) {
  1187. // Go through each module and find all updates that we need (including the
  1188. // first update that was requested and any updates that run after it).
  1189. $update_functions = array();
  1190. foreach ($starting_updates as $module => $version) {
  1191. $update_functions[$module] = array();
  1192. $updates = drupal_get_schema_versions($module);
  1193. if ($updates !== FALSE) {
  1194. $max_version = max($updates);
  1195. if ($version <= $max_version) {
  1196. foreach ($updates as $update) {
  1197. if ($update >= $version) {
  1198. $update_functions[$module][$update] = $module . '_update_' . $update;
  1199. }
  1200. }
  1201. }
  1202. }
  1203. }
  1204. return $update_functions;
  1205. }
  1206. /**
  1207. * Constructs a graph which encodes the dependencies between module updates.
  1208. *
  1209. * This function returns an associative array which contains a "directed graph"
  1210. * representation of the dependencies between a provided list of update
  1211. * functions, as well as any outside update functions that they directly depend
  1212. * on but that were not in the provided list. The vertices of the graph
  1213. * represent the update functions themselves, and each edge represents a
  1214. * requirement that the first update function needs to run before the second.
  1215. * For example, consider this graph:
  1216. *
  1217. * system_update_7000 ---> system_update_7001 ---> system_update_7002
  1218. *
  1219. * Visually, this indicates that system_update_7000() must run before
  1220. * system_update_7001(), which in turn must run before system_update_7002().
  1221. *
  1222. * The function takes into account standard dependencies within each module, as
  1223. * shown above (i.e., the fact that each module's updates must run in numerical
  1224. * order), but also finds any cross-module dependencies that are defined by
  1225. * modules which implement hook_update_dependencies(), and builds them into the
  1226. * graph as well.
  1227. *
  1228. * @param $update_functions
  1229. * An organized array of update functions, in the format returned by
  1230. * update_get_update_function_list().
  1231. *
  1232. * @return
  1233. * A multidimensional array representing the dependency graph, suitable for
  1234. * passing in to drupal_depth_first_search(), but with extra information
  1235. * about each update function also included. Each array key contains the name
  1236. * of an update function, including all update functions from the provided
  1237. * list as well as any outside update functions which they directly depend
  1238. * on. Each value is an associative array containing the following keys:
  1239. * - 'edges': A representation of any other update functions that immediately
  1240. * depend on this one. See drupal_depth_first_search() for more details on
  1241. * the format.
  1242. * - 'module': The name of the module that this update function belongs to.
  1243. * - 'number': The number of this update function within that module.
  1244. *
  1245. * @see drupal_depth_first_search()
  1246. * @see update_resolve_dependencies()
  1247. */
  1248. function update_build_dependency_graph($update_functions) {
  1249. // Initialize an array that will define a directed graph representing the
  1250. // dependencies between update functions.
  1251. $graph = array();
  1252. // Go through each update function and build an initial list of dependencies.
  1253. foreach ($update_functions as $module => $functions) {
  1254. $previous_function = NULL;
  1255. foreach ($functions as $number => $function) {
  1256. // Add an edge to the directed graph representing the fact that each
  1257. // update function in a given module must run after the update that
  1258. // numerically precedes it.
  1259. if ($previous_function) {
  1260. $graph[$previous_function]['edges'][$function] = TRUE;
  1261. }
  1262. $previous_function = $function;
  1263. // Define the module and update number associated with this function.
  1264. $graph[$function]['module'] = $module;
  1265. $graph[$function]['number'] = $number;
  1266. }
  1267. }
  1268. // Now add any explicit update dependencies declared by modules.
  1269. $update_dependencies = update_retrieve_dependencies();
  1270. foreach ($graph as $function => $data) {
  1271. if (!empty($update_dependencies[$data['module']][$data['number']])) {
  1272. foreach ($update_dependencies[$data['module']][$data['number']] as $module => $number) {
  1273. $dependency = $module . '_update_' . $number;
  1274. $graph[$dependency]['edges'][$function] = TRUE;
  1275. $graph[$dependency]['module'] = $module;
  1276. $graph[$dependency]['number'] = $number;
  1277. }
  1278. }
  1279. }
  1280. return $graph;
  1281. }
  1282. /**
  1283. * Determines if a module update is missing or unavailable.
  1284. *
  1285. * @param $module
  1286. * The name of the module.
  1287. * @param $number
  1288. * The number of the update within that module.
  1289. * @param $update_functions
  1290. * An organized array of update functions, in the format returned by
  1291. * update_get_update_function_list(). This should represent all module
  1292. * updates that are requested to run at the time this function is called.
  1293. *
  1294. * @return
  1295. * TRUE if the provided module update is not installed or is not in the
  1296. * provided list of updates to run; FALSE otherwise.
  1297. */
  1298. function update_is_missing($module, $number, $update_functions) {
  1299. return !isset($update_functions[$module][$number]) || !function_exists($update_functions[$module][$number]);
  1300. }
  1301. /**
  1302. * Determines if a module update has already been performed.
  1303. *
  1304. * @param $module
  1305. * The name of the module.
  1306. * @param $number
  1307. * The number of the update within that module.
  1308. *
  1309. * @return
  1310. * TRUE if the database schema indicates that the update has already been
  1311. * performed; FALSE otherwise.
  1312. */
  1313. function update_already_performed($module, $number) {
  1314. return $number <= drupal_get_installed_schema_version($module);
  1315. }
  1316. /**
  1317. * Invokes hook_update_dependencies() in all installed modules.
  1318. *
  1319. * This function is similar to module_invoke_all(), with the main difference
  1320. * that it does not require that a module be enabled to invoke its hook, only
  1321. * that it be installed. This allows the update system to properly perform
  1322. * updates even on modules that are currently disabled.
  1323. *
  1324. * @return
  1325. * An array of return values obtained by merging the results of the
  1326. * hook_update_dependencies() implementations in all installed modules.
  1327. *
  1328. * @see module_invoke_all()
  1329. * @see hook_update_dependencies()
  1330. */
  1331. function update_retrieve_dependencies() {
  1332. $return = array();
  1333. // Get a list of installed modules, arranged so that we invoke their hooks in
  1334. // the same order that module_invoke_all() does.
  1335. $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();
  1336. foreach ($modules as $module) {
  1337. $function = $module . '_update_dependencies';
  1338. if (function_exists($function)) {
  1339. $result = $function();
  1340. // Each implementation of hook_update_dependencies() returns a
  1341. // multidimensional, associative array containing some keys that
  1342. // represent module names (which are strings) and other keys that
  1343. // represent update function numbers (which are integers). We cannot use
  1344. // array_merge_recursive() to properly merge these results, since it
  1345. // treats strings and integers differently. Therefore, we have to
  1346. // explicitly loop through the expected array structure here and perform
  1347. // the merge manually.
  1348. if (isset($result) && is_array($result)) {
  1349. foreach ($result as $module => $module_data) {
  1350. foreach ($module_data as $update => $update_data) {
  1351. foreach ($update_data as $module_dependency => $update_dependency) {
  1352. // If there are redundant dependencies declared for the same
  1353. // update function (so that it is declared to depend on more than
  1354. // one update from a particular module), record the dependency on
  1355. // the highest numbered update here, since that automatically
  1356. // implies the previous ones. For example, if one module's
  1357. // implementation of hook_update_dependencies() required this
  1358. // ordering:
  1359. //
  1360. // system_update_7001 ---> user_update_7000
  1361. //
  1362. // but another module's implementation of the hook required this
  1363. // one:
  1364. //
  1365. // system_update_7002 ---> user_update_7000
  1366. //
  1367. // we record the second one, since system_update_7001() is always
  1368. // guaranteed to run before system_update_7002() anyway (within
  1369. // an individual module, updates are always run in numerical
  1370. // order).
  1371. if (!isset($return[$module][$update][$module_dependency]) || $update_dependency > $return[$module][$update][$module_dependency]) {
  1372. $return[$module][$update][$module_dependency] = $update_dependency;
  1373. }
  1374. }
  1375. }
  1376. }
  1377. }
  1378. }
  1379. }
  1380. return $return;
  1381. }