install.core.inc 90 KB

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