install.core.inc 78.8 KB
Newer Older
1
2
<?php

3
4
use Drupal\Core\Database\Database;
use Drupal\Core\Database\Install\TaskException;
5

6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * @file
 * API functions for installing Drupal.
 */

/**
 * Global flag to indicate that a task should not be run during the current
 * installation request.
 *
 * This can be used to skip running an installation task when certain
 * conditions are met, even though the task may still show on the list of
 * installation tasks presented to the user. For example, the Drupal installer
 * uses this flag to skip over the database configuration form when valid
 * database connection information is already available from settings.php. It
 * also uses this flag to skip language import tasks when the installation is
 * being performed in English.
 */
23
const INSTALL_TASK_SKIP = 1;
24
25
26
27
28
29
30

/**
 * Global flag to indicate that a task should be run on each installation
 * request that reaches it.
 *
 * This is primarily used by the Drupal installer for bootstrap-related tasks.
 */
31
const INSTALL_TASK_RUN_IF_REACHED = 2;
32
33
34
35
36
37
38
39
40
41
42
43
44

/**
 * Global flag to indicate that a task should be run on each installation
 * request that reaches it, until the database is set up and we are able to
 * record the fact that it already ran.
 *
 * This is the default method for running tasks and should be used for most
 * tasks that occur after the database is set up; these tasks will then run
 * once and be marked complete once they are successfully finished. For
 * example, the Drupal installer uses this flag for the batch installation of
 * modules on the new site, and also for the configuration form that collects
 * basic site information and sets up the site maintenance account.
 */
45
const INSTALL_TASK_RUN_IF_NOT_COMPLETED = 3;
46
47

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

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

/**
 * Begin an installation request, modifying the installation state as needed.
 *
 * This function performs commands that must run at the beginning of every page
 * request. It throws an exception if the installation should not proceed.
 *
 * @param $install_state
 *   An array of information about the current installation state. This is
 *   modified with information gleaned from the beginning of the page request.
 */
function install_begin_request(&$install_state) {
216
217
218
219
220
221
222
  // Add any installation parameters passed in via the URL.
  $install_state['parameters'] += $_GET;

  // Validate certain core settings that are used throughout the installation.
  if (!empty($install_state['parameters']['profile'])) {
    $install_state['parameters']['profile'] = preg_replace('/[^a-zA-Z_0-9]/', '', $install_state['parameters']['profile']);
  }
223
224
  if (!empty($install_state['parameters']['langcode'])) {
    $install_state['parameters']['langcode'] = preg_replace('/[^a-zA-Z_0-9\-]/', '', $install_state['parameters']['langcode']);
225
226
  }

227
  // Allow command line scripts to override server variables used by Drupal.
228
  require_once DRUPAL_ROOT . '/core/includes/bootstrap.inc';
229
230
231

  // Ensure that the class loader is available so that we can leverage classes
  // as part of the install routine.
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
  $loader = drupal_classloader();

  // Register explicit vendor namespaces.
  $loader->registerNamespaces(array(
    // All Symfony-borrowed code lives in /core/includes/Symfony.
    'Symfony' => DRUPAL_ROOT . '/core/vendor',
  ));
  // Register the Drupal namespace for classes in core as a fallback.
  // This allows to register additional namespaces within the Drupal namespace
  // (e.g., for modules) and avoids an additional file_exists() on the Drupal
  // core namespace, since the class loader can already determine the best
  // namespace match based on a string comparison. It further allows modules to
  // register/overload namespaces in Drupal core.
  $loader->registerNamespaceFallbacks(array(
    // All Drupal-namespaced code in core lives in /core/includes/Drupal.
    'Drupal' => DRUPAL_ROOT . '/core/lib',
  ));
249

250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
  if (!$install_state['interactive']) {
    drupal_override_server_variables($install_state['server']);
  }

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

  drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION);

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

267
268
269
270
  require_once DRUPAL_ROOT . '/core/modules/system/system.install';
  require_once DRUPAL_ROOT . '/core/includes/common.inc';
  require_once DRUPAL_ROOT . '/core/includes/file.inc';
  require_once DRUPAL_ROOT . '/core/includes/install.inc';
271
  require_once DRUPAL_ROOT . '/core/includes/schema.inc';
272
  require_once DRUPAL_ROOT . '/' . variable_get('path_inc', 'core/includes/path.inc');
273
274

  // Load module basics (needed for hook invokes).
275
276
  include_once DRUPAL_ROOT . '/core/includes/module.inc';
  include_once DRUPAL_ROOT . '/core/includes/session.inc';
277
278
279
280

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

281
282
283
284
  require_once DRUPAL_ROOT . '/core/includes/ajax.inc';
  $module_list['system']['filename'] = 'core/modules/system/system.module';
  $module_list['entity']['filename'] = 'core/modules/entity/entity.module';
  $module_list['user']['filename']   = 'core/modules/user/user.module';
285
286
  module_list(TRUE, FALSE, FALSE, $module_list);
  drupal_load('module', 'system');
287
  drupal_load('module', 'entity');
288
289
290
291
292
293
294
295
296
297
298
  drupal_load('module', 'user');

  // Load the cache infrastructure using a "fake" cache implementation that
  // does not attempt to write to the database. We need this during the initial
  // part of the installer because the database is not available yet. We
  // continue to use it even when the database does become available, in order
  // to preserve consistency between interactive and command-line installations
  // (the latter complete in one page request and therefore are forced to
  // continue using the cache implementation they started with) and also
  // because any data put in the cache during the installer is inherently
  // suspect, due to the fact that Drupal is not fully set up yet.
299
  require_once DRUPAL_ROOT . '/core/includes/cache.inc';
300
  $conf['cache_default_class'] = 'Drupal\Core\Cache\InstallBackend';
301

302
303
304
305
306
307
308
309
310
311
  // The install process cannot use the database lock backend since the database
  // is not fully up, so we use a null backend implementation durting the
  // installation process. This will also speed up the installation process.
  // The site being installed will use the real lock backend when doing AJAX
  // requests but, except for a WSOD, there is no chance for a a lock to stall
  // (as opposed to the cache backend) so we can afford having a null
  // implementation here.
  require_once DRUPAL_ROOT . '/core/includes/lock.inc';
  $conf['lock_backend'] = 'Drupal\Core\Lock\NullLockBackend';

312
313
314
315
316
317
  // Prepare for themed output. We need to run this at the beginning of the
  // page request to avoid a different theme accidentally getting set. (We also
  // need to run it even in the case of command-line installations, to prevent
  // any code in the installer that happens to initialize the theme system from
  // accessing the database before it is set up yet.)
  drupal_maintenance_theme();
318
319
320
321
322
323
324

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

  if ($install_state['settings_verified']) {
    // Initialize the database system. Note that the connection
    // won't be initialized until it is actually requested.
325
    require_once DRUPAL_ROOT . '/core/includes/database.inc';
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345

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

    // Since previous versions of Drupal stored database connection information
    // in the 'db_url' variable, we should never let an installation proceed if
    // this variable is defined and the settings file was not verified above
    // (otherwise we risk installing over an existing site whose settings file
    // has not yet been updated).
    if (!empty($GLOBALS['db_url'])) {
      throw new Exception(install_already_done_error());
    }
  }

  // Modify the installation state as appropriate.
  $install_state['completed_task'] = $task;
  $install_state['database_tables_exist'] = !empty($task);
346
347
348

  // Add the list of available profiles to the installation state.
  $install_state['profiles'] += install_find_profiles();
349
350
351
}

/**
352
 * Runs all tasks for the current installation request.
353
354
355
356
357
358
359
360
361
 *
 * In the case of an interactive installation, all tasks will be attempted
 * until one is reached that has output which needs to be displayed to the
 * user, or until a page redirect is required. Otherwise, tasks will be
 * attempted until the installation is finished.
 *
 * @param $install_state
 *   An array of information about the current installation state. This is
 *   passed along to each task, so it can be modified if necessary.
362
 *
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
 * @return
 *   HTML output from the last completed task.
 */
function install_run_tasks(&$install_state) {
  do {
    // Obtain a list of tasks to perform. The list of tasks itself can be
    // dynamic (e.g., some might be defined by the installation profile,
    // which is not necessarily known until the earlier tasks have run),
    // so we regenerate the remaining tasks based on the installation state,
    // each time through the loop.
    $tasks_to_perform = install_tasks_to_perform($install_state);
    // Run the first task on the list.
    reset($tasks_to_perform);
    $task_name = key($tasks_to_perform);
    $task = array_shift($tasks_to_perform);
    $install_state['active_task'] = $task_name;
    $original_parameters = $install_state['parameters'];
    $output = install_run_task($task, $install_state);
    $install_state['parameters_changed'] = ($install_state['parameters'] != $original_parameters);
    // Store this task as having been performed during the current request,
    // and save it to the database as completed, if we need to and if the
    // database is in a state that allows us to do so. Also mark the
    // installation as 'done' when we have run out of tasks.
    if (!$install_state['task_not_complete']) {
      $install_state['tasks_performed'][] = $task_name;
      $install_state['installation_finished'] = empty($tasks_to_perform);
      if ($install_state['database_tables_exist'] && ($task['run'] == INSTALL_TASK_RUN_IF_NOT_COMPLETED || $install_state['installation_finished'])) {
        variable_set('install_task', $install_state['installation_finished'] ? 'done' : $task_name);
      }
    }
    // Stop when there are no tasks left. In the case of an interactive
    // installation, also stop if we have some output to send to the browser,
    // the URL parameters have changed, or an end to the page request was
    // specifically called for.
    $finished = empty($tasks_to_perform) || ($install_state['interactive'] && (isset($output) || $install_state['parameters_changed'] || $install_state['stop_page_request']));
  } while (!$finished);
  return $output;
}

/**
403
 * Runs an individual installation task.
404
405
406
407
408
409
 *
 * @param $task
 *   An array of information about the task to be run.
 * @param $install_state
 *   An array of information about the current installation state. This is
 *   passed in by reference so that it can be modified by the task.
410
 *
411
412
413
414
415
416
417
 * @return
 *   The output of the task function, if there is any.
 */
function install_run_task($task, &$install_state) {
  $function = $task['function'];

  if ($task['type'] == 'form') {
418
    require_once DRUPAL_ROOT . '/core/includes/form.inc';
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
    if ($install_state['interactive']) {
      // For interactive forms, build the form and ensure that it will not
      // redirect, since the installer handles its own redirection only after
      // marking the form submission task complete.
      $form_state = array(
        // We need to pass $install_state by reference in order for forms to
        // modify it, since the form API will use it in call_user_func_array(),
        // which requires that referenced variables be passed explicitly.
        'build_info' => array('args' => array(&$install_state)),
        'no_redirect' => TRUE,
      );
      $form = drupal_build_form($function, $form_state);
      // If a successful form submission did not occur, the form needs to be
      // rendered, which means the task is not complete yet.
      if (empty($form_state['executed'])) {
        $install_state['task_not_complete'] = TRUE;
        return drupal_render($form);
      }
      // Otherwise, return nothing so the next task will run in the same
      // request.
      return;
    }
    else {
      // For non-interactive forms, submit the form programmatically with the
      // values taken from the installation state. Throw an exception if any
      // errors were encountered.
445
446
447
448
449
450
451
452
      $form_state = array(
        'values' => !empty($install_state['forms'][$function]) ? $install_state['forms'][$function] : array(),
        // We need to pass $install_state by reference in order for forms to
        // modify it, since the form API will use it in call_user_func_array(),
        // which requires that referenced variables be passed explicitly.
        'build_info' => array('args' => array(&$install_state)),
      );
      drupal_form_submit($function, $form_state);
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
      $errors = form_get_errors();
      if (!empty($errors)) {
        throw new Exception(implode("\n", $errors));
      }
    }
  }

  elseif ($task['type'] == 'batch') {
    // Start a new batch based on the task function, if one is not running
    // already.
    $current_batch = variable_get('install_current_batch');
    if (!$install_state['interactive'] || !$current_batch) {
      $batch = $function($install_state);
      if (empty($batch)) {
        // If the task did some processing and decided no batch was necessary,
        // there is nothing more to do here.
        return;
      }
      batch_set($batch);
      // For interactive batches, we need to store the fact that this batch
      // task is currently running. Otherwise, we need to make sure the batch
      // will complete in one page request.
      if ($install_state['interactive']) {
        variable_set('install_current_batch', $function);
      }
      else {
        $batch =& batch_get();
        $batch['progressive'] = FALSE;
      }
      // Process the batch. For progressive batches, this will redirect.
      // Otherwise, the batch will complete.
      batch_process(install_redirect_url($install_state), install_full_redirect_url($install_state));
    }
    // If we are in the middle of processing this batch, keep sending back
    // any output from the batch process, until the task is complete.
    elseif ($current_batch == $function) {
489
      include_once DRUPAL_ROOT . '/core/includes/batch.inc';
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
      $output = _batch_page();
      // The task is complete when we try to access the batch page and receive
      // FALSE in return, since this means we are at a URL where we are no
      // longer requesting a batch ID.
      if ($output === FALSE) {
        // Return nothing so the next task will run in the same request.
        variable_del('install_current_batch');
        return;
      }
      else {
        // We need to force the page request to end if the task is not
        // complete, since the batch API sometimes prints JSON output
        // rather than returning a themed page.
        $install_state['task_not_complete'] = $install_state['stop_page_request'] = TRUE;
        return $output;
      }
    }
  }

  else {
    // For normal tasks, just return the function result, whatever it is.
    return $function($install_state);
  }
}

/**
516
 * Returns a list of tasks to perform during the current installation request.
517
518
519
520
521
522
523
 *
 * Note that the list of tasks can change based on the installation state as
 * the page request evolves (for example, if an installation profile hasn't
 * been selected yet, we don't yet know which profile tasks need to be run).
 *
 * @param $install_state
 *   An array of information about the current installation state.
524
 *
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
 * @return
 *   A list of tasks to be performed, with associated metadata.
 */
function install_tasks_to_perform($install_state) {
  // Start with a list of all currently available tasks.
  $tasks = install_tasks($install_state);
  foreach ($tasks as $name => $task) {
    // Remove any tasks that were already performed or that never should run.
    // Also, if we started this page request with an indication of the last
    // task that was completed, skip that task and all those that come before
    // it, unless they are marked as always needing to run.
    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)) {
      unset($tasks[$name]);
    }
    if (!empty($install_state['completed_task']) && $name == $install_state['completed_task']) {
      $completed_task_found = TRUE;
    }
  }
  return $tasks;
}

/**
547
 * Returns a list of all tasks the installer currently knows about.
548
549
550
551
552
553
554
555
556
 *
 * This function will return tasks regardless of whether or not they are
 * intended to run on the current page request. However, the list can change
 * based on the installation state (for example, if an installation profile
 * hasn't been selected yet, we don't yet know which profile tasks will be
 * available).
 *
 * @param $install_state
 *   An array of information about the current installation state.
557
 *
558
559
560
561
562
 * @return
 *   A list of tasks, with associated metadata.
 */
function install_tasks($install_state) {
  // Determine whether translation import tasks will need to be performed.
563
  $needs_translations = count($install_state['translations']) > 1 && !empty($install_state['parameters']['langcode']) && $install_state['parameters']['langcode'] != 'en';
564

565
566
  // Start with the core installation tasks that run before handing control
  // to the install profile.
567
  $tasks = array(
568
569
570
571
    'install_select_language' => array(
      'display_name' => st('Choose language'),
      'run' => INSTALL_TASK_RUN_IF_REACHED,
    ),
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
    'install_select_profile' => array(
      'display_name' => st('Choose profile'),
      'display' => count($install_state['profiles']) != 1,
      'run' => INSTALL_TASK_RUN_IF_REACHED,
    ),
    'install_load_profile' => array(
      'run' => INSTALL_TASK_RUN_IF_REACHED,
    ),
    'install_verify_requirements' => array(
      'display_name' => st('Verify requirements'),
    ),
    'install_settings_form' => array(
      'display_name' => st('Set up database'),
      'type' => 'form',
      'run' => $install_state['settings_verified'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
    ),
    'install_system_module' => array(
    ),
    'install_bootstrap_full' => array(
      'run' => INSTALL_TASK_RUN_IF_REACHED,
    ),
    'install_profile_modules' => array(
      'display_name' => count($install_state['profiles']) == 1 ? st('Install site') : st('Install profile'),
      'type' => 'batch',
    ),
597
    'install_import_translations' => array(
598
599
600
601
602
603
604
605
606
607
608
609
610
      'display_name' => st('Set up translations'),
      'display' => $needs_translations,
      'type' => 'batch',
      'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
    ),
    'install_configure_form' => array(
      'display_name' => st('Configure site'),
      'type' => 'form',
    ),
  );

  // Now add any tasks defined by the installation profile.
  if (!empty($install_state['parameters']['profile'])) {
611
612
613
614
615
616
    // Load the profile install file, because it is not always loaded when
    // hook_install_tasks() is invoked (e.g. batch processing).
    $profile_install_file = DRUPAL_ROOT . '/profiles/' . $install_state['parameters']['profile'] . '/' . $install_state['parameters']['profile'] . '.install';
    if (file_exists($profile_install_file)) {
      include_once $profile_install_file;
    }
617
618
619
620
621
622
623
624
625
626
627
    $function = $install_state['parameters']['profile'] . '_install_tasks';
    if (function_exists($function)) {
      $result = $function($install_state);
      if (is_array($result)) {
        $tasks += $result;
      }
    }
  }

  // Finish by adding the remaining core tasks.
  $tasks += array(
628
    'install_import_translations_remaining' => array(
629
630
631
632
633
634
635
636
637
638
639
640
641
      'display_name' => st('Finish translations'),
      'display' => $needs_translations,
      'type' => 'batch',
      'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
    ),
    'install_finished' => array(
      'display_name' => st('Finished'),
    ),
  );

  // Allow the installation profile to modify the full list of tasks.
  if (!empty($install_state['parameters']['profile'])) {
    $profile_file = DRUPAL_ROOT . '/profiles/' . $install_state['parameters']['profile'] . '/' . $install_state['parameters']['profile'] . '.profile';
642
    if (file_exists($profile_file)) {
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
      include_once $profile_file;
      $function = $install_state['parameters']['profile'] . '_install_tasks_alter';
      if (function_exists($function)) {
        $function($tasks, $install_state);
      }
    }
  }

  // Fill in default parameters for each task before returning the list.
  foreach ($tasks as $task_name => &$task) {
    $task += array(
      'display_name' => NULL,
      'display' => !empty($task['display_name']),
      'type' => 'normal',
      'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
      'function' => $task_name,
    );
  }
  return $tasks;
}

/**
665
 * Returns a list of tasks that should be displayed to the end user.
666
667
668
669
670
671
 *
 * The output of this function is a list suitable for sending to
 * theme_task_list().
 *
 * @param $install_state
 *   An array of information about the current installation state.
672
 *
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
 * @return
 *   A list of tasks, with keys equal to the machine-readable task name and
 *   values equal to the name that should be displayed.
 *
 * @see theme_task_list()
 */
function install_tasks_to_display($install_state) {
  $displayed_tasks = array();
  foreach (install_tasks($install_state) as $name => $task) {
    if ($task['display']) {
      $displayed_tasks[$name] = $task['display_name'];
    }
  }
  return $displayed_tasks;
}

/**
690
 * Returns the URL that should be redirected to during an installation request.
691
692
693
694
695
 *
 * The output of this function is suitable for sending to install_goto().
 *
 * @param $install_state
 *   An array of information about the current installation state.
696
 *
697
698
699
700
701
702
 * @return
 *   The URL to redirect to.
 *
 * @see install_full_redirect_url()
 */
function install_redirect_url($install_state) {
703
  return 'core/install.php?' . drupal_http_build_query($install_state['parameters']);
704
705
706
}

/**
707
 * Returns the complete URL redirected to during an installation request.
708
709
710
 *
 * @param $install_state
 *   An array of information about the current installation state.
711
 *
712
713
714
715
716
717
718
719
720
721
722
 * @return
 *   The complete URL to redirect to.
 *
 * @see install_redirect_url()
 */
function install_full_redirect_url($install_state) {
  global $base_url;
  return $base_url . '/' . install_redirect_url($install_state);
}

/**
723
 * Displays themed installer output and ends the page request.
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
 *
 * Installation tasks should use drupal_set_title() to set the desired page
 * title, but otherwise this function takes care of theming the overall page
 * output during every step of the installation.
 *
 * @param $output
 *   The content to display on the main part of the page.
 * @param $install_state
 *   An array of information about the current installation state.
 */
function install_display_output($output, $install_state) {
  drupal_page_header();
  // Only show the task list if there is an active task; otherwise, the page
  // request has ended before tasks have even been started, so there is nothing
  // meaningful to show.
  if (isset($install_state['active_task'])) {
    // Let the theming function know when every step of the installation has
    // been completed.
    $active_task = $install_state['installation_finished'] ? NULL : $install_state['active_task'];
    drupal_add_region_content('sidebar_first', theme('task_list', array('items' => install_tasks_to_display($install_state), 'active' => $active_task)));
  }
745
  print theme('install_page', array('content' => $output));
746
747
748
749
750
751
752
753
  exit;
}

/**
 * Installation task; verify the requirements for installing Drupal.
 *
 * @param $install_state
 *   An array of information about the current installation state.
754
 *
755
756
 * @return
 *   A themed status report, or an exception if there are requirement errors.
757
758
759
760
 *   If there are only requirement warnings, a themed status report is shown
 *   initially, but the user is allowed to bypass it by providing 'continue=1'
 *   in the URL. Otherwise, no output is returned, so that the next task can be
 *   run in the same page request.
761
762
763
764
765
766
767
768
769
770
771
 */
function install_verify_requirements(&$install_state) {
  // Check the installation requirements for Drupal and this profile.
  $requirements = install_check_requirements($install_state);

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

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

772
773
774
775
  // If there are errors, always display them. If there are only warnings, skip
  // them if the user has provided a URL parameter acknowledging the warnings
  // and indicating a desire to continue anyway. See drupal_requirements_url().
  if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING && empty($install_state['parameters']['continue']))) {
776
777
778
    if ($install_state['interactive']) {
      drupal_set_title(st('Requirements problem'));
      $status_report = theme('status_report', array('requirements' => $requirements));
779
      $status_report .= st('Check the messages and <a href="!url">try again</a>.', array('!url' => check_url(drupal_requirements_url($severity))));
780
781
782
      return $status_report;
    }
    else {
783
      // Throw an exception showing any unmet requirements.
784
785
      $failures = array();
      foreach ($requirements as $requirement) {
786
787
788
        // Skip warnings altogether for non-interactive installations; these
        // proceed in a single request so there is no good opportunity (and no
        // good method) to warn the user anyway.
789
790
791
792
        if (isset($requirement['severity']) && $requirement['severity'] == REQUIREMENT_ERROR) {
          $failures[] = $requirement['title'] . ': ' . $requirement['value'] . "\n\n" . $requirement['description'];
        }
      }
793
794
795
      if (!empty($failures)) {
        throw new Exception(implode("\n\n", $failures));
      }
796
797
798
799
800
801
802
803
804
805
806
807
808
    }
  }
}

/**
 * Installation task; install the Drupal system module.
 *
 * @param $install_state
 *   An array of information about the current installation state.
 */
function install_system_module(&$install_state) {
  // Install system.module.
  drupal_install_system();
809
810
811
812
813

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

814
  // Save the list of other modules to install for the upcoming tasks.
815
  // variable_set() can be used now that system.module is installed.
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
  $modules = $install_state['profile_info']['dependencies'];

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

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

/**
 * Verify and return the last installation task that was completed.
 *
 * @return
 *   The last completed task, if there is one. An exception is thrown if Drupal
 *   is already installed.
 */
function install_verify_completed_task() {
  try {
    if ($result = db_query("SELECT value FROM {variable} WHERE name = :name", array('name' => 'install_task'))) {
      $task = unserialize($result->fetchField());
    }
  }
  // Do not trigger an error if the database query fails, since the database
  // might not be set up yet.
  catch (Exception $e) {
  }
  if (isset($task)) {
    if ($task == 'done') {
      throw new Exception(install_already_done_error());
    }
    return $task;
  }
}

/**
852
 * Verifies the existing settings in settings.php.
853
854
 */
function install_verify_settings() {
855
  global $databases;
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873

  // Verify existing settings (if any).
  if (!empty($databases) && install_verify_pdo()) {
    $database = $databases['default']['default'];
    drupal_static_reset('conf_path');
    $settings_file = './' . conf_path(FALSE) . '/settings.php';
    $errors = install_database_errors($database, $settings_file);
    if (empty($errors)) {
      return TRUE;
    }
  }
  return FALSE;
}

/**
 * Verify PDO library.
 */
function install_verify_pdo() {
874
875
876
877
878
879
  // PDO was moved to PHP core in 5.2.0, but the old extension (targeting 5.0
  // and 5.1) is still available from PECL, and can still be built without
  // errors. To verify that the correct version is in use, we check the
  // PDO::ATTR_DEFAULT_FETCH_MODE constant, which is not available in the
  // PECL extension.
  return extension_loaded('pdo') && defined('PDO::ATTR_DEFAULT_FETCH_MODE');
880
881
882
883
884
885
886
887
888
}

/**
 * Installation task; define a form to configure and rewrite settings.php.
 *
 * @param $form_state
 *   An associative array containing the current state of the form.
 * @param $install_state
 *   An array of information about the current installation state.
889
 *
890
891
892
893
 * @return
 *   The form API definition for the database configuration form.
 */
function install_settings_form($form, &$form_state, &$install_state) {
894
  global $databases;
895
896
897
898
899
900
901
902
903
  $profile = $install_state['parameters']['profile'];

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

  drupal_set_title(st('Database configuration'));

904
  $drivers = drupal_get_database_types();
905
  $drivers_keys = array_keys($drivers);
906

907
908
909
910
  $form['driver'] = array(
    '#type' => 'radios',
    '#title' => st('Database type'),
    '#required' => TRUE,
911
    '#default_value' => !empty($database['driver']) ? $database['driver'] : current($drivers_keys),
912
913
914
915
    '#description' => st('The type of database your @drupal data will be stored in.', array('@drupal' => drupal_install_profile_distribution_name())),
  );
  if (count($drivers) == 1) {
    $form['driver']['#disabled'] = TRUE;
916
    $form['driver']['#description'] .= ' ' . st('Your PHP configuration only supports a single database type, so it has been automatically selected.');
917
918
  }

919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
  // Add driver specific configuration options.
  foreach ($drivers as $key => $driver) {
    $form['driver']['#options'][$key] = $driver->name();

    $form['settings'][$key] = $driver->getFormOptions($database);
    $form['settings'][$key]['#prefix'] = '<h2 class="js-hide">' . st('@driver_name settings', array('@driver_name' => $driver->name())) . '</h2>';
    $form['settings'][$key]['#type'] = 'container';
    $form['settings'][$key]['#tree'] = TRUE;
    $form['settings'][$key]['advanced_options']['#parents'] = array($key);
    $form['settings'][$key]['#states'] = array(
      'visible' => array(
        ':input[name=driver]' => array('value' => $key),
      )
    );
  }
934

935
  $form['actions'] = array('#type' => 'actions');
936
937
938
  $form['actions']['save'] = array(
    '#type' => 'submit',
    '#value' => st('Save and continue'),
939
940
941
942
943
    '#limit_validation_errors' => array(
      array('driver'),
      array(isset($form_state['input']['driver']) ? $form_state['input']['driver'] : current($drivers_keys)),
    ),
    '#submit' => array('install_settings_form_submit'),
944
945
946
947
  );

  $form['errors'] = array();
  $form['settings_file'] = array('#type' => 'value', '#value' => $settings_file);
948
949
950
951
952
953
954
955

  return $form;
}

/**
 * Form API validate for install_settings form.
 */
function install_settings_form_validate($form, &$form_state) {
956
957
958
959
  $driver = $form_state['values']['driver'];
  $database = $form_state['values'][$driver];
  $database['driver'] = $driver;

960
961
  // TODO: remove when PIFR will be updated to use 'db_prefix' instead of
  // 'prefix' in the database settings form.
962
963
  $database['prefix'] = $database['db_prefix'];
  unset($database['db_prefix']);
964

965
966
  $form_state['storage']['database'] = $database;
  $errors = install_database_errors($database, $form_state['values']['settings_file']);
967
968
969
970
971
972
  foreach ($errors as $name => $message) {
    form_set_error($name, $message);
  }
}

/**
973
 * Checks a database connection and returns any errors.
974
975
976
977
978
 */
function install_database_errors($database, $settings_file) {
  global $databases;
  $errors = array();

979
  // Check database type.
980
  $database_types = drupal_get_database_types();
981
982
  $driver = $database['driver'];
  if (!isset($database_types[$driver])) {
983
    $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));
984
985
  }
  else {
986
987
988
    // Run driver specific validation
    $errors += $database_types[$driver]->validateDatabaseSettings($database);

989
    // Run tasks associated with the database type. Any errors are caught in the
990
    // calling function.
991
992
993
994
995
996
    $databases['default']['default'] = $database;
    // Just changing the global doesn't get the new information processed.
    // We tell tell the Database class to re-parse $databases.
    Database::parseConnectionInfo();

    try {
997
      db_run_tasks($driver);
998
    }
999
    catch (TaskException $e) {
1000
1001
1002
      // These are generic errors, so we do not have any specific key of the
      // database connection array to attach them to; therefore, we just put
      // them in the error array with standard numeric keys.
1003
      $errors[$driver . '][0'] = $e->getMessage();
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
    }
  }
  return $errors;
}

/**
 * Form API submit for install_settings form.
 */
function install_settings_form_submit($form, &$form_state) {
  global $install_state;

1015
  // Update global settings array and save.
1016
  $settings['databases'] = array(
1017
    'value'    => array('default' => array('default' => $form_state['storage']['database'])),
1018
1019
1020
    'required' => TRUE,
  );
  $settings['drupal_hash_salt'] = array(
1021
    'value'    => drupal_hash_base64(drupal_random_bytes(55)),
1022
1023
    'required' => TRUE,
  );
1024

1025
  $settings['config_signature_key'] = array(
1026
1027
1028
    'value'    => drupal_hash_base64(drupal_random_bytes(55)),
    'required' => TRUE,
  );
1029

1030
1031
1032
  // This duplicates drupal_get_token() because that function can't work yet.
  // Wondering if it makes sense to move this later in the process, but its
  // nice having all the settings stuff here.
gdd's avatar
gdd committed
1033
1034
1035
1036
1037
  //
  // @todo This is actually causing a bug right now, because you can install
  // without hitting install_settings_form_submit() if your settings.php
  // already has the db stuff in it, and right now in that case your
  // config directory never gets created. So this needs to be moved elsewhere.
1038
1039
  $settings['config_directory_name'] = array(
    'value'     => 'config_' . drupal_hmac_base64('', session_id() . $settings['config_signature_key']['value'] . $settings['drupal_hash_salt']['value']),
1040
1041
    'required'  => TRUE,
  );
1042

1043
  drupal_rewrite_settings($settings);
1044
  // Actually create the config directory named above.
1045
  $config_path = conf_path() . '/files/' . $settings['config_directory_name']['value'];
1046
1047
1048
  if (!file_prepare_directory($config_path, FILE_CREATE_DIRECTORY)) {
    // How best to handle errors here?
  };
gdd's avatar
gdd committed
1049

1050
1051
1052
  // Write out a .htaccess file that will protect the config directory from
  // prying eyes.
  file_save_htaccess($config_path, TRUE);
gdd's avatar
gdd committed
1053

1054
1055
1056
1057
1058
1059
1060
1061
1062
  // Indicate that the settings file has been verified, and check the database
  // for the last completed task, now that we have a valid connection. This
  // last step is important since we want to trigger an error if the new
  // database already has Drupal installed.
  $install_state['settings_verified'] = TRUE;
  $install_state['completed_task'] = install_verify_completed_task();
}

/**
1063
 * Finds all .profile files.
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
 */
function install_find_profiles() {
  return file_scan_directory('./profiles', '/\.profile$/', array('key' => 'name'));
}

/**
 * Installation task; select which profile to install.
 *
 * @param $install_state
 *   An array of information about the current installation state. The chosen
 *   profile will be added here, if it was not already selected previously, as
 *   will a list of all available profiles.
1076
 *
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
 * @return
 *   For interactive installations, a form allowing the profile to be selected,
 *   if the user has a choice that needs to be made. Otherwise, an exception is
 *   thrown if a profile cannot be chosen automatically.
 */
function install_select_profile(&$install_state) {
  if (empty($install_state['parameters']['profile'])) {
    // Try to find a profile.
    $profile = _install_select_profile($install_state['profiles']);
    if (empty($profile)) {
      // We still don't have a profile, so display a form for selecting one.
      // Only do this in the case of interactive installations, since this is
      // not a real form with submit handlers (the database isn't even set up
      // yet), rather just a convenience method for setting parameters in the
      // URL.
      if ($install_state['interactive']) {
1093
        include_once DRUPAL_ROOT . '/core/includes/form.inc';
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
        drupal_set_title(st('Select an installation profile'));
        $form = drupal_get_form('install_select_profile_form', $install_state['profiles']);
        return drupal_render($form);
      }
      else {
        throw new Exception(install_no_profile_error());
      }
    }
    else {
      $install_state['parameters']['profile'] = $profile;
    }
  }
}

/**
 * Helper function for automatically selecting an installation profile from a
 * list or from a selection passed in via $_POST.
 */
function _install_select_profile($profiles) {
  if (sizeof($profiles) == 0) {
    throw new Exception(install_no_profile_error());
  }
  // Don't need to choose profile if only one available.
  if (sizeof($profiles) == 1) {
    $profile = array_pop($profiles);
    // TODO: is this right?
1120
    require_once DRUPAL_ROOT . '/' . $profile->uri;
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
    return $profile->name;
  }
  else {
    foreach ($profiles as $profile) {
      if (!empty($_POST['profile']) && ($_POST['profile'] == $profile->name)) {
        return $profile->name;
      }
    }
  }
}

/**
 * Form API array definition for the profile selection form.
 *
 * @param $form_state
 *   Array of metadata about state of form processing.
 * @param $profile_files
 *   Array of .profile files, as returned from file_scan_directory().
 */
function install_select_profile_form($form, &$form_state, $profile_files) {
  $profiles = array();
  $names = array();

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

    $details = install_profile_info($profile->name);
1149
1150
1151
1152
1153
    // Don't show hidden profiles. This is used by to hide the testing profile,
    // which only exists to speed up test runs.
    if ($details['hidden'] === TRUE) {
      continue;
    }
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
    $profiles[$profile->name] = $details;

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

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

  foreach ($names as $profile => $name) {
1180
1181
1182
    // The profile name and description are extracted for translation from the
    // .info file, so we can use st() on them even though they are dynamic data
    // at this point.
1183
1184
1185
1186
    $form['profile'][$name] = array(
      '#type' => 'radio',
      '#value' => 'standard',
      '#return_value' => $profile,
1187
1188
      '#title' => st($name),
      '#description' => isset($profiles[$profile]['description']) ? st($profiles[$profile]['description']) : '',
1189
1190
1191
      '#parents' => array('profile'),
    );
  }
1192
  $form['actions'] = array('#type' => 'actions');
1193
1194
1195
1196
1197
1198
1199
1200
  $form['actions']['submit'] =  array(
    '#type' => 'submit',
    '#value' => st('Save and continue'),
  );
  return $form;
}

/**
1201
 * Find all .po files useful for the installer.
1202
 */
1203
1204
function install_find_translations() {
  $files = install_find_translation_files();
1205
1206
1207
1208
1209
  // English does not need a translation file.
  array_unshift($files, (object) array('name' => 'en'));
  foreach ($files as $key => $file) {
    // Strip off the file name component before the language code.
    $files[$key]->langcode = preg_replace('!^(.+\.)?([^\.]+)$!', '\2', $file->name);
1210
    // Language codes cannot exceed 12 characters to fit into the {language}
1211
    // table.
1212
1213
    if (strlen($files[$key]->langcode) > 12) {
      unset($files[$key]);
1214
    }
1215
  }
1216
1217
1218
1219
1220
  return $files;
}

/**
 * Find installer translations either for a specific langcode or all languages.
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
 *
 * @param $langcode
 *   (optional) The language code corresponding to the language for which we
 *   want to find translation files. If omitted, information on all available
 *   files will be returned.
 *
 * @return
 *   An associative array of file information objects keyed by file URIs as
 *   returned by file_scan_directory().
 *
 * @see file_scan_directory()
1232
 */
1233
function install_find_translation_files($langcode = NULL) {
1234
  $directory = variable_get('locale_translate_file_directory', conf_path() . '/files/translations');
1235
  $files = file_scan_directory($directory, '!install\.' . (!empty($langcode) ? preg_quote($langcode, '!') : '[^\.]+') . '\.po$!', array('recurse' => FALSE));
1236
  return $files;
1237
1238
1239
}

/**
1240
 * Installation task; select which language to use.
1241
1242
1243
 *
 * @param $install_state
 *   An array of information about the current installation state. The chosen
1244
1245
 *   langcode will be added here, if it was not already selected previously, as
 *   will a list of all available languages.
1246
 *
1247
1248
 * @return
 *   For interactive installations, a form or other page output allowing the
1249
1250
1251
 *   language to be selected or providing information about language selection,
 *   if a language has not been chosen. Otherwise, an exception is thrown if a
 *   language cannot be chosen automatically.
1252
 */
1253
1254
1255
1256
1257
1258
1259
1260
1261
function install_select_language(&$install_state) {
  // Find all available translations.
  $files = install_find_translations();
  $install_state['translations'] += $files;

  if (!empty($_POST['langcode'])) {
    foreach ($files as $file) {
      if ($_POST['langcode'] == $file->langcode) {
        $install_state['parameters']['langcode'] = $file->langcode;
1262
1263
1264
1265
1266
        return;
      }
    }
  }

1267
  if (empty($install_state['parameters']['langcode'])) {
1268
1269
    // If only the built-in (English) language is available, and we are
    // performing an interactive installation, inform the user that the
1270
    // installer can be translated. Otherwise we assume the user knows what he
1271
    // is doing.
1272
    if (count($files) == 1) {
1273
      if ($install_state['interactive']) {
1274
1275
        $directory = variable_get('locale_translate_file_directory', conf_path() . '/files/translations');

1276
        drupal_set_title(st('Choose language'));
1277
        if (!empty($install_state['parameters']['translate'])) {
1278
1279
1280
          $output = '<p>Follow these steps to translate Drupal into your language:</p>';
          $output .= '<ol>';
          $output .= '<li>Download a translation from the <a href="http://localize.drupal.org/download" target="_blank">translation server</a>.</li>';
1281
          $output .= '<li>Place it into the following directory:<pre>' . $directory . '</pre></li>';
1282
1283
1284
1285
          $output .= '</ol>';
          $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>';
          $output .= '<p>How should the installation continue?</p>';
          $output .= '<ul>';
1286
1287
          $output .= '<li><a href="' . check_url(drupal_current_script_url(array('translate' => NULL))) . '">Reload the language selection page after adding translations</a></li>';
          $output .= '<li><a href="' . check_url(drupal_current_script_url(array('langcode' => 'en', 'translate' => NULL))) . '">Continue installation in English</a></li>';
1288
          $output .= '</ul>';
1289
1290
        }
        else {
1291
          include_once DRUPAL_ROOT . '/core/includes/form.inc';
1292
          $elements = drupal_get_form('install_select_language_form', $files);
1293
          $output = drupal_render($elements);
1294
1295
1296
        }
        return $output;
      }
1297
1298
      // One language, but not an interactive installation. Assume the user
      // knows what he is doing.
1299
1300
      $langcode = current($files);
      $install_state['parameters']['langcode'] = $file->langcode;
1301
1302
1303
      return;
    }
    else {
1304
      // We still don't have a langcode, so display a form for selecting one.
1305
1306
1307
1308
1309
1310
      // Only do this in the case of interactive installations, since this is
      // not a real form with submit handlers (the database isn't even set up
      // yet), rather just a convenience method for setting parameters in the
      // URL.
      if ($install_state['interactive']) {
        drupal_set_title(st('Choose language'));
1311
        include_once DRUPAL_ROOT . '/core/includes/form.inc';
1312
        $elements = drupal_get_form('install_select_language_form', $files);
1313
        return drupal_render($elements);
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
      }
      else {
        throw new Exception(st('Sorry, you must select a language to continue the installation.'));
      }
    }
  }
}

/**
 * Form API array definition for language selection.
 */
1325
function install_select_language_form($form, &$form_state, $files) {
1326
  include_once DRUPAL_ROOT . '/core/includes/standard.inc';
1327
  include_once DRUPAL_ROOT . '/core/modules/language/language.negotiation.inc';
1328
1329
1330
1331
1332
1333
1334
1335
1336

  $standard_languages = standard_language_list();
  $select_options = array();
  $languages = array();

  foreach ($files as $file) {
    if (isset($standard_languages[$file->langcode])) {
      // Build a list of select list options based on files we found.
      $select_options[$file->langcode] = $standard_languages[$file->langcode][1];
1337
    }
1338
    else {
1339
      // If the language was not found in standard.inc, display its langcode.
1340
1341
1342
1343
      $select_options[$file->langcode] = $file->langcode;
    }
    // Build a list of languages simulated for browser detection.
    $languages[$file->langcode] = (object) array(
1344
      'langcode' => $file->langcode,
1345
1346
    );
  }
1347

1348
  $browser_langcode = language_from_browser($languages);
1349
1350
1351
1352
1353
1354
1355
1356
1357
  $form['langcode'] = array(
    '#type' => 'select',
    '#options' => $select_options,
    // Use the browser detected language as default or English if nothing found.
    '#default_value' => !empty($browser_langcode) ? $browser_langcode : 'en',
    '#size' => min(count($select_options), 10),
  );

  if (count($files) == 1) {
1358
    $form['help'] = array(
1359
      '#markup' => '<p><a href="' . check_url(drupal_current_script_url(array('translate' => 'true'))) . '">' . st('Learn how to install Drupal in other languages') . '</a></p>',
1360
1361
    );
  }
1362
  $form['actions'] = array('#type' => 'actions');
1363
1364
1365
1366
1367
1368
1369
1370
  $form['actions']['submit'] =  array(
    '#type' => 'submit',
    '#value' => st('Save and continue'),
  );
  return $form;
}

/**
1371
 * Indicates that there are no profiles available.
1372
1373
1374
1375
1376
1377
1378
 */
function install_no_profile_error() {
  drupal_set_title(st('No profiles available'));
  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.');
}

/**
1379
 * Indicates that Drupal has already been installed.
1380
1381
1382
1383
1384
 */
function install_already_done_error() {
  global $base_url;

  drupal_set_title(st('Drupal already installed'));
1385
  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/core/update.php">update script</a>.</li><li>View your <a href="@base-url">existing site</a>.</li></ul>', array('@base-url' => $base_url));
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
}

/**
 * Installation task; load information about the chosen profile.
 *
 * @param $install_state
 *   An array of information about the current installation state. The loaded
 *   profile information will be added here, or an exception will be thrown if
 *   the profile cannot be loaded.
 */
function install_load_profile(&$install_state) {
  $profile_file = DRUPAL_ROOT . '/profiles/' . $install_state['parameters']['profile'] . '/' . $install_state['parameters']['profile'] . '.profile';
1398
  if (file_exists($profile_file)) {
1399
    include_once $profile_file;
1400
    $install_state['profile_info'] = install_profile_info($install_state['parameters']['profile'], $install_state['parameters']['langcode']);
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
  }
  else {
    throw new Exception(st('Sorry, the profile you have chosen cannot be loaded.'));
  }
}

/**
 * Installation task; perform a full bootstrap of Drupal.
 *
 * @param $install_state
 *   An array of information about the current installation state.
 */
function install_bootstrap_full(&$install_state) {
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
}

/**
 * Installation task; install required modules via a batch process.
 *
 * @param $install_state
 *   An array of information about the current installation state.
1422
 *
1423
1424
1425
1426
1427
1428
1429
 * @return
 *   The batch definition.
 */
function install_profile_modules(&$install_state) {
  $modules = variable_get('install_profile_modules', array());
  $files = system_rebuild_module_data();
  variable_del('install_profile_modules');
1430

1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
  // Always install required modules first. Respect the dependencies between
  // the modules.
  $required = array();
  $non_required = array();
  // Although the profile module is marked as required, it needs to go after
  // every dependency, including non-required ones. So clear its required
  // flag for now to allow it to install late.
  $files[$install_state['parameters']['profile']]->info['required'] = FALSE;
  // Add modules that other modules depend on.
  foreach ($modules as $module) {
    if ($files[$module]->requires) {
      $modules = array_merge($modules, array_keys($files[$module]->requires));
    }
  }
  $modules = array_unique($modules);
  foreach ($modules as $module) {
    if (!empty($files[$module]->info['required'])) {
      $required[$module] = $files[$module]->sort;
    }
    else {
      $non_required[$module] = $files[$module]->sort;
    }
1453
  }
1454
1455
  arsort($required);
  arsort($non_required);
1456

1457
  $operations = array();
1458
  foreach ($required + $non_required as $module => $weight) {
1459
1460
1461
1462
1463
1464
    $operations[] = array('_install_module_batch', array($module, $files[$module]->info['name']));
  }
  $batch = array(
    'operations' => $operations,
    'title' => st('Installing @drupal', array('@drupal' => drupal_install_profile_distribution_name())),
    'error_message' => st('The installation has encountered an error.'),
1465
    'finished' => '_install_profile_modules_finished',
1466
1467
1468
1469
1470
1471
1472
1473
1474
  );
  return $batch;
}

/**
 * Installation task; import languages via a batch process.
 *
 * @param $install_state
 *   An array of information about the current installation state.
1475
 *
1476
1477
1478
 * @return
 *   The batch definition, if there are language files to import.
 */
1479
function install_import_translations(&$install_state) {
1480
  include_once drupal_get_path('module', 'locale') . '/locale.bulk.inc';
1481
  $langcode = $install_state['parameters']['langcode'];
1482

1483
  include_once DRUPAL_ROOT . '/core/includes/standard.inc';
1484
1485
  $standard_languages = standard_language_list();
  if (!isset($standard_languages[$langcode])) {
1486
1487
    // Drupal does not know about this language, so we prefill its values with
    // our best guess. The user will be able to edit afterwards.
1488
    $language = (object) array(
1489
      'langcode' => $langcode,
1490
      'name' => $langcode,
1491
1492
      'default' => TRUE,
    );
1493
    language_save($language);
1494
1495
1496
  }
  else {
    // A known predefined language, details will be filled in properly.
1497
    $language = (object) array(
1498
      'langcode' => $langcode,
1499
1500
      'default' => TRUE,
    );
1501
    language_save($language);
1502
1503
  }

1504
  // Collect files to import for this language.
1505
  $batch = locale_translate_batch_import_files($langcode);
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
  if (!empty($batch)) {
    return $batch;
  }
}

/**
 * Installation task; configure settings for the new site.
 *
 * @param $form_state
 *   An associative array containing the current state of the form.
 * @param $install_state
 *   An array of information about the current installation state.
1518
 *
1519
1520
1521
 * @return
 *   The form API definition for the site configuration form.
 */
1522
function install_configure_form($form, &$form_state, &$install_state) {
1523
1524
1525
  drupal_set_title(st('Configure site'));

  // Warn about settings.php permissions risk
1526
  $settings_dir = conf_path();
1527
  $settings_file = $settings_dir . '/settings.php';
1528
1529
1530
1531
1532
1533
1534
1535
  // Check that $_POST is empty so we only show this message when the form is
  // first displayed, not on the next page after it is submitted. (We do not
  // want to repeat it multiple times because it is a general warning that is
  // not related to the rest of the installation process; it would also be
  // especially out of place on the last page of the installer, where it would
  // distract from the message that the Drupal installation has completed
  // successfully.)
  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'))) {
1536
    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