update.manager.inc

Administrative screens and processing functions of the Update Manager module.

This allows site administrators with the 'administer software updates' permission to either upgrade existing projects, or download and install new ones, so long as the killswitch setting ('allow_authorize_operations') is still TRUE.

To install new code, the administrator is prompted for either the URL of an archive file, or to directly upload the archive file. The archive is loaded into a temporary location, extracted, and verified. If everything is successful, the user is redirected to authorize.php to type in file transfer credentials and authorize the installation to proceed with elevated privileges, such that the extracted files can be copied out of the temporary location and into the live web root.

Updating existing code is a more elaborate process. The first step is a selection form where the user is presented with a table of installed projects that are missing newer releases. The user selects which projects they wish to update, and presses the "Download updates" button to continue. This sets up a batch to fetch all the selected releases, and redirects to admin/update/download to display the batch progress bar as it runs. Each batch operation is responsible for downloading a single file, extracting the archive, and verifying the contents. If there are any errors, the user is redirected back to the first page with the error messages. If all downloads were extacted and verified, the user is instead redirected to admin/update/ready, a landing page which reminds them to backup their database and asks if they want to put the site offline during the update. Once the user presses the "Install updates" button, they are redirected to authorize.php to supply their web root file access credentials. The authorized operation (which lives in update.authorize.inc) sets up a batch to copy each extracted update from the temporary location into the live web root.

File

drupal-7.x/modules/update/update.manager.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Administrative screens and processing functions of the Update Manager module.
  5. *
  6. * This allows site administrators with the 'administer software updates'
  7. * permission to either upgrade existing projects, or download and install new
  8. * ones, so long as the killswitch setting ('allow_authorize_operations') is
  9. * still TRUE.
  10. *
  11. * To install new code, the administrator is prompted for either the URL of an
  12. * archive file, or to directly upload the archive file. The archive is loaded
  13. * into a temporary location, extracted, and verified. If everything is
  14. * successful, the user is redirected to authorize.php to type in file transfer
  15. * credentials and authorize the installation to proceed with elevated
  16. * privileges, such that the extracted files can be copied out of the temporary
  17. * location and into the live web root.
  18. *
  19. * Updating existing code is a more elaborate process. The first step is a
  20. * selection form where the user is presented with a table of installed projects
  21. * that are missing newer releases. The user selects which projects they wish to
  22. * update, and presses the "Download updates" button to continue. This sets up a
  23. * batch to fetch all the selected releases, and redirects to
  24. * admin/update/download to display the batch progress bar as it runs. Each
  25. * batch operation is responsible for downloading a single file, extracting the
  26. * archive, and verifying the contents. If there are any errors, the user is
  27. * redirected back to the first page with the error messages. If all downloads
  28. * were extacted and verified, the user is instead redirected to
  29. * admin/update/ready, a landing page which reminds them to backup their
  30. * database and asks if they want to put the site offline during the update.
  31. * Once the user presses the "Install updates" button, they are redirected to
  32. * authorize.php to supply their web root file access credentials. The
  33. * authorized operation (which lives in update.authorize.inc) sets up a batch to
  34. * copy each extracted update from the temporary location into the live web
  35. * root.
  36. */
  37. /**
  38. * @defgroup update_manager_update Update Manager module: update
  39. * @{
  40. * Update Manager module functionality for updating existing code.
  41. *
  42. * Provides a user interface to update existing code.
  43. */
  44. /**
  45. * Form constructor for the update form of the Update Manager module.
  46. *
  47. * This presents a table with all projects that have available updates with
  48. * checkboxes to select which ones to upgrade.
  49. *
  50. * @param $context
  51. * String representing the context from which we're trying to update.
  52. * Allowed values are 'module', 'theme', and 'report'.
  53. *
  54. * @see update_manager_update_form_validate()
  55. * @see update_manager_update_form_submit()
  56. * @see update_menu()
  57. * @ingroup forms
  58. */
  59. function update_manager_update_form($form, $form_state = array(), $context) {
  60. if (!_update_manager_check_backends($form, 'update')) {
  61. return $form;
  62. }
  63. $form['#theme'] = 'update_manager_update_form';
  64. $available = update_get_available(TRUE);
  65. if (empty($available)) {
  66. $form['message'] = array(
  67. '#markup' => t('There was a problem getting update information. Try again later.'),
  68. );
  69. return $form;
  70. }
  71. $form['#attached']['css'][] = drupal_get_path('module', 'update') . '/update.css';
  72. // This will be a nested array. The first key is the kind of project, which
  73. // can be either 'enabled', 'disabled', 'manual' (projects which require
  74. // manual updates, such as core). Then, each subarray is an array of
  75. // projects of that type, indexed by project short name, and containing an
  76. // array of data for cells in that project's row in the appropriate table.
  77. $projects = array();
  78. // This stores the actual download link we're going to update from for each
  79. // project in the form, regardless of if it's enabled or disabled.
  80. $form['project_downloads'] = array('#tree' => TRUE);
  81. module_load_include('inc', 'update', 'update.compare');
  82. $project_data = update_calculate_project_data($available);
  83. foreach ($project_data as $name => $project) {
  84. // Filter out projects which are up to date already.
  85. if ($project['status'] == UPDATE_CURRENT) {
  86. continue;
  87. }
  88. // The project name to display can vary based on the info we have.
  89. if (!empty($project['title'])) {
  90. if (!empty($project['link'])) {
  91. $project_name = l($project['title'], $project['link']);
  92. }
  93. else {
  94. $project_name = check_plain($project['title']);
  95. }
  96. }
  97. elseif (!empty($project['info']['name'])) {
  98. $project_name = check_plain($project['info']['name']);
  99. }
  100. else {
  101. $project_name = check_plain($name);
  102. }
  103. if ($project['project_type'] == 'theme' || $project['project_type'] == 'theme-disabled') {
  104. $project_name .= ' ' . t('(Theme)');
  105. }
  106. if (empty($project['recommended'])) {
  107. // If we don't know what to recommend they upgrade to, we should skip
  108. // the project entirely.
  109. continue;
  110. }
  111. $recommended_release = $project['releases'][$project['recommended']];
  112. $recommended_version = $recommended_release['version'] . ' ' . l(t('(Release notes)'), $recommended_release['release_link'], array('attributes' => array('title' => t('Release notes for @project_title', array('@project_title' => $project['title'])))));
  113. if ($recommended_release['version_major'] != $project['existing_major']) {
  114. $recommended_version .= '<div title="Major upgrade warning" class="update-major-version-warning">' . t('This update is a major version update which means that it may not be backwards compatible with your currently running version. It is recommended that you read the release notes and proceed at your own risk.') . '</div>';
  115. }
  116. // Create an entry for this project.
  117. $entry = array(
  118. 'title' => $project_name,
  119. 'installed_version' => $project['existing_version'],
  120. 'recommended_version' => $recommended_version,
  121. );
  122. switch ($project['status']) {
  123. case UPDATE_NOT_SECURE:
  124. case UPDATE_REVOKED:
  125. $entry['title'] .= ' ' . t('(Security update)');
  126. $entry['#weight'] = -2;
  127. $type = 'security';
  128. break;
  129. case UPDATE_NOT_SUPPORTED:
  130. $type = 'unsupported';
  131. $entry['title'] .= ' ' . t('(Unsupported)');
  132. $entry['#weight'] = -1;
  133. break;
  134. case UPDATE_UNKNOWN:
  135. case UPDATE_NOT_FETCHED:
  136. case UPDATE_NOT_CHECKED:
  137. case UPDATE_NOT_CURRENT:
  138. $type = 'recommended';
  139. break;
  140. default:
  141. // Jump out of the switch and onto the next project in foreach.
  142. continue 2;
  143. }
  144. $entry['#attributes'] = array('class' => array('update-' . $type));
  145. // Drupal core needs to be upgraded manually.
  146. $needs_manual = $project['project_type'] == 'core';
  147. if ($needs_manual) {
  148. // There are no checkboxes in the 'Manual updates' table so it will be
  149. // rendered by theme('table'), not theme('tableselect'). Since the data
  150. // formats are incompatible, we convert now to the format expected by
  151. // theme('table').
  152. unset($entry['#weight']);
  153. $attributes = $entry['#attributes'];
  154. unset($entry['#attributes']);
  155. $entry = array(
  156. 'data' => $entry,
  157. ) + $attributes;
  158. }
  159. else {
  160. $form['project_downloads'][$name] = array(
  161. '#type' => 'value',
  162. '#value' => $recommended_release['download_link'],
  163. );
  164. }
  165. // Based on what kind of project this is, save the entry into the
  166. // appropriate subarray.
  167. switch ($project['project_type']) {
  168. case 'core':
  169. // Core needs manual updates at this time.
  170. $projects['manual'][$name] = $entry;
  171. break;
  172. case 'module':
  173. case 'theme':
  174. $projects['enabled'][$name] = $entry;
  175. break;
  176. case 'module-disabled':
  177. case 'theme-disabled':
  178. $projects['disabled'][$name] = $entry;
  179. break;
  180. }
  181. }
  182. if (empty($projects)) {
  183. $form['message'] = array(
  184. '#markup' => t('All of your projects are up to date.'),
  185. );
  186. return $form;
  187. }
  188. $headers = array(
  189. 'title' => array(
  190. 'data' => t('Name'),
  191. 'class' => array('update-project-name'),
  192. ),
  193. 'installed_version' => t('Installed version'),
  194. 'recommended_version' => t('Recommended version'),
  195. );
  196. if (!empty($projects['enabled'])) {
  197. $form['projects'] = array(
  198. '#type' => 'tableselect',
  199. '#header' => $headers,
  200. '#options' => $projects['enabled'],
  201. );
  202. if (!empty($projects['disabled'])) {
  203. $form['projects']['#prefix'] = '<h2>' . t('Enabled') . '</h2>';
  204. }
  205. }
  206. if (!empty($projects['disabled'])) {
  207. $form['disabled_projects'] = array(
  208. '#type' => 'tableselect',
  209. '#header' => $headers,
  210. '#options' => $projects['disabled'],
  211. '#weight' => 1,
  212. '#prefix' => '<h2>' . t('Disabled') . '</h2>',
  213. );
  214. }
  215. // If either table has been printed yet, we need a submit button and to
  216. // validate the checkboxes.
  217. if (!empty($projects['enabled']) || !empty($projects['disabled'])) {
  218. $form['actions'] = array('#type' => 'actions');
  219. $form['actions']['submit'] = array(
  220. '#type' => 'submit',
  221. '#value' => t('Download these updates'),
  222. );
  223. $form['#validate'][] = 'update_manager_update_form_validate';
  224. }
  225. if (!empty($projects['manual'])) {
  226. $prefix = '<h2>' . t('Manual updates required') . '</h2>';
  227. $prefix .= '<p>' . t('Updates of Drupal core are not supported at this time.') . '</p>';
  228. $form['manual_updates'] = array(
  229. '#type' => 'markup',
  230. '#markup' => theme('table', array('header' => $headers, 'rows' => $projects['manual'])),
  231. '#prefix' => $prefix,
  232. '#weight' => 120,
  233. );
  234. }
  235. return $form;
  236. }
  237. /**
  238. * Returns HTML for the first page in the process of updating projects.
  239. *
  240. * @param $variables
  241. * An associative array containing:
  242. * - form: A render element representing the form.
  243. *
  244. * @ingroup themeable
  245. */
  246. function theme_update_manager_update_form($variables) {
  247. $form = $variables['form'];
  248. $last = variable_get('update_last_check', 0);
  249. $output = theme('update_last_check', array('last' => $last));
  250. $output .= drupal_render_children($form);
  251. return $output;
  252. }
  253. /**
  254. * Form validation handler for update_manager_update_form().
  255. *
  256. * Ensures that at least one project is selected.
  257. *
  258. * @see update_manager_update_form_submit()
  259. */
  260. function update_manager_update_form_validate($form, &$form_state) {
  261. if (!empty($form_state['values']['projects'])) {
  262. $enabled = array_filter($form_state['values']['projects']);
  263. }
  264. if (!empty($form_state['values']['disabled_projects'])) {
  265. $disabled = array_filter($form_state['values']['disabled_projects']);
  266. }
  267. if (empty($enabled) && empty($disabled)) {
  268. form_set_error('projects', t('You must select at least one project to update.'));
  269. }
  270. }
  271. /**
  272. * Form submission handler for update_manager_update_form().
  273. *
  274. * Sets up a batch that downloads, extracts, and verifies the selected releases.
  275. *
  276. * @see update_manager_update_form_validate()
  277. */
  278. function update_manager_update_form_submit($form, &$form_state) {
  279. $projects = array();
  280. foreach (array('projects', 'disabled_projects') as $type) {
  281. if (!empty($form_state['values'][$type])) {
  282. $projects = array_merge($projects, array_keys(array_filter($form_state['values'][$type])));
  283. }
  284. }
  285. $operations = array();
  286. foreach ($projects as $project) {
  287. $operations[] = array(
  288. 'update_manager_batch_project_get',
  289. array(
  290. $project,
  291. $form_state['values']['project_downloads'][$project],
  292. ),
  293. );
  294. }
  295. $batch = array(
  296. 'title' => t('Downloading updates'),
  297. 'init_message' => t('Preparing to download selected updates'),
  298. 'operations' => $operations,
  299. 'finished' => 'update_manager_download_batch_finished',
  300. 'file' => drupal_get_path('module', 'update') . '/update.manager.inc',
  301. );
  302. batch_set($batch);
  303. }
  304. /**
  305. * Batch callback: Performs actions when the download batch is completed.
  306. *
  307. * @param $success
  308. * TRUE if the batch operation was successful, FALSE if there were errors.
  309. * @param $results
  310. * An associative array of results from the batch operation.
  311. */
  312. function update_manager_download_batch_finished($success, $results) {
  313. if (!empty($results['errors'])) {
  314. $error_list = array(
  315. 'title' => t('Downloading updates failed:'),
  316. 'items' => $results['errors'],
  317. );
  318. drupal_set_message(theme('item_list', $error_list), 'error');
  319. }
  320. elseif ($success) {
  321. drupal_set_message(t('Updates downloaded successfully.'));
  322. $_SESSION['update_manager_update_projects'] = $results['projects'];
  323. drupal_goto('admin/update/ready');
  324. }
  325. else {
  326. // Ideally we're catching all Exceptions, so they should never see this,
  327. // but just in case, we have to tell them something.
  328. drupal_set_message(t('Fatal error trying to download.'), 'error');
  329. }
  330. }
  331. /**
  332. * Form constructor for the update ready form.
  333. *
  334. * Build the form when the site is ready to update (after downloading).
  335. *
  336. * This form is an intermediary step in the automated update workflow. It is
  337. * presented to the site administrator after all the required updates have been
  338. * downloaded and verified. The point of this page is to encourage the user to
  339. * backup their site, give them the opportunity to put the site offline, and
  340. * then ask them to confirm that the update should continue. After this step,
  341. * the user is redirected to authorize.php to enter their file transfer
  342. * credentials and attempt to complete the update.
  343. *
  344. * @see update_manager_update_ready_form_submit()
  345. * @see update_menu()
  346. * @ingroup forms
  347. */
  348. function update_manager_update_ready_form($form, &$form_state) {
  349. if (!_update_manager_check_backends($form, 'update')) {
  350. return $form;
  351. }
  352. $form['backup'] = array(
  353. '#prefix' => '<strong>',
  354. '#markup' => t('Back up your database and site before you continue. <a href="@backup_url">Learn how</a>.', array('@backup_url' => url('http://drupal.org/node/22281'))),
  355. '#suffix' => '</strong>',
  356. );
  357. $form['maintenance_mode'] = array(
  358. '#title' => t('Perform updates with site in maintenance mode (strongly recommended)'),
  359. '#type' => 'checkbox',
  360. '#default_value' => TRUE,
  361. );
  362. $form['actions'] = array('#type' => 'actions');
  363. $form['actions']['submit'] = array(
  364. '#type' => 'submit',
  365. '#value' => t('Continue'),
  366. );
  367. return $form;
  368. }
  369. /**
  370. * Form submission handler for update_manager_update_ready_form().
  371. *
  372. * If the site administrator requested that the site is put offline during the
  373. * update, do so now. Otherwise, pull information about all the required updates
  374. * out of the SESSION, figure out what Drupal\Core\Updater\Updater class is
  375. * needed for each one, generate an array of update operations to perform, and
  376. * hand it all off to system_authorized_init(), then redirect to authorize.php.
  377. *
  378. * @see update_authorize_run_update()
  379. * @see system_authorized_init()
  380. * @see system_authorized_get_url()
  381. */
  382. function update_manager_update_ready_form_submit($form, &$form_state) {
  383. // Store maintenance_mode setting so we can restore it when done.
  384. $_SESSION['maintenance_mode'] = variable_get('maintenance_mode', FALSE);
  385. if ($form_state['values']['maintenance_mode'] == TRUE) {
  386. variable_set('maintenance_mode', TRUE);
  387. }
  388. if (!empty($_SESSION['update_manager_update_projects'])) {
  389. // Make sure the Updater registry is loaded.
  390. drupal_get_updaters();
  391. $updates = array();
  392. $directory = _update_manager_extract_directory();
  393. $projects = $_SESSION['update_manager_update_projects'];
  394. unset($_SESSION['update_manager_update_projects']);
  395. foreach ($projects as $project => $url) {
  396. $project_location = $directory . '/' . $project;
  397. $updater = Updater::factory($project_location);
  398. $project_real_location = drupal_realpath($project_location);
  399. $updates[] = array(
  400. 'project' => $project,
  401. 'updater_name' => get_class($updater),
  402. 'local_url' => $project_real_location,
  403. );
  404. }
  405. // If the owner of the last directory we extracted is the same as the
  406. // owner of our configuration directory (e.g. sites/default) where we're
  407. // trying to install the code, there's no need to prompt for FTP/SSH
  408. // credentials. Instead, we instantiate a FileTransferLocal and invoke
  409. // update_authorize_run_update() directly.
  410. if (fileowner($project_real_location) == fileowner(conf_path())) {
  411. module_load_include('inc', 'update', 'update.authorize');
  412. $filetransfer = new FileTransferLocal(DRUPAL_ROOT);
  413. update_authorize_run_update($filetransfer, $updates);
  414. }
  415. // Otherwise, go through the regular workflow to prompt for FTP/SSH
  416. // credentials and invoke update_authorize_run_update() indirectly with
  417. // whatever FileTransfer object authorize.php creates for us.
  418. else {
  419. system_authorized_init('update_authorize_run_update', drupal_get_path('module', 'update') . '/update.authorize.inc', array($updates), t('Update manager'));
  420. $form_state['redirect'] = system_authorized_get_url();
  421. }
  422. }
  423. }
  424. /**
  425. * @} End of "defgroup update_manager_update".
  426. */
  427. /**
  428. * @defgroup update_manager_install Update Manager module: install
  429. * @{
  430. * Update Manager module functionality for installing new code.
  431. *
  432. * Provides a user interface to install new code.
  433. */
  434. /**
  435. * Form constructor for the install form of the Update Manager module.
  436. *
  437. * This presents a place to enter a URL or upload an archive file to use to
  438. * install a new module or theme.
  439. *
  440. * @param $context
  441. * String representing the context from which we're trying to install.
  442. * Allowed values are 'module', 'theme', and 'report'.
  443. *
  444. * @see update_manager_install_form_validate()
  445. * @see update_manager_install_form_submit()
  446. * @see update_menu()
  447. * @ingroup forms
  448. */
  449. function update_manager_install_form($form, &$form_state, $context) {
  450. if (!_update_manager_check_backends($form, 'install')) {
  451. return $form;
  452. }
  453. $form['help_text'] = array(
  454. '#prefix' => '<p>',
  455. '#markup' => t('You can find <a href="@module_url">modules</a> and <a href="@theme_url">themes</a> on <a href="@drupal_org_url">drupal.org</a>. The following file extensions are supported: %extensions.', array(
  456. '@module_url' => 'http://drupal.org/project/modules',
  457. '@theme_url' => 'http://drupal.org/project/themes',
  458. '@drupal_org_url' => 'http://drupal.org',
  459. '%extensions' => archiver_get_extensions(),
  460. )),
  461. '#suffix' => '</p>',
  462. );
  463. $form['project_url'] = array(
  464. '#type' => 'textfield',
  465. '#title' => t('Install from a URL'),
  466. '#description' => t('For example: %url', array('%url' => 'http://ftp.drupal.org/files/projects/name.tar.gz')),
  467. );
  468. $form['information'] = array(
  469. '#prefix' => '<strong>',
  470. '#markup' => t('Or'),
  471. '#suffix' => '</strong>',
  472. );
  473. $form['project_upload'] = array(
  474. '#type' => 'file',
  475. '#title' => t('Upload a module or theme archive to install'),
  476. '#description' => t('For example: %filename from your local computer', array('%filename' => 'name.tar.gz')),
  477. );
  478. $form['actions'] = array('#type' => 'actions');
  479. $form['actions']['submit'] = array(
  480. '#type' => 'submit',
  481. '#value' => t('Install'),
  482. );
  483. return $form;
  484. }
  485. /**
  486. * Checks for file transfer backends and prepares a form fragment about them.
  487. *
  488. * @param array $form
  489. * Reference to the form array we're building.
  490. * @param string $operation
  491. * The update manager operation we're in the middle of. Can be either 'update'
  492. * or 'install'. Use to provide operation-specific interface text.
  493. *
  494. * @return
  495. * TRUE if the update manager should continue to the next step in the
  496. * workflow, or FALSE if we've hit a fatal configuration and must halt the
  497. * workflow.
  498. */
  499. function _update_manager_check_backends(&$form, $operation) {
  500. // If file transfers will be performed locally, we do not need to display any
  501. // warnings or notices to the user and should automatically continue the
  502. // workflow, since we won't be using a FileTransfer backend that requires
  503. // user input or a specific server configuration.
  504. if (update_manager_local_transfers_allowed()) {
  505. return TRUE;
  506. }
  507. // Otherwise, show the available backends.
  508. $form['available_backends'] = array(
  509. '#prefix' => '<p>',
  510. '#suffix' => '</p>',
  511. );
  512. $available_backends = drupal_get_filetransfer_info();
  513. if (empty($available_backends)) {
  514. if ($operation == 'update') {
  515. $form['available_backends']['#markup'] = t('Your server does not support updating modules and themes from this interface. Instead, update modules and themes by uploading the new versions directly to the server, as described in the <a href="@handbook_url">handbook</a>.', array('@handbook_url' => 'http://drupal.org/getting-started/install-contrib'));
  516. }
  517. else {
  518. $form['available_backends']['#markup'] = t('Your server does not support installing modules and themes from this interface. Instead, install modules and themes by uploading them directly to the server, as described in the <a href="@handbook_url">handbook</a>.', array('@handbook_url' => 'http://drupal.org/getting-started/install-contrib'));
  519. }
  520. return FALSE;
  521. }
  522. $backend_names = array();
  523. foreach ($available_backends as $backend) {
  524. $backend_names[] = $backend['title'];
  525. }
  526. if ($operation == 'update') {
  527. $form['available_backends']['#markup'] = format_plural(
  528. count($available_backends),
  529. 'Updating modules and themes requires <strong>@backends access</strong> to your server. See the <a href="@handbook_url">handbook</a> for other update methods.',
  530. 'Updating modules and themes requires access to your server via one of the following methods: <strong>@backends</strong>. See the <a href="@handbook_url">handbook</a> for other update methods.',
  531. array(
  532. '@backends' => implode(', ', $backend_names),
  533. '@handbook_url' => 'http://drupal.org/getting-started/install-contrib',
  534. ));
  535. }
  536. else {
  537. $form['available_backends']['#markup'] = format_plural(
  538. count($available_backends),
  539. 'Installing modules and themes requires <strong>@backends access</strong> to your server. See the <a href="@handbook_url">handbook</a> for other installation methods.',
  540. 'Installing modules and themes requires access to your server via one of the following methods: <strong>@backends</strong>. See the <a href="@handbook_url">handbook</a> for other installation methods.',
  541. array(
  542. '@backends' => implode(', ', $backend_names),
  543. '@handbook_url' => 'http://drupal.org/getting-started/install-contrib',
  544. ));
  545. }
  546. return TRUE;
  547. }
  548. /**
  549. * Form validation handler for update_manager_install_form().
  550. *
  551. * @see update_manager_install_form_submit()
  552. */
  553. function update_manager_install_form_validate($form, &$form_state) {
  554. if (!($form_state['values']['project_url'] XOR !empty($_FILES['files']['name']['project_upload']))) {
  555. form_set_error('project_url', t('You must either provide a URL or upload an archive file to install.'));
  556. }
  557. if ($form_state['values']['project_url']) {
  558. if (!valid_url($form_state['values']['project_url'], TRUE)) {
  559. form_set_error('project_url', t('The provided URL is invalid.'));
  560. }
  561. }
  562. }
  563. /**
  564. * Form submission handler for update_manager_install_form().
  565. *
  566. * Either downloads the file specified in the URL to a temporary cache, or
  567. * uploads the file attached to the form, then attempts to extract the archive
  568. * into a temporary location and verify it. Instantiate the appropriate
  569. * Updater class for this project and make sure it is not already installed in
  570. * the live webroot. If everything is successful, setup an operation to run
  571. * via authorize.php which will copy the extracted files from the temporary
  572. * location into the live site.
  573. *
  574. * @see update_manager_install_form_validate()
  575. * @see update_authorize_run_install()
  576. * @see system_authorized_init()
  577. * @see system_authorized_get_url()
  578. */
  579. function update_manager_install_form_submit($form, &$form_state) {
  580. if ($form_state['values']['project_url']) {
  581. $field = 'project_url';
  582. $local_cache = update_manager_file_get($form_state['values']['project_url']);
  583. if (!$local_cache) {
  584. form_set_error($field, t('Unable to retrieve Drupal project from %url.', array('%url' => $form_state['values']['project_url'])));
  585. return;
  586. }
  587. }
  588. elseif ($_FILES['files']['name']['project_upload']) {
  589. $validators = array('file_validate_extensions' => array(archiver_get_extensions()));
  590. $field = 'project_upload';
  591. if (!($finfo = file_save_upload($field, $validators, NULL, FILE_EXISTS_REPLACE))) {
  592. // Failed to upload the file. file_save_upload() calls form_set_error() on
  593. // failure.
  594. return;
  595. }
  596. $local_cache = $finfo->uri;
  597. }
  598. $directory = _update_manager_extract_directory();
  599. try {
  600. $archive = update_manager_archive_extract($local_cache, $directory);
  601. }
  602. catch (Exception $e) {
  603. form_set_error($field, $e->getMessage());
  604. return;
  605. }
  606. $files = $archive->listContents();
  607. if (!$files) {
  608. form_set_error($field, t('Provided archive contains no files.'));
  609. return;
  610. }
  611. // Unfortunately, we can only use the directory name to determine the project
  612. // name. Some archivers list the first file as the directory (i.e., MODULE/)
  613. // and others list an actual file (i.e., MODULE/README.TXT).
  614. $project = strtok($files[0], '/\\');
  615. $archive_errors = update_manager_archive_verify($project, $local_cache, $directory);
  616. if (!empty($archive_errors)) {
  617. form_set_error($field, array_shift($archive_errors));
  618. // @todo: Fix me in D8: We need a way to set multiple errors on the same
  619. // form element and have all of them appear!
  620. if (!empty($archive_errors)) {
  621. foreach ($archive_errors as $error) {
  622. drupal_set_message($error, 'error');
  623. }
  624. }
  625. return;
  626. }
  627. // Make sure the Updater registry is loaded.
  628. drupal_get_updaters();
  629. $project_location = $directory . '/' . $project;
  630. try {
  631. $updater = Updater::factory($project_location);
  632. }
  633. catch (Exception $e) {
  634. form_set_error($field, $e->getMessage());
  635. return;
  636. }
  637. try {
  638. $project_title = Updater::getProjectTitle($project_location);
  639. }
  640. catch (Exception $e) {
  641. form_set_error($field, $e->getMessage());
  642. return;
  643. }
  644. if (!$project_title) {
  645. form_set_error($field, t('Unable to determine %project name.', array('%project' => $project)));
  646. }
  647. if ($updater->isInstalled()) {
  648. form_set_error($field, t('%project is already installed.', array('%project' => $project_title)));
  649. return;
  650. }
  651. $project_real_location = drupal_realpath($project_location);
  652. $arguments = array(
  653. 'project' => $project,
  654. 'updater_name' => get_class($updater),
  655. 'local_url' => $project_real_location,
  656. );
  657. // If the owner of the directory we extracted is the same as the
  658. // owner of our configuration directory (e.g. sites/default) where we're
  659. // trying to install the code, there's no need to prompt for FTP/SSH
  660. // credentials. Instead, we instantiate a FileTransferLocal and invoke
  661. // update_authorize_run_install() directly.
  662. if (fileowner($project_real_location) == fileowner(conf_path())) {
  663. module_load_include('inc', 'update', 'update.authorize');
  664. $filetransfer = new FileTransferLocal(DRUPAL_ROOT);
  665. call_user_func_array('update_authorize_run_install', array_merge(array($filetransfer), $arguments));
  666. }
  667. // Otherwise, go through the regular workflow to prompt for FTP/SSH
  668. // credentials and invoke update_authorize_run_install() indirectly with
  669. // whatever FileTransfer object authorize.php creates for us.
  670. else {
  671. system_authorized_init('update_authorize_run_install', drupal_get_path('module', 'update') . '/update.authorize.inc', $arguments, t('Update manager'));
  672. $form_state['redirect'] = system_authorized_get_url();
  673. }
  674. }
  675. /**
  676. * @} End of "defgroup update_manager_install".
  677. */
  678. /**
  679. * @defgroup update_manager_file Update Manager module: file management
  680. * @{
  681. * Update Manager module file management functions.
  682. *
  683. * These functions are used by the update manager to copy, extract, and verify
  684. * archive files.
  685. */
  686. /**
  687. * Unpacks a downloaded archive file.
  688. *
  689. * @param string $file
  690. * The filename of the archive you wish to extract.
  691. * @param string $directory
  692. * The directory you wish to extract the archive into.
  693. *
  694. * @return Archiver
  695. * The Archiver object used to extract the archive.
  696. *
  697. * @throws Exception
  698. */
  699. function update_manager_archive_extract($file, $directory) {
  700. $archiver = archiver_get_archiver($file);
  701. if (!$archiver) {
  702. throw new Exception(t('Cannot extract %file, not a valid archive.', array ('%file' => $file)));
  703. }
  704. // Remove the directory if it exists, otherwise it might contain a mixture of
  705. // old files mixed with the new files (e.g. in cases where files were removed
  706. // from a later release).
  707. $files = $archiver->listContents();
  708. // Unfortunately, we can only use the directory name to determine the project
  709. // name. Some archivers list the first file as the directory (i.e., MODULE/)
  710. // and others list an actual file (i.e., MODULE/README.TXT).
  711. $project = strtok($files[0], '/\\');
  712. $extract_location = $directory . '/' . $project;
  713. if (file_exists($extract_location)) {
  714. file_unmanaged_delete_recursive($extract_location);
  715. }
  716. $archiver->extract($directory);
  717. return $archiver;
  718. }
  719. /**
  720. * Verifies an archive after it has been downloaded and extracted.
  721. *
  722. * This function is responsible for invoking hook_verify_update_archive().
  723. *
  724. * @param string $project
  725. * The short name of the project to download.
  726. * @param string $archive_file
  727. * The filename of the unextracted archive.
  728. * @param string $directory
  729. * The directory that the archive was extracted into.
  730. *
  731. * @return array
  732. * An array of error messages to display if the archive was invalid. If there
  733. * are no errors, it will be an empty array.
  734. */
  735. function update_manager_archive_verify($project, $archive_file, $directory) {
  736. return module_invoke_all('verify_update_archive', $project, $archive_file, $directory);
  737. }
  738. /**
  739. * Copies a file from the specified URL to the temporary directory for updates.
  740. *
  741. * Returns the local path if the file has already been downloaded.
  742. *
  743. * @param $url
  744. * The URL of the file on the server.
  745. *
  746. * @return string
  747. * Path to local file.
  748. */
  749. function update_manager_file_get($url) {
  750. $parsed_url = parse_url($url);
  751. $remote_schemes = array('http', 'https', 'ftp', 'ftps', 'smb', 'nfs');
  752. if (!in_array($parsed_url['scheme'], $remote_schemes)) {
  753. // This is a local file, just return the path.
  754. return drupal_realpath($url);
  755. }
  756. // Check the cache and download the file if needed.
  757. $cache_directory = _update_manager_cache_directory();
  758. $local = $cache_directory . '/' . drupal_basename($parsed_url['path']);
  759. if (!file_exists($local) || update_delete_file_if_stale($local)) {
  760. return system_retrieve_file($url, $local, FALSE, FILE_EXISTS_REPLACE);
  761. }
  762. else {
  763. return $local;
  764. }
  765. }
  766. /**
  767. * Batch callback: Downloads, unpacks, and verifies a project.
  768. *
  769. * This function assumes that the provided URL points to a file archive of some
  770. * sort. The URL can have any scheme that we have a file stream wrapper to
  771. * support. The file is downloaded to a local cache.
  772. *
  773. * @param string $project
  774. * The short name of the project to download.
  775. * @param string $url
  776. * The URL to download a specific project release archive file.
  777. * @param array $context
  778. * Reference to an array used for Batch API storage.
  779. *
  780. * @see update_manager_download_page()
  781. */
  782. function update_manager_batch_project_get($project, $url, &$context) {
  783. // This is here to show the user that we are in the process of downloading.
  784. if (!isset($context['sandbox']['started'])) {
  785. $context['sandbox']['started'] = TRUE;
  786. $context['message'] = t('Downloading %project', array('%project' => $project));
  787. $context['finished'] = 0;
  788. return;
  789. }
  790. // Actually try to download the file.
  791. if (!($local_cache = update_manager_file_get($url))) {
  792. $context['results']['errors'][$project] = t('Failed to download %project from %url', array('%project' => $project, '%url' => $url));
  793. return;
  794. }
  795. // Extract it.
  796. $extract_directory = _update_manager_extract_directory();
  797. try {
  798. update_manager_archive_extract($local_cache, $extract_directory);
  799. }
  800. catch (Exception $e) {
  801. $context['results']['errors'][$project] = $e->getMessage();
  802. return;
  803. }
  804. // Verify it.
  805. $archive_errors = update_manager_archive_verify($project, $local_cache, $extract_directory);
  806. if (!empty($archive_errors)) {
  807. // We just need to make sure our array keys don't collide, so use the
  808. // numeric keys from the $archive_errors array.
  809. foreach ($archive_errors as $key => $error) {
  810. $context['results']['errors']["$project-$key"] = $error;
  811. }
  812. return;
  813. }
  814. // Yay, success.
  815. $context['results']['projects'][$project] = $url;
  816. $context['finished'] = 1;
  817. }
  818. /**
  819. * Determines if file transfers will be performed locally.
  820. *
  821. * If the server is configured such that webserver-created files have the same
  822. * owner as the configuration directory (e.g., sites/default) where new code
  823. * will eventually be installed, the update manager can transfer files entirely
  824. * locally, without changing their ownership (in other words, without prompting
  825. * the user for FTP, SSH or other credentials).
  826. *
  827. * This server configuration is an inherent security weakness because it allows
  828. * a malicious webserver process to append arbitrary PHP code and then execute
  829. * it. However, it is supported here because it is a common configuration on
  830. * shared hosting, and there is nothing Drupal can do to prevent it.
  831. *
  832. * @return
  833. * TRUE if local file transfers are allowed on this server, or FALSE if not.
  834. *
  835. * @see update_manager_update_ready_form_submit()
  836. * @see update_manager_install_form_submit()
  837. * @see install_check_requirements()
  838. */
  839. function update_manager_local_transfers_allowed() {
  840. // Compare the owner of a webserver-created temporary file to the owner of
  841. // the configuration directory to determine if local transfers will be
  842. // allowed.
  843. $temporary_file = drupal_tempnam('temporary://', 'update_');
  844. $local_transfers_allowed = fileowner($temporary_file) === fileowner(conf_path());
  845. // Clean up. If this fails, we can ignore it (since this is just a temporary
  846. // file anyway).
  847. @drupal_unlink($temporary_file);
  848. return $local_transfers_allowed;
  849. }
  850. /**
  851. * @} End of "defgroup update_manager_file".
  852. */