install.core.inc 91 KB

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