Projet

Général

Profil

Paste
Télécharger (77,4 ko) Statistiques
| Branche: | Révision:

root / drupal7 / includes / install.core.inc @ bfb52287

1
<?php
2

    
3
/**
4
 * @file
5
 * API functions for installing Drupal.
6
 */
7

    
8
/**
9
 * Do not run the task during the current installation request.
10
 *
11
 * This can be used to skip running an installation task when certain
12
 * conditions are met, even though the task may still show on the list of
13
 * installation tasks presented to the user. For example, the Drupal installer
14
 * uses this flag to skip over the database configuration form when valid
15
 * database connection information is already available from settings.php. It
16
 * also uses this flag to skip language import tasks when the installation is
17
 * being performed in English.
18
 */
19
define('INSTALL_TASK_SKIP', 1);
20

    
21
/**
22
 * Run the task on each installation request until the database is set up.
23
 *
24
 * This is primarily used by the Drupal installer for bootstrap-related tasks.
25
 */
26
define('INSTALL_TASK_RUN_IF_REACHED', 2);
27

    
28
/**
29
 * Global flag to indicate that a task should be run on each installation
30
 * request that reaches it, until the database is set up and we are able to
31
 * record the fact that it already ran.
32
 *
33
 * This is the default method for running tasks and should be used for most
34
 * tasks that occur after the database is set up; these tasks will then run
35
 * once and be marked complete once they are successfully finished. For
36
 * example, the Drupal installer uses this flag for the batch installation of
37
 * modules on the new site, and also for the configuration form that collects
38
 * basic site information and sets up the site maintenance account.
39
 */
40
define('INSTALL_TASK_RUN_IF_NOT_COMPLETED', 3);
41

    
42
/**
43
 * Installs Drupal either interactively or via an array of passed-in settings.
44
 *
45
 * The Drupal installation happens in a series of steps, which may be spread
46
 * out over multiple page requests. Each request begins by trying to determine
47
 * the last completed installation step (also known as a "task"), if one is
48
 * available from a previous request. Control is then passed to the task
49
 * handler, which processes the remaining tasks that need to be run until (a)
50
 * an error is thrown, (b) a new page needs to be displayed, or (c) the
51
 * installation finishes (whichever happens first).
52
 *
53
 * @param $settings
54
 *   An optional array of installation settings. Leave this empty for a normal,
55
 *   interactive, browser-based installation intended to occur over multiple
56
 *   page requests. Alternatively, if an array of settings is passed in, the
57
 *   installer will attempt to use it to perform the installation in a single
58
 *   page request (optimized for the command line) and not send any output
59
 *   intended for the web browser. See install_state_defaults() for a list of
60
 *   elements that are allowed to appear in this array.
61
 *
62
 * @see install_state_defaults()
63
 */
64
function install_drupal($settings = array()) {
65
  global $install_state;
66
  // Initialize the installation state with the settings that were passed in,
67
  // as well as a boolean indicating whether or not this is an interactive
68
  // installation.
69
  $interactive = empty($settings);
70
  $install_state = $settings + array('interactive' => $interactive) + install_state_defaults();
71
  try {
72
    // Begin the page request. This adds information about the current state of
73
    // the Drupal installation to the passed-in array.
74
    install_begin_request($install_state);
75
    // Based on the installation state, run the remaining tasks for this page
76
    // request, and collect any output.
77
    $output = install_run_tasks($install_state);
78
  }
79
  catch (Exception $e) {
80
    // When an installation error occurs, either send the error to the web
81
    // browser or pass on the exception so the calling script can use it.
82
    if ($install_state['interactive']) {
83
      install_display_output($e->getMessage(), $install_state);
84
    }
85
    else {
86
      throw $e;
87
    }
88
  }
89
  // All available tasks for this page request are now complete. Interactive
90
  // installations can send output to the browser or redirect the user to the
91
  // next page.
92
  if ($install_state['interactive']) {
93
    if ($install_state['parameters_changed']) {
94
      // Redirect to the correct page if the URL parameters have changed.
95
      install_goto(install_redirect_url($install_state));
96
    }
97
    elseif (isset($output)) {
98
      // Display a page only if some output is available. Otherwise it is
99
      // possible that we are printing a JSON page and theme output should
100
      // not be shown.
101
      install_display_output($output, $install_state);
102
    }
103
  }
104
}
105

    
106
/**
107
 * Returns an array of default settings for the global installation state.
108
 *
109
 * The installation state is initialized with these settings at the beginning
110
 * of each page request. They may evolve during the page request, but they are
111
 * initialized again once the next request begins.
112
 *
113
 * Non-interactive Drupal installations can override some of these default
114
 * settings by passing in an array to the installation script, most notably
115
 * 'parameters' (which contains one-time parameters such as 'profile' and
116
 * 'locale' that are normally passed in via the URL) and 'forms' (which can
117
 * be used to programmatically submit forms during the installation; the keys
118
 * of each element indicate the name of the installation task that the form
119
 * submission is for, and the values are used as the $form_state['values']
120
 * array that is passed on to the form submission via drupal_form_submit()).
121
 *
122
 * @see drupal_form_submit()
123
 */
124
function install_state_defaults() {
125
  $defaults = array(
126
    // The current task being processed.
127
    'active_task' => NULL,
128
    // The last task that was completed during the previous installation
129
    // request.
130
    'completed_task' => NULL,
131
    // This becomes TRUE only when Drupal's system module is installed.
132
    'database_tables_exist' => FALSE,
133
    // An array of forms to be programmatically submitted during the
134
    // installation. The keys of each element indicate the name of the
135
    // installation task that the form submission is for, and the values are
136
    // used as the $form_state['values'] array that is passed on to the form
137
    // submission via drupal_form_submit().
138
    'forms' => array(),
139
    // This becomes TRUE only at the end of the installation process, after
140
    // all available tasks have been completed and Drupal is fully installed.
141
    // It is used by the installer to store correct information in the database
142
    // about the completed installation, as well as to inform theme functions
143
    // that all tasks are finished (so that the task list can be displayed
144
    // correctly).
145
    'installation_finished' => FALSE,
146
    // Whether or not this installation is interactive. By default this will
147
    // be set to FALSE if settings are passed in to install_drupal().
148
    'interactive' => TRUE,
149
    // An array of available languages for the installation.
150
    'locales' => array(),
151
    // An array of parameters for the installation, pre-populated by the URL
152
    // or by the settings passed in to install_drupal(). This is primarily
153
    // used to store 'profile' (the name of the chosen installation profile)
154
    // and 'locale' (the name of the chosen installation language), since
155
    // these settings need to persist from page request to page request before
156
    // the database is available for storage.
157
    'parameters' => array(),
158
    // Whether or not the parameters have changed during the current page
159
    // request. For interactive installations, this will trigger a page
160
    // redirect.
161
    'parameters_changed' => FALSE,
162
    // An array of information about the chosen installation profile. This will
163
    // be filled in based on the profile's .info file.
164
    'profile_info' => array(),
165
    // An array of available installation profiles.
166
    'profiles' => array(),
167
    // An array of server variables that will be substituted into the global
168
    // $_SERVER array via drupal_override_server_variables(). Used by
169
    // non-interactive installations only.
170
    'server' => array(),
171
    // This becomes TRUE only when a valid database connection can be
172
    // established.
173
    'settings_verified' => FALSE,
174
    // Installation tasks can set this to TRUE to force the page request to
175
    // end (even if there is no themable output), in the case of an interactive
176
    // installation. This is needed only rarely; for example, it would be used
177
    // by an installation task that prints JSON output rather than returning a
178
    // themed page. The most common example of this is during batch processing,
179
    // but the Drupal installer automatically takes care of setting this
180
    // parameter properly in that case, so that individual installation tasks
181
    // which implement the batch API do not need to set it themselves.
182
    'stop_page_request' => FALSE,
183
    // Installation tasks can set this to TRUE to indicate that the task should
184
    // be run again, even if it normally wouldn't be. This can be used, for
185
    // example, if a single task needs to be spread out over multiple page
186
    // requests, or if it needs to perform some validation before allowing
187
    // itself to be marked complete. The most common examples of this are batch
188
    // processing and form submissions, but the Drupal installer automatically
189
    // takes care of setting this parameter properly in those cases, so that
190
    // individual installation tasks which implement the batch API or form API
191
    // do not need to set it themselves.
192
    'task_not_complete' => FALSE,
193
    // A list of installation tasks which have already been performed during
194
    // the current page request.
195
    'tasks_performed' => array(),
196
  );
197
  return $defaults;
198
}
199

    
200
/**
201
 * Begins an installation request, modifying the installation state as needed.
202
 *
203
 * This function performs commands that must run at the beginning of every page
204
 * request. It throws an exception if the installation should not proceed.
205
 *
206
 * @param $install_state
207
 *   An array of information about the current installation state. This is
208
 *   modified with information gleaned from the beginning of the page request.
209
 */
210
function install_begin_request(&$install_state) {
211
  // Add any installation parameters passed in via the URL.
212
  $install_state['parameters'] += $_GET;
213

    
214
  // Validate certain core settings that are used throughout the installation.
215
  if (!empty($install_state['parameters']['profile'])) {
216
    $install_state['parameters']['profile'] = preg_replace('/[^a-zA-Z_0-9]/', '', $install_state['parameters']['profile']);
217
  }
218
  if (!empty($install_state['parameters']['locale'])) {
219
    $install_state['parameters']['locale'] = preg_replace('/[^a-zA-Z_0-9\-]/', '', $install_state['parameters']['locale']);
220
  }
221

    
222
  // Allow command line scripts to override server variables used by Drupal.
223
  require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
224
  if (!$install_state['interactive']) {
225
    drupal_override_server_variables($install_state['server']);
226
  }
227

    
228
  // The user agent header is used to pass a database prefix in the request when
229
  // running tests. However, for security reasons, it is imperative that no
230
  // installation be permitted using such a prefix.
231
  if (isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], "simpletest") !== FALSE) {
232
    header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
233
    exit;
234
  }
235

    
236
  drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION);
237

    
238
  // This must go after drupal_bootstrap(), which unsets globals!
239
  global $conf;
240

    
241
  require_once DRUPAL_ROOT . '/modules/system/system.install';
242
  require_once DRUPAL_ROOT . '/includes/common.inc';
243
  require_once DRUPAL_ROOT . '/includes/file.inc';
244
  require_once DRUPAL_ROOT . '/includes/install.inc';
245
  require_once DRUPAL_ROOT . '/' . variable_get('path_inc', 'includes/path.inc');
246

    
247
  // Load module basics (needed for hook invokes).
248
  include_once DRUPAL_ROOT . '/includes/module.inc';
249
  include_once DRUPAL_ROOT . '/includes/session.inc';
250

    
251
  // Set up $language, so t() caller functions will still work.
252
  drupal_language_initialize();
253

    
254
  include_once DRUPAL_ROOT . '/includes/entity.inc';
255
  require_once DRUPAL_ROOT . '/includes/ajax.inc';
256
  $module_list['system']['filename'] = 'modules/system/system.module';
257
  $module_list['user']['filename'] = 'modules/user/user.module';
258
  module_list(TRUE, FALSE, FALSE, $module_list);
259
  drupal_load('module', 'system');
260
  drupal_load('module', 'user');
261

    
262
  // Load the cache infrastructure using a "fake" cache implementation that
263
  // does not attempt to write to the database. We need this during the initial
264
  // part of the installer because the database is not available yet. We
265
  // continue to use it even when the database does become available, in order
266
  // to preserve consistency between interactive and command-line installations
267
  // (the latter complete in one page request and therefore are forced to
268
  // continue using the cache implementation they started with) and also
269
  // because any data put in the cache during the installer is inherently
270
  // suspect, due to the fact that Drupal is not fully set up yet.
271
  require_once DRUPAL_ROOT . '/includes/cache.inc';
272
  require_once DRUPAL_ROOT . '/includes/cache-install.inc';
273
  $conf['cache_default_class'] = 'DrupalFakeCache';
274

    
275
  // Prepare for themed output. We need to run this at the beginning of the
276
  // page request to avoid a different theme accidentally getting set. (We also
277
  // need to run it even in the case of command-line installations, to prevent
278
  // any code in the installer that happens to initialize the theme system from
279
  // accessing the database before it is set up yet.)
280
  drupal_maintenance_theme();
281

    
282
  // Check existing settings.php.
283
  $install_state['settings_verified'] = install_verify_settings();
284

    
285
  if ($install_state['settings_verified']) {
286
    // Initialize the database system. Note that the connection
287
    // won't be initialized until it is actually requested.
288
    require_once DRUPAL_ROOT . '/includes/database/database.inc';
289

    
290
    // Verify the last completed task in the database, if there is one.
291
    $task = install_verify_completed_task();
292
  }
293
  else {
294
    $task = NULL;
295

    
296
    // Do not install over a configured settings.php. Check the 'db_url'
297
    // variable in addition to 'databases', since previous versions of Drupal
298
    // used that (and we do not want to allow installations on an existing site
299
    // whose settings file has not yet been updated).
300
    if (!empty($GLOBALS['databases']) || !empty($GLOBALS['db_url'])) {
301
      throw new Exception(install_already_done_error());
302
    }
303
  }
304

    
305
  // Modify the installation state as appropriate.
306
  $install_state['completed_task'] = $task;
307
  $install_state['database_tables_exist'] = !empty($task);
308
}
309

    
310
/**
311
 * Runs all tasks for the current installation request.
312
 *
313
 * In the case of an interactive installation, all tasks will be attempted
314
 * until one is reached that has output which needs to be displayed to the
315
 * user, or until a page redirect is required. Otherwise, tasks will be
316
 * attempted until the installation is finished.
317
 *
318
 * @param $install_state
319
 *   An array of information about the current installation state. This is
320
 *   passed along to each task, so it can be modified if necessary.
321
 *
322
 * @return
323
 *   HTML output from the last completed task.
324
 */
325
function install_run_tasks(&$install_state) {
326
  do {
327
    // Obtain a list of tasks to perform. The list of tasks itself can be
328
    // dynamic (e.g., some might be defined by the installation profile,
329
    // which is not necessarily known until the earlier tasks have run),
330
    // so we regenerate the remaining tasks based on the installation state,
331
    // each time through the loop.
332
    $tasks_to_perform = install_tasks_to_perform($install_state);
333
    // Run the first task on the list.
334
    reset($tasks_to_perform);
335
    $task_name = key($tasks_to_perform);
336
    $task = array_shift($tasks_to_perform);
337
    $install_state['active_task'] = $task_name;
338
    $original_parameters = $install_state['parameters'];
339
    $output = install_run_task($task, $install_state);
340
    $install_state['parameters_changed'] = ($install_state['parameters'] != $original_parameters);
341
    // Store this task as having been performed during the current request,
342
    // and save it to the database as completed, if we need to and if the
343
    // database is in a state that allows us to do so. Also mark the
344
    // installation as 'done' when we have run out of tasks.
345
    if (!$install_state['task_not_complete']) {
346
      $install_state['tasks_performed'][] = $task_name;
347
      $install_state['installation_finished'] = empty($tasks_to_perform);
348
      if ($install_state['database_tables_exist'] && ($task['run'] == INSTALL_TASK_RUN_IF_NOT_COMPLETED || $install_state['installation_finished'])) {
349
        variable_set('install_task', $install_state['installation_finished'] ? 'done' : $task_name);
350
      }
351
    }
352
    // Stop when there are no tasks left. In the case of an interactive
353
    // installation, also stop if we have some output to send to the browser,
354
    // the URL parameters have changed, or an end to the page request was
355
    // specifically called for.
356
    $finished = empty($tasks_to_perform) || ($install_state['interactive'] && (isset($output) || $install_state['parameters_changed'] || $install_state['stop_page_request']));
357
  } while (!$finished);
358
  return $output;
359
}
360

    
361
/**
362
 * Runs an individual installation task.
363
 *
364
 * @param $task
365
 *   An array of information about the task to be run.
366
 * @param $install_state
367
 *   An array of information about the current installation state. This is
368
 *   passed in by reference so that it can be modified by the task.
369
 *
370
 * @return
371
 *   The output of the task function, if there is any.
372
 */
373
function install_run_task($task, &$install_state) {
374
  $function = $task['function'];
375

    
376
  if ($task['type'] == 'form') {
377
    require_once DRUPAL_ROOT . '/includes/form.inc';
378
    if ($install_state['interactive']) {
379
      // For interactive forms, build the form and ensure that it will not
380
      // redirect, since the installer handles its own redirection only after
381
      // marking the form submission task complete.
382
      $form_state = array(
383
        // We need to pass $install_state by reference in order for forms to
384
        // modify it, since the form API will use it in call_user_func_array(),
385
        // which requires that referenced variables be passed explicitly.
386
        'build_info' => array('args' => array(&$install_state)),
387
        'no_redirect' => TRUE,
388
      );
389
      $form = drupal_build_form($function, $form_state);
390
      // If a successful form submission did not occur, the form needs to be
391
      // rendered, which means the task is not complete yet.
392
      if (empty($form_state['executed'])) {
393
        $install_state['task_not_complete'] = TRUE;
394
        return drupal_render($form);
395
      }
396
      // Otherwise, return nothing so the next task will run in the same
397
      // request.
398
      return;
399
    }
400
    else {
401
      // For non-interactive forms, submit the form programmatically with the
402
      // values taken from the installation state. Throw an exception if any
403
      // errors were encountered.
404
      $form_state = array(
405
        'values' => !empty($install_state['forms'][$function]) ? $install_state['forms'][$function] : array(),
406
        // We need to pass $install_state by reference in order for forms to
407
        // modify it, since the form API will use it in call_user_func_array(),
408
        // which requires that referenced variables be passed explicitly.
409
        'build_info' => array('args' => array(&$install_state)),
410
      );
411
      drupal_form_submit($function, $form_state);
412
      $errors = form_get_errors();
413
      if (!empty($errors)) {
414
        throw new Exception(implode("\n", $errors));
415
      }
416
    }
417
  }
418

    
419
  elseif ($task['type'] == 'batch') {
420
    // Start a new batch based on the task function, if one is not running
421
    // already.
422
    $current_batch = variable_get('install_current_batch');
423
    if (!$install_state['interactive'] || !$current_batch) {
424
      $batch = $function($install_state);
425
      if (empty($batch)) {
426
        // If the task did some processing and decided no batch was necessary,
427
        // there is nothing more to do here.
428
        return;
429
      }
430
      batch_set($batch);
431
      // For interactive batches, we need to store the fact that this batch
432
      // task is currently running. Otherwise, we need to make sure the batch
433
      // will complete in one page request.
434
      if ($install_state['interactive']) {
435
        variable_set('install_current_batch', $function);
436
      }
437
      else {
438
        $batch =& batch_get();
439
        $batch['progressive'] = FALSE;
440
      }
441
      // Process the batch. For progressive batches, this will redirect.
442
      // Otherwise, the batch will complete.
443
      batch_process(install_redirect_url($install_state), install_full_redirect_url($install_state));
444
    }
445
    // If we are in the middle of processing this batch, keep sending back
446
    // any output from the batch process, until the task is complete.
447
    elseif ($current_batch == $function) {
448
      include_once DRUPAL_ROOT . '/includes/batch.inc';
449
      $output = _batch_page();
450
      // The task is complete when we try to access the batch page and receive
451
      // FALSE in return, since this means we are at a URL where we are no
452
      // longer requesting a batch ID.
453
      if ($output === FALSE) {
454
        // Return nothing so the next task will run in the same request.
455
        variable_del('install_current_batch');
456
        return;
457
      }
458
      else {
459
        // We need to force the page request to end if the task is not
460
        // complete, since the batch API sometimes prints JSON output
461
        // rather than returning a themed page.
462
        $install_state['task_not_complete'] = $install_state['stop_page_request'] = TRUE;
463
        return $output;
464
      }
465
    }
466
  }
467

    
468
  else {
469
    // For normal tasks, just return the function result, whatever it is.
470
    return $function($install_state);
471
  }
472
}
473

    
474
/**
475
 * Returns a list of tasks to perform during the current installation request.
476
 *
477
 * Note that the list of tasks can change based on the installation state as
478
 * the page request evolves (for example, if an installation profile hasn't
479
 * been selected yet, we don't yet know which profile tasks need to be run).
480
 *
481
 * @param $install_state
482
 *   An array of information about the current installation state.
483
 *
484
 * @return
485
 *   A list of tasks to be performed, with associated metadata.
486
 */
487
function install_tasks_to_perform($install_state) {
488
  // Start with a list of all currently available tasks.
489
  $tasks = install_tasks($install_state);
490
  foreach ($tasks as $name => $task) {
491
    // Remove any tasks that were already performed or that never should run.
492
    // Also, if we started this page request with an indication of the last
493
    // task that was completed, skip that task and all those that come before
494
    // it, unless they are marked as always needing to run.
495
    if ($task['run'] == INSTALL_TASK_SKIP || in_array($name, $install_state['tasks_performed']) || (!empty($install_state['completed_task']) && empty($completed_task_found) && $task['run'] != INSTALL_TASK_RUN_IF_REACHED)) {
496
      unset($tasks[$name]);
497
    }
498
    if (!empty($install_state['completed_task']) && $name == $install_state['completed_task']) {
499
      $completed_task_found = TRUE;
500
    }
501
  }
502
  return $tasks;
503
}
504

    
505
/**
506
 * Returns a list of all tasks the installer currently knows about.
507
 *
508
 * This function will return tasks regardless of whether or not they are
509
 * intended to run on the current page request. However, the list can change
510
 * based on the installation state (for example, if an installation profile
511
 * hasn't been selected yet, we don't yet know which profile tasks will be
512
 * available).
513
 *
514
 * @param $install_state
515
 *   An array of information about the current installation state.
516
 *
517
 * @return
518
 *   A list of tasks, with associated metadata.
519
 */
520
function install_tasks($install_state) {
521
  // Determine whether translation import tasks will need to be performed.
522
  $needs_translations = count($install_state['locales']) > 1 && !empty($install_state['parameters']['locale']) && $install_state['parameters']['locale'] != 'en';
523

    
524
  // Start with the core installation tasks that run before handing control
525
  // to the installation profile.
526
  $tasks = array(
527
    'install_select_profile' => array(
528
      'display_name' => st('Choose profile'),
529
      'display' => count($install_state['profiles']) != 1,
530
      'run' => INSTALL_TASK_RUN_IF_REACHED,
531
    ),
532
    'install_select_locale' => array(
533
      'display_name' => st('Choose language'),
534
      'run' => INSTALL_TASK_RUN_IF_REACHED,
535
    ),
536
    'install_load_profile' => array(
537
      'run' => INSTALL_TASK_RUN_IF_REACHED,
538
    ),
539
    'install_verify_requirements' => array(
540
      'display_name' => st('Verify requirements'),
541
    ),
542
    'install_settings_form' => array(
543
      'display_name' => st('Set up database'),
544
      'type' => 'form',
545
      'run' => $install_state['settings_verified'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
546
    ),
547
    'install_system_module' => array(
548
    ),
549
    'install_bootstrap_full' => array(
550
      'run' => INSTALL_TASK_RUN_IF_REACHED,
551
    ),
552
    'install_profile_modules' => array(
553
      'display_name' => count($install_state['profiles']) == 1 ? st('Install site') : st('Install profile'),
554
      'type' => 'batch',
555
    ),
556
    'install_import_locales' => array(
557
      'display_name' => st('Set up translations'),
558
      'display' => $needs_translations,
559
      'type' => 'batch',
560
      'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
561
    ),
562
    'install_configure_form' => array(
563
      'display_name' => st('Configure site'),
564
      'type' => 'form',
565
    ),
566
  );
567

    
568
  // Now add any tasks defined by the installation profile.
569
  if (!empty($install_state['parameters']['profile'])) {
570
    // Load the profile install file, because it is not always loaded when
571
    // hook_install_tasks() is invoked (e.g. batch processing).
572
    $profile_install_file = DRUPAL_ROOT . '/profiles/' . $install_state['parameters']['profile'] . '/' . $install_state['parameters']['profile'] . '.install';
573
    if (file_exists($profile_install_file)) {
574
      include_once $profile_install_file;
575
    }
576
    $function = $install_state['parameters']['profile'] . '_install_tasks';
577
    if (function_exists($function)) {
578
      $result = $function($install_state);
579
      if (is_array($result)) {
580
        $tasks += $result;
581
      }
582
    }
583
  }
584

    
585
  // Finish by adding the remaining core tasks.
586
  $tasks += array(
587
    'install_import_locales_remaining' => array(
588
      'display_name' => st('Finish translations'),
589
      'display' => $needs_translations,
590
      'type' => 'batch',
591
      'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
592
    ),
593
    'install_finished' => array(
594
      'display_name' => st('Finished'),
595
    ),
596
  );
597

    
598
  // Allow the installation profile to modify the full list of tasks.
599
  if (!empty($install_state['parameters']['profile'])) {
600
    $profile_file = DRUPAL_ROOT . '/profiles/' . $install_state['parameters']['profile'] . '/' . $install_state['parameters']['profile'] . '.profile';
601
    if (file_exists($profile_file)) {
602
      include_once $profile_file;
603
      $function = $install_state['parameters']['profile'] . '_install_tasks_alter';
604
      if (function_exists($function)) {
605
        $function($tasks, $install_state);
606
      }
607
    }
608
  }
609

    
610
  // Fill in default parameters for each task before returning the list.
611
  foreach ($tasks as $task_name => &$task) {
612
    $task += array(
613
      'display_name' => NULL,
614
      'display' => !empty($task['display_name']),
615
      'type' => 'normal',
616
      'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
617
      'function' => $task_name,
618
    );
619
  }
620
  return $tasks;
621
}
622

    
623
/**
624
 * Returns a list of tasks that should be displayed to the end user.
625
 *
626
 * The output of this function is a list suitable for sending to
627
 * theme_task_list().
628
 *
629
 * @param $install_state
630
 *   An array of information about the current installation state.
631
 *
632
 * @return
633
 *   A list of tasks, with keys equal to the machine-readable task name and
634
 *   values equal to the name that should be displayed.
635
 *
636
 * @see theme_task_list()
637
 */
638
function install_tasks_to_display($install_state) {
639
  $displayed_tasks = array();
640
  foreach (install_tasks($install_state) as $name => $task) {
641
    if ($task['display']) {
642
      $displayed_tasks[$name] = $task['display_name'];
643
    }
644
  }
645
  return $displayed_tasks;
646
}
647

    
648
/**
649
 * Returns the URL that should be redirected to during an installation request.
650
 *
651
 * The output of this function is suitable for sending to install_goto().
652
 *
653
 * @param $install_state
654
 *   An array of information about the current installation state.
655
 *
656
 * @return
657
 *   The URL to redirect to.
658
 *
659
 * @see install_full_redirect_url()
660
 */
661
function install_redirect_url($install_state) {
662
  return 'install.php?' . drupal_http_build_query($install_state['parameters']);
663
}
664

    
665
/**
666
 * Returns the complete URL redirected to during an installation request.
667
 *
668
 * @param $install_state
669
 *   An array of information about the current installation state.
670
 *
671
 * @return
672
 *   The complete URL to redirect to.
673
 *
674
 * @see install_redirect_url()
675
 */
676
function install_full_redirect_url($install_state) {
677
  global $base_url;
678
  return $base_url . '/' . install_redirect_url($install_state);
679
}
680

    
681
/**
682
 * Displays themed installer output and ends the page request.
683
 *
684
 * Installation tasks should use drupal_set_title() to set the desired page
685
 * title, but otherwise this function takes care of theming the overall page
686
 * output during every step of the installation.
687
 *
688
 * @param $output
689
 *   The content to display on the main part of the page.
690
 * @param $install_state
691
 *   An array of information about the current installation state.
692
 */
693
function install_display_output($output, $install_state) {
694
  drupal_page_header();
695

    
696
  // Prevent install.php from being indexed when installed in a sub folder.
697
  // robots.txt rules are not read if the site is within domain.com/subfolder
698
  // resulting in /subfolder/install.php being found through search engines.
699
  // When settings.php is writeable this can be used via an external database
700
  // leading a malicious user to gain php access to the server.
701
  $noindex_meta_tag = array(
702
    '#tag' => 'meta',
703
    '#attributes' => array(
704
      'name' => 'robots',
705
      'content' => 'noindex, nofollow',
706
    ),
707
  );
708
  drupal_add_html_head($noindex_meta_tag, 'install_meta_robots');
709

    
710
  // Only show the task list if there is an active task; otherwise, the page
711
  // request has ended before tasks have even been started, so there is nothing
712
  // meaningful to show.
713
  if (isset($install_state['active_task'])) {
714
    // Let the theming function know when every step of the installation has
715
    // been completed.
716
    $active_task = $install_state['installation_finished'] ? NULL : $install_state['active_task'];
717
    drupal_add_region_content('sidebar_first', theme('task_list', array('items' => install_tasks_to_display($install_state), 'active' => $active_task)));
718
  }
719
  print theme('install_page', array('content' => $output));
720
  exit;
721
}
722

    
723
/**
724
 * Verifies the requirements for installing Drupal.
725
 *
726
 * @param $install_state
727
 *   An array of information about the current installation state.
728
 *
729
 * @return
730
 *   A themed status report, or an exception if there are requirement errors.
731
 *   If there are only requirement warnings, a themed status report is shown
732
 *   initially, but the user is allowed to bypass it by providing 'continue=1'
733
 *   in the URL. Otherwise, no output is returned, so that the next task can be
734
 *   run in the same page request.
735
 */
736
function install_verify_requirements(&$install_state) {
737
  // Check the installation requirements for Drupal and this profile.
738
  $requirements = install_check_requirements($install_state);
739

    
740
  // Verify existence of all required modules.
741
  $requirements += drupal_verify_profile($install_state);
742

    
743
  // Check the severity of the requirements reported.
744
  $severity = drupal_requirements_severity($requirements);
745

    
746
  // If there are errors, always display them. If there are only warnings, skip
747
  // them if the user has provided a URL parameter acknowledging the warnings
748
  // and indicating a desire to continue anyway. See drupal_requirements_url().
749
  if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING && empty($install_state['parameters']['continue']))) {
750
    if ($install_state['interactive']) {
751
      drupal_set_title(st('Requirements problem'));
752
      $status_report = theme('status_report', array('requirements' => $requirements));
753
      $status_report .= st('Check the error messages and <a href="!url">proceed with the installation</a>.', array('!url' => check_url(drupal_requirements_url($severity))));
754
      return $status_report;
755
    }
756
    else {
757
      // Throw an exception showing any unmet requirements.
758
      $failures = array();
759
      foreach ($requirements as $requirement) {
760
        // Skip warnings altogether for non-interactive installations; these
761
        // proceed in a single request so there is no good opportunity (and no
762
        // good method) to warn the user anyway.
763
        if (isset($requirement['severity']) && $requirement['severity'] == REQUIREMENT_ERROR) {
764
          $failures[] = $requirement['title'] . ': ' . $requirement['value'] . "\n\n" . $requirement['description'];
765
        }
766
      }
767
      if (!empty($failures)) {
768
        throw new Exception(implode("\n\n", $failures));
769
      }
770
    }
771
  }
772
}
773

    
774
/**
775
 * Installation task; install the Drupal system module.
776
 *
777
 * @param $install_state
778
 *   An array of information about the current installation state.
779
 */
780
function install_system_module(&$install_state) {
781
  // Install system.module.
782
  drupal_install_system();
783

    
784
  // Call file_ensure_htaccess() to ensure that all of Drupal's standard
785
  // directories (e.g., the public and private files directories) have
786
  // appropriate .htaccess files. These directories will have already been
787
  // created by this point in the installer, since Drupal creates them during
788
  // the install_verify_requirements() task. Note that we cannot call
789
  // file_ensure_htaccess() any earlier than this, since it relies on
790
  // system.module in order to work.
791
  file_ensure_htaccess();
792

    
793
  // Enable the user module so that sessions can be recorded during the
794
  // upcoming bootstrap step.
795
  module_enable(array('user'), FALSE);
796

    
797
  // Save the list of other modules to install for the upcoming tasks.
798
  // variable_set() can be used now that system.module is installed.
799
  $modules = $install_state['profile_info']['dependencies'];
800

    
801
  // The installation profile is also a module, which needs to be installed
802
  // after all the dependencies have been installed.
803
  $modules[] = drupal_get_profile();
804

    
805
  variable_set('install_profile_modules', array_diff($modules, array('system')));
806
  $install_state['database_tables_exist'] = TRUE;
807
}
808

    
809
/**
810
 * Verifies and returns the last installation task that was completed.
811
 *
812
 * @return
813
 *   The last completed task, if there is one. An exception is thrown if Drupal
814
 *   is already installed.
815
 */
816
function install_verify_completed_task() {
817
  try {
818
    if ($result = db_query("SELECT value FROM {variable} WHERE name = :name", array('name' => 'install_task'))) {
819
      $task = unserialize($result->fetchField());
820
    }
821
  }
822
  // Do not trigger an error if the database query fails, since the database
823
  // might not be set up yet.
824
  catch (Exception $e) {
825
  }
826
  if (isset($task)) {
827
    if ($task == 'done') {
828
      throw new Exception(install_already_done_error());
829
    }
830
    return $task;
831
  }
832
}
833

    
834
/**
835
 * Verifies the existing settings in settings.php.
836
 */
837
function install_verify_settings() {
838
  global $databases;
839

    
840
  // Verify existing settings (if any).
841
  if (!empty($databases) && install_verify_pdo()) {
842
    $database = $databases['default']['default'];
843
    drupal_static_reset('conf_path');
844
    $settings_file = './' . conf_path(FALSE) . '/settings.php';
845
    $errors = install_database_errors($database, $settings_file);
846
    if (empty($errors)) {
847
      return TRUE;
848
    }
849
  }
850
  return FALSE;
851
}
852

    
853
/**
854
 * Verifies the PDO library.
855
 */
856
function install_verify_pdo() {
857
  // PDO was moved to PHP core in 5.2.0, but the old extension (targeting 5.0
858
  // and 5.1) is still available from PECL, and can still be built without
859
  // errors. To verify that the correct version is in use, we check the
860
  // PDO::ATTR_DEFAULT_FETCH_MODE constant, which is not available in the
861
  // PECL extension.
862
  return extension_loaded('pdo') && defined('PDO::ATTR_DEFAULT_FETCH_MODE');
863
}
864

    
865
/**
866
 * Form constructor for a form to configure and rewrite settings.php.
867
 *
868
 * @param $install_state
869
 *   An array of information about the current installation state.
870
 *
871
 * @see install_settings_form_validate()
872
 * @see install_settings_form_submit()
873
 * @ingroup forms
874
 */
875
function install_settings_form($form, &$form_state, &$install_state) {
876
  global $databases;
877
  $profile = $install_state['parameters']['profile'];
878
  $install_locale = $install_state['parameters']['locale'];
879

    
880
  drupal_static_reset('conf_path');
881
  $conf_path = './' . conf_path(FALSE);
882
  $settings_file = $conf_path . '/settings.php';
883
  $database = isset($databases['default']['default']) ? $databases['default']['default'] : array();
884

    
885
  drupal_set_title(st('Database configuration'));
886

    
887
  $drivers = drupal_get_database_types();
888
  $drivers_keys = array_keys($drivers);
889

    
890
  $form['driver'] = array(
891
    '#type' => 'radios',
892
    '#title' => st('Database type'),
893
    '#required' => TRUE,
894
    '#default_value' => !empty($database['driver']) ? $database['driver'] : current($drivers_keys),
895
    '#description' => st('The type of database your @drupal data will be stored in.', array('@drupal' => drupal_install_profile_distribution_name())),
896
  );
897
  if (count($drivers) == 1) {
898
    $form['driver']['#disabled'] = TRUE;
899
    $form['driver']['#description'] .= ' ' . st('Your PHP configuration only supports a single database type, so it has been automatically selected.');
900
  }
901

    
902
  // Add driver specific configuration options.
903
  foreach ($drivers as $key => $driver) {
904
    $form['driver']['#options'][$key] = $driver->name();
905

    
906
    $form['settings'][$key] = $driver->getFormOptions($database);
907
    $form['settings'][$key]['#prefix'] = '<h2 class="js-hide">' . st('@driver_name settings', array('@driver_name' => $driver->name())) . '</h2>';
908
    $form['settings'][$key]['#type'] = 'container';
909
    $form['settings'][$key]['#tree'] = TRUE;
910
    $form['settings'][$key]['advanced_options']['#parents'] = array($key);
911
    $form['settings'][$key]['#states'] = array(
912
      'visible' => array(
913
        ':input[name=driver]' => array('value' => $key),
914
      )
915
    );
916
  }
917

    
918
  $form['actions'] = array('#type' => 'actions');
919
  $form['actions']['save'] = array(
920
    '#type' => 'submit',
921
    '#value' => st('Save and continue'),
922
    '#limit_validation_errors' => array(
923
      array('driver'),
924
      array(isset($form_state['input']['driver']) ? $form_state['input']['driver'] : current($drivers_keys)),
925
    ),
926
    '#submit' => array('install_settings_form_submit'),
927
  );
928

    
929
  $form['errors'] = array();
930
  $form['settings_file'] = array('#type' => 'value', '#value' => $settings_file);
931

    
932
  return $form;
933
}
934

    
935
/**
936
 * Form validation handler for install_settings_form().
937
 *
938
 * @see install_settings_form_submit()
939
 */
940
function install_settings_form_validate($form, &$form_state) {
941
  $driver = $form_state['values']['driver'];
942
  $database = $form_state['values'][$driver];
943
  $database['driver'] = $driver;
944

    
945
  // TODO: remove when PIFR will be updated to use 'db_prefix' instead of
946
  // 'prefix' in the database settings form.
947
  $database['prefix'] = $database['db_prefix'];
948
  unset($database['db_prefix']);
949

    
950
  $form_state['storage']['database'] = $database;
951
  $errors = install_database_errors($database, $form_state['values']['settings_file']);
952
  foreach ($errors as $name => $message) {
953
    form_set_error($name, $message);
954
  }
955
}
956

    
957
/**
958
 * Checks a database connection and returns any errors.
959
 */
960
function install_database_errors($database, $settings_file) {
961
  global $databases;
962
  $errors = array();
963

    
964
  // Check database type.
965
  $database_types = drupal_get_database_types();
966
  $driver = $database['driver'];
967
  if (!isset($database_types[$driver])) {
968
    $errors['driver'] = st("In your %settings_file file you have configured @drupal to use a %driver server, however your PHP installation currently does not support this database type.", array('%settings_file' => $settings_file, '@drupal' => drupal_install_profile_distribution_name(), '%driver' => $driver));
969
  }
970
  else {
971
    // Run driver specific validation
972
    $errors += $database_types[$driver]->validateDatabaseSettings($database);
973

    
974
    // Run tasks associated with the database type. Any errors are caught in the
975
    // calling function.
976
    $databases['default']['default'] = $database;
977
    // Just changing the global doesn't get the new information processed.
978
    // We tell tell the Database class to re-parse $databases.
979
    Database::parseConnectionInfo();
980

    
981
    try {
982
      db_run_tasks($driver);
983
    }
984
    catch (DatabaseTaskException $e) {
985
      // These are generic errors, so we do not have any specific key of the
986
      // database connection array to attach them to; therefore, we just put
987
      // them in the error array with standard numeric keys.
988
      $errors[$driver . '][0'] = $e->getMessage();
989
    }
990
  }
991
  return $errors;
992
}
993

    
994
/**
995
 * Form submission handler for install_settings_form().
996
 *
997
 * @see install_settings_form_validate()
998
 */
999
function install_settings_form_submit($form, &$form_state) {
1000
  global $install_state;
1001

    
1002
  // Update global settings array and save.
1003
  $settings['databases'] = array(
1004
    'value'    => array('default' => array('default' => $form_state['storage']['database'])),
1005
    'required' => TRUE,
1006
  );
1007
  $settings['drupal_hash_salt'] = array(
1008
    'value'    => drupal_random_key(),
1009
    'required' => TRUE,
1010
  );
1011
  drupal_rewrite_settings($settings);
1012
  // Indicate that the settings file has been verified, and check the database
1013
  // for the last completed task, now that we have a valid connection. This
1014
  // last step is important since we want to trigger an error if the new
1015
  // database already has Drupal installed.
1016
  $install_state['settings_verified'] = TRUE;
1017
  $install_state['completed_task'] = install_verify_completed_task();
1018
}
1019

    
1020
/**
1021
 * Finds all .profile files.
1022
 */
1023
function install_find_profiles() {
1024
  return file_scan_directory('./profiles', '/\.profile$/', array('key' => 'name'));
1025
}
1026

    
1027
/**
1028
 * Selects which profile to install.
1029
 *
1030
 * @param $install_state
1031
 *   An array of information about the current installation state. The chosen
1032
 *   profile will be added here, if it was not already selected previously, as
1033
 *   will a list of all available profiles.
1034
 *
1035
 * @return
1036
 *   For interactive installations, a form allowing the profile to be selected,
1037
 *   if the user has a choice that needs to be made. Otherwise, an exception is
1038
 *   thrown if a profile cannot be chosen automatically.
1039
 */
1040
function install_select_profile(&$install_state) {
1041
  $install_state['profiles'] += install_find_profiles();
1042
  if (empty($install_state['parameters']['profile'])) {
1043
    // Try to find a profile.
1044
    $profile = _install_select_profile($install_state['profiles']);
1045
    if (empty($profile)) {
1046
      // We still don't have a profile, so display a form for selecting one.
1047
      // Only do this in the case of interactive installations, since this is
1048
      // not a real form with submit handlers (the database isn't even set up
1049
      // yet), rather just a convenience method for setting parameters in the
1050
      // URL.
1051
      if ($install_state['interactive']) {
1052
        include_once DRUPAL_ROOT . '/includes/form.inc';
1053
        drupal_set_title(st('Select an installation profile'));
1054
        $form = drupal_get_form('install_select_profile_form', $install_state['profiles']);
1055
        return drupal_render($form);
1056
      }
1057
      else {
1058
        throw new Exception(install_no_profile_error());
1059
      }
1060
    }
1061
    else {
1062
      $install_state['parameters']['profile'] = $profile;
1063
    }
1064
  }
1065
}
1066

    
1067
/**
1068
 * Selects an installation profile.
1069
 *
1070
 * A profile will be selected if:
1071
 * - Only one profile is available,
1072
 * - A profile was submitted through $_POST,
1073
 * - Exactly one of the profiles is marked as "exclusive".
1074
 * If multiple profiles are marked as "exclusive" then no profile will be
1075
 * selected.
1076
 *
1077
 * @param array $profiles
1078
 *   An associative array of profiles with the machine-readable names as keys.
1079
 *
1080
 * @return
1081
 *   The machine-readable name of the selected profile or NULL if no profile was
1082
 *   selected.
1083
 */
1084
function _install_select_profile($profiles) {
1085
  if (sizeof($profiles) == 0) {
1086
    throw new Exception(install_no_profile_error());
1087
  }
1088
  // Don't need to choose profile if only one available.
1089
  if (sizeof($profiles) == 1) {
1090
    $profile = array_pop($profiles);
1091
    // TODO: is this right?
1092
    require_once DRUPAL_ROOT . '/' . $profile->uri;
1093
    return $profile->name;
1094
  }
1095
  else {
1096
    foreach ($profiles as $profile) {
1097
      if (!empty($_POST['profile']) && ($_POST['profile'] == $profile->name)) {
1098
        return $profile->name;
1099
      }
1100
    }
1101
  }
1102
  // Check for a profile marked as "exclusive" and ensure that only one
1103
  // profile is marked as such.
1104
  $exclusive_profile = NULL;
1105
  foreach ($profiles as $profile) {
1106
    $profile_info = install_profile_info($profile->name);
1107
    if (!empty($profile_info['exclusive'])) {
1108
      if (empty($exclusive_profile)) {
1109
        $exclusive_profile = $profile->name;
1110
      }
1111
      else {
1112
        // We found a second "exclusive" profile. There's no way to choose
1113
        // between them, so we ignore the property.
1114
        return;
1115
      }
1116
    }
1117
  }
1118
  return $exclusive_profile;
1119
}
1120

    
1121
/**
1122
 * Form constructor for the profile selection form.
1123
 *
1124
 * @param $form_state
1125
 *   Array of metadata about state of form processing.
1126
 * @param $profile_files
1127
 *   Array of .profile files, as returned from file_scan_directory().
1128
 *
1129
 * @ingroup forms
1130
 */
1131
function install_select_profile_form($form, &$form_state, $profile_files) {
1132
  $profiles = array();
1133
  $names = array();
1134

    
1135
  foreach ($profile_files as $profile) {
1136
    // TODO: is this right?
1137
    include_once DRUPAL_ROOT . '/' . $profile->uri;
1138

    
1139
    $details = install_profile_info($profile->name);
1140
    // Don't show hidden profiles. This is used by to hide the testing profile,
1141
    // which only exists to speed up test runs.
1142
    if ($details['hidden'] === TRUE) {
1143
      continue;
1144
    }
1145
    $profiles[$profile->name] = $details;
1146

    
1147
    // Determine the name of the profile; default to file name if defined name
1148
    // is unspecified.
1149
    $name = isset($details['name']) ? $details['name'] : $profile->name;
1150
    $names[$profile->name] = $name;
1151
  }
1152

    
1153
  // Display radio buttons alphabetically by human-readable name, but always
1154
  // put the core profiles first (if they are present in the filesystem).
1155
  natcasesort($names);
1156
  if (isset($names['minimal'])) {
1157
    // If the expert ("Minimal") core profile is present, put it in front of
1158
    // any non-core profiles rather than including it with them alphabetically,
1159
    // since the other profiles might be intended to group together in a
1160
    // particular way.
1161
    $names = array('minimal' => $names['minimal']) + $names;
1162
  }
1163
  if (isset($names['standard'])) {
1164
    // If the default ("Standard") core profile is present, put it at the very
1165
    // top of the list. This profile will have its radio button pre-selected,
1166
    // so we want it to always appear at the top.
1167
    $names = array('standard' => $names['standard']) + $names;
1168
  }
1169

    
1170
  foreach ($names as $profile => $name) {
1171
    $form['profile'][$name] = array(
1172
      '#type' => 'radio',
1173
      '#value' => 'standard',
1174
      '#return_value' => $profile,
1175
      '#title' => $name,
1176
      '#description' => isset($profiles[$profile]['description']) ? $profiles[$profile]['description'] : '',
1177
      '#parents' => array('profile'),
1178
    );
1179
  }
1180
  $form['actions'] = array('#type' => 'actions');
1181
  $form['actions']['submit'] =  array(
1182
    '#type' => 'submit',
1183
    '#value' => st('Save and continue'),
1184
  );
1185
  return $form;
1186
}
1187

    
1188
/**
1189
 * Find all .po files for the current profile.
1190
 */
1191
function install_find_locales($profilename) {
1192
  $locales = file_scan_directory('./profiles/' . $profilename . '/translations', '/\.po$/', array('recurse' => FALSE));
1193
  array_unshift($locales, (object) array('name' => 'en'));
1194
  foreach ($locales as $key => $locale) {
1195
    // The locale (file name) might be drupal-7.2.cs.po instead of cs.po.
1196
    $locales[$key]->langcode = preg_replace('!^(.+\.)?([^\.]+)$!', '\2', $locale->name);
1197
    // Language codes cannot exceed 12 characters to fit into the {languages}
1198
    // table.
1199
    if (strlen($locales[$key]->langcode) > 12) {
1200
      unset($locales[$key]);
1201
    }
1202
  }
1203
  return $locales;
1204
}
1205

    
1206
/**
1207
 * Installation task; select which locale to use for the current profile.
1208
 *
1209
 * @param $install_state
1210
 *   An array of information about the current installation state. The chosen
1211
 *   locale will be added here, if it was not already selected previously, as
1212
 *   will a list of all available locales.
1213
 *
1214
 * @return
1215
 *   For interactive installations, a form or other page output allowing the
1216
 *   locale to be selected or providing information about locale selection, if
1217
 *   a locale has not been chosen. Otherwise, an exception is thrown if a
1218
 *   locale cannot be chosen automatically.
1219
 */
1220
function install_select_locale(&$install_state) {
1221
  // Find all available locales.
1222
  $profilename = $install_state['parameters']['profile'];
1223
  $locales = install_find_locales($profilename);
1224
  $install_state['locales'] += $locales;
1225

    
1226
  if (!empty($_POST['locale'])) {
1227
    foreach ($locales as $locale) {
1228
      if ($_POST['locale'] == $locale->langcode) {
1229
        $install_state['parameters']['locale'] = $locale->langcode;
1230
        return;
1231
      }
1232
    }
1233
  }
1234

    
1235
  if (empty($install_state['parameters']['locale'])) {
1236
    // If only the built-in (English) language is available, and we are
1237
    // performing an interactive installation, inform the user that the
1238
    // installer can be localized. Otherwise we assume the user knows what he
1239
    // is doing.
1240
    if (count($locales) == 1) {
1241
      if ($install_state['interactive']) {
1242
        drupal_set_title(st('Choose language'));
1243
        if (!empty($install_state['parameters']['localize'])) {
1244
          $output = '<p>Follow these steps to translate Drupal into your language:</p>';
1245
          $output .= '<ol>';
1246
          $output .= '<li>Download a translation from the <a href="http://localize.drupal.org/download" target="_blank">translation server</a>.</li>';
1247
          $output .= '<li>Place it into the following directory:
1248
<pre>
1249
/profiles/' . $profilename . '/translations/
1250
</pre></li>';
1251
          $output .= '</ol>';
1252
          $output .= '<p>For more information on installing Drupal in different languages, visit the <a href="http://drupal.org/localize" target="_blank">drupal.org handbook page</a>.</p>';
1253
          $output .= '<p>How should the installation continue?</p>';
1254
          $output .= '<ul>';
1255
          $output .= '<li><a href="install.php?profile=' . $profilename . '">Reload the language selection page after adding translations</a></li>';
1256
          $output .= '<li><a href="install.php?profile=' . $profilename . '&amp;locale=en">Continue installation in English</a></li>';
1257
          $output .= '</ul>';
1258
        }
1259
        else {
1260
          include_once DRUPAL_ROOT . '/includes/form.inc';
1261
          $elements = drupal_get_form('install_select_locale_form', $locales, $profilename);
1262
          $output = drupal_render($elements);
1263
        }
1264
        return $output;
1265
      }
1266
      // One language, but not an interactive installation. Assume the user
1267
      // knows what he is doing.
1268
      $locale = current($locales);
1269
      $install_state['parameters']['locale'] = $locale->name;
1270
      return;
1271
    }
1272
    else {
1273
      // Allow profile to pre-select the language, skipping the selection.
1274
      $function = $profilename . '_profile_details';
1275
      if (function_exists($function)) {
1276
        $details = $function();
1277
        if (isset($details['language'])) {
1278
          foreach ($locales as $locale) {
1279
            if ($details['language'] == $locale->name) {
1280
              $install_state['parameters']['locale'] = $locale->name;
1281
              return;
1282
            }
1283
          }
1284
        }
1285
      }
1286

    
1287
      // We still don't have a locale, so display a form for selecting one.
1288
      // Only do this in the case of interactive installations, since this is
1289
      // not a real form with submit handlers (the database isn't even set up
1290
      // yet), rather just a convenience method for setting parameters in the
1291
      // URL.
1292
      if ($install_state['interactive']) {
1293
        drupal_set_title(st('Choose language'));
1294
        include_once DRUPAL_ROOT . '/includes/form.inc';
1295
        $elements = drupal_get_form('install_select_locale_form', $locales, $profilename);
1296
        return drupal_render($elements);
1297
      }
1298
      else {
1299
        throw new Exception(st('Sorry, you must select a language to continue the installation.'));
1300
      }
1301
    }
1302
  }
1303
}
1304

    
1305
/**
1306
 * Form constructor for the language selection form.
1307
 *
1308
 * @ingroup forms
1309
 */
1310
function install_select_locale_form($form, &$form_state, $locales, $profilename) {
1311
  include_once DRUPAL_ROOT . '/includes/iso.inc';
1312
  $languages = _locale_get_predefined_list();
1313
  foreach ($locales as $locale) {
1314
    $name = $locale->langcode;
1315
    if (isset($languages[$name])) {
1316
      $name = $languages[$name][0] . (isset($languages[$name][1]) ? ' ' . st('(@language)', array('@language' => $languages[$name][1])) : '');
1317
    }
1318
    $form['locale'][$locale->langcode] = array(
1319
      '#type' => 'radio',
1320
      '#return_value' => $locale->langcode,
1321
      '#default_value' => $locale->langcode == 'en' ? 'en' : '',
1322
      '#title' => $name . ($locale->langcode == 'en' ? ' ' . st('(built-in)') : ''),
1323
      '#parents' => array('locale')
1324
    );
1325
  }
1326
  if (count($locales) == 1) {
1327
    $form['help'] = array(
1328
      '#markup' => '<p><a href="install.php?profile=' . $profilename . '&amp;localize=true">' . st('Learn how to install Drupal in other languages') . '</a></p>',
1329
    );
1330
  }
1331
  $form['actions'] = array('#type' => 'actions');
1332
  $form['actions']['submit'] =  array(
1333
    '#type' => 'submit',
1334
    '#value' => st('Save and continue'),
1335
  );
1336
  return $form;
1337
}
1338

    
1339
/**
1340
 * Indicates that there are no profiles available.
1341
 */
1342
function install_no_profile_error() {
1343
  drupal_set_title(st('No profiles available'));
1344
  return st('We were unable to find any installation profiles. Installation profiles tell us what modules to enable and what schema to install in the database. A profile is necessary to continue with the installation process.');
1345
}
1346

    
1347
/**
1348
 * Indicates that Drupal has already been installed.
1349
 */
1350
function install_already_done_error() {
1351
  global $base_url;
1352

    
1353
  drupal_set_title(st('Drupal already installed'));
1354
  return st('<ul><li>To start over, you must empty your existing database.</li><li>To install to a different database, edit the appropriate <em>settings.php</em> file in the <em>sites</em> folder.</li><li>To upgrade an existing installation, proceed to the <a href="@base-url/update.php">update script</a>.</li><li>View your <a href="@base-url">existing site</a>.</li></ul>', array('@base-url' => $base_url));
1355
}
1356

    
1357
/**
1358
 * Loads information about the chosen profile during installation.
1359
 *
1360
 * @param $install_state
1361
 *   An array of information about the current installation state. The loaded
1362
 *   profile information will be added here, or an exception will be thrown if
1363
 *   the profile cannot be loaded.
1364
 */
1365
function install_load_profile(&$install_state) {
1366
  $profile_file = DRUPAL_ROOT . '/profiles/' . $install_state['parameters']['profile'] . '/' . $install_state['parameters']['profile'] . '.profile';
1367
  if (file_exists($profile_file)) {
1368
    include_once $profile_file;
1369
    $install_state['profile_info'] = install_profile_info($install_state['parameters']['profile'], $install_state['parameters']['locale']);
1370
  }
1371
  else {
1372
    throw new Exception(st('Sorry, the profile you have chosen cannot be loaded.'));
1373
  }
1374
}
1375

    
1376
/**
1377
 * Performs a full bootstrap of Drupal during installation.
1378
 *
1379
 * @param $install_state
1380
 *   An array of information about the current installation state.
1381
 */
1382
function install_bootstrap_full(&$install_state) {
1383
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
1384
}
1385

    
1386
/**
1387
 * Installs required modules via a batch process.
1388
 *
1389
 * @param $install_state
1390
 *   An array of information about the current installation state.
1391
 *
1392
 * @return
1393
 *   The batch definition.
1394
 */
1395
function install_profile_modules(&$install_state) {
1396
  $modules = variable_get('install_profile_modules', array());
1397
  $files = system_rebuild_module_data();
1398
  variable_del('install_profile_modules');
1399

    
1400
  // Always install required modules first. Respect the dependencies between
1401
  // the modules.
1402
  $required = array();
1403
  $non_required = array();
1404
  // Although the profile module is marked as required, it needs to go after
1405
  // every dependency, including non-required ones. So clear its required
1406
  // flag for now to allow it to install late.
1407
  $files[$install_state['parameters']['profile']]->info['required'] = FALSE;
1408
  // Add modules that other modules depend on.
1409
  foreach ($modules as $module) {
1410
    if ($files[$module]->requires) {
1411
      $modules = array_merge($modules, array_keys($files[$module]->requires));
1412
    }
1413
  }
1414
  $modules = array_unique($modules);
1415
  foreach ($modules as $module) {
1416
    if (!empty($files[$module]->info['required'])) {
1417
      $required[$module] = $files[$module]->sort;
1418
    }
1419
    else {
1420
      $non_required[$module] = $files[$module]->sort;
1421
    }
1422
  }
1423
  arsort($required);
1424
  arsort($non_required);
1425

    
1426
  $operations = array();
1427
  foreach ($required + $non_required as $module => $weight) {
1428
    $operations[] = array('_install_module_batch', array($module, $files[$module]->info['name']));
1429
  }
1430
  $batch = array(
1431
    'operations' => $operations,
1432
    'title' => st('Installing @drupal', array('@drupal' => drupal_install_profile_distribution_name())),
1433
    'error_message' => st('The installation has encountered an error.'),
1434
    'finished' => '_install_profile_modules_finished',
1435
  );
1436
  return $batch;
1437
}
1438

    
1439
/**
1440
 * Imports languages via a batch process during installation.
1441
 *
1442
 * @param $install_state
1443
 *   An array of information about the current installation state.
1444
 *
1445
 * @return
1446
 *   The batch definition, if there are language files to import.
1447
 */
1448
function install_import_locales(&$install_state) {
1449
  include_once DRUPAL_ROOT . '/includes/locale.inc';
1450
  $install_locale = $install_state['parameters']['locale'];
1451

    
1452
  include_once DRUPAL_ROOT . '/includes/iso.inc';
1453
  $predefined = _locale_get_predefined_list();
1454
  if (!isset($predefined[$install_locale])) {
1455
    // Drupal does not know about this language, so we prefill its values with
1456
    // our best guess. The user will be able to edit afterwards.
1457
    locale_add_language($install_locale, $install_locale, $install_locale, LANGUAGE_LTR, '', '', TRUE, TRUE);
1458
  }
1459
  else {
1460
    // A known predefined language, details will be filled in properly.
1461
    locale_add_language($install_locale, NULL, NULL, NULL, '', '', TRUE, TRUE);
1462
  }
1463

    
1464
  // Collect files to import for this language.
1465
  $batch = locale_batch_by_language($install_locale, NULL);
1466
  if (!empty($batch)) {
1467
    // Remember components we cover in this batch set.
1468
    variable_set('install_locale_batch_components', $batch['#components']);
1469
    return $batch;
1470
  }
1471
}
1472

    
1473
/**
1474
 * Form constructor for a form to configure the new site.
1475
 *
1476
 * @param $install_state
1477
 *   An array of information about the current installation state.
1478
 *
1479
 * @see install_configure_form_validate()
1480
 * @see install_configure_form_submit()
1481
 * @ingroup forms
1482
 */
1483
function install_configure_form($form, &$form_state, &$install_state) {
1484
  drupal_set_title(st('Configure site'));
1485

    
1486
  // Warn about settings.php permissions risk
1487
  $settings_dir = conf_path();
1488
  $settings_file = $settings_dir . '/settings.php';
1489
  // Check that $_POST is empty so we only show this message when the form is
1490
  // first displayed, not on the next page after it is submitted. (We do not
1491
  // want to repeat it multiple times because it is a general warning that is
1492
  // not related to the rest of the installation process; it would also be
1493
  // especially out of place on the last page of the installer, where it would
1494
  // distract from the message that the Drupal installation has completed
1495
  // successfully.)
1496
  if (empty($_POST) && (!drupal_verify_install_file(DRUPAL_ROOT . '/' . $settings_file, FILE_EXIST|FILE_READABLE|FILE_NOT_WRITABLE) || !drupal_verify_install_file(DRUPAL_ROOT . '/' . $settings_dir, FILE_NOT_WRITABLE, 'dir'))) {
1497
    drupal_set_message(st('All necessary changes to %dir and %file have been made, so you should remove write permissions to them now in order to avoid security risks. If you are unsure how to do so, consult the <a href="@handbook_url">online handbook</a>.', array('%dir' => $settings_dir, '%file' => $settings_file, '@handbook_url' => 'http://drupal.org/server-permissions')), 'warning');
1498
  }
1499

    
1500
  drupal_add_js(drupal_get_path('module', 'system') . '/system.js');
1501
  // Add JavaScript time zone detection.
1502
  drupal_add_js('misc/timezone.js');
1503
  // We add these strings as settings because JavaScript translation does not
1504
  // work during installation.
1505
  drupal_add_js(array('copyFieldValue' => array('edit-site-mail' => array('edit-account-mail'))), 'setting');
1506
  drupal_add_js('jQuery(function () { Drupal.cleanURLsInstallCheck(); });', 'inline');
1507
  // Add JS to show / hide the 'Email administrator about site updates' elements
1508
  drupal_add_js('jQuery(function () { Drupal.hideEmailAdministratorCheckbox() });', 'inline');
1509
  // Build menu to allow clean URL check.
1510
  menu_rebuild();
1511

    
1512
  // Cache a fully-built schema. This is necessary for any invocation of
1513
  // index.php because: (1) setting cache table entries requires schema
1514
  // information, (2) that occurs during bootstrap before any module are
1515
  // loaded, so (3) if there is no cached schema, drupal_get_schema() will
1516
  // try to generate one but with no loaded modules will return nothing.
1517
  //
1518
  // This logically could be done during the 'install_finished' task, but the
1519
  // clean URL check requires it now.
1520
  drupal_get_schema(NULL, TRUE);
1521

    
1522
  // Return the form.
1523
  return _install_configure_form($form, $form_state, $install_state);
1524
}
1525

    
1526
/**
1527
 * Installation task; import remaining languages via a batch process.
1528
 *
1529
 * @param $install_state
1530
 *   An array of information about the current installation state.
1531
 *
1532
 * @return
1533
 *   The batch definition, if there are language files to import.
1534
 */
1535
function install_import_locales_remaining(&$install_state) {
1536
  include_once DRUPAL_ROOT . '/includes/locale.inc';
1537
  // Collect files to import for this language. Skip components already covered
1538
  // in the initial batch set.
1539
  $install_locale = $install_state['parameters']['locale'];
1540
  $batch = locale_batch_by_language($install_locale, NULL, variable_get('install_locale_batch_components', array()));
1541
  // Remove temporary variable.
1542
  variable_del('install_locale_batch_components');
1543
  return $batch;
1544
}
1545

    
1546
/**
1547
 * Finishes importing files at end of installation.
1548
 *
1549
 * @param $install_state
1550
 *   An array of information about the current installation state.
1551
 *
1552
 * @return
1553
 *   A message informing the user that the installation is complete.
1554
 */
1555
function install_finished(&$install_state) {
1556
  drupal_set_title(st('@drupal installation complete', array('@drupal' => drupal_install_profile_distribution_name())), PASS_THROUGH);
1557
  $messages = drupal_set_message();
1558
  $output = '<p>' . st('Congratulations, you installed @drupal!', array('@drupal' => drupal_install_profile_distribution_name())) . '</p>';
1559
  $output .= '<p>' . (isset($messages['error']) ? st('Review the messages above before visiting <a href="@url">your new site</a>.', array('@url' => url(''))) : st('<a href="@url">Visit your new site</a>.', array('@url' => url('')))) . '</p>';
1560

    
1561
  // Flush all caches to ensure that any full bootstraps during the installer
1562
  // do not leave stale cached data, and that any content types or other items
1563
  // registered by the installation profile are registered correctly.
1564
  drupal_flush_all_caches();
1565

    
1566
  // Remember the profile which was used.
1567
  variable_set('install_profile', drupal_get_profile());
1568

    
1569
  // Installation profiles are always loaded last
1570
  db_update('system')
1571
    ->fields(array('weight' => 1000))
1572
    ->condition('type', 'module')
1573
    ->condition('name', drupal_get_profile())
1574
    ->execute();
1575

    
1576
  // Cache a fully-built schema.
1577
  drupal_get_schema(NULL, TRUE);
1578

    
1579
  // Run cron to populate update status tables (if available) so that users
1580
  // will be warned if they've installed an out of date Drupal version.
1581
  // Will also trigger indexing of profile-supplied content or feeds.
1582
  drupal_cron_run();
1583

    
1584
  return $output;
1585
}
1586

    
1587
/**
1588
 * Batch callback for batch installation of modules.
1589
 */
1590
function _install_module_batch($module, $module_name, &$context) {
1591
  // Install and enable the module right away, so that the module will be
1592
  // loaded by drupal_bootstrap in subsequent batch requests, and other
1593
  // modules possibly depending on it can safely perform their installation
1594
  // steps.
1595
  module_enable(array($module), FALSE);
1596
  $context['results'][] = $module;
1597
  $context['message'] = st('Installed %module module.', array('%module' => $module_name));
1598
}
1599

    
1600
/**
1601
 * 'Finished' callback for module installation batch.
1602
 */
1603
function _install_profile_modules_finished($success, $results, $operations) {
1604
  // Flush all caches to complete the module installation process. Subsequent
1605
  // installation tasks will now have full access to the profile's modules.
1606
  drupal_flush_all_caches();
1607
}
1608

    
1609
/**
1610
 * Checks installation requirements and reports any errors.
1611
 */
1612
function install_check_requirements($install_state) {
1613
  $profile = $install_state['parameters']['profile'];
1614

    
1615
  // Check the profile requirements.
1616
  $requirements = drupal_check_profile($profile);
1617

    
1618
  // If Drupal is not set up already, we need to create a settings file.
1619
  if (!$install_state['settings_verified']) {
1620
    $writable = FALSE;
1621
    $conf_path = './' . conf_path(FALSE, TRUE);
1622
    $settings_file = $conf_path . '/settings.php';
1623
    $default_settings_file = './sites/default/default.settings.php';
1624
    $file = $conf_path;
1625
    $exists = FALSE;
1626
    // Verify that the directory exists.
1627
    if (drupal_verify_install_file($conf_path, FILE_EXIST, 'dir')) {
1628
      // Check if a settings.php file already exists.
1629
      $file = $settings_file;
1630
      if (drupal_verify_install_file($settings_file, FILE_EXIST)) {
1631
        // If it does, make sure it is writable.
1632
        $writable = drupal_verify_install_file($settings_file, FILE_READABLE|FILE_WRITABLE);
1633
        $exists = TRUE;
1634
      }
1635
    }
1636

    
1637
    // If default.settings.php does not exist, or is not readable, throw an
1638
    // error.
1639
    if (!drupal_verify_install_file($default_settings_file, FILE_EXIST|FILE_READABLE)) {
1640
      $requirements['default settings file exists'] = array(
1641
        'title'       => st('Default settings file'),
1642
        'value'       => st('The default settings file does not exist.'),
1643
        'severity'    => REQUIREMENT_ERROR,
1644
        'description' => st('The @drupal installer requires that the %default-file file not be modified in any way from the original download.', array('@drupal' => drupal_install_profile_distribution_name(), '%default-file' => $default_settings_file)),
1645
      );
1646
    }
1647
    // Otherwise, if settings.php does not exist yet, we can try to copy
1648
    // default.settings.php to create it.
1649
    elseif (!$exists) {
1650
      $copied = drupal_verify_install_file($conf_path, FILE_EXIST|FILE_WRITABLE, 'dir') && @copy($default_settings_file, $settings_file);
1651
      if ($copied) {
1652
        // If the new settings file has the same owner as default.settings.php,
1653
        // this means default.settings.php is owned by the webserver user.
1654
        // This is an inherent security weakness because it allows a malicious
1655
        // webserver process to append arbitrary PHP code and then execute it.
1656
        // However, it is also a common configuration on shared hosting, and
1657
        // there is nothing Drupal can do to prevent it. In this situation,
1658
        // having settings.php also owned by the webserver does not introduce
1659
        // any additional security risk, so we keep the file in place.
1660
        if (fileowner($default_settings_file) === fileowner($settings_file)) {
1661
          $writable = drupal_verify_install_file($settings_file, FILE_READABLE|FILE_WRITABLE);
1662
          $exists = TRUE;
1663
        }
1664
        // If settings.php and default.settings.php have different owners, this
1665
        // probably means the server is set up "securely" (with the webserver
1666
        // running as its own user, distinct from the user who owns all the
1667
        // Drupal PHP files), although with either a group or world writable
1668
        // sites directory. Keeping settings.php owned by the webserver would
1669
        // therefore introduce a security risk. It would also cause a usability
1670
        // problem, since site owners who do not have root access to the file
1671
        // system would be unable to edit their settings file later on. We
1672
        // therefore must delete the file we just created and force the
1673
        // administrator to log on to the server and create it manually.
1674
        else {
1675
          $deleted = @drupal_unlink($settings_file);
1676
          // We expect deleting the file to be successful (since we just
1677
          // created it ourselves above), but if it fails somehow, we set a
1678
          // variable so we can display a one-time error message to the
1679
          // administrator at the bottom of the requirements list. We also try
1680
          // to make the file writable, to eliminate any conflicting error
1681
          // messages in the requirements list.
1682
          $exists = !$deleted;
1683
          if ($exists) {
1684
            $settings_file_ownership_error = TRUE;
1685
            $writable = drupal_verify_install_file($settings_file, FILE_READABLE|FILE_WRITABLE);
1686
          }
1687
        }
1688
      }
1689
    }
1690

    
1691
    // If settings.php does not exist, throw an error.
1692
    if (!$exists) {
1693
      $requirements['settings file exists'] = array(
1694
        'title'       => st('Settings file'),
1695
        'value'       => st('The settings file does not exist.'),
1696
        'severity'    => REQUIREMENT_ERROR,
1697
        'description' => st('The @drupal installer requires that you create a settings file as part of the installation process. Copy the %default_file file to %file. More details about installing Drupal are available in <a href="@install_txt">INSTALL.txt</a>.', array('@drupal' => drupal_install_profile_distribution_name(), '%file' => $file, '%default_file' => $default_settings_file, '@install_txt' => base_path() . 'INSTALL.txt')),
1698
      );
1699
    }
1700
    else {
1701
      $requirements['settings file exists'] = array(
1702
        'title'       => st('Settings file'),
1703
        'value'       => st('The %file file exists.', array('%file' => $file)),
1704
      );
1705
      // If settings.php is not writable, throw an error.
1706
      if (!$writable) {
1707
        $requirements['settings file writable'] = array(
1708
          'title'       => st('Settings file'),
1709
          'value'       => st('The settings file is not writable.'),
1710
          'severity'    => REQUIREMENT_ERROR,
1711
          'description' => st('The @drupal installer requires write permissions to %file during the installation process. If you are unsure how to grant file permissions, consult the <a href="@handbook_url">online handbook</a>.', array('@drupal' => drupal_install_profile_distribution_name(), '%file' => $file, '@handbook_url' => 'http://drupal.org/server-permissions')),
1712
        );
1713
      }
1714
      else {
1715
        $requirements['settings file'] = array(
1716
          'title'       => st('Settings file'),
1717
          'value'       => st('The settings file is writable.'),
1718
        );
1719
      }
1720
      if (!empty($settings_file_ownership_error)) {
1721
        $requirements['settings file ownership'] = array(
1722
          'title'       => st('Settings file'),
1723
          'value'       => st('The settings file is owned by the web server.'),
1724
          'severity'    => REQUIREMENT_ERROR,
1725
          'description' => st('The @drupal installer failed to create a settings file with proper file ownership. Log on to your web server, remove the existing %file file, and create a new one by copying the %default_file file to %file. More details about installing Drupal are available in <a href="@install_txt">INSTALL.txt</a>. If you have problems with the file permissions on your server, consult the <a href="@handbook_url">online handbook</a>.', array('@drupal' => drupal_install_profile_distribution_name(), '%file' => $file, '%default_file' => $default_settings_file, '@install_txt' => base_path() . 'INSTALL.txt', '@handbook_url' => 'http://drupal.org/server-permissions')),
1726
        );
1727
      }
1728
    }
1729
  }
1730
  return $requirements;
1731
}
1732

    
1733
/**
1734
 * Form constructor for a site configuration form.
1735
 *
1736
 * @param $install_state
1737
 *   An array of information about the current installation state.
1738
 *
1739
 * @see install_configure_form()
1740
 * @see install_configure_form_validate()
1741
 * @see install_configure_form_submit()
1742
 * @ingroup forms
1743
 */
1744
function _install_configure_form($form, &$form_state, &$install_state) {
1745
  include_once DRUPAL_ROOT . '/includes/locale.inc';
1746

    
1747
  $form['site_information'] = array(
1748
    '#type' => 'fieldset',
1749
    '#title' => st('Site information'),
1750
    '#collapsible' => FALSE,
1751
  );
1752
  $form['site_information']['site_name'] = array(
1753
    '#type' => 'textfield',
1754
    '#title' => st('Site name'),
1755
    '#required' => TRUE,
1756
    '#weight' => -20,
1757
  );
1758
  $form['site_information']['site_mail'] = array(
1759
    '#type' => 'textfield',
1760
    '#title' => st('Site e-mail address'),
1761
    '#default_value' => ini_get('sendmail_from'),
1762
    '#description' => st("Automated e-mails, such as registration information, will be sent from this address. Use an address ending in your site's domain to help prevent these e-mails from being flagged as spam."),
1763
    '#required' => TRUE,
1764
    '#weight' => -15,
1765
  );
1766
  $form['admin_account'] = array(
1767
    '#type' => 'fieldset',
1768
    '#title' => st('Site maintenance account'),
1769
    '#collapsible' => FALSE,
1770
  );
1771

    
1772
  $form['admin_account']['account']['#tree'] = TRUE;
1773
  $form['admin_account']['account']['name'] = array('#type' => 'textfield',
1774
    '#title' => st('Username'),
1775
    '#maxlength' => USERNAME_MAX_LENGTH,
1776
    '#description' => st('Spaces are allowed; punctuation is not allowed except for periods, hyphens, and underscores.'),
1777
    '#required' => TRUE,
1778
    '#weight' => -10,
1779
    '#attributes' => array('class' => array('username')),
1780
  );
1781

    
1782
  $form['admin_account']['account']['mail'] = array('#type' => 'textfield',
1783
    '#title' => st('E-mail address'),
1784
    '#maxlength' => EMAIL_MAX_LENGTH,
1785
    '#required' => TRUE,
1786
    '#weight' => -5,
1787
  );
1788
  $form['admin_account']['account']['pass'] = array(
1789
    '#type' => 'password_confirm',
1790
    '#required' => TRUE,
1791
    '#size' => 25,
1792
    '#weight' => 0,
1793
  );
1794

    
1795
  $form['server_settings'] = array(
1796
    '#type' => 'fieldset',
1797
    '#title' => st('Server settings'),
1798
    '#collapsible' => FALSE,
1799
  );
1800

    
1801
  $countries = country_get_list();
1802
  $form['server_settings']['site_default_country'] = array(
1803
    '#type' => 'select',
1804
    '#title' => st('Default country'),
1805
    '#empty_value' => '',
1806
    '#default_value' => variable_get('site_default_country', NULL),
1807
    '#options' => $countries,
1808
    '#description' => st('Select the default country for the site.'),
1809
    '#weight' => 0,
1810
  );
1811

    
1812
  $form['server_settings']['date_default_timezone'] = array(
1813
    '#type' => 'select',
1814
    '#title' => st('Default time zone'),
1815
    '#default_value' => date_default_timezone_get(),
1816
    '#options' => system_time_zones(),
1817
    '#description' => st('By default, dates in this site will be displayed in the chosen time zone.'),
1818
    '#weight' => 5,
1819
    '#attributes' => array('class' => array('timezone-detect')),
1820
  );
1821

    
1822
  $form['server_settings']['clean_url'] = array(
1823
    '#type' => 'hidden',
1824
    '#default_value' => 0,
1825
    '#attributes' => array('id' => 'edit-clean-url', 'class' => array('install')),
1826
  );
1827

    
1828
  $form['update_notifications'] = array(
1829
    '#type' => 'fieldset',
1830
    '#title' => st('Update notifications'),
1831
    '#collapsible' => FALSE,
1832
  );
1833
  $form['update_notifications']['update_status_module'] = array(
1834
    '#type' => 'checkboxes',
1835
    '#options' => array(
1836
      1 => st('Check for updates automatically'),
1837
      2 => st('Receive e-mail notifications'),
1838
    ),
1839
    '#default_value' => array(1, 2),
1840
    '#description' => st('The system will notify you when updates and important security releases are available for installed components. Anonymous information about your site is sent to <a href="@drupal">Drupal.org</a>.', array('@drupal' => 'http://drupal.org')),
1841
    '#weight' => 15,
1842
  );
1843

    
1844
  $form['actions'] = array('#type' => 'actions');
1845
  $form['actions']['submit'] = array(
1846
    '#type' => 'submit',
1847
    '#value' => st('Save and continue'),
1848
    '#weight' => 15,
1849
  );
1850

    
1851
  return $form;
1852
}
1853

    
1854
/**
1855
 * Form validation handler for install_configure_form().
1856
 *
1857
 * @see install_configure_form_submit()
1858
 */
1859
function install_configure_form_validate($form, &$form_state) {
1860
  if ($error = user_validate_name($form_state['values']['account']['name'])) {
1861
    form_error($form['admin_account']['account']['name'], $error);
1862
  }
1863
  if ($error = user_validate_mail($form_state['values']['account']['mail'])) {
1864
    form_error($form['admin_account']['account']['mail'], $error);
1865
  }
1866
  if ($error = user_validate_mail($form_state['values']['site_mail'])) {
1867
    form_error($form['site_information']['site_mail'], $error);
1868
  }
1869
}
1870

    
1871
/**
1872
 * Form submission handler for install_configure_form().
1873
 *
1874
 * @see install_configure_form_validate()
1875
 */
1876
function install_configure_form_submit($form, &$form_state) {
1877
  global $user;
1878

    
1879
  variable_set('site_name', $form_state['values']['site_name']);
1880
  variable_set('site_mail', $form_state['values']['site_mail']);
1881
  variable_set('date_default_timezone', $form_state['values']['date_default_timezone']);
1882
  variable_set('site_default_country', $form_state['values']['site_default_country']);
1883

    
1884
  // Enable update.module if this option was selected.
1885
  if ($form_state['values']['update_status_module'][1]) {
1886
    module_enable(array('update'), FALSE);
1887

    
1888
    // Add the site maintenance account's email address to the list of
1889
    // addresses to be notified when updates are available, if selected.
1890
    if ($form_state['values']['update_status_module'][2]) {
1891
      variable_set('update_notify_emails', array($form_state['values']['account']['mail']));
1892
    }
1893
  }
1894

    
1895
  // We precreated user 1 with placeholder values. Let's save the real values.
1896
  $account = user_load(1);
1897
  $merge_data = array('init' => $form_state['values']['account']['mail'], 'roles' => !empty($account->roles) ? $account->roles : array(), 'status' => 1, 'timezone' => $form_state['values']['date_default_timezone']);
1898
  user_save($account, array_merge($form_state['values']['account'], $merge_data));
1899
  // Load global $user and perform final login tasks.
1900
  $user = user_load(1);
1901
  user_login_finalize();
1902

    
1903
  if (isset($form_state['values']['clean_url'])) {
1904
    variable_set('clean_url', $form_state['values']['clean_url']);
1905
  }
1906

    
1907
  // Record when this install ran.
1908
  variable_set('install_time', $_SERVER['REQUEST_TIME']);
1909
}