Project

General

Profile

Paste
Download (33.8 KB) Statistics
| Branch: | Revision:

root / drupal7 / modules / update / update.manager.inc @ b0dc3a2e

1
<?php
2

    
3
/**
4
 * @file
5
 * Administrative screens and processing functions of the Update Manager module.
6
 *
7
 * This allows site administrators with the 'administer software updates'
8
 * permission to either upgrade existing projects, or download and install new
9
 * ones, so long as the killswitch setting ('allow_authorize_operations') is
10
 * still TRUE.
11
 *
12
 * To install new code, the administrator is prompted for either the URL of an
13
 * archive file, or to directly upload the archive file. The archive is loaded
14
 * into a temporary location, extracted, and verified. If everything is
15
 * successful, the user is redirected to authorize.php to type in file transfer
16
 * credentials and authorize the installation to proceed with elevated
17
 * privileges, such that the extracted files can be copied out of the temporary
18
 * location and into the live web root.
19
 *
20
 * Updating existing code is a more elaborate process. The first step is a
21
 * selection form where the user is presented with a table of installed projects
22
 * that are missing newer releases. The user selects which projects they wish to
23
 * update, and presses the "Download updates" button to continue. This sets up a
24
 * batch to fetch all the selected releases, and redirects to
25
 * admin/update/download to display the batch progress bar as it runs. Each
26
 * batch operation is responsible for downloading a single file, extracting the
27
 * archive, and verifying the contents. If there are any errors, the user is
28
 * redirected back to the first page with the error messages. If all downloads
29
 * were extacted and verified, the user is instead redirected to
30
 * admin/update/ready, a landing page which reminds them to backup their
31
 * database and asks if they want to put the site offline during the update.
32
 * Once the user presses the "Install updates" button, they are redirected to
33
 * authorize.php to supply their web root file access credentials. The
34
 * authorized operation (which lives in update.authorize.inc) sets up a batch to
35
 * copy each extracted update from the temporary location into the live web
36
 * root.
37
 */
38

    
39
/**
40
 * @defgroup update_manager_update Update Manager module: update
41
 * @{
42
 * Update Manager module functionality for updating existing code.
43
 *
44
 * Provides a user interface to update existing code.
45
 */
46

    
47
/**
48
 * Form constructor for the update form of the Update Manager module.
49
 *
50
 * This presents a table with all projects that have available updates with
51
 * checkboxes to select which ones to upgrade.
52
 *
53
 * @param $context
54
 *   String representing the context from which we're trying to update.
55
 *   Allowed values are 'module', 'theme', and 'report'.
56
 *
57
 * @see update_manager_update_form_validate()
58
 * @see update_manager_update_form_submit()
59
 * @see update_menu()
60
 * @ingroup forms
61
 */
62
function update_manager_update_form($form, $form_state, $context) {
63
  if (!_update_manager_check_backends($form, 'update')) {
64
    return $form;
65
  }
66

    
67
  $form['#theme'] = 'update_manager_update_form';
68

    
69
  $available = update_get_available(TRUE);
70
  if (empty($available)) {
71
    $form['message'] = array(
72
      '#markup' => t('There was a problem getting update information. Try again later.'),
73
    );
74
    return $form;
75
  }
76

    
77
  $form['#attached']['css'][] = drupal_get_path('module', 'update') . '/update.css';
78

    
79
  // This will be a nested array. The first key is the kind of project, which
80
  // can be either 'enabled', 'disabled', 'manual' (projects which require
81
  // manual updates, such as core). Then, each subarray is an array of
82
  // projects of that type, indexed by project short name, and containing an
83
  // array of data for cells in that project's row in the appropriate table.
84
  $projects = array();
85

    
86
  // This stores the actual download link we're going to update from for each
87
  // project in the form, regardless of if it's enabled or disabled.
88
  $form['project_downloads'] = array('#tree' => TRUE);
89

    
90
  module_load_include('inc', 'update', 'update.compare');
91
  $project_data = update_calculate_project_data($available);
92
  foreach ($project_data as $name => $project) {
93
    // Filter out projects which are up to date already.
94
    if ($project['status'] == UPDATE_CURRENT) {
95
      continue;
96
    }
97
    // The project name to display can vary based on the info we have.
98
    if (!empty($project['title'])) {
99
      if (!empty($project['link'])) {
100
        $project_name = l($project['title'], $project['link']);
101
      }
102
      else {
103
        $project_name = check_plain($project['title']);
104
      }
105
    }
106
    elseif (!empty($project['info']['name'])) {
107
      $project_name = check_plain($project['info']['name']);
108
    }
109
    else {
110
      $project_name = check_plain($name);
111
    }
112
    if ($project['project_type'] == 'theme' || $project['project_type'] == 'theme-disabled') {
113
      $project_name .= ' ' . t('(Theme)');
114
    }
115

    
116
    if (empty($project['recommended'])) {
117
      // If we don't know what to recommend they upgrade to, we should skip
118
      // the project entirely.
119
      continue;
120
    }
121

    
122
    $recommended_release = $project['releases'][$project['recommended']];
123
    $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'])))));
124
    if ($recommended_release['version_major'] != $project['existing_major']) {
125
      $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>';
126
    }
127

    
128
    // Create an entry for this project.
129
    $entry = array(
130
      'title' => $project_name,
131
      'installed_version' => $project['existing_version'],
132
      'recommended_version' => $recommended_version,
133
    );
134

    
135
    switch ($project['status']) {
136
      case UPDATE_NOT_SECURE:
137
      case UPDATE_REVOKED:
138
        $entry['title'] .= ' ' . t('(Security update)');
139
        $entry['#weight'] = -2;
140
        $type = 'security';
141
        break;
142

    
143
      case UPDATE_NOT_SUPPORTED:
144
        $type = 'unsupported';
145
        $entry['title'] .= ' ' . t('(Unsupported)');
146
        $entry['#weight'] = -1;
147
        break;
148

    
149
      case UPDATE_UNKNOWN:
150
      case UPDATE_NOT_FETCHED:
151
      case UPDATE_NOT_CHECKED:
152
      case UPDATE_NOT_CURRENT:
153
        $type = 'recommended';
154
        break;
155

    
156
      default:
157
        // Jump out of the switch and onto the next project in foreach.
158
        continue 2;
159
    }
160

    
161
    $entry['#attributes'] = array('class' => array('update-' . $type));
162

    
163
    // Drupal core needs to be upgraded manually.
164
    $needs_manual = $project['project_type'] == 'core';
165

    
166
    if ($needs_manual) {
167
      // There are no checkboxes in the 'Manual updates' table so it will be
168
      // rendered by theme('table'), not theme('tableselect'). Since the data
169
      // formats are incompatible, we convert now to the format expected by
170
      // theme('table').
171
      unset($entry['#weight']);
172
      $attributes = $entry['#attributes'];
173
      unset($entry['#attributes']);
174
      $entry = array(
175
        'data' => $entry,
176
      ) + $attributes;
177
    }
178
    else {
179
      $form['project_downloads'][$name] = array(
180
        '#type' => 'value',
181
        '#value' => $recommended_release['download_link'],
182
      );
183
    }
184

    
185
    // Based on what kind of project this is, save the entry into the
186
    // appropriate subarray.
187
    switch ($project['project_type']) {
188
      case 'core':
189
        // Core needs manual updates at this time.
190
        $projects['manual'][$name] = $entry;
191
        break;
192

    
193
      case 'module':
194
      case 'theme':
195
        $projects['enabled'][$name] = $entry;
196
        break;
197

    
198
      case 'module-disabled':
199
      case 'theme-disabled':
200
        $projects['disabled'][$name] = $entry;
201
        break;
202
    }
203
  }
204

    
205
  if (empty($projects)) {
206
    $form['message'] = array(
207
      '#markup' => t('All of your projects are up to date.'),
208
    );
209
    return $form;
210
  }
211

    
212
  $headers = array(
213
    'title' => array(
214
      'data' => t('Name'),
215
      'class' => array('update-project-name'),
216
    ),
217
    'installed_version' => t('Installed version'),
218
    'recommended_version' => t('Recommended version'),
219
  );
220

    
221
  if (!empty($projects['enabled'])) {
222
    $form['projects'] = array(
223
      '#type' => 'tableselect',
224
      '#header' => $headers,
225
      '#options' => $projects['enabled'],
226
    );
227
    if (!empty($projects['disabled'])) {
228
      $form['projects']['#prefix'] = '<h2>' . t('Enabled') . '</h2>';
229
    }
230
  }
231

    
232
  if (!empty($projects['disabled'])) {
233
    $form['disabled_projects'] = array(
234
      '#type' => 'tableselect',
235
      '#header' => $headers,
236
      '#options' => $projects['disabled'],
237
      '#weight' => 1,
238
      '#prefix' => '<h2>' . t('Disabled') . '</h2>',
239
    );
240
  }
241

    
242
  // If either table has been printed yet, we need a submit button and to
243
  // validate the checkboxes.
244
  if (!empty($projects['enabled']) || !empty($projects['disabled'])) {
245
    $form['actions'] = array('#type' => 'actions');
246
    $form['actions']['submit'] = array(
247
      '#type' => 'submit',
248
      '#value' => t('Download these updates'),
249
    );
250
    $form['#validate'][] = 'update_manager_update_form_validate';
251
  }
252

    
253
  if (!empty($projects['manual'])) {
254
    $prefix = '<h2>' . t('Manual updates required') . '</h2>';
255
    $prefix .= '<p>' . t('Updates of Drupal core are not supported at this time.') . '</p>';
256
    $form['manual_updates'] = array(
257
      '#type' => 'markup',
258
      '#markup' => theme('table', array('header' => $headers, 'rows' => $projects['manual'])),
259
      '#prefix' => $prefix,
260
      '#weight' => 120,
261
    );
262
  }
263

    
264
  return $form;
265
}
266

    
267
/**
268
 * Returns HTML for the first page in the process of updating projects.
269
 *
270
 * @param $variables
271
 *   An associative array containing:
272
 *   - form: A render element representing the form.
273
 *
274
 * @ingroup themeable
275
 */
276
function theme_update_manager_update_form($variables) {
277
  $form = $variables['form'];
278
  $last = variable_get('update_last_check', 0);
279
  $output = theme('update_last_check', array('last' => $last));
280
  $output .= drupal_render_children($form);
281
  return $output;
282
}
283

    
284
/**
285
 * Form validation handler for update_manager_update_form().
286
 *
287
 * Ensures that at least one project is selected.
288
 *
289
 * @see update_manager_update_form_submit()
290
 */
291
function update_manager_update_form_validate($form, &$form_state) {
292
  if (!empty($form_state['values']['projects'])) {
293
    $enabled = array_filter($form_state['values']['projects']);
294
  }
295
  if (!empty($form_state['values']['disabled_projects'])) {
296
    $disabled = array_filter($form_state['values']['disabled_projects']);
297
  }
298
  if (empty($enabled) && empty($disabled)) {
299
    form_set_error('projects', t('You must select at least one project to update.'));
300
  }
301
}
302

    
303
/**
304
 * Form submission handler for update_manager_update_form().
305
 *
306
 * Sets up a batch that downloads, extracts, and verifies the selected releases.
307
 *
308
 * @see update_manager_update_form_validate()
309
 */
310
function update_manager_update_form_submit($form, &$form_state) {
311
  $projects = array();
312
  foreach (array('projects', 'disabled_projects') as $type) {
313
    if (!empty($form_state['values'][$type])) {
314
      $projects = array_merge($projects, array_keys(array_filter($form_state['values'][$type])));
315
    }
316
  }
317
  $operations = array();
318
  foreach ($projects as $project) {
319
    $operations[] = array(
320
      'update_manager_batch_project_get',
321
      array(
322
        $project,
323
        $form_state['values']['project_downloads'][$project],
324
      ),
325
    );
326
  }
327
  $batch = array(
328
    'title' => t('Downloading updates'),
329
    'init_message' => t('Preparing to download selected updates'),
330
    'operations' => $operations,
331
    'finished' => 'update_manager_download_batch_finished',
332
    'file' => drupal_get_path('module', 'update') . '/update.manager.inc',
333
  );
334
  batch_set($batch);
335
}
336

    
337
/**
338
 * Implements callback_batch_finished().
339
 *
340
 * Batch callback: Performs actions when the download batch is completed.
341
 *
342
 * @param $success
343
 *   TRUE if the batch operation was successful, FALSE if there were errors.
344
 * @param $results
345
 *   An associative array of results from the batch operation.
346
 */
347
function update_manager_download_batch_finished($success, $results) {
348
  if (!empty($results['errors'])) {
349
    $error_list = array(
350
      'title' => t('Downloading updates failed:'),
351
      'items' => $results['errors'],
352
    );
353
    drupal_set_message(theme('item_list', $error_list), 'error');
354
  }
355
  elseif ($success) {
356
    drupal_set_message(t('Updates downloaded successfully.'));
357
    $_SESSION['update_manager_update_projects'] = $results['projects'];
358
    drupal_goto('admin/update/ready');
359
  }
360
  else {
361
    // Ideally we're catching all Exceptions, so they should never see this,
362
    // but just in case, we have to tell them something.
363
    drupal_set_message(t('Fatal error trying to download.'), 'error');
364
  }
365
}
366

    
367
/**
368
 * Form constructor for the update ready form.
369
 *
370
 * Build the form when the site is ready to update (after downloading).
371
 *
372
 * This form is an intermediary step in the automated update workflow. It is
373
 * presented to the site administrator after all the required updates have been
374
 * downloaded and verified. The point of this page is to encourage the user to
375
 * backup their site, give them the opportunity to put the site offline, and
376
 * then ask them to confirm that the update should continue. After this step,
377
 * the user is redirected to authorize.php to enter their file transfer
378
 * credentials and attempt to complete the update.
379
 *
380
 * @see update_manager_update_ready_form_submit()
381
 * @see update_menu()
382
 * @ingroup forms
383
 */
384
function update_manager_update_ready_form($form, &$form_state) {
385
  if (!_update_manager_check_backends($form, 'update')) {
386
    return $form;
387
  }
388

    
389
  $form['backup'] = array(
390
    '#prefix' => '<strong>',
391
    '#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'))),
392
    '#suffix' => '</strong>',
393
  );
394

    
395
  $form['maintenance_mode'] = array(
396
    '#title' => t('Perform updates with site in maintenance mode (strongly recommended)'),
397
    '#type' => 'checkbox',
398
    '#default_value' => TRUE,
399
  );
400

    
401
  $form['actions'] = array('#type' => 'actions');
402
  $form['actions']['submit'] = array(
403
    '#type' => 'submit',
404
    '#value' => t('Continue'),
405
  );
406

    
407
  return $form;
408
}
409

    
410
/**
411
 * Form submission handler for update_manager_update_ready_form().
412
 *
413
 * If the site administrator requested that the site is put offline during the
414
 * update, do so now. Otherwise, pull information about all the required updates
415
 * out of the SESSION, figure out what Drupal\Core\Updater\Updater class is
416
 * needed for each one, generate an array of update operations to perform, and
417
 * hand it all off to system_authorized_init(), then redirect to authorize.php.
418
 *
419
 * @see update_authorize_run_update()
420
 * @see system_authorized_init()
421
 * @see system_authorized_get_url()
422
 */
423
function update_manager_update_ready_form_submit($form, &$form_state) {
424
  // Store maintenance_mode setting so we can restore it when done.
425
  $_SESSION['maintenance_mode'] = variable_get('maintenance_mode', FALSE);
426
  if ($form_state['values']['maintenance_mode'] == TRUE) {
427
    variable_set('maintenance_mode', TRUE);
428
  }
429

    
430
  if (!empty($_SESSION['update_manager_update_projects'])) {
431
    // Make sure the Updater registry is loaded.
432
    drupal_get_updaters();
433

    
434
    $updates = array();
435
    $directory = _update_manager_extract_directory();
436

    
437
    $projects = $_SESSION['update_manager_update_projects'];
438
    unset($_SESSION['update_manager_update_projects']);
439

    
440
    foreach ($projects as $project => $url) {
441
      $project_location = $directory . '/' . $project;
442
      $updater = Updater::factory($project_location);
443
      $project_real_location = drupal_realpath($project_location);
444
      $updates[] = array(
445
        'project' => $project,
446
        'updater_name' => get_class($updater),
447
        'local_url' => $project_real_location,
448
      );
449
    }
450

    
451
    // If the owner of the last directory we extracted is the same as the
452
    // owner of our configuration directory (e.g. sites/default) where we're
453
    // trying to install the code, there's no need to prompt for FTP/SSH
454
    // credentials. Instead, we instantiate a FileTransferLocal and invoke
455
    // update_authorize_run_update() directly.
456
    if (fileowner($project_real_location) == fileowner(conf_path())) {
457
      module_load_include('inc', 'update', 'update.authorize');
458
      $filetransfer = new FileTransferLocal(DRUPAL_ROOT);
459
      update_authorize_run_update($filetransfer, $updates);
460
    }
461
    // Otherwise, go through the regular workflow to prompt for FTP/SSH
462
    // credentials and invoke update_authorize_run_update() indirectly with
463
    // whatever FileTransfer object authorize.php creates for us.
464
    else {
465
      system_authorized_init('update_authorize_run_update', drupal_get_path('module', 'update') . '/update.authorize.inc', array($updates), t('Update manager'));
466
      $form_state['redirect'] = system_authorized_get_url();
467
    }
468
  }
469
}
470

    
471
/**
472
 * @} End of "defgroup update_manager_update".
473
 */
474

    
475
/**
476
 * @defgroup update_manager_install Update Manager module: install
477
 * @{
478
 * Update Manager module functionality for installing new code.
479
 *
480
 * Provides a user interface to install new code.
481
 */
482

    
483
/**
484
 * Form constructor for the install form of the Update Manager module.
485
 *
486
 * This presents a place to enter a URL or upload an archive file to use to
487
 * install a new module or theme.
488
 *
489
 * @param $context
490
 *   String representing the context from which we're trying to install.
491
 *   Allowed values are 'module', 'theme', and 'report'.
492
 *
493
 * @see update_manager_install_form_validate()
494
 * @see update_manager_install_form_submit()
495
 * @see update_menu()
496
 * @ingroup forms
497
 */
498
function update_manager_install_form($form, &$form_state, $context) {
499
  if (!_update_manager_check_backends($form, 'install')) {
500
    return $form;
501
  }
502

    
503
  $form['help_text'] = array(
504
    '#prefix' => '<p>',
505
    '#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(
506
      '@module_url' => 'http://drupal.org/project/modules',
507
      '@theme_url' => 'http://drupal.org/project/themes',
508
      '@drupal_org_url' => 'http://drupal.org',
509
      '%extensions' => archiver_get_extensions(),
510
    )),
511
    '#suffix' => '</p>',
512
  );
513

    
514
  $form['project_url'] = array(
515
    '#type' => 'textfield',
516
    '#title' => t('Install from a URL'),
517
    '#description' => t('For example: %url', array('%url' => 'http://ftp.drupal.org/files/projects/name.tar.gz')),
518
  );
519

    
520
  $form['information'] = array(
521
    '#prefix' => '<strong>',
522
    '#markup' => t('Or'),
523
    '#suffix' => '</strong>',
524
  );
525

    
526
  $form['project_upload'] = array(
527
    '#type' => 'file',
528
    '#title' => t('Upload a module or theme archive to install'),
529
    '#description' => t('For example: %filename from your local computer', array('%filename' => 'name.tar.gz')),
530
  );
531

    
532
  $form['actions'] = array('#type' => 'actions');
533
  $form['actions']['submit'] = array(
534
    '#type' => 'submit',
535
    '#value' => t('Install'),
536
  );
537

    
538
  return $form;
539
}
540

    
541
/**
542
 * Checks for file transfer backends and prepares a form fragment about them.
543
 *
544
 * @param array $form
545
 *   Reference to the form array we're building.
546
 * @param string $operation
547
 *   The update manager operation we're in the middle of. Can be either 'update'
548
 *   or 'install'. Use to provide operation-specific interface text.
549
 *
550
 * @return
551
 *   TRUE if the update manager should continue to the next step in the
552
 *   workflow, or FALSE if we've hit a fatal configuration and must halt the
553
 *   workflow.
554
 */
555
function _update_manager_check_backends(&$form, $operation) {
556
  // If file transfers will be performed locally, we do not need to display any
557
  // warnings or notices to the user and should automatically continue the
558
  // workflow, since we won't be using a FileTransfer backend that requires
559
  // user input or a specific server configuration.
560
  if (update_manager_local_transfers_allowed()) {
561
    return TRUE;
562
  }
563

    
564
  // Otherwise, show the available backends.
565
  $form['available_backends'] = array(
566
    '#prefix' => '<p>',
567
    '#suffix' => '</p>',
568
  );
569

    
570
  $available_backends = drupal_get_filetransfer_info();
571
  if (empty($available_backends)) {
572
    if ($operation == 'update') {
573
      $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'));
574
    }
575
    else {
576
      $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'));
577
    }
578
    return FALSE;
579
  }
580

    
581
  $backend_names = array();
582
  foreach ($available_backends as $backend) {
583
    $backend_names[] = $backend['title'];
584
  }
585
  if ($operation == 'update') {
586
    $form['available_backends']['#markup'] = format_plural(
587
      count($available_backends),
588
      'Updating modules and themes requires <strong>@backends access</strong> to your server. See the <a href="@handbook_url">handbook</a> for other update methods.',
589
      '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.',
590
      array(
591
        '@backends' => implode(', ', $backend_names),
592
        '@handbook_url' => 'http://drupal.org/getting-started/install-contrib',
593
      ));
594
  }
595
  else {
596
    $form['available_backends']['#markup'] = format_plural(
597
      count($available_backends),
598
      'Installing modules and themes requires <strong>@backends access</strong> to your server. See the <a href="@handbook_url">handbook</a> for other installation methods.',
599
      '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.',
600
      array(
601
        '@backends' => implode(', ', $backend_names),
602
        '@handbook_url' => 'http://drupal.org/getting-started/install-contrib',
603
      ));
604
  }
605
  return TRUE;
606
}
607

    
608
/**
609
 * Form validation handler for update_manager_install_form().
610
 *
611
 * @see update_manager_install_form_submit()
612
 */
613
function update_manager_install_form_validate($form, &$form_state) {
614
  if (!($form_state['values']['project_url'] XOR !empty($_FILES['files']['name']['project_upload']))) {
615
    form_set_error('project_url', t('You must either provide a URL or upload an archive file to install.'));
616
  }
617

    
618
  if ($form_state['values']['project_url']) {
619
    if (!valid_url($form_state['values']['project_url'], TRUE)) {
620
      form_set_error('project_url', t('The provided URL is invalid.'));
621
    }
622
  }
623
}
624

    
625
/**
626
 * Form submission handler for update_manager_install_form().
627
 *
628
 * Either downloads the file specified in the URL to a temporary cache, or
629
 * uploads the file attached to the form, then attempts to extract the archive
630
 * into a temporary location and verify it. Instantiate the appropriate
631
 * Updater class for this project and make sure it is not already installed in
632
 * the live webroot. If everything is successful, setup an operation to run
633
 * via authorize.php which will copy the extracted files from the temporary
634
 * location into the live site.
635
 *
636
 * @see update_manager_install_form_validate()
637
 * @see update_authorize_run_install()
638
 * @see system_authorized_init()
639
 * @see system_authorized_get_url()
640
 */
641
function update_manager_install_form_submit($form, &$form_state) {
642
  if ($form_state['values']['project_url']) {
643
    $field = 'project_url';
644
    $local_cache = update_manager_file_get($form_state['values']['project_url']);
645
    if (!$local_cache) {
646
      form_set_error($field, t('Unable to retrieve Drupal project from %url.', array('%url' => $form_state['values']['project_url'])));
647
      return;
648
    }
649
  }
650
  elseif ($_FILES['files']['name']['project_upload']) {
651
    $validators = array('file_validate_extensions' => array(archiver_get_extensions()));
652
    $field = 'project_upload';
653
    if (!($finfo = file_save_upload($field, $validators, NULL, FILE_EXISTS_REPLACE))) {
654
      // Failed to upload the file. file_save_upload() calls form_set_error() on
655
      // failure.
656
      return;
657
    }
658
    $local_cache = $finfo->uri;
659
  }
660

    
661
  $directory = _update_manager_extract_directory();
662
  try {
663
    $archive = update_manager_archive_extract($local_cache, $directory);
664
  }
665
  catch (Exception $e) {
666
    form_set_error($field, $e->getMessage());
667
    return;
668
  }
669

    
670
  $files = $archive->listContents();
671
  if (!$files) {
672
    form_set_error($field, t('Provided archive contains no files.'));
673
    return;
674
  }
675

    
676
  // Unfortunately, we can only use the directory name to determine the project
677
  // name. Some archivers list the first file as the directory (i.e., MODULE/)
678
  // and others list an actual file (i.e., MODULE/README.TXT).
679
  $project = strtok($files[0], '/\\');
680

    
681
  $archive_errors = update_manager_archive_verify($project, $local_cache, $directory);
682
  if (!empty($archive_errors)) {
683
    form_set_error($field, array_shift($archive_errors));
684
    // @todo: Fix me in D8: We need a way to set multiple errors on the same
685
    // form element and have all of them appear!
686
    if (!empty($archive_errors)) {
687
      foreach ($archive_errors as $error) {
688
        drupal_set_message($error, 'error');
689
      }
690
    }
691
    return;
692
  }
693

    
694
  // Make sure the Updater registry is loaded.
695
  drupal_get_updaters();
696

    
697
  $project_location = $directory . '/' . $project;
698
  try {
699
    $updater = Updater::factory($project_location);
700
  }
701
  catch (Exception $e) {
702
    form_set_error($field, $e->getMessage());
703
    return;
704
  }
705

    
706
  try {
707
    $project_title = Updater::getProjectTitle($project_location);
708
  }
709
  catch (Exception $e) {
710
    form_set_error($field, $e->getMessage());
711
    return;
712
  }
713

    
714
  if (!$project_title) {
715
    form_set_error($field, t('Unable to determine %project name.', array('%project' => $project)));
716
  }
717

    
718
  if ($updater->isInstalled()) {
719
    form_set_error($field, t('%project is already installed.', array('%project' => $project_title)));
720
    return;
721
  }
722

    
723
  $project_real_location = drupal_realpath($project_location);
724
  $arguments = array(
725
    'project' => $project,
726
    'updater_name' => get_class($updater),
727
    'local_url' => $project_real_location,
728
  );
729

    
730
  // If the owner of the directory we extracted is the same as the
731
  // owner of our configuration directory (e.g. sites/default) where we're
732
  // trying to install the code, there's no need to prompt for FTP/SSH
733
  // credentials. Instead, we instantiate a FileTransferLocal and invoke
734
  // update_authorize_run_install() directly.
735
  if (fileowner($project_real_location) == fileowner(conf_path())) {
736
    module_load_include('inc', 'update', 'update.authorize');
737
    $filetransfer = new FileTransferLocal(DRUPAL_ROOT);
738
    call_user_func_array('update_authorize_run_install', array_merge(array($filetransfer), $arguments));
739
  }
740
  // Otherwise, go through the regular workflow to prompt for FTP/SSH
741
  // credentials and invoke update_authorize_run_install() indirectly with
742
  // whatever FileTransfer object authorize.php creates for us.
743
  else {
744
    system_authorized_init('update_authorize_run_install', drupal_get_path('module', 'update') . '/update.authorize.inc', $arguments, t('Update manager'));
745
    $form_state['redirect'] = system_authorized_get_url();
746
  }
747
}
748

    
749
/**
750
 * @} End of "defgroup update_manager_install".
751
 */
752

    
753
/**
754
 * @defgroup update_manager_file Update Manager module: file management
755
 * @{
756
 * Update Manager module file management functions.
757
 *
758
 * These functions are used by the update manager to copy, extract, and verify
759
 * archive files.
760
 */
761

    
762
/**
763
 * Unpacks a downloaded archive file.
764
 *
765
 * @param string $file
766
 *   The filename of the archive you wish to extract.
767
 * @param string $directory
768
 *   The directory you wish to extract the archive into.
769
 *
770
 * @return Archiver
771
 *   The Archiver object used to extract the archive.
772
 *
773
 * @throws Exception
774
 */
775
function update_manager_archive_extract($file, $directory) {
776
  $archiver = archiver_get_archiver($file);
777
  if (!$archiver) {
778
    throw new Exception(t('Cannot extract %file, not a valid archive.', array ('%file' => $file)));
779
  }
780

    
781
  // Remove the directory if it exists, otherwise it might contain a mixture of
782
  // old files mixed with the new files (e.g. in cases where files were removed
783
  // from a later release).
784
  $files = $archiver->listContents();
785

    
786
  // Unfortunately, we can only use the directory name to determine the project
787
  // name. Some archivers list the first file as the directory (i.e., MODULE/)
788
  // and others list an actual file (i.e., MODULE/README.TXT).
789
  $project = strtok($files[0], '/\\');
790

    
791
  $extract_location = $directory . '/' . $project;
792
  if (file_exists($extract_location)) {
793
    file_unmanaged_delete_recursive($extract_location);
794
  }
795

    
796
  $archiver->extract($directory);
797
  return $archiver;
798
}
799

    
800
/**
801
 * Verifies an archive after it has been downloaded and extracted.
802
 *
803
 * This function is responsible for invoking hook_verify_update_archive().
804
 *
805
 * @param string $project
806
 *   The short name of the project to download.
807
 * @param string $archive_file
808
 *   The filename of the unextracted archive.
809
 * @param string $directory
810
 *   The directory that the archive was extracted into.
811
 *
812
 * @return array
813
 *   An array of error messages to display if the archive was invalid. If there
814
 *   are no errors, it will be an empty array.
815
 */
816
function update_manager_archive_verify($project, $archive_file, $directory) {
817
  return module_invoke_all('verify_update_archive', $project, $archive_file, $directory);
818
}
819

    
820
/**
821
 * Copies a file from the specified URL to the temporary directory for updates.
822
 *
823
 * Returns the local path if the file has already been downloaded.
824
 *
825
 * @param $url
826
 *   The URL of the file on the server.
827
 *
828
 * @return string
829
 *   Path to local file.
830
 */
831
function update_manager_file_get($url) {
832
  $parsed_url = parse_url($url);
833
  $remote_schemes = array('http', 'https', 'ftp', 'ftps', 'smb', 'nfs');
834
  if (!in_array($parsed_url['scheme'], $remote_schemes)) {
835
    // This is a local file, just return the path.
836
    return drupal_realpath($url);
837
  }
838

    
839
  // Check the cache and download the file if needed.
840
  $cache_directory = _update_manager_cache_directory();
841
  $local = $cache_directory . '/' . drupal_basename($parsed_url['path']);
842

    
843
  if (!file_exists($local) || update_delete_file_if_stale($local)) {
844
    return system_retrieve_file($url, $local, FALSE, FILE_EXISTS_REPLACE);
845
  }
846
  else {
847
    return $local;
848
  }
849
}
850

    
851
/**
852
 * Implements callback_batch_operation().
853
 *
854
 * Downloads, unpacks, and verifies a project.
855
 *
856
 * This function assumes that the provided URL points to a file archive of some
857
 * sort. The URL can have any scheme that we have a file stream wrapper to
858
 * support. The file is downloaded to a local cache.
859
 *
860
 * @param string $project
861
 *   The short name of the project to download.
862
 * @param string $url
863
 *   The URL to download a specific project release archive file.
864
 * @param array $context
865
 *   Reference to an array used for Batch API storage.
866
 *
867
 * @see update_manager_download_page()
868
 */
869
function update_manager_batch_project_get($project, $url, &$context) {
870
  // This is here to show the user that we are in the process of downloading.
871
  if (!isset($context['sandbox']['started'])) {
872
    $context['sandbox']['started'] = TRUE;
873
    $context['message'] = t('Downloading %project', array('%project' => $project));
874
    $context['finished'] = 0;
875
    return;
876
  }
877

    
878
  // Actually try to download the file.
879
  if (!($local_cache = update_manager_file_get($url))) {
880
    $context['results']['errors'][$project] = t('Failed to download %project from %url', array('%project' => $project, '%url' => $url));
881
    return;
882
  }
883

    
884
  // Extract it.
885
  $extract_directory = _update_manager_extract_directory();
886
  try {
887
    update_manager_archive_extract($local_cache, $extract_directory);
888
  }
889
  catch (Exception $e) {
890
    $context['results']['errors'][$project] = $e->getMessage();
891
    return;
892
  }
893

    
894
  // Verify it.
895
  $archive_errors = update_manager_archive_verify($project, $local_cache, $extract_directory);
896
  if (!empty($archive_errors)) {
897
    // We just need to make sure our array keys don't collide, so use the
898
    // numeric keys from the $archive_errors array.
899
    foreach ($archive_errors as $key => $error) {
900
      $context['results']['errors']["$project-$key"] = $error;
901
    }
902
    return;
903
  }
904

    
905
  // Yay, success.
906
  $context['results']['projects'][$project] = $url;
907
  $context['finished'] = 1;
908
}
909

    
910
/**
911
 * Determines if file transfers will be performed locally.
912
 *
913
 * If the server is configured such that webserver-created files have the same
914
 * owner as the configuration directory (e.g., sites/default) where new code
915
 * will eventually be installed, the update manager can transfer files entirely
916
 * locally, without changing their ownership (in other words, without prompting
917
 * the user for FTP, SSH or other credentials).
918
 *
919
 * This server configuration is an inherent security weakness because it allows
920
 * a malicious webserver process to append arbitrary PHP code and then execute
921
 * it. However, it is supported here because it is a common configuration on
922
 * shared hosting, and there is nothing Drupal can do to prevent it.
923
 *
924
 * @return
925
 *   TRUE if local file transfers are allowed on this server, or FALSE if not.
926
 *
927
 * @see update_manager_update_ready_form_submit()
928
 * @see update_manager_install_form_submit()
929
 * @see install_check_requirements()
930
 */
931
function update_manager_local_transfers_allowed() {
932
  // Compare the owner of a webserver-created temporary file to the owner of
933
  // the configuration directory to determine if local transfers will be
934
  // allowed.
935
  $temporary_file = drupal_tempnam('temporary://', 'update_');
936
  $local_transfers_allowed = fileowner($temporary_file) === fileowner(conf_path());
937

    
938
  // Clean up. If this fails, we can ignore it (since this is just a temporary
939
  // file anyway).
940
  @drupal_unlink($temporary_file);
941

    
942
  return $local_transfers_allowed;
943
}
944

    
945
/**
946
 * @} End of "defgroup update_manager_file".
947
 */