update.inc 58 KB

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