install.core.inc 101 KB

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