install.core.inc 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451
  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. * Depending on the context from which it's being called, this method
  1191. * may be used to:
  1192. * - Automatically select a profile under certain conditions.
  1193. * - Indicate which profile has already been selected.
  1194. * - Indicate that a profile still needs to be selected.
  1195. *
  1196. * A profile will be selected automatically if one of the following conditions
  1197. * is met. They are checked in the given order:
  1198. * - Only one profile is available.
  1199. * - A specific profile name is requested in installation parameters:
  1200. * - For interactive installations via request query parameters.
  1201. * - For non-interactive installations via install_drupal() settings.
  1202. * - One of the available profiles is a distribution. If multiple profiles are
  1203. * distributions, then the first discovered profile will be selected.
  1204. * - Only one visible profile is available.
  1205. *
  1206. * @param array $install_state
  1207. * The current installer state, containing a 'profiles' key, which is an
  1208. * associative array of profiles with the machine-readable names as keys.
  1209. *
  1210. * @return string|null
  1211. * The machine-readable name of the selected profile or NULL if no profile was
  1212. * selected.
  1213. *
  1214. * @see install_select_profile()
  1215. */
  1216. function _install_select_profile(&$install_state) {
  1217. // If there is only one profile available it will always be the one selected.
  1218. if (count($install_state['profiles']) == 1) {
  1219. return key($install_state['profiles']);
  1220. }
  1221. // If a valid profile has already been selected, return the selection.
  1222. if (!empty($install_state['parameters']['profile'])) {
  1223. $profile = $install_state['parameters']['profile'];
  1224. if (isset($install_state['profiles'][$profile])) {
  1225. return $profile;
  1226. }
  1227. }
  1228. // If any of the profiles are distribution profiles, return the first one.
  1229. foreach ($install_state['profiles'] as $profile) {
  1230. $profile_info = install_profile_info($profile->getName());
  1231. if (!empty($profile_info['distribution'])) {
  1232. return $profile->getName();
  1233. }
  1234. }
  1235. // Get all visible (not hidden) profiles.
  1236. $visible_profiles = array_filter($install_state['profiles'], function ($profile) {
  1237. $profile_info = install_profile_info($profile->getName());
  1238. return !isset($profile_info['hidden']) || !$profile_info['hidden'];
  1239. });
  1240. // If there is only one visible profile, return it.
  1241. if (count($visible_profiles) == 1) {
  1242. return (key($visible_profiles));
  1243. }
  1244. }
  1245. /**
  1246. * Finds all .po files that are useful to the installer.
  1247. *
  1248. * @return
  1249. * An associative array of file URIs keyed by language code. URIs as
  1250. * returned by file_scan_directory().
  1251. *
  1252. * @see file_scan_directory()
  1253. */
  1254. function install_find_translations() {
  1255. $translations = [];
  1256. $files = \Drupal::service('string_translator.file_translation')->findTranslationFiles();
  1257. // English does not need a translation file.
  1258. array_unshift($files, (object) ['name' => 'en']);
  1259. foreach ($files as $uri => $file) {
  1260. // Strip off the file name component before the language code.
  1261. $langcode = preg_replace('!^(.+\.)?([^\.]+)$!', '\2', $file->name);
  1262. // Language codes cannot exceed 12 characters to fit into the {language}
  1263. // table.
  1264. if (strlen($langcode) <= 12) {
  1265. $translations[$langcode] = $uri;
  1266. }
  1267. }
  1268. return $translations;
  1269. }
  1270. /**
  1271. * Selects which language to use during installation.
  1272. *
  1273. * @param $install_state
  1274. * An array of information about the current installation state. The chosen
  1275. * langcode will be added here, if it was not already selected previously, as
  1276. * will a list of all available languages.
  1277. *
  1278. * @return
  1279. * For interactive installations, a form or other page output allowing the
  1280. * language to be selected or providing information about language selection,
  1281. * if a language has not been chosen. Otherwise, an exception is thrown if a
  1282. * language cannot be chosen automatically.
  1283. */
  1284. function install_select_language(&$install_state) {
  1285. // Find all available translation files.
  1286. $files = install_find_translations();
  1287. $install_state['translations'] += $files;
  1288. // If a valid language code is set, continue with the next installation step.
  1289. // When translations from the localization server are used, any language code
  1290. // is accepted because the standard language list is kept in sync with the
  1291. // languages available at http://localize.drupal.org.
  1292. // When files from the translation directory are used, we only accept
  1293. // languages for which a file is available.
  1294. if (!empty($install_state['parameters']['langcode'])) {
  1295. $standard_languages = LanguageManager::getStandardLanguageList();
  1296. $langcode = $install_state['parameters']['langcode'];
  1297. if ($langcode == 'en' || isset($files[$langcode]) || isset($standard_languages[$langcode])) {
  1298. $install_state['parameters']['langcode'] = $langcode;
  1299. return;
  1300. }
  1301. }
  1302. if (empty($install_state['parameters']['langcode'])) {
  1303. // If we are performing an interactive installation, we display a form to
  1304. // select a right language. If no translation files were found in the
  1305. // translations directory, the form shows a list of standard languages. If
  1306. // translation files were found the form shows a select list of the
  1307. // corresponding languages to choose from.
  1308. if ($install_state['interactive']) {
  1309. return install_get_form('Drupal\Core\Installer\Form\SelectLanguageForm', $install_state);
  1310. }
  1311. // If we are performing a non-interactive installation. If only one language
  1312. // (English) is available, assume the user knows what he is doing. Otherwise
  1313. // throw an error.
  1314. else {
  1315. if (count($files) == 1) {
  1316. $install_state['parameters']['langcode'] = current(array_keys($files));
  1317. return;
  1318. }
  1319. else {
  1320. throw new InstallerException(t('You must select a language to continue the installation.'));
  1321. }
  1322. }
  1323. }
  1324. }
  1325. /**
  1326. * Download a translation file for the selected language.
  1327. *
  1328. * @param array $install_state
  1329. * An array of information about the current installation state.
  1330. *
  1331. * @return string
  1332. * A themed status report, or an exception if there are requirement errors.
  1333. * Upon successful download the page is reloaded and no output is returned.
  1334. */
  1335. function install_download_translation(&$install_state) {
  1336. // Check whether all conditions are met to download. Download the translation
  1337. // if possible.
  1338. $requirements = install_check_translations($install_state['parameters']['langcode'], $install_state['server_pattern']);
  1339. if ($output = install_display_requirements($install_state, $requirements)) {
  1340. return $output;
  1341. }
  1342. // The download was successful, reload the page in the new language.
  1343. $install_state['translations'][$install_state['parameters']['langcode']] = TRUE;
  1344. if ($install_state['interactive']) {
  1345. install_goto(install_redirect_url($install_state));
  1346. }
  1347. }
  1348. /**
  1349. * Attempts to get a file using a HTTP request and to store it locally.
  1350. *
  1351. * @param string $uri
  1352. * The URI of the file to grab.
  1353. * @param string $destination
  1354. * Stream wrapper URI specifying where the file should be placed. If a
  1355. * directory path is provided, the file is saved into that directory under its
  1356. * original name. If the path contains a filename as well, that one will be
  1357. * used instead.
  1358. *
  1359. * @return bool
  1360. * TRUE on success, FALSE on failure.
  1361. */
  1362. function install_retrieve_file($uri, $destination) {
  1363. $parsed_url = parse_url($uri);
  1364. if (is_dir(\Drupal::service('file_system')->realpath($destination))) {
  1365. // Prevent URIs with triple slashes when gluing parts together.
  1366. $path = str_replace('///', '//', "$destination/") . drupal_basename($parsed_url['path']);
  1367. }
  1368. else {
  1369. $path = $destination;
  1370. }
  1371. try {
  1372. $response = \Drupal::httpClient()->get($uri, ['headers' => ['Accept' => 'text/plain']]);
  1373. $data = (string) $response->getBody();
  1374. if (empty($data)) {
  1375. return FALSE;
  1376. }
  1377. }
  1378. catch (RequestException $e) {
  1379. return FALSE;
  1380. }
  1381. return file_put_contents($path, $data) !== FALSE;
  1382. }
  1383. /**
  1384. * Checks if the localization server can be contacted.
  1385. *
  1386. * @param string $uri
  1387. * The URI to contact.
  1388. *
  1389. * @return string
  1390. * TRUE if the URI was contacted successfully, FALSE if not.
  1391. */
  1392. function install_check_localization_server($uri) {
  1393. try {
  1394. \Drupal::httpClient()->head($uri);
  1395. return TRUE;
  1396. }
  1397. catch (RequestException $e) {
  1398. return FALSE;
  1399. }
  1400. }
  1401. /**
  1402. * Extracts version information from a drupal core version string.
  1403. *
  1404. * @param string $version
  1405. * Version info string (e.g., 8.0.0, 8.1.0, 8.0.0-dev, 8.0.0-unstable1,
  1406. * 8.0.0-alpha2, 8.0.0-beta3, 8.6.x, and 8.0.0-rc4).
  1407. *
  1408. * @return array
  1409. * Associative array of version info:
  1410. * - major: Major version (e.g., "8").
  1411. * - minor: Minor version (e.g., "0").
  1412. * - patch: Patch version (e.g., "0").
  1413. * - extra: Extra version info (e.g., "alpha2").
  1414. * - extra_text: The text part of "extra" (e.g., "alpha").
  1415. * - extra_number: The number part of "extra" (e.g., "2").
  1416. */
  1417. function _install_get_version_info($version) {
  1418. preg_match('/
  1419. (
  1420. (?P<major>[0-9]+) # Major release number.
  1421. \. # .
  1422. (?P<minor>[0-9]+) # Minor release number.
  1423. \. # .
  1424. (?P<patch>[0-9]+|x) # Patch release number.
  1425. ) #
  1426. ( #
  1427. - # - separator for "extra" version information.
  1428. (?P<extra> #
  1429. (?P<extra_text>[a-z]+) # Release extra text (e.g., "alpha").
  1430. (?P<extra_number>[0-9]*) # Release extra number (no separator between text and number).
  1431. ) #
  1432. | # OR no "extra" information.
  1433. )
  1434. /sx', $version, $matches);
  1435. return $matches;
  1436. }
  1437. /**
  1438. * Loads information about the chosen profile during installation.
  1439. *
  1440. * @param $install_state
  1441. * An array of information about the current installation state. The loaded
  1442. * profile information will be added here.
  1443. */
  1444. function install_load_profile(&$install_state) {
  1445. global $config_directories;
  1446. $profile = $install_state['parameters']['profile'];
  1447. $install_state['profiles'][$profile]->load();
  1448. $install_state['profile_info'] = install_profile_info($profile, isset($install_state['parameters']['langcode']) ? $install_state['parameters']['langcode'] : 'en');
  1449. if (!empty($install_state['parameters']['existing_config']) && !empty($config_directories[CONFIG_SYNC_DIRECTORY])) {
  1450. $install_state['config_install_path'] = $config_directories[CONFIG_SYNC_DIRECTORY];
  1451. }
  1452. // If the profile has a config/sync directory copy the information to the
  1453. // install_state global.
  1454. elseif (!empty($install_state['profile_info']['config_install_path'])) {
  1455. $install_state['config_install_path'] = $install_state['profile_info']['config_install_path'];
  1456. }
  1457. if (!empty($install_state['config_install_path'])) {
  1458. $sync = new FileStorage($install_state['config_install_path']);
  1459. $install_state['config']['system.site'] = $sync->read('system.site');
  1460. }
  1461. }
  1462. /**
  1463. * Performs a full bootstrap of Drupal during installation.
  1464. */
  1465. function install_bootstrap_full() {
  1466. // Store the session on the request object and start it.
  1467. /** @var \Symfony\Component\HttpFoundation\Session\SessionInterface $session */
  1468. $session = \Drupal::service('session');
  1469. \Drupal::request()->setSession($session);
  1470. $session->start();
  1471. }
  1472. /**
  1473. * Installs required modules via a batch process.
  1474. *
  1475. * @param $install_state
  1476. * An array of information about the current installation state.
  1477. *
  1478. * @return
  1479. * The batch definition.
  1480. */
  1481. function install_profile_modules(&$install_state) {
  1482. // We need to manually trigger the installation of core-provided entity types,
  1483. // as those will not be handled by the module installer.
  1484. install_core_entity_type_definitions();
  1485. $modules = \Drupal::state()->get('install_profile_modules') ?: [];
  1486. $files = system_rebuild_module_data();
  1487. \Drupal::state()->delete('install_profile_modules');
  1488. // Always install required modules first. Respect the dependencies between
  1489. // the modules.
  1490. $required = [];
  1491. $non_required = [];
  1492. // Add modules that other modules depend on.
  1493. foreach ($modules as $module) {
  1494. if ($files[$module]->requires) {
  1495. $modules = array_merge($modules, array_keys($files[$module]->requires));
  1496. }
  1497. }
  1498. $modules = array_unique($modules);
  1499. foreach ($modules as $module) {
  1500. if (!empty($files[$module]->info['required'])) {
  1501. $required[$module] = $files[$module]->sort;
  1502. }
  1503. else {
  1504. $non_required[$module] = $files[$module]->sort;
  1505. }
  1506. }
  1507. arsort($required);
  1508. arsort($non_required);
  1509. $operations = [];
  1510. foreach ($required + $non_required as $module => $weight) {
  1511. $operations[] = ['_install_module_batch', [$module, $files[$module]->info['name']]];
  1512. }
  1513. $batch = [
  1514. 'operations' => $operations,
  1515. 'title' => t('Installing @drupal', ['@drupal' => drupal_install_profile_distribution_name()]),
  1516. 'error_message' => t('The installation has encountered an error.'),
  1517. ];
  1518. return $batch;
  1519. }
  1520. /**
  1521. * Installs entity type definitions provided by core.
  1522. */
  1523. function install_core_entity_type_definitions() {
  1524. $update_manager = \Drupal::entityDefinitionUpdateManager();
  1525. foreach (\Drupal::entityManager()->getDefinitions() as $entity_type) {
  1526. if ($entity_type->getProvider() == 'core') {
  1527. $update_manager->installEntityType($entity_type);
  1528. }
  1529. }
  1530. }
  1531. /**
  1532. * Installs themes.
  1533. *
  1534. * This does not use a batch, since installing themes is faster than modules and
  1535. * because an installation profile typically installs 1-3 themes only (default
  1536. * theme, base theme, admin theme).
  1537. *
  1538. * @param $install_state
  1539. * An array of information about the current installation state.
  1540. */
  1541. function install_profile_themes(&$install_state) {
  1542. // Install the themes specified by the installation profile.
  1543. $themes = $install_state['profile_info']['themes'];
  1544. \Drupal::service('theme_handler')->install($themes);
  1545. // Ensure that the install profile's theme is used.
  1546. // @see _drupal_maintenance_theme()
  1547. \Drupal::theme()->resetActiveTheme();
  1548. }
  1549. /**
  1550. * Installs the install profile.
  1551. *
  1552. * @param $install_state
  1553. * An array of information about the current installation state.
  1554. */
  1555. function install_install_profile(&$install_state) {
  1556. \Drupal::service('module_installer')->install([drupal_get_profile()], FALSE);
  1557. // Install all available optional config. During installation the module order
  1558. // is determined by dependencies. If there are no dependencies between modules
  1559. // then the order in which they are installed is dependent on random factors
  1560. // like PHP version. Optional configuration therefore might or might not be
  1561. // created depending on this order. Ensuring that we have installed all of the
  1562. // optional configuration whose dependencies can be met at this point removes
  1563. // any disparities that this creates.
  1564. \Drupal::service('config.installer')->installOptionalConfig();
  1565. // Ensure that the install profile's theme is used.
  1566. // @see _drupal_maintenance_theme()
  1567. \Drupal::theme()->resetActiveTheme();
  1568. }
  1569. /**
  1570. * Prepares the system for import and downloads additional translations.
  1571. *
  1572. * @param $install_state
  1573. * An array of information about the current installation state.
  1574. *
  1575. * @return
  1576. * The batch definition, if there are language files to download.
  1577. */
  1578. function install_download_additional_translations_operations(&$install_state) {
  1579. \Drupal::moduleHandler()->loadInclude('locale', 'bulk.inc');
  1580. $langcode = $install_state['parameters']['langcode'];
  1581. if (!($language = ConfigurableLanguage::load($langcode))) {
  1582. // Create the language if not already shipped with a profile.
  1583. $language = ConfigurableLanguage::createFromLangcode($langcode);
  1584. }
  1585. $language->save();
  1586. // If a non-English language was selected, change the default language and
  1587. // remove English.
  1588. if ($langcode != 'en') {
  1589. \Drupal::configFactory()->getEditable('system.site')
  1590. ->set('langcode', $langcode)
  1591. ->set('default_langcode', $langcode)
  1592. ->save();
  1593. \Drupal::service('language.default')->set($language);
  1594. if (empty($install_state['profile_info']['keep_english'])) {
  1595. entity_delete_multiple('configurable_language', ['en']);
  1596. }
  1597. }
  1598. // If there is more than one language or the single one is not English, we
  1599. // should download/import translations.
  1600. $languages = \Drupal::languageManager()->getLanguages();
  1601. $operations = [];
  1602. foreach ($languages as $langcode => $language) {
  1603. // The installer language was already downloaded. Check downloads for the
  1604. // other languages if any. Ignore any download errors here, since we
  1605. // are in the middle of an install process and there is no way back. We
  1606. // will not import what we cannot download.
  1607. if ($langcode != 'en' && $langcode != $install_state['parameters']['langcode']) {
  1608. $operations[] = ['install_check_translations', [$langcode, $install_state['server_pattern']]];
  1609. }
  1610. }
  1611. return $operations;
  1612. }
  1613. /**
  1614. * Imports languages via a batch process during installation.
  1615. *
  1616. * @param $install_state
  1617. * An array of information about the current installation state.
  1618. *
  1619. * @return
  1620. * The batch definition, if there are language files to import.
  1621. */
  1622. function install_import_translations(&$install_state) {
  1623. \Drupal::moduleHandler()->loadInclude('locale', 'translation.inc');
  1624. // If there is more than one language or the single one is not English, we
  1625. // should import translations.
  1626. $operations = install_download_additional_translations_operations($install_state);
  1627. $languages = \Drupal::languageManager()->getLanguages();
  1628. if (count($languages) > 1 || !isset($languages['en'])) {
  1629. $operations[] = ['_install_prepare_import', [array_keys($languages), $install_state['server_pattern']]];
  1630. // Set up a batch to import translations for drupal core. Translation import
  1631. // for contrib modules happens in install_import_translations_remaining.
  1632. foreach ($languages as $language) {
  1633. if (locale_translation_use_remote_source()) {
  1634. $operations[] = ['locale_translation_batch_fetch_download', ['drupal', $language->getId()]];
  1635. }
  1636. $operations[] = ['locale_translation_batch_fetch_import', ['drupal', $language->getId(), []]];
  1637. }
  1638. module_load_include('fetch.inc', 'locale');
  1639. $batch = [
  1640. 'operations' => $operations,
  1641. 'title' => t('Updating translations.'),
  1642. 'progress_message' => '',
  1643. 'error_message' => t('Error importing translation files'),
  1644. 'finished' => 'locale_translation_batch_fetch_finished',
  1645. 'file' => drupal_get_path('module', 'locale') . '/locale.batch.inc',
  1646. ];
  1647. return $batch;
  1648. }
  1649. }
  1650. /**
  1651. * Tells the translation import process that Drupal core is installed.
  1652. *
  1653. * @param array $langcodes
  1654. * Language codes used for the translations.
  1655. * @param string $server_pattern
  1656. * Server access pattern (to replace language code, version number, etc. in).
  1657. */
  1658. function _install_prepare_import($langcodes, $server_pattern) {
  1659. \Drupal::moduleHandler()->loadInclude('locale', 'bulk.inc');
  1660. $matches = [];
  1661. foreach ($langcodes as $langcode) {
  1662. // Get the translation files located in the translations directory.
  1663. $files = locale_translate_get_interface_translation_files(['drupal'], [$langcode]);
  1664. // Pick the first file which matches the language, if any.
  1665. $file = reset($files);
  1666. if (is_object($file)) {
  1667. $filename = $file->filename;
  1668. preg_match('/drupal-([0-9a-z\.-]+)\.' . $langcode . '\.po/', $filename, $matches);
  1669. // Get the version information.
  1670. if ($version = $matches[1]) {
  1671. $info = _install_get_version_info($version);
  1672. // Picking the first file does not necessarily result in the right file. So
  1673. // we check if at least the major version number is available.
  1674. if ($info['major']) {
  1675. $core = $info['major'] . '.x';
  1676. $data = [
  1677. 'name' => 'drupal',
  1678. 'project_type' => 'module',
  1679. 'core' => $core,
  1680. 'version' => $version,
  1681. 'server_pattern' => $server_pattern,
  1682. 'status' => 1,
  1683. ];
  1684. \Drupal::service('locale.project')->set($data['name'], $data);
  1685. module_load_include('compare.inc', 'locale');
  1686. // Reset project information static cache so that it uses the data
  1687. // set above.
  1688. locale_translation_clear_cache_projects();
  1689. locale_translation_check_projects_local(['drupal'], [$langcode]);
  1690. }
  1691. }
  1692. }
  1693. }
  1694. }
  1695. /**
  1696. * Finishes importing files at end of installation.
  1697. *
  1698. * If other projects besides Drupal core have been installed, their translation
  1699. * will be imported here.
  1700. *
  1701. * @param $install_state
  1702. * An array of information about the current installation state.
  1703. *
  1704. * @return array
  1705. * An array of batch definitions.
  1706. */
  1707. function install_finish_translations(&$install_state) {
  1708. \Drupal::moduleHandler()->loadInclude('locale', 'fetch.inc');
  1709. \Drupal::moduleHandler()->loadInclude('locale', 'compare.inc');
  1710. \Drupal::moduleHandler()->loadInclude('locale', 'bulk.inc');
  1711. // Build a fresh list of installed projects. When more projects than core are
  1712. // installed, their translations will be downloaded (if required) and imported
  1713. // using a batch.
  1714. $projects = locale_translation_build_projects();
  1715. $languages = \Drupal::languageManager()->getLanguages();
  1716. $batches = [];
  1717. if (count($projects) > 1) {
  1718. $options = _locale_translation_default_update_options();
  1719. if ($batch = locale_translation_batch_update_build([], array_keys($languages), $options)) {
  1720. $batches[] = $batch;
  1721. }
  1722. }
  1723. // Creates configuration translations.
  1724. $batches[] = locale_config_batch_update_components([], array_keys($languages));
  1725. return $batches;
  1726. }
  1727. /**
  1728. * Performs final installation steps and displays a 'finished' page.
  1729. *
  1730. * @param $install_state
  1731. * An array of information about the current installation state.
  1732. *
  1733. * @return
  1734. * A message informing the user that the installation is complete.
  1735. */
  1736. function install_finished(&$install_state) {
  1737. $profile = drupal_get_profile();
  1738. // Installation profiles are always loaded last.
  1739. module_set_weight($profile, 1000);
  1740. // Build the router once after installing all modules.
  1741. // This would normally happen upon KernelEvents::TERMINATE, but since the
  1742. // installer does not use an HttpKernel, that event is never triggered.
  1743. \Drupal::service('router.builder')->rebuild();
  1744. // Run cron to populate update status tables (if available) so that users
  1745. // will be warned if they've installed an out of date Drupal version.
  1746. // Will also trigger indexing of profile-supplied content or feeds.
  1747. \Drupal::service('cron')->run();
  1748. if ($install_state['interactive']) {
  1749. // Load current user and perform final login tasks.
  1750. // This has to be done after drupal_flush_all_caches()
  1751. // to avoid session regeneration.
  1752. $account = User::load(1);
  1753. user_login_finalize($account);
  1754. }
  1755. $success_message = t('Congratulations, you installed @drupal!', [
  1756. '@drupal' => drupal_install_profile_distribution_name(),
  1757. ]);
  1758. \Drupal::messenger()->addStatus($success_message);
  1759. }
  1760. /**
  1761. * Implements callback_batch_operation().
  1762. *
  1763. * Performs batch installation of modules.
  1764. */
  1765. function _install_module_batch($module, $module_name, &$context) {
  1766. \Drupal::service('module_installer')->install([$module], FALSE);
  1767. $context['results'][] = $module;
  1768. $context['message'] = t('Installed %module module.', ['%module' => $module_name]);
  1769. }
  1770. /**
  1771. * Checks installation requirements and reports any errors.
  1772. *
  1773. * @param string $langcode
  1774. * Language code to check for download.
  1775. * @param string $server_pattern
  1776. * Server access pattern (to replace language code, version number, etc. in).
  1777. *
  1778. * @return array|null
  1779. * Requirements compliance array. If the translation was downloaded
  1780. * successfully then an empty array is returned. Otherwise the requirements
  1781. * error with detailed information. NULL if the file already exists for this
  1782. * language code.
  1783. */
  1784. function install_check_translations($langcode, $server_pattern) {
  1785. $requirements = [];
  1786. $readable = FALSE;
  1787. $writable = FALSE;
  1788. // @todo: Make this configurable.
  1789. $site_path = \Drupal::service('site.path');
  1790. $files_directory = $site_path . '/files';
  1791. $translations_directory = $site_path . '/files/translations';
  1792. $translations_directory_exists = FALSE;
  1793. $online = FALSE;
  1794. // First attempt to create or make writable the files directory.
  1795. file_prepare_directory($files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  1796. // Then, attempt to create or make writable the translations directory.
  1797. file_prepare_directory($translations_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
  1798. // Get values so the requirements errors can be specific.
  1799. if (drupal_verify_install_file($translations_directory, FILE_EXIST, 'dir')) {
  1800. $readable = is_readable($translations_directory);
  1801. $writable = is_writable($translations_directory);
  1802. $translations_directory_exists = TRUE;
  1803. }
  1804. // The file already exists, no need to attempt to download.
  1805. if ($existing_file = glob($translations_directory . '/drupal-*.' . $langcode . '.po')) {
  1806. return;
  1807. }
  1808. $version = \Drupal::VERSION;
  1809. // For dev releases, remove the '-dev' part and trust the translation server
  1810. // to fall back to the latest stable release for that branch.
  1811. // @see locale_translation_build_projects()
  1812. if (preg_match("/^(\d+\.\d+\.).*-dev$/", $version, $matches)) {
  1813. // Example match: 8.0.0-dev => 8.0.x (Drupal core)
  1814. $version = $matches[1] . 'x';
  1815. }
  1816. // Build URL for the translation file and the translation server.
  1817. $variables = [
  1818. '%project' => 'drupal',
  1819. '%version' => $version,
  1820. '%core' => \Drupal::CORE_COMPATIBILITY,
  1821. '%language' => $langcode,
  1822. ];
  1823. $translation_url = strtr($server_pattern, $variables);
  1824. $elements = parse_url($translation_url);
  1825. $server_url = $elements['scheme'] . '://' . $elements['host'];
  1826. // Build the language name for display.
  1827. $languages = LanguageManager::getStandardLanguageList();
  1828. $language = isset($languages[$langcode]) ? $languages[$langcode][0] : $langcode;
  1829. // Check if any of the desired translation files are available or if the
  1830. // translation server can be reached. In other words, check if we are online
  1831. // and have an internet connection.
  1832. if ($translation_available = install_check_localization_server($translation_url)) {
  1833. $online = TRUE;
  1834. }
  1835. if (!$translation_available) {
  1836. if (install_check_localization_server($server_url)) {
  1837. $online = TRUE;
  1838. }
  1839. }
  1840. // If the translations directory does not exist, throw an error.
  1841. if (!$translations_directory_exists) {
  1842. $requirements['translations directory exists'] = [
  1843. 'title' => t('Translations directory'),
  1844. 'value' => t('The translations directory does not exist.'),
  1845. 'severity' => REQUIREMENT_ERROR,
  1846. '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']),
  1847. ];
  1848. }
  1849. else {
  1850. $requirements['translations directory exists'] = [
  1851. 'title' => t('Translations directory'),
  1852. 'value' => t('The directory %translations_directory exists.', ['%translations_directory' => $translations_directory]),
  1853. ];
  1854. // If the translations directory is not readable, throw an error.
  1855. if (!$readable) {
  1856. $requirements['translations directory readable'] = [
  1857. 'title' => t('Translations directory'),
  1858. 'value' => t('The translations directory is not readable.'),
  1859. 'severity' => REQUIREMENT_ERROR,
  1860. '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']),
  1861. ];
  1862. }
  1863. // If translations directory is not writable, throw an error.
  1864. if (!$writable) {
  1865. $requirements['translations directory writable'] = [
  1866. 'title' => t('Translations directory'),
  1867. 'value' => t('The translations directory is not writable.'),
  1868. 'severity' => REQUIREMENT_ERROR,
  1869. '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']),
  1870. ];
  1871. }
  1872. else {
  1873. $requirements['translations directory writable'] = [
  1874. 'title' => t('Translations directory'),
  1875. 'value' => t('The translations directory is writable.'),
  1876. ];
  1877. }
  1878. }
  1879. // If the translations server can not be contacted, throw an error.
  1880. if (!$online) {
  1881. $requirements['online'] = [
  1882. 'title' => t('Internet'),
  1883. 'value' => t('The translation server is offline.'),
  1884. 'severity' => REQUIREMENT_ERROR,
  1885. '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]),
  1886. ];
  1887. }
  1888. else {
  1889. $requirements['online'] = [
  1890. 'title' => t('Internet'),
  1891. 'value' => t('The translation server is online.'),
  1892. ];
  1893. // If translation file is not found at the translation server, throw an
  1894. // error.
  1895. if (!$translation_available) {
  1896. $requirements['translation available'] = [
  1897. 'title' => t('Translation'),
  1898. 'value' => t('The %language translation is not available.', ['%language' => $language]),
  1899. 'severity' => REQUIREMENT_ERROR,
  1900. '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']]),
  1901. ];
  1902. }
  1903. else {
  1904. $requirements['translation available'] = [
  1905. 'title' => t('Translation'),
  1906. 'value' => t('The %language translation is available.', ['%language' => $language]),
  1907. ];
  1908. }
  1909. }
  1910. if ($translations_directory_exists && $readable && $writable && $translation_available) {
  1911. $translation_downloaded = install_retrieve_file($translation_url, $translations_directory);
  1912. if (!$translation_downloaded) {
  1913. $requirements['translation downloaded'] = [
  1914. 'title' => t('Translation'),
  1915. 'value' => t('The %language translation could not be downloaded.', ['%language' => $language]),
  1916. 'severity' => REQUIREMENT_ERROR,
  1917. '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']]),
  1918. ];
  1919. }
  1920. }
  1921. return $requirements;
  1922. }
  1923. /**
  1924. * Checks installation requirements and reports any errors.
  1925. */
  1926. function install_check_requirements($install_state) {
  1927. $profile = $install_state['parameters']['profile'];
  1928. // Check the profile requirements.
  1929. $requirements = drupal_check_profile($profile);
  1930. if ($install_state['settings_verified']) {
  1931. return $requirements;
  1932. }
  1933. // If Drupal is not set up already, we need to try to create the default
  1934. // settings and services files.
  1935. $default_files = [];
  1936. $default_files['settings.php'] = [
  1937. 'file' => 'settings.php',
  1938. 'file_default' => 'default.settings.php',
  1939. 'title_default' => t('Default settings file'),
  1940. 'description_default' => t('The default settings file does not exist.'),
  1941. 'title' => t('Settings file'),
  1942. ];
  1943. foreach ($default_files as $default_file_info) {
  1944. $readable = FALSE;
  1945. $writable = FALSE;
  1946. $site_path = './' . \Drupal::service('site.path');
  1947. $file = $site_path . "/{$default_file_info['file']}";
  1948. $default_file = "./sites/default/{$default_file_info['file_default']}";
  1949. $exists = FALSE;
  1950. // Verify that the directory exists.
  1951. if (drupal_verify_install_file($site_path, FILE_EXIST, 'dir')) {
  1952. if (drupal_verify_install_file($file, FILE_EXIST)) {
  1953. // If it does, make sure it is writable.
  1954. $readable = drupal_verify_install_file($file, FILE_READABLE);
  1955. $writable = drupal_verify_install_file($file, FILE_WRITABLE);
  1956. $exists = TRUE;
  1957. }
  1958. }
  1959. // If the default $default_file does not exist, or is not readable,
  1960. // report an error.
  1961. if (!drupal_verify_install_file($default_file, FILE_EXIST | FILE_READABLE)) {
  1962. $requirements["default $file file exists"] = [
  1963. 'title' => $default_file_info['title_default'],
  1964. 'value' => $default_file_info['description_default'],
  1965. 'severity' => REQUIREMENT_ERROR,
  1966. 'description' => t('The @drupal installer requires that the %default-file file not be modified in any way from the original download.', [
  1967. '@drupal' => drupal_install_profile_distribution_name(),
  1968. '%default-file' => $default_file,
  1969. ]),
  1970. ];
  1971. }
  1972. // Otherwise, if $file does not exist yet, we can try to copy
  1973. // $default_file to create it.
  1974. elseif (!$exists) {
  1975. $copied = drupal_verify_install_file($site_path, FILE_EXIST | FILE_WRITABLE, 'dir') && @copy($default_file, $file);
  1976. if ($copied) {
  1977. // If the new $file file has the same owner as $default_file this means
  1978. // $default_file is owned by the webserver user. This is an inherent
  1979. // security weakness because it allows a malicious webserver process to
  1980. // append arbitrary PHP code and then execute it. However, it is also a
  1981. // common configuration on shared hosting, and there is nothing Drupal
  1982. // can do to prevent it. In this situation, having $file also owned by
  1983. // the webserver does not introduce any additional security risk, so we
  1984. // keep the file in place. Additionally, this situation also occurs when
  1985. // the test runner is being run be different user than the webserver.
  1986. if (fileowner($default_file) === fileowner($file) || DRUPAL_TEST_IN_CHILD_SITE) {
  1987. $readable = drupal_verify_install_file($file, FILE_READABLE);
  1988. $writable = drupal_verify_install_file($file, FILE_WRITABLE);
  1989. $exists = TRUE;
  1990. }
  1991. // If $file and $default_file have different owners, this probably means
  1992. // the server is set up "securely" (with the webserver running as its
  1993. // own user, distinct from the user who owns all the Drupal PHP files),
  1994. // although with either a group or world writable sites directory.
  1995. // Keeping $file owned by the webserver would therefore introduce a
  1996. // security risk. It would also cause a usability problem, since site
  1997. // owners who do not have root access to the file system would be unable
  1998. // to edit their settings file later on. We therefore must delete the
  1999. // file we just created and force the administrator to log on to the
  2000. // server and create it manually.
  2001. else {
  2002. $deleted = @drupal_unlink($file);
  2003. // We expect deleting the file to be successful (since we just
  2004. // created it ourselves above), but if it fails somehow, we set a
  2005. // variable so we can display a one-time error message to the
  2006. // administrator at the bottom of the requirements list. We also try
  2007. // to make the file writable, to eliminate any conflicting error
  2008. // messages in the requirements list.
  2009. $exists = !$deleted;
  2010. if ($exists) {
  2011. $settings_file_ownership_error = TRUE;
  2012. $readable = drupal_verify_install_file($file, FILE_READABLE);
  2013. $writable = drupal_verify_install_file($file, FILE_WRITABLE);
  2014. }
  2015. }
  2016. }
  2017. }
  2018. // If the $file does not exist, throw an error.
  2019. if (!$exists) {
  2020. $requirements["$file file exists"] = [
  2021. 'title' => $default_file_info['title'],
  2022. 'value' => t('The %file does not exist.', ['%file' => $default_file_info['title']]),
  2023. 'severity' => REQUIREMENT_ERROR,
  2024. '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>.', [
  2025. '@drupal' => drupal_install_profile_distribution_name(),
  2026. '%file' => $file,
  2027. '%default_file' => $default_file,
  2028. ':install_txt' => base_path() . 'core/INSTALL.txt',
  2029. ]),
  2030. ];
  2031. }
  2032. else {
  2033. $requirements["$file file exists"] = [
  2034. 'title' => $default_file_info['title'],
  2035. 'value' => t('The %file exists.', ['%file' => $file]),
  2036. ];
  2037. // If the $file is not readable, throw an error.
  2038. if (!$readable) {
  2039. $requirements["$file file readable"] = [
  2040. 'title' => $default_file_info['title'],
  2041. 'value' => t('The %file is not readable.', ['%file' => $default_file_info['title']]),
  2042. 'severity' => REQUIREMENT_ERROR,
  2043. '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.', [
  2044. '@drupal' => drupal_install_profile_distribution_name(),
  2045. '%file' => $file,
  2046. ':handbook_url' => 'https://www.drupal.org/server-permissions',
  2047. ]),
  2048. ];
  2049. }
  2050. // If the $file is not writable, throw an error.
  2051. if (!$writable) {
  2052. $requirements["$file file writeable"] = [
  2053. 'title' => $default_file_info['title'],
  2054. 'value' => t('The %file is not writable.', ['%file' => $default_file_info['title']]),
  2055. 'severity' => REQUIREMENT_ERROR,
  2056. '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.', [
  2057. '@drupal' => drupal_install_profile_distribution_name(),
  2058. '%file' => $file,
  2059. ':handbook_url' => 'https://www.drupal.org/server-permissions',
  2060. ]),
  2061. ];
  2062. }
  2063. else {
  2064. $requirements["$file file"] = [
  2065. 'title' => $default_file_info['title'],
  2066. 'value' => t('The @file is writable.', ['@file' => $default_file_info['title']]),
  2067. ];
  2068. }
  2069. if (!empty($settings_file_ownership_error)) {
  2070. $requirements["$file file ownership"] = [
  2071. 'title' => $default_file_info['title'],
  2072. 'value' => t('The @file is owned by the web server.', ['@file' => $default_file_info['title']]),
  2073. 'severity' => REQUIREMENT_ERROR,
  2074. '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.', [
  2075. '@drupal' => drupal_install_profile_distribution_name(),
  2076. '%file' => $file,
  2077. '%default_file' => $default_file,
  2078. ':install_txt' => base_path() . 'core/INSTALL.txt',
  2079. ':handbook_url' => 'https://www.drupal.org/server-permissions',
  2080. ]),
  2081. ];
  2082. }
  2083. }
  2084. }
  2085. return $requirements;
  2086. }
  2087. /**
  2088. * Displays installation requirements.
  2089. *
  2090. * @param array $install_state
  2091. * An array of information about the current installation state.
  2092. * @param array $requirements
  2093. * An array of requirements, in the same format as is returned by
  2094. * hook_requirements().
  2095. *
  2096. * @return
  2097. * A themed status report, or an exception if there are requirement errors.
  2098. * If there are only requirement warnings, a themed status report is shown
  2099. * initially, but the user is allowed to bypass it by providing 'continue=1'
  2100. * in the URL. Otherwise, no output is returned, so that the next task can be
  2101. * run in the same page request.
  2102. *
  2103. * @throws \Drupal\Core\Installer\Exception\InstallerException
  2104. */
  2105. function install_display_requirements($install_state, $requirements) {
  2106. // Check the severity of the requirements reported.
  2107. $severity = drupal_requirements_severity($requirements);
  2108. // If there are errors, always display them. If there are only warnings, skip
  2109. // them if the user has provided a URL parameter acknowledging the warnings
  2110. // and indicating a desire to continue anyway. See drupal_requirements_url().
  2111. if ($severity == REQUIREMENT_ERROR || ($severity == REQUIREMENT_WARNING && empty($install_state['parameters']['continue']))) {
  2112. if ($install_state['interactive']) {
  2113. $build['report']['#type'] = 'status_report';
  2114. $build['report']['#requirements'] = $requirements;
  2115. if ($severity == REQUIREMENT_WARNING) {
  2116. $build['#title'] = t('Requirements review');
  2117. $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)]);
  2118. }
  2119. else {
  2120. $build['#title'] = t('Requirements problem');
  2121. $build['#suffix'] = t('Check the messages and <a href=":url">try again</a>.', [':url' => drupal_requirements_url($severity)]);
  2122. }
  2123. return $build;
  2124. }
  2125. else {
  2126. // Throw an exception showing any unmet requirements.
  2127. $failures = [];
  2128. foreach ($requirements as $requirement) {
  2129. // Skip warnings altogether for non-interactive installations; these
  2130. // proceed in a single request so there is no good opportunity (and no
  2131. // good method) to warn the user anyway.
  2132. if (isset($requirement['severity']) && $requirement['severity'] == REQUIREMENT_ERROR) {
  2133. $failures[] = $requirement['title'] . ': ' . $requirement['value'] . "\n\n" . $requirement['description'];
  2134. }
  2135. }
  2136. if (!empty($failures)) {
  2137. throw new InstallerException(implode("\n\n", $failures));
  2138. }
  2139. }
  2140. }
  2141. }
  2142. /**
  2143. * Installation task; writes profile to settings.php if possible.
  2144. *
  2145. * @param array $install_state
  2146. * An array of information about the current installation state.
  2147. *
  2148. * @see _install_select_profile()
  2149. *
  2150. * @deprecated in Drupal 8.3.0 and will be removed before Drupal 9.0.0. The
  2151. * install profile is written to core.extension.
  2152. */
  2153. function install_write_profile($install_state) {
  2154. // Only write the install profile to settings.php if it already exists. The
  2155. // value from settings.php is never used but drupal_rewrite_settings() does
  2156. // not support removing a setting. If the value is present in settings.php
  2157. // there will be an informational notice on the status report.
  2158. $settings_path = \Drupal::service('site.path') . '/settings.php';
  2159. if (is_writable($settings_path) && array_key_exists('install_profile', Settings::getAll())) {
  2160. // Remember the profile which was used.
  2161. $settings['settings']['install_profile'] = (object) [
  2162. 'value' => $install_state['parameters']['profile'],
  2163. 'required' => TRUE,
  2164. ];
  2165. drupal_rewrite_settings($settings);
  2166. }
  2167. }
  2168. /**
  2169. * Creates a batch for the config importer to process.
  2170. *
  2171. * @see install_tasks()
  2172. */
  2173. function install_config_import_batch() {
  2174. // We need to manually trigger the installation of core-provided entity types,
  2175. // as those will not be handled by the module installer.
  2176. // @see install_profile_modules()
  2177. install_core_entity_type_definitions();
  2178. // Get the sync storage.
  2179. $sync = \Drupal::service('config.storage.sync');
  2180. // Match up the site UUIDs, the install_base_system install task will have
  2181. // installed the system module and created a new UUID.
  2182. $system_site = $sync->read('system.site');
  2183. \Drupal::configFactory()->getEditable('system.site')->set('uuid', $system_site['uuid'])->save();
  2184. // Create the storage comparer and the config importer.
  2185. $config_manager = \Drupal::service('config.manager');
  2186. $storage_comparer = new StorageComparer($sync, \Drupal::service('config.storage'), $config_manager);
  2187. $storage_comparer->createChangelist();
  2188. $config_importer = new ConfigImporter(
  2189. $storage_comparer,
  2190. \Drupal::service('event_dispatcher'),
  2191. $config_manager,
  2192. \Drupal::service('lock.persistent'),
  2193. \Drupal::service('config.typed'),
  2194. \Drupal::service('module_handler'),
  2195. \Drupal::service('module_installer'),
  2196. \Drupal::service('theme_handler'),
  2197. \Drupal::service('string_translation')
  2198. );
  2199. try {
  2200. $sync_steps = $config_importer->initialize();
  2201. $batch_builder = new BatchBuilder();
  2202. $batch_builder
  2203. ->setFinishCallback([ConfigImporterBatch::class, 'finish'])
  2204. ->setTitle(t('Importing configuration'))
  2205. ->setInitMessage(t('Starting configuration import.'))
  2206. ->setErrorMessage(t('Configuration import has encountered an error.'));
  2207. foreach ($sync_steps as $sync_step) {
  2208. $batch_builder->addOperation([ConfigImporterBatch::class, 'process'], [$config_importer, $sync_step]);
  2209. }
  2210. return $batch_builder->toArray();
  2211. }
  2212. catch (ConfigImporterException $e) {
  2213. global $install_state;
  2214. // There are validation errors.
  2215. $messenger = \Drupal::messenger();
  2216. $messenger->addError(t('The configuration synchronization failed validation.'));
  2217. foreach ($config_importer->getErrors() as $message) {
  2218. $messenger->addError($message);
  2219. }
  2220. install_display_output(['#title' => t('Configuration validation')], $install_state);
  2221. }
  2222. }
  2223. /**
  2224. * Replaces install_download_translation() during configuration installs.
  2225. *
  2226. * @param array $install_state
  2227. * An array of information about the current installation state.
  2228. *
  2229. * @return string
  2230. * A themed status report, or an exception if there are requirement errors.
  2231. * Upon successful download the page is reloaded and no output is returned.
  2232. *
  2233. * @see install_download_translation()
  2234. */
  2235. function install_config_download_translations(&$install_state) {
  2236. $needs_download = isset($install_state['parameters']['langcode']) && !isset($install_state['translations'][$install_state['parameters']['langcode']]) && $install_state['parameters']['langcode'] !== 'en';
  2237. if ($needs_download) {
  2238. return install_download_translation($install_state);
  2239. }
  2240. }
  2241. /**
  2242. * Reverts configuration if hook_install() implementations have made changes.
  2243. *
  2244. * This step ensures that the final configuration matches the configuration
  2245. * provided to the installer.
  2246. */
  2247. function install_config_revert_install_changes() {
  2248. global $install_state;
  2249. $config_manager = \Drupal::service('config.manager');
  2250. $storage_comparer = new StorageComparer(\Drupal::service('config.storage.sync'), \Drupal::service('config.storage'), $config_manager);
  2251. $storage_comparer->createChangelist();
  2252. if ($storage_comparer->hasChanges()) {
  2253. $config_importer = new ConfigImporter(
  2254. $storage_comparer,
  2255. \Drupal::service('event_dispatcher'),
  2256. $config_manager,
  2257. \Drupal::service('lock.persistent'),
  2258. \Drupal::service('config.typed'),
  2259. \Drupal::service('module_handler'),
  2260. \Drupal::service('module_installer'),
  2261. \Drupal::service('theme_handler'),
  2262. \Drupal::service('string_translation')
  2263. );
  2264. try {
  2265. $config_importer->import();
  2266. }
  2267. catch (ConfigImporterException $e) {
  2268. global $install_state;
  2269. $messenger = \Drupal::messenger();
  2270. // There are validation errors.
  2271. $messenger->addError(t('The configuration synchronization failed validation.'));
  2272. foreach ($config_importer->getErrors() as $message) {
  2273. $messenger->addError($message);
  2274. }
  2275. install_display_output(['#title' => t('Configuration validation')], $install_state);
  2276. }
  2277. // At this point the configuration should match completely.
  2278. if (\Drupal::moduleHandler()->moduleExists('language')) {
  2279. // If the English language exists at this point we need to ensure
  2280. // install_download_additional_translations_operations() does not delete
  2281. // it.
  2282. if (ConfigurableLanguage::load('en')) {
  2283. $install_state['profile_info']['keep_english'] = TRUE;
  2284. }
  2285. }
  2286. }
  2287. }