install.core.inc 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187
  1. <?php
  2. /**
  3. * @file
  4. * API functions for installing Drupal.
  5. */
  6. use Drupal\Component\Utility\UrlHelper;
  7. use Drupal\Core\DrupalKernel;
  8. use Drupal\Core\Database\Database;
  9. use Drupal\Core\Database\DatabaseExceptionWrapper;
  10. use Drupal\Core\Form\FormState;
  11. use Drupal\Core\Installer\Exception\AlreadyInstalledException;
  12. use Drupal\Core\Installer\Exception\InstallerException;
  13. use Drupal\Core\Installer\Exception\NoProfilesException;
  14. use Drupal\Core\Installer\InstallerKernel;
  15. use Drupal\Core\Language\Language;
  16. use Drupal\Core\Language\LanguageManager;
  17. use Drupal\Core\Logger\LoggerChannelFactory;
  18. use Drupal\Core\Site\Settings;
  19. use Drupal\Core\StringTranslation\Translator\FileTranslation;
  20. use Drupal\Core\StackMiddleware\ReverseProxyMiddleware;
  21. use Drupal\Core\Extension\ExtensionDiscovery;
  22. use Drupal\Core\DependencyInjection\ContainerBuilder;
  23. use Drupal\Core\Url;
  24. use Drupal\language\Entity\ConfigurableLanguage;
  25. use Symfony\Cmf\Component\Routing\RouteObjectInterface;
  26. use Symfony\Component\DependencyInjection\Reference;
  27. use Symfony\Component\HttpFoundation\Request;
  28. use Symfony\Component\HttpFoundation\Response;
  29. use Symfony\Component\Routing\Route;
  30. use Drupal\user\Entity\User;
  31. use GuzzleHttp\Exception\RequestException;
  32. /**
  33. * Do not run the task during the current installation request.
  34. *
  35. * This can be used to skip running an installation task when certain
  36. * conditions are met, even though the task may still show on the list of
  37. * installation tasks presented to the user. For example, the Drupal installer
  38. * uses this flag to skip over the database configuration form when valid
  39. * database connection information is already available from settings.php. It
  40. * also uses this flag to skip language import tasks when the installation is
  41. * being performed in English.
  42. */
  43. const INSTALL_TASK_SKIP = 1;
  44. /**
  45. * Run the task on each installation request that reaches it.
  46. *
  47. * This is primarily used by the Drupal installer for bootstrap-related tasks.
  48. */
  49. const INSTALL_TASK_RUN_IF_REACHED = 2;
  50. /**
  51. * Run the task on each installation request until the database is set up.
  52. *
  53. * This is the default method for running tasks and should be used for most
  54. * tasks that occur after the database is set up; these tasks will then run
  55. * once and be marked complete once they are successfully finished. For
  56. * example, the Drupal installer uses this flag for the batch installation of
  57. * modules on the new site, and also for the configuration form that collects
  58. * basic site information and sets up the site maintenance account.
  59. */
  60. const INSTALL_TASK_RUN_IF_NOT_COMPLETED = 3;
  61. /**
  62. * Installs Drupal either interactively or via an array of passed-in settings.
  63. *
  64. * The Drupal installation happens in a series of steps, which may be spread
  65. * out over multiple page requests. Each request begins by trying to determine
  66. * the last completed installation step (also known as a "task"), if one is
  67. * available from a previous request. Control is then passed to the task
  68. * handler, which processes the remaining tasks that need to be run until (a)
  69. * an error is thrown, (b) a new page needs to be displayed, or (c) the
  70. * installation finishes (whichever happens first).
  71. *
  72. * @param $class_loader
  73. * The class loader. Normally Composer's ClassLoader, as included by the
  74. * front controller, but may also be decorated; e.g.,
  75. * \Symfony\Component\ClassLoader\ApcClassLoader.
  76. * @param $settings
  77. * An optional array of installation settings. Leave this empty for a normal,
  78. * interactive, browser-based installation intended to occur over multiple
  79. * page requests. Alternatively, if an array of settings is passed in, the
  80. * installer will attempt to use it to perform the installation in a single
  81. * page request (optimized for the command line) and not send any output
  82. * intended for the web browser. See install_state_defaults() for a list of
  83. * elements that are allowed to appear in this array.
  84. *
  85. * @see install_state_defaults()
  86. */
  87. function install_drupal($class_loader, $settings = array()) {
  88. // Support the old way of calling this function with just a settings array.
  89. // @todo Remove this when Drush is updated in the Drupal testing
  90. // infrastructure in https://www.drupal.org/node/2389243
  91. if (is_array($class_loader) && $settings === array()) {
  92. $settings = $class_loader;
  93. $class_loader = require __DIR__ . '/../../autoload.php';
  94. }
  95. global $install_state;
  96. // Initialize the installation state with the settings that were passed in,
  97. // as well as a boolean indicating whether or not this is an interactive
  98. // installation.
  99. $interactive = empty($settings);
  100. $install_state = $settings + array('interactive' => $interactive) + install_state_defaults();
  101. try {
  102. // Begin the page request. This adds information about the current state of
  103. // the Drupal installation to the passed-in array.
  104. install_begin_request($class_loader, $install_state);
  105. // Based on the installation state, run the remaining tasks for this page
  106. // request, and collect any output.
  107. $output = install_run_tasks($install_state);
  108. }
  109. catch (InstallerException $e) {
  110. // In the non-interactive installer, exceptions are always thrown directly.
  111. if (!$install_state['interactive']) {
  112. throw $e;
  113. }
  114. $output = array(
  115. '#title' => $e->getTitle(),
  116. '#markup' => $e->getMessage(),
  117. );
  118. }
  119. // After execution, all tasks might be complete, in which case
  120. // $install_state['installation_finished'] is TRUE. In case the last task
  121. // has been processed, remove the global $install_state, so other code can
  122. // reliably check whether it is running during the installer.
  123. // @see drupal_installation_attempted()
  124. $state = $install_state;
  125. if (!empty($install_state['installation_finished'])) {
  126. unset($GLOBALS['install_state']);
  127. }
  128. // All available tasks for this page request are now complete. Interactive
  129. // installations can send output to the browser or redirect the user to the
  130. // next page.
  131. if ($state['interactive']) {
  132. // If a session has been initiated in this request, make sure to save it.
  133. if ($session = \Drupal::request()->getSession()) {
  134. $session->save();
  135. }
  136. if ($state['parameters_changed']) {
  137. // Redirect to the correct page if the URL parameters have changed.
  138. install_goto(install_redirect_url($state));
  139. }
  140. elseif (isset($output)) {
  141. // Display a page only if some output is available. Otherwise it is
  142. // possible that we are printing a JSON page and theme output should
  143. // not be shown.
  144. install_display_output($output, $state);
  145. }
  146. elseif ($state['installation_finished']) {
  147. // Redirect to the newly installed site.
  148. install_goto('');
  149. }
  150. }
  151. }
  152. /**
  153. * Returns an array of default settings for the global installation state.
  154. *
  155. * The installation state is initialized with these settings at the beginning
  156. * of each page request. They may evolve during the page request, but they are
  157. * initialized again once the next request begins.
  158. *
  159. * Non-interactive Drupal installations can override some of these default
  160. * settings by passing in an array to the installation script, most notably
  161. * 'parameters' (which contains one-time parameters such as 'profile' and
  162. * 'langcode' that are normally passed in via the URL) and 'forms' (which can
  163. * be used to programmatically submit forms during the installation; the keys
  164. * of each element indicate the name of the installation task that the form
  165. * submission is for, and the values are used as the $form_state->getValues()
  166. * array that is passed on to the form submission via
  167. * \Drupal::formBuilder()->submitForm()).
  168. *
  169. * @see \Drupal\Core\Form\FormBuilderInterface::submitForm()
  170. */
  171. function install_state_defaults() {
  172. $defaults = array(
  173. // The current task being processed.
  174. 'active_task' => NULL,
  175. // The last task that was completed during the previous installation
  176. // request.
  177. 'completed_task' => NULL,
  178. // TRUE when there are valid config directories.
  179. 'config_verified' => FALSE,
  180. // TRUE when there is a valid database connection.
  181. 'database_verified' => FALSE,
  182. // TRUE if database is empty & ready to install.
  183. 'database_ready' => FALSE,
  184. // TRUE when a valid settings.php exists (containing both database
  185. // connection information and config directory names).
  186. 'settings_verified' => FALSE,
  187. // TRUE when the base system has been installed and is ready to operate.
  188. 'base_system_verified' => FALSE,
  189. // Whether a translation file for the selected language will be downloaded
  190. // from the translation server.
  191. 'download_translation' => FALSE,
  192. // An array of forms to be programmatically submitted during the
  193. // installation. The keys of each element indicate the name of the
  194. // installation task that the form submission is for, and the values are
  195. // used as the $form_state->getValues() array that is passed on to the form
  196. // submission via \Drupal::formBuilder()->submitForm().
  197. 'forms' => array(),
  198. // This becomes TRUE only at the end of the installation process, after
  199. // all available tasks have been completed and Drupal is fully installed.
  200. // It is used by the installer to store correct information in the database
  201. // about the completed installation, as well as to inform theme functions
  202. // that all tasks are finished (so that the task list can be displayed
  203. // correctly).
  204. 'installation_finished' => FALSE,
  205. // Whether or not this installation is interactive. By default this will
  206. // be set to FALSE if settings are passed in to install_drupal().
  207. 'interactive' => TRUE,
  208. // An array of parameters for the installation, pre-populated by the URL
  209. // or by the settings passed in to install_drupal(). This is primarily
  210. // used to store 'profile' (the name of the chosen installation profile)
  211. // and 'langcode' (the code of the chosen installation language), since
  212. // these settings need to persist from page request to page request before
  213. // the database is available for storage.
  214. 'parameters' => array(),
  215. // Whether or not the parameters have changed during the current page
  216. // request. For interactive installations, this will trigger a page
  217. // redirect.
  218. 'parameters_changed' => FALSE,
  219. // An array of information about the chosen installation profile. This will
  220. // be filled in based on the profile's .info.yml file.
  221. 'profile_info' => array(),
  222. // An array of available installation profiles.
  223. 'profiles' => array(),
  224. // The name of the theme to use during installation.
  225. 'theme' => 'seven',
  226. // The server URL where the interface translation files can be downloaded.
  227. // Tokens in the pattern will be replaced by appropriate values for the
  228. // required translation file.
  229. 'server_pattern' => 'http://ftp.drupal.org/files/translations/%core/%project/%project-%version.%language.po',
  230. // Installation tasks can set this to TRUE to force the page request to
  231. // end (even if there is no themable output), in the case of an interactive
  232. // installation. This is needed only rarely; for example, it would be used
  233. // by an installation task that prints JSON output rather than returning a
  234. // themed page. The most common example of this is during batch processing,
  235. // but the Drupal installer automatically takes care of setting this
  236. // parameter properly in that case, so that individual installation tasks
  237. // which implement the batch API do not need to set it themselves.
  238. 'stop_page_request' => FALSE,
  239. // Installation tasks can set this to TRUE to indicate that the task should
  240. // be run again, even if it normally wouldn't be. This can be used, for
  241. // example, if a single task needs to be spread out over multiple page
  242. // requests, or if it needs to perform some validation before allowing
  243. // itself to be marked complete. The most common examples of this are batch
  244. // processing and form submissions, but the Drupal installer automatically
  245. // takes care of setting this parameter properly in those cases, so that
  246. // individual installation tasks which implement the batch API or form API
  247. // do not need to set it themselves.
  248. 'task_not_complete' => FALSE,
  249. // A list of installation tasks which have already been performed during
  250. // the current page request.
  251. 'tasks_performed' => array(),
  252. // An array of translation files URIs available for the installation. Keyed
  253. // by the translation language code.
  254. 'translations' => array(),
  255. );
  256. return $defaults;
  257. }
  258. /**
  259. * Begins an installation request, modifying the installation state as needed.
  260. *
  261. * This function performs commands that must run at the beginning of every page
  262. * request. It throws an exception if the installation should not proceed.
  263. *
  264. * @param $class_loader
  265. * The class loader. Normally Composer's ClassLoader, as included by the
  266. * front controller, but may also be decorated; e.g.,
  267. * \Symfony\Component\ClassLoader\ApcClassLoader.
  268. * @param $install_state
  269. * An array of information about the current installation state. This is
  270. * modified with information gleaned from the beginning of the page request.
  271. */
  272. function install_begin_request($class_loader, &$install_state) {
  273. $request = Request::createFromGlobals();
  274. // Add any installation parameters passed in via the URL.
  275. if ($install_state['interactive']) {
  276. $install_state['parameters'] += $request->query->all();
  277. }
  278. // Validate certain core settings that are used throughout the installation.
  279. if (!empty($install_state['parameters']['profile'])) {
  280. $install_state['parameters']['profile'] = preg_replace('/[^a-zA-Z_0-9]/', '', $install_state['parameters']['profile']);
  281. }
  282. if (!empty($install_state['parameters']['langcode'])) {
  283. $install_state['parameters']['langcode'] = preg_replace('/[^a-zA-Z_0-9\-]/', '', $install_state['parameters']['langcode']);
  284. }
  285. // Allow command line scripts to override server variables used by Drupal.
  286. require_once __DIR__ . '/bootstrap.inc';
  287. // Before having installed the system module and being able to do a module
  288. // rebuild, prime the drupal_get_filename() static cache with the module's
  289. // exact location.
  290. // @todo Remove as part of https://www.drupal.org/node/2186491
  291. drupal_get_filename('module', 'system', 'core/modules/system/system.info.yml');
  292. // If the hash salt leaks, it becomes possible to forge a valid testing user
  293. // agent, install a new copy of Drupal, and take over the original site.
  294. // The user agent header is used to pass a database prefix in the request when
  295. // running tests. However, for security reasons, it is imperative that no
  296. // installation be permitted using such a prefix.
  297. $user_agent = $request->cookies->get('SIMPLETEST_USER_AGENT') ?: $request->server->get('HTTP_USER_AGENT');
  298. if ($install_state['interactive'] && strpos($user_agent, 'simpletest') !== FALSE && !drupal_valid_test_ua()) {
  299. header($request->server->get('SERVER_PROTOCOL') . ' 403 Forbidden');
  300. exit;
  301. }
  302. $site_path = DrupalKernel::findSitePath($request, FALSE);
  303. Settings::initialize(dirname(dirname(__DIR__)), $site_path, $class_loader);
  304. // Ensure that procedural dependencies are loaded as early as possible,
  305. // since the error/exception handlers depend on them.
  306. require_once __DIR__ . '/../modules/system/system.install';
  307. require_once __DIR__ . '/common.inc';
  308. require_once __DIR__ . '/file.inc';
  309. require_once __DIR__ . '/install.inc';
  310. require_once __DIR__ . '/schema.inc';
  311. require_once __DIR__ . '/database.inc';
  312. require_once __DIR__ . '/form.inc';
  313. require_once __DIR__ . '/batch.inc';
  314. // Load module basics (needed for hook invokes).
  315. include_once __DIR__ . '/module.inc';
  316. require_once __DIR__ . '/entity.inc';
  317. // Create a minimal mocked container to support calls to t() in the pre-kernel
  318. // base system verification code paths below. The strings are not actually
  319. // used or output for these calls.
  320. // @todo Separate API level checks from UI-facing error messages.
  321. $container = new ContainerBuilder();
  322. $container->setParameter('language.default_values', Language::$defaultValues);
  323. $container
  324. ->register('language.default', 'Drupal\Core\Language\LanguageDefault')
  325. ->addArgument('%language.default_values%');
  326. $container
  327. ->register('string_translation', 'Drupal\Core\StringTranslation\TranslationManager')
  328. ->addArgument(new Reference('language.default'));
  329. // Register the stream wrapper manager.
  330. $container
  331. ->register('stream_wrapper_manager', 'Drupal\Core\StreamWrapper\StreamWrapperManager')
  332. ->addMethodCall('setContainer', array(new Reference('service_container')));
  333. $container
  334. ->register('file_system', 'Drupal\Core\File\FileSystem')
  335. ->addArgument(new Reference('stream_wrapper_manager'))
  336. ->addArgument(Settings::getInstance())
  337. ->addArgument((new LoggerChannelFactory())->get('file'));
  338. \Drupal::setContainer($container);
  339. // Determine whether base system services are ready to operate.
  340. try {
  341. $sync_directory = config_get_config_directory(CONFIG_SYNC_DIRECTORY);
  342. $install_state['config_verified'] = file_exists($sync_directory);
  343. }
  344. catch (Exception $e) {
  345. $install_state['config_verified'] = FALSE;
  346. }
  347. $install_state['database_verified'] = install_verify_database_settings($site_path);
  348. $install_state['settings_verified'] = $install_state['config_verified'] && $install_state['database_verified'];
  349. // Install factory tables only after checking the database.
  350. if ($install_state['database_verified'] && $install_state['database_ready']) {
  351. $container
  352. ->register('path.matcher', 'Drupal\Core\Path\PathMatcher')
  353. ->addArgument(new Reference('config.factory'));
  354. }
  355. if ($install_state['settings_verified']) {
  356. try {
  357. $system_schema = system_schema();
  358. end($system_schema);
  359. $table = key($system_schema);
  360. $install_state['base_system_verified'] = Database::getConnection()->schema()->tableExists($table);
  361. }
  362. catch (DatabaseExceptionWrapper $e) {
  363. // The last defined table of the base system_schema() does not exist yet.
  364. // $install_state['base_system_verified'] defaults to FALSE, so the code
  365. // following below will use the minimal installer service container.
  366. // As soon as the base system is verified here, the installer operates in
  367. // a full and regular Drupal environment, without any kind of exceptions.
  368. }
  369. }
  370. // Replace services with in-memory and null implementations. This kernel is
  371. // replaced with a regular one in drupal_install_system().
  372. if (!$install_state['base_system_verified']) {
  373. $environment = 'install';
  374. $GLOBALS['conf']['container_service_providers']['InstallerServiceProvider'] = 'Drupal\Core\Installer\InstallerServiceProvider';
  375. }
  376. else {
  377. $environment = 'prod';
  378. }
  379. // Only allow dumping the container once the hash salt has been created.
  380. $kernel = InstallerKernel::createFromRequest($request, $class_loader, $environment, (bool) Settings::get('hash_salt', FALSE));
  381. $kernel->setSitePath($site_path);
  382. $kernel->boot();
  383. $container = $kernel->getContainer();
  384. // If Drupal is being installed behind a proxy, configure the request.
  385. ReverseProxyMiddleware::setSettingsOnRequest($request, Settings::getInstance());
  386. // Register the file translation service.
  387. if (isset($GLOBALS['config']['locale.settings']['translation']['path'])) {
  388. $directory = $GLOBALS['config']['locale.settings']['translation']['path'];
  389. }
  390. else {
  391. $directory = $site_path . '/files/translations';
  392. }
  393. $container->set('string_translator.file_translation', new FileTranslation($directory));
  394. $container->get('string_translation')
  395. ->addTranslator($container->get('string_translator.file_translation'));
  396. // Add list of all available profiles to the installation state.
  397. $listing = new ExtensionDiscovery($container->get('app.root'));
  398. $listing->setProfileDirectories(array());
  399. $install_state['profiles'] += $listing->scan('profile');
  400. // Prime drupal_get_filename()'s static cache.
  401. foreach ($install_state['profiles'] as $name => $profile) {
  402. drupal_get_filename('profile', $name, $profile->getPathname());
  403. }
  404. if ($profile = _install_select_profile($install_state)) {
  405. $install_state['parameters']['profile'] = $profile;
  406. install_load_profile($install_state);
  407. if (isset($install_state['profile_info']['distribution']['install']['theme'])) {
  408. $install_state['theme'] = $install_state['profile_info']['distribution']['install']['theme'];
  409. }
  410. }
  411. // Use the language from the profile configuration, if available, to override
  412. // the language previously set in the parameters.
  413. if (isset($install_state['profile_info']['distribution']['langcode'])) {
  414. $install_state['parameters']['langcode'] = $install_state['profile_info']['distribution']['langcode'];
  415. }
  416. // Set the default language to the selected language, if any.
  417. if (isset($install_state['parameters']['langcode'])) {
  418. $default_language = new Language(array('id' => $install_state['parameters']['langcode']));
  419. $container->get('language.default')->set($default_language);
  420. \Drupal::translation()->setDefaultLangcode($install_state['parameters']['langcode']);
  421. }
  422. // Override the module list with a minimal set of modules.
  423. $module_handler = \Drupal::moduleHandler();
  424. if (!$module_handler->moduleExists('system')) {
  425. $module_handler->addModule('system', 'core/modules/system');
  426. }
  427. if ($profile && !$module_handler->moduleExists($profile)) {
  428. $module_handler->addProfile($profile, $install_state['profiles'][$profile]->getPath());
  429. }
  430. // Load all modules and perform request related initialization.
  431. $kernel->preHandle($request);
  432. // Initialize a route on this legacy request similar to
  433. // \Drupal\Core\DrupalKernel::prepareLegacyRequest() since normal routing
  434. // will not happen.
  435. $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('<none>'));
  436. $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<none>');
  437. // Prepare for themed output. We need to run this at the beginning of the
  438. // page request to avoid a different theme accidentally getting set. (We also
  439. // need to run it even in the case of command-line installations, to prevent
  440. // any code in the installer that happens to initialize the theme system from
  441. // accessing the database before it is set up yet.)
  442. drupal_maintenance_theme();
  443. if ($install_state['database_verified']) {
  444. // Verify the last completed task in the database, if there is one.
  445. $task = install_verify_completed_task();
  446. }
  447. else {
  448. $task = NULL;
  449. // Do not install over a configured settings.php.
  450. if (Database::getConnectionInfo()) {
  451. throw new AlreadyInstalledException($container->get('string_translation'));
  452. }
  453. }
  454. // Ensure that the active configuration is empty before installation starts.
  455. if ($install_state['config_verified'] && empty($task)) {
  456. if (count($kernel->getConfigStorage()->listAll())) {
  457. $task = NULL;
  458. throw new AlreadyInstalledException($container->get('string_translation'));
  459. }
  460. }
  461. // Modify the installation state as appropriate.
  462. $install_state['completed_task'] = $task;
  463. }
  464. /**
  465. * Runs all tasks for the current installation request.
  466. *
  467. * In the case of an interactive installation, all tasks will be attempted
  468. * until one is reached that has output which needs to be displayed to the
  469. * user, or until a page redirect is required. Otherwise, tasks will be
  470. * attempted until the installation is finished.
  471. *
  472. * @param $install_state
  473. * An array of information about the current installation state. This is
  474. * passed along to each task, so it can be modified if necessary.
  475. *
  476. * @return
  477. * HTML output from the last completed task.
  478. */
  479. function install_run_tasks(&$install_state) {
  480. do {
  481. // Obtain a list of tasks to perform. The list of tasks itself can be
  482. // dynamic (e.g., some might be defined by the installation profile,
  483. // which is not necessarily known until the earlier tasks have run),
  484. // so we regenerate the remaining tasks based on the installation state,
  485. // each time through the loop.
  486. $tasks_to_perform = install_tasks_to_perform($install_state);
  487. // Run the first task on the list.
  488. reset($tasks_to_perform);
  489. $task_name = key($tasks_to_perform);
  490. $task = array_shift($tasks_to_perform);
  491. $install_state['active_task'] = $task_name;
  492. $original_parameters = $install_state['parameters'];
  493. $output = install_run_task($task, $install_state);
  494. // Ensure the maintenance theme is initialized. If the install task has
  495. // rebuilt the container the active theme will not be set. This can occur if
  496. // the task has installed a module.
  497. drupal_maintenance_theme();
  498. $install_state['parameters_changed'] = ($install_state['parameters'] != $original_parameters);
  499. // Store this task as having been performed during the current request,
  500. // and save it to the database as completed, if we need to and if the
  501. // database is in a state that allows us to do so. Also mark the
  502. // installation as 'done' when we have run out of tasks.
  503. if (!$install_state['task_not_complete']) {
  504. $install_state['tasks_performed'][] = $task_name;
  505. $install_state['installation_finished'] = empty($tasks_to_perform);
  506. if ($task['run'] == INSTALL_TASK_RUN_IF_NOT_COMPLETED || $install_state['installation_finished']) {
  507. \Drupal::state()->set('install_task', $install_state['installation_finished'] ? 'done' : $task_name);
  508. }
  509. }
  510. // Stop when there are no tasks left. In the case of an interactive
  511. // installation, also stop if we have some output to send to the browser,
  512. // the URL parameters have changed, or an end to the page request was
  513. // specifically called for.
  514. $finished = empty($tasks_to_perform) || ($install_state['interactive'] && (isset($output) || $install_state['parameters_changed'] || $install_state['stop_page_request']));
  515. } while (!$finished);
  516. return $output;
  517. }
  518. /**
  519. * Runs an individual installation task.
  520. *
  521. * @param $task
  522. * An array of information about the task to be run as returned by
  523. * hook_install_tasks().
  524. * @param $install_state
  525. * An array of information about the current installation state. This is
  526. * passed in by reference so that it can be modified by the task.
  527. *
  528. * @return
  529. * The output of the task function, if there is any.
  530. */
  531. function install_run_task($task, &$install_state) {
  532. $function = $task['function'];
  533. if ($task['type'] == 'form') {
  534. return install_get_form($function, $install_state);
  535. }
  536. elseif ($task['type'] == 'batch') {
  537. // Start a new batch based on the task function, if one is not running
  538. // already.
  539. $current_batch = \Drupal::state()->get('install_current_batch');
  540. if (!$install_state['interactive'] || !$current_batch) {
  541. $batches = $function($install_state);
  542. if (empty($batches)) {
  543. // If the task did some processing and decided no batch was necessary,
  544. // there is nothing more to do here.
  545. return;
  546. }
  547. // Create a one item list of batches if only one batch was provided.
  548. if (isset($batches['operations'])) {
  549. $batches = array($batches);
  550. }
  551. foreach ($batches as $batch) {
  552. batch_set($batch);
  553. // For interactive batches, we need to store the fact that this batch
  554. // task is currently running. Otherwise, we need to make sure the batch
  555. // will complete in one page request.
  556. if ($install_state['interactive']) {
  557. \Drupal::state()->set('install_current_batch', $function);
  558. }
  559. else {
  560. $batch =& batch_get();
  561. $batch['progressive'] = FALSE;
  562. }
  563. }
  564. // Process the batch. For progressive batches, this will redirect.
  565. // Otherwise, the batch will complete.
  566. // Disable the default script for the URL and clone the object, as
  567. // batch_process() will add additional options to the batch URL.
  568. $url = Url::fromUri('base:install.php', ['query' => $install_state['parameters'], 'script' => '']);
  569. $response = batch_process($url, clone $url);
  570. if ($response instanceof Response) {
  571. if ($session = \Drupal::request()->getSession()) {
  572. $session->save();
  573. }
  574. // Send the response.
  575. $response->send();
  576. exit;
  577. }
  578. }
  579. // If we are in the middle of processing this batch, keep sending back
  580. // any output from the batch process, until the task is complete.
  581. elseif ($current_batch == $function) {
  582. $output = _batch_page(\Drupal::request());
  583. // Because Batch API now returns a JSON response for intermediary steps,
  584. // but the installer doesn't handle Response objects yet, just send the
  585. // output here and emulate the old model.
  586. // @todo Replace this when we refactor the installer to use a request-
  587. // response workflow.
  588. if ($output instanceof Response) {
  589. $output->send();
  590. $output = NULL;
  591. }
  592. // The task is complete when we try to access the batch page and receive
  593. // FALSE in return, since this means we are at a URL where we are no
  594. // longer requesting a batch ID.
  595. if ($output === FALSE) {
  596. // Return nothing so the next task will run in the same request.
  597. \Drupal::state()->delete('install_current_batch');
  598. return;
  599. }
  600. else {
  601. // We need to force the page request to end if the task is not
  602. // complete, since the batch API sometimes prints JSON output
  603. // rather than returning a themed page.
  604. $install_state['task_not_complete'] = $install_state['stop_page_request'] = TRUE;
  605. return $output;
  606. }
  607. }
  608. }
  609. else {
  610. // For normal tasks, just return the function result, whatever it is.
  611. return $function($install_state);
  612. }
  613. }
  614. /**
  615. * Returns a list of tasks to perform during the current installation request.
  616. *
  617. * Note that the list of tasks can change based on the installation state as
  618. * the page request evolves (for example, if an installation profile hasn't
  619. * been selected yet, we don't yet know which profile tasks need to be run).
  620. *
  621. * @param $install_state
  622. * An array of information about the current installation state.
  623. *
  624. * @return
  625. * A list of tasks to be performed, with associated metadata.
  626. */
  627. function install_tasks_to_perform($install_state) {
  628. // Start with a list of all currently available tasks.
  629. $tasks = install_tasks($install_state);
  630. foreach ($tasks as $name => $task) {
  631. // Remove any tasks that were already performed or that never should run.
  632. // Also, if we started this page request with an indication of the last
  633. // task that was completed, skip that task and all those that come before
  634. // it, unless they are marked as always needing to run.
  635. 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)) {
  636. unset($tasks[$name]);
  637. }
  638. if (!empty($install_state['completed_task']) && $name == $install_state['completed_task']) {
  639. $completed_task_found = TRUE;
  640. }
  641. }
  642. return $tasks;
  643. }
  644. /**
  645. * Returns a list of all tasks the installer currently knows about.
  646. *
  647. * This function will return tasks regardless of whether or not they are
  648. * intended to run on the current page request. However, the list can change
  649. * based on the installation state (for example, if an installation profile
  650. * hasn't been selected yet, we don't yet know which profile tasks will be
  651. * available).
  652. *
  653. * You can override this using hook_install_tasks() or
  654. * hook_install_tasks_alter().
  655. *
  656. * @param $install_state
  657. * An array of information about the current installation state.
  658. *
  659. * @return
  660. * A list of tasks, with associated metadata as returned by
  661. * hook_install_tasks().
  662. */
  663. function install_tasks($install_state) {
  664. // Determine whether a translation file must be imported during the
  665. // 'install_import_translations' task. Import when a non-English language is
  666. // available and selected. Also we will need translations even if the
  667. // installer language is English but there are other languages on the system.
  668. $needs_translations = (count($install_state['translations']) > 1 && !empty($install_state['parameters']['langcode']) && $install_state['parameters']['langcode'] != 'en') || \Drupal::languageManager()->isMultilingual();
  669. // Determine whether a translation file must be downloaded during the
  670. // 'install_download_translation' task. Download when a non-English language
  671. // is selected, but no translation is yet in the translations directory.
  672. $needs_download = isset($install_state['parameters']['langcode']) && !isset($install_state['translations'][$install_state['parameters']['langcode']]) && $install_state['parameters']['langcode'] != 'en';
  673. // Start with the core installation tasks that run before handing control
  674. // to the installation profile.
  675. $tasks = array(
  676. 'install_select_language' => array(
  677. 'display_name' => t('Choose language'),
  678. 'run' => INSTALL_TASK_RUN_IF_REACHED,
  679. ),
  680. 'install_download_translation' => array(
  681. 'run' => $needs_download ? INSTALL_TASK_RUN_IF_REACHED : INSTALL_TASK_SKIP,
  682. ),
  683. 'install_select_profile' => array(
  684. 'display_name' => t('Choose profile'),
  685. 'display' => empty($install_state['profile_info']['distribution']['name']) && count($install_state['profiles']) != 1,
  686. 'run' => INSTALL_TASK_RUN_IF_REACHED,
  687. ),
  688. 'install_load_profile' => array(
  689. 'run' => INSTALL_TASK_RUN_IF_REACHED,
  690. ),
  691. 'install_verify_requirements' => array(
  692. 'display_name' => t('Verify requirements'),
  693. ),
  694. 'install_settings_form' => array(
  695. 'display_name' => t('Set up database'),
  696. 'type' => 'form',
  697. // Even though the form only allows the user to enter database settings,
  698. // we still need to display it if settings.php is invalid in any way,
  699. // since the form submit handler is where settings.php is rewritten.
  700. 'run' => $install_state['settings_verified'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
  701. 'function' => 'Drupal\Core\Installer\Form\SiteSettingsForm',
  702. ),
  703. 'install_write_profile' => array(
  704. ),
  705. 'install_verify_database_ready' => array(
  706. 'run' => $install_state['database_ready'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
  707. ),
  708. 'install_base_system' => array(
  709. 'run' => $install_state['base_system_verified'] ? INSTALL_TASK_SKIP : INSTALL_TASK_RUN_IF_NOT_COMPLETED,
  710. ),
  711. // All tasks below are executed in a regular, full Drupal environment.
  712. 'install_bootstrap_full' => array(
  713. 'run' => INSTALL_TASK_RUN_IF_REACHED,
  714. ),
  715. 'install_profile_modules' => array(
  716. 'display_name' => t('Install site'),
  717. 'type' => 'batch',
  718. ),
  719. 'install_profile_themes' => array(
  720. ),
  721. 'install_install_profile' => array(
  722. ),
  723. 'install_import_translations' => array(
  724. 'display_name' => t('Set up translations'),
  725. 'display' => $needs_translations,
  726. 'type' => 'batch',
  727. 'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
  728. ),
  729. 'install_configure_form' => array(
  730. 'display_name' => t('Configure site'),
  731. 'type' => 'form',
  732. 'function' => 'Drupal\Core\Installer\Form\SiteConfigureForm',
  733. ),
  734. );
  735. // Now add any tasks defined by the installation profile.
  736. if (!empty($install_state['parameters']['profile'])) {
  737. // Load the profile install file, because it is not always loaded when
  738. // hook_install_tasks() is invoked (e.g. batch processing).
  739. $profile = $install_state['parameters']['profile'];
  740. $profile_install_file = $install_state['profiles'][$profile]->getPath() . '/' . $profile . '.install';
  741. if (file_exists($profile_install_file)) {
  742. include_once \Drupal::root() . '/' . $profile_install_file;
  743. }
  744. $function = $install_state['parameters']['profile'] . '_install_tasks';
  745. if (function_exists($function)) {
  746. $result = $function($install_state);
  747. if (is_array($result)) {
  748. $tasks += $result;
  749. }
  750. }
  751. }
  752. // Finish by adding the remaining core tasks.
  753. $tasks += array(
  754. 'install_finish_translations' => array(
  755. 'display_name' => t('Finish translations'),
  756. 'display' => $needs_translations,
  757. 'type' => 'batch',
  758. 'run' => $needs_translations ? INSTALL_TASK_RUN_IF_NOT_COMPLETED : INSTALL_TASK_SKIP,
  759. ),
  760. 'install_finished' => array(
  761. ),
  762. );
  763. // Allow the installation profile to modify the full list of tasks.
  764. if (!empty($install_state['parameters']['profile'])) {
  765. $profile = $install_state['parameters']['profile'];
  766. if ($install_state['profiles'][$profile]->load()) {
  767. $function = $install_state['parameters']['profile'] . '_install_tasks_alter';
  768. if (function_exists($function)) {
  769. $function($tasks, $install_state);
  770. }
  771. }
  772. }
  773. // Fill in default parameters for each task before returning the list.
  774. foreach ($tasks as $task_name => &$task) {
  775. $task += array(
  776. 'display_name' => NULL,
  777. 'display' => !empty($task['display_name']),
  778. 'type' => 'normal',
  779. 'run' => INSTALL_TASK_RUN_IF_NOT_COMPLETED,
  780. 'function' => $task_name,
  781. );
  782. }
  783. return $tasks;
  784. }
  785. /**
  786. * Returns a list of tasks that should be displayed to the end user.
  787. *
  788. * The output of this function is a list suitable for sending to
  789. * maintenance-task-list.html.twig.
  790. *
  791. * @param $install_state
  792. * An array of information about the current installation state.
  793. *
  794. * @return
  795. * A list of tasks, with keys equal to the machine-readable task name and
  796. * values equal to the name that should be displayed.
  797. *
  798. * @see maintenance-task-list.html.twig
  799. */
  800. function install_tasks_to_display($install_state) {
  801. $displayed_tasks = array();
  802. foreach (install_tasks($install_state) as $name => $task) {
  803. if ($task['display']) {
  804. $displayed_tasks[$name] = $task['display_name'];
  805. }
  806. }
  807. return $displayed_tasks;
  808. }
  809. /**
  810. * Builds and processes a form for the installer environment.
  811. *
  812. * Ensures that FormBuilder does not redirect after submitting a form, since the
  813. * installer uses a custom step/flow logic via install_run_tasks().
  814. *
  815. * @param string|array $form_id
  816. * The form ID to build and process.
  817. * @param array $install_state
  818. * The current state of the installation.
  819. *
  820. * @return array|null
  821. * A render array containing the form to render, or NULL in case the form was
  822. * successfully submitted.
  823. *
  824. * @throws \Drupal\Core\Installer\Exception\InstallerException
  825. */
  826. function install_get_form($form_id, array &$install_state) {
  827. // Ensure the form will not redirect, since install_run_tasks() uses a custom
  828. // redirection logic.
  829. $form_state = (new FormState())
  830. ->addBuildInfo('args', [&$install_state])
  831. ->disableRedirect();
  832. $form_builder = \Drupal::formBuilder();
  833. if ($install_state['interactive']) {
  834. $form = $form_builder->buildForm($form_id, $form_state);
  835. // If the form submission was not successful, the form needs to be rendered,
  836. // which means the task is not complete yet.
  837. if (!$form_state->isExecuted()) {
  838. $install_state['task_not_complete'] = TRUE;
  839. return $form;
  840. }
  841. }
  842. else {
  843. // For non-interactive installs, submit the form programmatically with the
  844. // values taken from the installation state.
  845. $install_form_id = $form_builder->getFormId($form_id, $form_state);
  846. if (!empty($install_state['forms'][$install_form_id])) {
  847. $form_state->setValues($install_state['forms'][$install_form_id]);
  848. }
  849. $form_builder->submitForm($form_id, $form_state);
  850. // Throw an exception in case of any form validation error.
  851. if ($errors = $form_state->getErrors()) {
  852. throw new InstallerException(implode("\n", $errors));
  853. }
  854. }
  855. }
  856. /**
  857. * Returns the URL that should be redirected to during an installation request.
  858. *
  859. * The output of this function is suitable for sending to install_goto().
  860. *
  861. * @param $install_state
  862. * An array of information about the current installation state.
  863. *
  864. * @return
  865. * The URL to redirect to.
  866. *
  867. * @see install_full_redirect_url()
  868. */
  869. function install_redirect_url($install_state) {
  870. return 'core/install.php?' . UrlHelper::buildQuery($install_state['parameters']);
  871. }
  872. /**
  873. * Returns the complete URL redirected to during an installation request.
  874. *
  875. * @param $install_state
  876. * An array of information about the current installation state.
  877. *
  878. * @return
  879. * The complete URL to redirect to.
  880. *
  881. * @see install_redirect_url()
  882. */
  883. function install_full_redirect_url($install_state) {
  884. global $base_url;
  885. return $base_url . '/' . install_redirect_url($install_state);
  886. }
  887. /**
  888. * Displays themed installer output and ends the page request.
  889. *
  890. * Installation tasks should use #title to set the desired page
  891. * title, but otherwise this function takes care of theming the overall page
  892. * output during every step of the installation.
  893. *
  894. * @param $output
  895. * The content to display on the main part of the page.
  896. * @param $install_state
  897. * An array of information about the current installation state.
  898. */
  899. function install_display_output($output, $install_state) {
  900. // Ensure the maintenance theme is initialized.
  901. // The regular initialization call in install_begin_request() may not be
  902. // reached in case of an early installer error.
  903. drupal_maintenance_theme();
  904. // Prevent install.php from being indexed when installed in a sub folder.
  905. // robots.txt rules are not read if the site is within domain.com/subfolder
  906. // resulting in /subfolder/install.php being found through search engines.
  907. // When settings.php is writeable this can be used via an external database
  908. // leading a malicious user to gain php access to the server.
  909. $noindex_meta_tag = array(
  910. '#tag' => 'meta',
  911. '#attributes' => array(
  912. 'name' => 'robots',
  913. 'content' => 'noindex, nofollow',
  914. ),
  915. );
  916. $output['#attached']['html_head'][] = [$noindex_meta_tag, 'install_meta_robots'];
  917. // Only show the task list if there is an active task; otherwise, the page
  918. // request has ended before tasks have even been started, so there is nothing
  919. // meaningful to show.
  920. $regions = array();
  921. if (isset($install_state['active_task'])) {
  922. // Let the theming function know when every step of the installation has
  923. // been completed.
  924. $active_task = $install_state['installation_finished'] ? NULL : $install_state['active_task'];
  925. $task_list = array(
  926. '#theme' => 'maintenance_task_list',
  927. '#items' => install_tasks_to_display($install_state),
  928. '#active' => $active_task,
  929. );
  930. $regions['sidebar_first'] = $task_list;
  931. }
  932. $bare_html_page_renderer = \Drupal::service('bare_html_page_renderer');
  933. $response = $bare_html_page_renderer->renderBarePage($output, $output['#title'], 'install_page', $regions);
  934. $default_headers = array(
  935. 'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
  936. 'Last-Modified' => gmdate(DATE_RFC1123, REQUEST_TIME),
  937. 'Cache-Control' => 'no-cache, must-revalidate',
  938. 'ETag' => '"' . REQUEST_TIME . '"',
  939. );
  940. $response->headers->add($default_headers);
  941. $response->send();
  942. exit;
  943. }
  944. /**
  945. * Verifies the requirements for installing Drupal.
  946. *
  947. * @param $install_state
  948. * An array of information about the current installation state.
  949. *
  950. * @return
  951. * A themed status report, or an exception if there are requirement errors.
  952. */
  953. function install_verify_requirements(&$install_state) {
  954. // Check the installation requirements for Drupal and this profile.
  955. $requirements = install_check_requirements($install_state);
  956. // Verify existence of all required modules.
  957. $requirements += drupal_verify_profile($install_state);
  958. return install_display_requirements($install_state, $requirements);
  959. }
  960. /**
  961. * Installation task; install the base functionality Drupal needs to bootstrap.
  962. *
  963. * @param $install_state
  964. * An array of information about the current installation state.
  965. */
  966. function install_base_system(&$install_state) {
  967. // Install system.module.
  968. drupal_install_system($install_state);
  969. // Call file_ensure_htaccess() to ensure that all of Drupal's standard
  970. // directories (e.g., the public files directory and config directory) have
  971. // appropriate .htaccess files. These directories will have already been
  972. // created by this point in the installer, since Drupal creates them during
  973. // the install_verify_requirements() task. Note that we cannot call
  974. // file_ensure_access() any earlier than this, since it relies on
  975. // system.module in order to work.
  976. file_ensure_htaccess();
  977. // Prime the drupal_get_filename() static cache with the user module's
  978. // exact location.
  979. // @todo Remove as part of https://www.drupal.org/node/2186491
  980. drupal_get_filename('module', 'user', 'core/modules/user/user.info.yml');
  981. // Enable the user module so that sessions can be recorded during the
  982. // upcoming bootstrap step.
  983. \Drupal::service('module_installer')->install(array('user'), FALSE);
  984. // Save the list of other modules to install for the upcoming tasks.
  985. // State can be set to the database now that system.module is installed.
  986. $modules = $install_state['profile_info']['dependencies'];
  987. \Drupal::state()->set('install_profile_modules', array_diff($modules, array('system')));
  988. $install_state['base_system_verified'] = TRUE;
  989. }
  990. /**
  991. * Verifies and returns the last installation task that was completed.
  992. *
  993. * @return
  994. * The last completed task, if there is one. An exception is thrown if Drupal
  995. * is already installed.
  996. */
  997. function install_verify_completed_task() {
  998. try {
  999. $task = \Drupal::state()->get('install_task');
  1000. }
  1001. // Do not trigger an error if the database query fails, since the database
  1002. // might not be set up yet.
  1003. catch (\Exception $e) {
  1004. }
  1005. if (isset($task)) {
  1006. if ($task == 'done') {
  1007. throw new AlreadyInstalledException(\Drupal::service('string_translation'));
  1008. }
  1009. return $task;
  1010. }
  1011. }
  1012. /**
  1013. * Verifies that settings.php specifies a valid database connection.
  1014. *
  1015. * @param string $site_path
  1016. * The site path.
  1017. *
  1018. * @return bool
  1019. * TRUE if there are no database errors.
  1020. */
  1021. function install_verify_database_settings($site_path) {
  1022. if ($database = Database::getConnectionInfo()) {
  1023. $database = $database['default'];
  1024. $settings_file = './' . $site_path . '/settings.php';
  1025. $errors = install_database_errors($database, $settings_file);
  1026. if (empty($errors)) {
  1027. return TRUE;
  1028. }
  1029. }
  1030. return FALSE;
  1031. }
  1032. /**
  1033. * Verify that the database is ready (no existing Drupal installation).
  1034. */
  1035. function install_verify_database_ready() {
  1036. $system_schema = system_schema();
  1037. end($system_schema);
  1038. $table = key($system_schema);
  1039. if ($database = Database::getConnectionInfo()) {
  1040. if (Database::getConnection()->schema()->tableExists($table)) {
  1041. throw new AlreadyInstalledException(\Drupal::service('string_translation'));
  1042. }
  1043. }
  1044. }
  1045. /**
  1046. * Checks a database connection and returns any errors.
  1047. */
  1048. function install_database_errors($database, $settings_file) {
  1049. $errors = array();
  1050. // Check database type.
  1051. $database_types = drupal_get_database_types();
  1052. $driver = $database['driver'];
  1053. if (!isset($database_types[$driver])) {
  1054. $errors['driver'] = t("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));
  1055. }
  1056. else {
  1057. // Run driver specific validation
  1058. $errors += $database_types[$driver]->validateDatabaseSettings($database);
  1059. if (!empty($errors)) {
  1060. // No point to try further.
  1061. return $errors;
  1062. }
  1063. // Run tasks associated with the database type. Any errors are caught in the
  1064. // calling function.
  1065. Database::addConnectionInfo('default', 'default', $database);
  1066. $errors = db_installer_object($driver)->runTasks();
  1067. }
  1068. return $errors;
  1069. }
  1070. /**
  1071. * Selects which profile to install.
  1072. *
  1073. * @param $install_state
  1074. * An array of information about the current installation state. The chosen
  1075. * profile will be added here, if it was not already selected previously, as
  1076. * will a list of all available profiles.
  1077. *
  1078. * @return
  1079. * For interactive installations, a form allowing the profile to be selected,
  1080. * if the user has a choice that needs to be made. Otherwise, an exception is
  1081. * thrown if a profile cannot be chosen automatically.
  1082. */
  1083. function install_select_profile(&$install_state) {
  1084. if (empty($install_state['parameters']['profile'])) {
  1085. // If there are no profiles at all, installation cannot proceed.
  1086. if (empty($install_state['profiles'])) {
  1087. throw new NoProfilesException(\Drupal::service('string_translation'));
  1088. }
  1089. // Try to automatically select a profile.
  1090. if ($profile = _install_select_profile($install_state)) {
  1091. $install_state['parameters']['profile'] = $profile;
  1092. }
  1093. else {
  1094. // The non-interactive installer requires a profile parameter.
  1095. if (!$install_state['interactive']) {
  1096. throw new InstallerException(t('Missing profile parameter.'));
  1097. }
  1098. // Otherwise, display a form to select a profile.
  1099. return install_get_form('Drupal\Core\Installer\Form\SelectProfileForm', $install_state);
  1100. }
  1101. }
  1102. }
  1103. /**
  1104. * Determines the installation profile to use in the installer.
  1105. *
  1106. * A profile will be selected in the following order of conditions:
  1107. * - Only one profile is available.
  1108. * - A specific profile name is requested in installation parameters:
  1109. * - For interactive installations via request query parameters.
  1110. * - For non-interactive installations via install_drupal() settings.
  1111. * - A discovered profile that is a distribution. If multiple profiles are
  1112. * distributions, then the first discovered profile will be selected.
  1113. * - Only one visible profile is available.
  1114. *
  1115. * @param array $install_state
  1116. * The current installer state, containing a 'profiles' key, which is an
  1117. * associative array of profiles with the machine-readable names as keys.
  1118. *
  1119. * @return
  1120. * The machine-readable name of the selected profile or NULL if no profile was
  1121. * selected.
  1122. */
  1123. function _install_select_profile(&$install_state) {
  1124. // Don't need to choose profile if only one available.
  1125. if (count($install_state['profiles']) == 1) {
  1126. return key($install_state['profiles']);
  1127. }
  1128. if (!empty($install_state['parameters']['profile'])) {
  1129. $profile = $install_state['parameters']['profile'];
  1130. if (isset($install_state['profiles'][$profile])) {
  1131. return $profile;
  1132. }
  1133. }
  1134. // Check for a distribution profile.
  1135. foreach ($install_state['profiles'] as $profile) {
  1136. $profile_info = install_profile_info($profile->getName());
  1137. if (!empty($profile_info['distribution'])) {
  1138. return $profile->getName();
  1139. }
  1140. }
  1141. // Get all visible (not hidden) profiles.
  1142. $visible_profiles = array_filter($install_state['profiles'], function ($profile) {
  1143. $profile_info = install_profile_info($profile->getName());
  1144. return !isset($profile_info['hidden']) || !$profile_info['hidden'];
  1145. });
  1146. if (count($visible_profiles) == 1) {
  1147. return (key($visible_profiles));
  1148. }
  1149. }
  1150. /**
  1151. * Finds all .po files that are useful to the installer.
  1152. *
  1153. * @return
  1154. * An associative array of file URIs keyed by language code. URIs as
  1155. * returned by file_scan_directory().
  1156. *
  1157. * @see file_scan_directory()
  1158. */
  1159. function install_find_translations() {
  1160. $translations = array();
  1161. $files = \Drupal::service('string_translator.file_translation')->findTranslationFiles();
  1162. // English does not need a translation file.
  1163. array_unshift($files, (object) array('name' => 'en'));
  1164. foreach ($files as $uri => $file) {
  1165. // Strip off the file name component before the language code.
  1166. $langcode = preg_replace('!^(.+\.)?([^\.]+)$!', '\2', $file->name);
  1167. // Language codes cannot exceed 12 characters to fit into the {language}
  1168. // table.
  1169. if (strlen($langcode) <= 12) {
  1170. $translations[$langcode] = $uri;
  1171. }
  1172. }
  1173. return $translations;
  1174. }
  1175. /**
  1176. * Selects which language to use during installation.
  1177. *
  1178. * @param $install_state
  1179. * An array of information about the current installation state. The chosen
  1180. * langcode will be added here, if it was not already selected previously, as
  1181. * will a list of all available languages.
  1182. *
  1183. * @return
  1184. * For interactive installations, a form or other page output allowing the
  1185. * language to be selected or providing information about language selection,
  1186. * if a language has not been chosen. Otherwise, an exception is thrown if a
  1187. * language cannot be chosen automatically.
  1188. */
  1189. function install_select_language(&$install_state) {
  1190. // Find all available translation files.
  1191. $files = install_find_translations();
  1192. $install_state['translations'] += $files;
  1193. // If a valid language code is set, continue with the next installation step.
  1194. // When translations from the localization server are used, any language code
  1195. // is accepted because the standard language list is kept in sync with the
  1196. // languages available at http://localize.drupal.org.
  1197. // When files from the translation directory are used, we only accept
  1198. // languages for which a file is available.
  1199. if (!empty($install_state['parameters']['langcode'])) {
  1200. $standard_languages = LanguageManager::getStandardLanguageList();
  1201. $langcode = $install_state['parameters']['langcode'];
  1202. if ($langcode == 'en' || isset($files[$langcode]) || isset($standard_languages[$langcode])) {
  1203. $install_state['parameters']['langcode'] = $langcode;
  1204. return;
  1205. }
  1206. }
  1207. if (empty($install_state['parameters']['langcode'])) {
  1208. // If we are performing an interactive installation, we display a form to
  1209. // select a right language. If no translation files were found in the
  1210. // translations directory, the form shows a list of standard languages. If
  1211. // translation files were found the form shows a select list of the
  1212. // corresponding languages to choose from.
  1213. if ($install_state['interactive']) {
  1214. return install_get_form('Drupal\Core\Installer\Form\SelectLanguageForm', $install_state);
  1215. }
  1216. // If we are performing a non-interactive installation. If only one language
  1217. // (English) is available, assume the user knows what he is doing. Otherwise
  1218. // throw an error.
  1219. else {
  1220. if (count($files) == 1) {
  1221. $install_state['parameters']['langcode'] = current(array_keys($files));
  1222. return;
  1223. }
  1224. else {
  1225. throw new InstallerException(t('You must select a language to continue the installation.'));
  1226. }
  1227. }
  1228. }
  1229. }
  1230. /**
  1231. * Download a translation file for the selected language.
  1232. *
  1233. * @param array $install_state
  1234. * An array of information about the current installation state.
  1235. *
  1236. * @return string
  1237. * A themed status report, or an exception if there are requirement errors.
  1238. * Upon successful download the page is reloaded and no output is returned.
  1239. */
  1240. function install_download_translation(&$install_state) {
  1241. // Check whether all conditions are met to download. Download the translation
  1242. // if possible.
  1243. $requirements = install_check_translations($install_state['parameters']['langcode'], $install_state['server_pattern']);
  1244. if ($output = install_display_requirements($install_state, $requirements)) {
  1245. return $output;
  1246. }
  1247. // The download was successful, reload the page in the new language.
  1248. $install_state['translations'][$install_state['parameters']['langcode']] = TRUE;
  1249. if ($install_state['interactive']) {
  1250. install_goto(install_redirect_url($install_state));
  1251. }
  1252. }
  1253. /**
  1254. * Attempts to get a file using a HTTP request and to store it locally.
  1255. *
  1256. * @param string $uri
  1257. * The URI of the file to grab.
  1258. * @param string $destination
  1259. * Stream wrapper URI specifying where the file should be placed. If a
  1260. * directory path is provided, the file is saved into that directory under its
  1261. * original name. If the path contains a filename as well, that one will be
  1262. * used instead.
  1263. *
  1264. * @return bool
  1265. * TRUE on success, FALSE on failure.
  1266. */
  1267. function install_retrieve_file($uri, $destination) {
  1268. $parsed_url = parse_url($uri);
  1269. if (is_dir(drupal_realpath($destination))) {
  1270. // Prevent URIs with triple slashes when gluing parts together.
  1271. $path = str_replace('///', '//', "$destination/") . drupal_basename($parsed_url['path']);
  1272. }
  1273. else {
  1274. $path = $destination;
  1275. }
  1276. try {
  1277. $response = \Drupal::httpClient()->get($uri, array('headers' => array('Accept' => 'text/plain')));
  1278. $data = (string) $response->getBody();
  1279. if (empty($data)) {
  1280. return FALSE;
  1281. }
  1282. }
  1283. catch (RequestException $e) {
  1284. return FALSE;
  1285. }
  1286. return file_put_contents($path, $data) !== FALSE;
  1287. }
  1288. /**
  1289. * Checks if the localization server can be contacted.
  1290. *
  1291. * @param string $uri
  1292. * The URI to contact.
  1293. *
  1294. * @return string
  1295. * TRUE if the URI was contacted successfully, FALSE if not.
  1296. */
  1297. function install_check_localization_server($uri) {
  1298. try {
  1299. \Drupal::httpClient()->head($uri);
  1300. return TRUE;
  1301. }
  1302. catch (RequestException $e) {
  1303. return FALSE;
  1304. }
  1305. }
  1306. /**
  1307. * Extracts version information from a drupal core version string.
  1308. *
  1309. * @param string $version
  1310. * Version info string (e.g., 8.0.0, 8.1.0, 8.0.0-dev, 8.0.0-unstable1,
  1311. * 8.0.0-alpha2, 8.0.0-beta3, and 8.0.0-rc4).
  1312. *
  1313. * @return array
  1314. * Associative array of version info:
  1315. * - major: Major version (e.g., "8").
  1316. * - minor: Minor version (e.g., "0").
  1317. * - patch: Patch version (e.g., "0").
  1318. * - extra: Extra version info (e.g., "alpha2").
  1319. * - extra_text: The text part of "extra" (e.g., "alpha").
  1320. * - extra_number: The number part of "extra" (e.g., "2").
  1321. */
  1322. function _install_get_version_info($version) {
  1323. preg_match('/
  1324. (
  1325. (?P<major>[0-9]+) # Major release number.
  1326. \. # .
  1327. (?P<minor>[0-9]+) # Minor release number.
  1328. \. # .
  1329. (?P<patch>[0-9]+) # Patch release number.
  1330. ) #
  1331. ( #
  1332. - # - separator for "extra" version information.
  1333. (?P<extra> #
  1334. (?P<extra_text>[a-z]+) # Release extra text (e.g., "alpha").
  1335. (?P<extra_number>[0-9]*) # Release extra number (no separator between text and number).
  1336. ) #
  1337. | # OR no "extra" information.
  1338. )
  1339. /sx', $version, $matches);
  1340. return $matches;
  1341. }
  1342. /**
  1343. * Loads information about the chosen profile during installation.
  1344. *
  1345. * @param $install_state
  1346. * An array of information about the current installation state. The loaded
  1347. * profile information will be added here.
  1348. */
  1349. function install_load_profile(&$install_state) {
  1350. $profile = $install_state['parameters']['profile'];
  1351. $install_state['profiles'][$profile]->load();
  1352. $install_state['profile_info'] = install_profile_info($profile, isset($install_state['parameters']['langcode']) ? $install_state['parameters']['langcode'] : 'en');
  1353. }
  1354. /**
  1355. * Performs a full bootstrap of Drupal during installation.
  1356. */
  1357. function install_bootstrap_full() {
  1358. // Store the session on the request object and start it.
  1359. /** @var \Symfony\Component\HttpFoundation\Session\SessionInterface $session */
  1360. $session = \Drupal::service('session');
  1361. \Drupal::request()->setSession($session);
  1362. $session->start();
  1363. }
  1364. /**
  1365. * Installs required modules via a batch process.
  1366. *
  1367. * @param $install_state
  1368. * An array of information about the current installation state.
  1369. *
  1370. * @return
  1371. * The batch definition.
  1372. */
  1373. function install_profile_modules(&$install_state) {
  1374. // We need to manually trigger the installation of core-provided entity types,
  1375. // as those will not be handled by the module installer.
  1376. install_core_entity_type_definitions();
  1377. $modules = \Drupal::state()->get('install_profile_modules') ?: array();
  1378. $files = system_rebuild_module_data();
  1379. \Drupal::state()->delete('install_profile_modules');
  1380. // Always install required modules first. Respect the dependencies between
  1381. // the modules.
  1382. $required = array();
  1383. $non_required = array();
  1384. // Add modules that other modules depend on.
  1385. foreach ($modules as $module) {
  1386. if ($files[$module]->requires) {
  1387. $modules = array_merge($modules, array_keys($files[$module]->requires));
  1388. }
  1389. }
  1390. $modules = array_unique($modules);
  1391. foreach ($modules as $module) {
  1392. if (!empty($files[$module]->info['required'])) {
  1393. $required[$module] = $files[$module]->sort;
  1394. }
  1395. else {
  1396. $non_required[$module] = $files[$module]->sort;
  1397. }
  1398. }
  1399. arsort($required);
  1400. arsort($non_required);
  1401. $operations = array();
  1402. foreach ($required + $non_required as $module => $weight) {
  1403. $operations[] = array('_install_module_batch', array($module, $files[$module]->info['name']));
  1404. }
  1405. $batch = array(
  1406. 'operations' => $operations,
  1407. 'title' => t('Installing @drupal', array('@drupal' => drupal_install_profile_distribution_name())),
  1408. 'error_message' => t('The installation has encountered an error.'),
  1409. );
  1410. return $batch;
  1411. }
  1412. /**
  1413. * Installs entity type definitions provided by core.
  1414. */
  1415. function install_core_entity_type_definitions() {
  1416. $update_manager = \Drupal::entityDefinitionUpdateManager();
  1417. foreach (\Drupal::entityManager()->getDefinitions() as $entity_type) {
  1418. if ($entity_type->getProvider() == 'core') {
  1419. $update_manager->installEntityType($entity_type);
  1420. }
  1421. }
  1422. }
  1423. /**
  1424. * Installs themes.
  1425. *
  1426. * This does not use a batch, since installing themes is faster than modules and
  1427. * because an installation profile typically installs 1-3 themes only (default
  1428. * theme, base theme, admin theme).
  1429. *
  1430. * @param $install_state
  1431. * An array of information about the current installation state.
  1432. */
  1433. function install_profile_themes(&$install_state) {
  1434. // Install the themes specified by the installation profile.
  1435. $themes = $install_state['profile_info']['themes'];
  1436. \Drupal::service('theme_handler')->install($themes);
  1437. // Ensure that the install profile's theme is used.
  1438. // @see _drupal_maintenance_theme()
  1439. \Drupal::service('theme.manager')->resetActiveTheme();
  1440. }
  1441. /**
  1442. * Installs the install profile.
  1443. *
  1444. * @param $install_state
  1445. * An array of information about the current installation state.
  1446. */
  1447. function install_install_profile(&$install_state) {
  1448. \Drupal::service('module_installer')->install(array(drupal_get_profile()), FALSE);
  1449. // Install all available optional config. During installation the module order
  1450. // is determined by dependencies. If there are no dependencies between modules
  1451. // then the order in which they are installed is dependent on random factors
  1452. // like PHP version. Optional configuration therefore might or might not be
  1453. // created depending on this order. Ensuring that we have installed all of the
  1454. // optional configuration whose dependencies can be met at this point removes
  1455. // any disparities that this creates.
  1456. \Drupal::service('config.installer')->installOptionalConfig();
  1457. // Ensure that the install profile's theme is used.
  1458. // @see _drupal_maintenance_theme()
  1459. \Drupal::service('theme.manager')->resetActiveTheme();
  1460. }
  1461. /**
  1462. * Prepares the system for import and downloads additional translations.
  1463. *
  1464. * @param $install_state
  1465. * An array of information about the current installation state.
  1466. *
  1467. * @return
  1468. * The batch definition, if there are language files to download.
  1469. */
  1470. function install_download_additional_translations_operations(&$install_state) {
  1471. \Drupal::moduleHandler()->loadInclude('locale', 'bulk.inc');
  1472. $langcode = $install_state['parameters']['langcode'];
  1473. if (!($language = entity_load('configurable_language', $langcode))) {
  1474. // Create the language if not already shipped with a profile.
  1475. $language = ConfigurableLanguage::createFromLangcode($langcode);
  1476. }
  1477. $language->save();
  1478. // If a non-English language was selected, change the default language and
  1479. // remove English.
  1480. if ($langcode != 'en') {
  1481. \Drupal::configFactory()->getEditable('system.site')
  1482. ->set('langcode', $langcode)
  1483. ->set('default_langcode', $langcode)
  1484. ->save();
  1485. \Drupal::service('language.default')->set($language);
  1486. if (empty($install_state['profile_info']['keep_english'])) {
  1487. entity_delete_multiple('configurable_language', array('en'));
  1488. }
  1489. }
  1490. // If there is more than one language or the single one is not English, we
  1491. // should download/import translations.
  1492. $languages = \Drupal::languageManager()->getLanguages();
  1493. $operations = array();
  1494. foreach ($languages as $langcode => $language) {
  1495. // The installer language was already downloaded. Check downloads for the
  1496. // other languages if any. Ignore any download errors here, since we
  1497. // are in the middle of an install process and there is no way back. We
  1498. // will not import what we cannot download.
  1499. if ($langcode != 'en' && $langcode != $install_state['parameters']['langcode']) {
  1500. $operations[] = array('install_check_translations', array($langcode, $install_state['server_pattern']));
  1501. }
  1502. }
  1503. return $operations;
  1504. }
  1505. /**
  1506. * Imports languages via a batch process during installation.
  1507. *
  1508. * @param $install_state
  1509. * An array of information about the current installation state.
  1510. *
  1511. * @return
  1512. * The batch definition, if there are language files to import.
  1513. */
  1514. function install_import_translations(&$install_state) {
  1515. \Drupal::moduleHandler()->loadInclude('locale', 'translation.inc');
  1516. // If there is more than one language or the single one is not English, we
  1517. // should import translations.
  1518. $operations = install_download_additional_translations_operations($install_state);
  1519. $languages = \Drupal::languageManager()->getLanguages();
  1520. if (count($languages) > 1 || !isset($languages['en'])) {
  1521. $operations[] = array('_install_prepare_import', array(array_keys($languages), $install_state['server_pattern']));
  1522. // Set up a batch to import translations for drupal core. Translation import
  1523. // for contrib modules happens in install_import_translations_remaining.
  1524. foreach ($languages as $language) {
  1525. if (locale_translation_use_remote_source()) {
  1526. $operations[] = array('locale_translation_batch_fetch_download', array('drupal', $language->getId()));
  1527. }
  1528. $operations[] = array('locale_translation_batch_fetch_import', array('drupal', $language->getId(), array()));
  1529. }
  1530. module_load_include('fetch.inc', 'locale');
  1531. $batch = array(
  1532. 'operations' => $operations,
  1533. 'title' => t('Updating translations.'),
  1534. 'progress_message' => '',
  1535. 'error_message' => t('Error importing translation files'),
  1536. 'finished' => 'locale_translation_batch_fetch_finished',
  1537. 'file' => drupal_get_path('module', 'locale') . '/locale.batch.inc',
  1538. );
  1539. return $batch;
  1540. }
  1541. }
  1542. /**
  1543. * Tells the translation import process that Drupal core is installed.
  1544. *
  1545. * @param array $langcodes
  1546. * Language codes used for the translations.
  1547. * @param string $server_pattern
  1548. * Server access pattern (to replace language code, version number, etc. in).
  1549. */
  1550. function _install_prepare_import($langcodes, $server_pattern) {
  1551. \Drupal::moduleHandler()->loadInclude('locale', 'bulk.inc');
  1552. $matches = array();
  1553. foreach ($langcodes as $langcode) {
  1554. // Get the translation files located in the translations directory.
  1555. $files = locale_translate_get_interface_translation_files(array('drupal'), array($langcode));
  1556. // Pick the first file which matches the language, if any.
  1557. $file = reset($files);
  1558. if (is_object($file)) {
  1559. $filename = $file->filename;
  1560. preg_match('/drupal-([0-9a-z\.-]+)\.' . $langcode . '\.po/', $filename, $matches);
  1561. // Get the version information.
  1562. if ($version = $matches[1]) {
  1563. $info = _install_get_version_info($version);
  1564. // Picking the first file does not necessarily result in the right file. So
  1565. // we check if at least the major version number is available.
  1566. if ($info['major']) {
  1567. $core = $info['major'] . '.x';
  1568. $data = array(
  1569. 'name' => 'drupal',
  1570. 'project_type' => 'module',
  1571. 'core' => $core,
  1572. 'version' => $version,
  1573. 'server_pattern' => $server_pattern,
  1574. 'status' => 1,
  1575. );
  1576. \Drupal::service('locale.project')->set($data['name'], $data);
  1577. module_load_include('compare.inc', 'locale');
  1578. locale_translation_check_projects_local(array('drupal'), array($langcode));
  1579. }
  1580. }
  1581. }
  1582. }
  1583. }
  1584. /**
  1585. * Finishes importing files at end of installation.
  1586. *
  1587. * If other projects besides Drupal core have been installed, their translation
  1588. * will be imported here.
  1589. *
  1590. * @param $install_state
  1591. * An array of information about the current installation state.
  1592. *
  1593. * @return array
  1594. * An array of batch definitions.
  1595. */
  1596. function install_finish_translations(&$install_state) {
  1597. \Drupal::moduleHandler()->loadInclude('locale', 'fetch.inc');
  1598. \Drupal::moduleHandler()->loadInclude('locale', 'compare.inc');
  1599. \Drupal::moduleHandler()->loadInclude('locale', 'bulk.inc');
  1600. // Build a fresh list of installed projects. When more projects than core are
  1601. // installed, their translations will be downloaded (if required) and imported
  1602. // using a batch.
  1603. $projects = locale_translation_build_projects();
  1604. $languages = \Drupal::languageManager()->getLanguages();
  1605. $batches = array();
  1606. if (count($projects) > 1) {
  1607. $options = _locale_translation_default_update_options();
  1608. if ($batch = locale_translation_batch_update_build(array(), array_keys($languages), $options)) {
  1609. $batches[] = $batch;
  1610. }
  1611. }
  1612. // Creates configuration translations.
  1613. $batches[] = locale_config_batch_update_components(array(), array_keys($languages));
  1614. return $batches;
  1615. }
  1616. /**
  1617. * Performs final installation steps and displays a 'finished' page.
  1618. *
  1619. * @param $install_state
  1620. * An array of information about the current installation state.
  1621. *
  1622. * @return
  1623. * A message informing the user that the installation is complete.
  1624. */
  1625. function install_finished(&$install_state) {
  1626. $profile = drupal_get_profile();
  1627. // Installation profiles are always loaded last.
  1628. module_set_weight($profile, 1000);
  1629. // Build the router once after installing all modules.
  1630. // This would normally happen upon KernelEvents::TERMINATE, but since the
  1631. // installer does not use an HttpKernel, that event is never triggered.
  1632. \Drupal::service('router.builder')->rebuild();
  1633. // Run cron to populate update status tables (if available) so that users
  1634. // will be warned if they've installed an out of date Drupal version.
  1635. // Will also trigger indexing of profile-supplied content or feeds.
  1636. \Drupal::service('cron')->run();
  1637. if ($install_state['interactive']) {
  1638. // Load current user and perform final login tasks.
  1639. // This has to be done after drupal_flush_all_caches()
  1640. // to avoid session regeneration.
  1641. $account = User::load(1);
  1642. user_login_finalize($account);
  1643. }
  1644. $success_message = t('Congratulations, you installed @drupal!', array(
  1645. '@drupal' => drupal_install_profile_distribution_name(),
  1646. ));
  1647. drupal_set_message($success_message);
  1648. }
  1649. /**
  1650. * Implements callback_batch_operation().
  1651. *
  1652. * Performs batch installation of modules.
  1653. */
  1654. function _install_module_batch($module, $module_name, &$context) {
  1655. \Drupal::service('module_installer')->install(array($module), FALSE);
  1656. $context['results'][] = $module;
  1657. $context['message'] = t('Installed %module module.', array('%module' => $module_name));
  1658. }
  1659. /**
  1660. * Checks installation requirements and reports any errors.
  1661. *
  1662. * @param string $langcode
  1663. * Language code to check for download.
  1664. * @param string $server_pattern
  1665. * Server access pattern (to replace language code, version number, etc. in).
  1666. *
  1667. * @return array
  1668. * Requirements compliance array. If the translation was downloaded
  1669. * successfully then an empty array is returned. Otherwise the requirements
  1670. * error with detailed information.
  1671. */
  1672. function install_check_translations($langcode, $server_pattern) {
  1673. $requirements = array();
  1674. $readable = FALSE;
  1675. $writable = FALSE;
  1676. // @todo: Make this configurable.
  1677. $site_path = \Drupal::service('site.path');
  1678. $files_directory = $site_path . '/files';
  1679. $translations_directory = $site_path . '/files/translations';
  1680. $translations_directory_exists = FALSE;
  1681. $online = FALSE;
  1682. // First attempt to create or make writable the files directory.
  1683. file_prepare_directory($files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  1684. // Then, attempt to create or make writable the translations directory.
  1685. file_prepare_directory($translations_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  1686. // Get values so the requirements errors can be specific.
  1687. if (drupal_verify_install_file($translations_directory, FILE_EXIST, 'dir')) {
  1688. $readable = is_readable($translations_directory);
  1689. $writable = is_writable($translations_directory);
  1690. $translations_directory_exists = TRUE;
  1691. }
  1692. // The file already exists, no need to attempt to download.
  1693. if ($existing_file = glob($translations_directory . '/drupal-*.' . $langcode . '.po')) {
  1694. return;
  1695. }
  1696. // Build URL for the translation file and the translation server.
  1697. $variables = array(
  1698. '%project' => 'drupal',
  1699. '%version' => \Drupal::VERSION,
  1700. '%core' => \Drupal::CORE_COMPATIBILITY,
  1701. '%language' => $langcode,
  1702. );
  1703. $translation_url = strtr($server_pattern, $variables);
  1704. $elements = parse_url($translation_url);
  1705. $server_url = $elements['scheme'] . '://' . $elements['host'];
  1706. // Build the language name for display.
  1707. $languages = LanguageManager::getStandardLanguageList();
  1708. $language = isset($languages[$langcode]) ? $languages[$langcode][0] : $langcode;
  1709. // Check if any of the desired translation files are available or if the
  1710. // translation server can be reached. In other words, check if we are online
  1711. // and have an internet connection.
  1712. if ($translation_available = install_check_localization_server($translation_url)) {
  1713. $online = TRUE;
  1714. }
  1715. if (!$translation_available) {
  1716. if (install_check_localization_server($server_url)) {
  1717. $online = TRUE;
  1718. }
  1719. }
  1720. // If the translations directory does not exists, throw an error.
  1721. if (!$translations_directory_exists) {
  1722. $requirements['translations directory exists'] = array(
  1723. 'title' => t('Translations directory'),
  1724. 'value' => t('The translations directory does not exist.'),
  1725. 'severity' => REQUIREMENT_ERROR,
  1726. 'description' => t('The installer requires that you create a translations directory as part of the installation process. Create the directory %translations_directory . More details about installing Drupal are available in <a href=":install_txt">INSTALL.txt</a>.', array('%translations_directory' => $translations_directory, ':install_txt' => base_path() . 'core/INSTALL.txt')),
  1727. );
  1728. }
  1729. else {
  1730. $requirements['translations directory exists'] = array(
  1731. 'title' => t('Translations directory'),
  1732. 'value' => t('The directory %translations_directory exists.', array('%translations_directory' => $translations_directory)),
  1733. );
  1734. // If the translations directory is not readable, throw an error.
  1735. if (!$readable) {
  1736. $requirements['translations directory readable'] = array(
  1737. 'title' => t('Translations directory'),
  1738. 'value' => t('The translations directory is not readable.'),
  1739. 'severity' => REQUIREMENT_ERROR,
  1740. 'description' => t('The installer requires read permissions to %translations_directory at all times. The <a href=":handbook_url">webhosting issues</a> documentation section offers help on this and other topics.', array('%translations_directory' => $translations_directory, ':handbook_url' => 'https://www.drupal.org/server-permissions')),
  1741. );
  1742. }
  1743. // If translations directory is not writable, throw an error.
  1744. if (!$writable) {
  1745. $requirements['translations directory writable'] = array(
  1746. 'title' => t('Translations directory'),
  1747. 'value' => t('The translations directory is not writable.'),
  1748. 'severity' => REQUIREMENT_ERROR,
  1749. 'description' => t('The installer requires write permissions to %translations_directory during the installation process. The <a href=":handbook_url">webhosting issues</a> documentation section offers help on this and other topics.', array('%translations_directory' => $translations_directory, ':handbook_url' => 'https://www.drupal.org/server-permissions')),
  1750. );
  1751. }
  1752. else {
  1753. $requirements['translations directory writable'] = array(
  1754. 'title' => t('Translations directory'),
  1755. 'value' => t('The translations directory is writable.'),
  1756. );
  1757. }
  1758. }
  1759. // If the translations server can not be contacted, throw an error.
  1760. if (!$online) {
  1761. $requirements['online'] = array(
  1762. 'title' => t('Internet'),
  1763. 'value' => t('The translation server is offline.'),
  1764. 'severity' => REQUIREMENT_ERROR,
  1765. 'description' => t('The installer requires to contact the translation server to download a translation file. Check your internet connection and verify that your website can reach the translation server at <a href=":server_url">@server_url</a>.', array(':server_url' => $server_url, '@server_url' => $server_url)),
  1766. );
  1767. }
  1768. else {
  1769. $requirements['online'] = array(
  1770. 'title' => t('Internet'),
  1771. 'value' => t('The translation server is online.'),
  1772. );
  1773. // If translation file is not found at the translation server, throw an
  1774. // error.
  1775. if (!$translation_available) {
  1776. $requirements['translation available'] = array(
  1777. 'title' => t('Translation'),
  1778. 'value' => t('The %language translation is not available.', array('%language' => $language)),
  1779. 'severity' => REQUIREMENT_ERROR,
  1780. 'description' => t('The %language translation file is not available at the translation server. <a href=":url">Choose a different language</a> or select English and translate your website later.', array('%language' => $language, ':url' => $_SERVER['SCRIPT_NAME'])),
  1781. );
  1782. }
  1783. else {
  1784. $requirements['translation available'] = array(
  1785. 'title' => t('Translation'),
  1786. 'value' => t('The %language translation is available.', array('%language' => $language)),
  1787. );
  1788. }
  1789. }
  1790. if ($translations_directory_exists && $readable && $writable && $translation_available) {
  1791. $translation_downloaded = install_retrieve_file($translation_url, $translations_directory);
  1792. if (!$translation_downloaded) {
  1793. $requirements['translation downloaded'] = array(
  1794. 'title' => t('Translation'),
  1795. 'value' => t('The %language translation could not be downloaded.', array('%language' => $language)),
  1796. 'severity' => REQUIREMENT_ERROR,
  1797. 'description' => t('The %language translation file could not be downloaded. <a href=":url">Choose a different language</a> or select English and translate your website later.', array('%language' => $language, ':url' => $_SERVER['SCRIPT_NAME'])),
  1798. );
  1799. }
  1800. }
  1801. return $requirements;
  1802. }
  1803. /**
  1804. * Checks installation requirements and reports any errors.
  1805. */
  1806. function install_check_requirements($install_state) {
  1807. $profile = $install_state['parameters']['profile'];
  1808. // Check the profile requirements.
  1809. $requirements = drupal_check_profile($profile);
  1810. if ($install_state['settings_verified']) {
  1811. return $requirements;
  1812. }
  1813. // If Drupal is not set up already, we need to try to create the default
  1814. // settings and services files.
  1815. $default_files = array();
  1816. $default_files['settings.php'] = array(
  1817. 'file' => 'settings.php',
  1818. 'file_default' => 'default.settings.php',
  1819. 'title_default' => t('Default settings file'),
  1820. 'description_default' => t('The default settings file does not exist.'),
  1821. 'title' => t('Settings file'),
  1822. );
  1823. foreach ($default_files as $default_file_info) {
  1824. $readable = FALSE;
  1825. $writable = FALSE;
  1826. $site_path = './' . \Drupal::service('site.path');
  1827. $file = $site_path . "/{$default_file_info['file']}";
  1828. $default_file = "./sites/default/{$default_file_info['file_default']}";
  1829. $exists = FALSE;
  1830. // Verify that the directory exists.
  1831. if (drupal_verify_install_file($site_path, FILE_EXIST, 'dir')) {
  1832. if (drupal_verify_install_file($file, FILE_EXIST)) {
  1833. // If it does, make sure it is writable.
  1834. $readable = drupal_verify_install_file($file, FILE_READABLE);
  1835. $writable = drupal_verify_install_file($file, FILE_WRITABLE);
  1836. $exists = TRUE;
  1837. }
  1838. }
  1839. // If the default $default_file does not exist, or is not readable,
  1840. // report an error.
  1841. if (!drupal_verify_install_file($default_file, FILE_EXIST | FILE_READABLE)) {
  1842. $requirements["default $file file exists"] = array(
  1843. 'title' => $default_file_info['title_default'],
  1844. 'value' => $default_file_info['description_default'],
  1845. 'severity' => REQUIREMENT_ERROR,
  1846. 'description' => t('The @drupal installer requires that the %default-file file not be modified in any way from the original download.', array(
  1847. '@drupal' => drupal_install_profile_distribution_name(),
  1848. '%default-file' => $default_file
  1849. )),
  1850. );
  1851. }
  1852. // Otherwise, if $file does not exist yet, we can try to copy
  1853. // $default_file to create it.
  1854. elseif (!$exists) {
  1855. $copied = drupal_verify_install_file($site_path, FILE_EXIST | FILE_WRITABLE, 'dir') && @copy($default_file, $file);
  1856. if ($copied) {
  1857. // If the new $file file has the same owner as $default_file this means
  1858. // $default_file is owned by the webserver user. This is an inherent
  1859. // security weakness because it allows a malicious webserver process to
  1860. // append arbitrary PHP code and then execute it. However, it is also a
  1861. // common configuration on shared hosting, and there is nothing Drupal
  1862. // can do to prevent it. In this situation, having $file also owned by
  1863. // the webserver does not introduce any additional security risk, so we
  1864. // keep the file in place. Additionally, this situation also occurs when
  1865. // the test runner is being run be different user than the webserver.
  1866. if (fileowner($default_file) === fileowner($file) || DRUPAL_TEST_IN_CHILD_SITE) {
  1867. $readable = drupal_verify_install_file($file, FILE_READABLE);
  1868. $writable = drupal_verify_install_file($file, FILE_WRITABLE);
  1869. $exists = TRUE;
  1870. }
  1871. // If $file and $default_file have different owners, this probably means
  1872. // the server is set up "securely" (with the webserver running as its
  1873. // own user, distinct from the user who owns all the Drupal PHP files),
  1874. // although with either a group or world writable sites directory.
  1875. // Keeping $file owned by the webserver would therefore introduce a
  1876. // security risk. It would also cause a usability problem, since site
  1877. // owners who do not have root access to the file system would be unable
  1878. // to edit their settings file later on. We therefore must delete the
  1879. // file we just created and force the administrator to log on to the
  1880. // server and create it manually.
  1881. else {
  1882. $deleted = @drupal_unlink($file);
  1883. // We expect deleting the file to be successful (since we just
  1884. // created it ourselves above), but if it fails somehow, we set a
  1885. // variable so we can display a one-time error message to the
  1886. // administrator at the bottom of the requirements list. We also try
  1887. // to make the file writable, to eliminate any conflicting error
  1888. // messages in the requirements list.
  1889. $exists = !$deleted;
  1890. if ($exists) {
  1891. $settings_file_ownership_error = TRUE;
  1892. $readable = drupal_verify_install_file($file, FILE_READABLE);
  1893. $writable = drupal_verify_install_file($file, FILE_WRITABLE);
  1894. }
  1895. }
  1896. }
  1897. }
  1898. // If the $file does not exist, throw an error.
  1899. if (!$exists) {
  1900. $requirements["$file file exists"] = array(
  1901. 'title' => $default_file_info['title'],
  1902. 'value' => t('The %file does not exist.', array('%file' => $default_file_info['title'])),
  1903. 'severity' => REQUIREMENT_ERROR,
  1904. 'description' => t('The @drupal installer requires that you create a %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(
  1905. '@drupal' => drupal_install_profile_distribution_name(),
  1906. '%file' => $file,
  1907. '%default_file' => $default_file,
  1908. ':install_txt' => base_path() . 'core/INSTALL.txt'
  1909. )),
  1910. );
  1911. }
  1912. else {
  1913. $requirements["$file file exists"] = array(
  1914. 'title' => $default_file_info['title'],
  1915. 'value' => t('The %file exists.', array('%file' => $file)),
  1916. );
  1917. // If the $file is not readable, throw an error.
  1918. if (!$readable) {
  1919. $requirements["$file file readable"] = array(
  1920. 'title' => $default_file_info['title'],
  1921. 'value' => t('The %file is not readable.', array('%file' => $default_file_info['title'])),
  1922. 'severity' => REQUIREMENT_ERROR,
  1923. 'description' => t('@drupal requires read permissions to %file at all times. The <a href=":handbook_url">webhosting issues</a> documentation section offers help on this and other topics.', array(
  1924. '@drupal' => drupal_install_profile_distribution_name(),
  1925. '%file' => $file,
  1926. ':handbook_url' => 'https://www.drupal.org/server-permissions'
  1927. )),
  1928. );
  1929. }
  1930. // If the $file is not writable, throw an error.
  1931. if (!$writable) {
  1932. $requirements["$file file writeable"] = array(
  1933. 'title' => $default_file_info['title'],
  1934. 'value' => t('The %file is not writable.', array('%file' => $default_file_info['title'])),
  1935. 'severity' => REQUIREMENT_ERROR,
  1936. 'description' => t('The @drupal installer requires write permissions to %file during the installation process. The <a href=":handbook_url">webhosting issues</a> documentation section offers help on this and other topics.', array(
  1937. '@drupal' => drupal_install_profile_distribution_name(),
  1938. '%file' => $file,
  1939. ':handbook_url' => 'https://www.drupal.org/server-permissions'
  1940. )),
  1941. );
  1942. }
  1943. else {
  1944. $requirements["$file file"] = array(
  1945. 'title' => $default_file_info['title'],
  1946. 'value' => t('The @file is writable.', array('@file' => $default_file_info['title'])),
  1947. );
  1948. }
  1949. if (!empty($settings_file_ownership_error)) {
  1950. $requirements["$file file ownership"] = array(
  1951. 'title' => $default_file_info['title'],
  1952. 'value' => t('The @file is owned by the web server.', array('@file' => $default_file_info['title'])),
  1953. 'severity' => REQUIREMENT_ERROR,
  1954. 'description' => t('The @drupal installer failed to create a %file 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>. The <a href=":handbook_url">webhosting issues</a> documentation section offers help on this and other topics.', array(
  1955. '@drupal' => drupal_install_profile_distribution_name(),
  1956. '%file' => $file,
  1957. '%default_file' => $default_file,
  1958. ':install_txt' => base_path() . 'core/INSTALL.txt',
  1959. ':handbook_url' => 'https://www.drupal.org/server-permissions'
  1960. )),
  1961. );
  1962. }
  1963. }
  1964. }
  1965. return $requirements;
  1966. }
  1967. /**
  1968. * Displays installation requirements.
  1969. *
  1970. * @param array $install_state
  1971. * An array of information about the current installation state.
  1972. * @param array $requirements
  1973. * An array of requirements, in the same format as is returned by
  1974. * hook_requirements().
  1975. *
  1976. * @return
  1977. * A themed status report, or an exception if there are requirement errors.
  1978. * If there are only requirement warnings, a themed status report is shown
  1979. * initially, but the user is allowed to bypass it by providing 'continue=1'
  1980. * in the URL. Otherwise, no output is returned, so that the next task can be
  1981. * run in the same page request.
  1982. *
  1983. * @throws \Drupal\Core\Installer\Exception\InstallerException
  1984. */
  1985. function install_display_requirements($install_state, $requirements) {
  1986. // Check the severity of the requirements reported.
  1987. $severity = drupal_requirements_severity($requirements);
  1988. // If there are errors, always display them. If there are only warnings, skip
  1989. // them if the user has provided a URL parameter acknowledging the warnings
  1990. // and indicating a desire to continue anyway. See drupal_requirements_url().
  1991. if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING && empty($install_state['parameters']['continue']))) {
  1992. if ($install_state['interactive']) {
  1993. $build['report']['#theme'] = 'status_report';
  1994. $build['report']['#requirements'] = $requirements;
  1995. if ($severity == REQUIREMENT_WARNING) {
  1996. $build['#title'] = t('Requirements review');
  1997. $build['#suffix'] = t('Check the messages and <a href=":retry">retry</a>, or you may choose to <a href=":cont">continue anyway</a>.', array(':retry' => drupal_requirements_url(REQUIREMENT_ERROR), ':cont' => drupal_requirements_url($severity)));
  1998. }
  1999. else {
  2000. $build['#title'] = t('Requirements problem');
  2001. $build['#suffix'] = t('Check the messages and <a href=":url">try again</a>.', array(':url' => drupal_requirements_url($severity)));
  2002. }
  2003. return $build;
  2004. }
  2005. else {
  2006. // Throw an exception showing any unmet requirements.
  2007. $failures = array();
  2008. foreach ($requirements as $requirement) {
  2009. // Skip warnings altogether for non-interactive installations; these
  2010. // proceed in a single request so there is no good opportunity (and no
  2011. // good method) to warn the user anyway.
  2012. if (isset($requirement['severity']) && $requirement['severity'] == REQUIREMENT_ERROR) {
  2013. $failures[] = $requirement['title'] . ': ' . $requirement['value'] . "\n\n" . $requirement['description'];
  2014. }
  2015. }
  2016. if (!empty($failures)) {
  2017. throw new InstallerException(implode("\n\n", $failures));
  2018. }
  2019. }
  2020. }
  2021. }
  2022. /**
  2023. * Installation task; ensures install profile is written to settings.php.
  2024. *
  2025. * @param array $install_state
  2026. * An array of information about the current installation state.
  2027. */
  2028. function install_write_profile($install_state) {
  2029. if (Settings::get('install_profile') !== $install_state['parameters']['profile']) {
  2030. // Remember the profile which was used.
  2031. $settings['settings']['install_profile'] = (object) array(
  2032. 'value' => $install_state['parameters']['profile'],
  2033. 'required' => TRUE,
  2034. );
  2035. drupal_rewrite_settings($settings);
  2036. }
  2037. }