install.core.inc 100 KB

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