update.inc 58 KB

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