0b046d9967597bc1648b95846840a4c6789fb989
[yaffs-website] / vendor / drush / drush / src / Commands / core / SiteInstallCommands.php
1 <?php
2 namespace Drush\Commands\core;
3
4 use Consolidation\AnnotatedCommand\CommandData;
5 use Drupal\Core\Database\ConnectionNotDefinedException;
6 use Drush\Commands\DrushCommands;
7 use Drush\Drush;
8 use Drush\Exceptions\UserAbortException;
9 use Drush\Log\LogLevel;
10 use Drupal\Core\Config\FileStorage;
11 use Drush\SiteAlias\SiteAliasManager;
12 use Drush\SiteAlias\SiteAliasManagerAwareInterface;
13 use Drush\SiteAlias\SiteAliasManagerAwareTrait;
14 use Drush\Sql\SqlBase;
15 use Drush\Utils\StringUtils;
16 use Webmozart\PathUtil\Path;
17
18 class SiteInstallCommands extends DrushCommands implements SiteAliasManagerAwareInterface
19 {
20     use SiteAliasManagerAwareTrait;
21
22     /**
23      * Install Drupal along with modules/themes/configuration/profile.
24      *
25      * @command site:install
26      * @param $profile An install profile name. Defaults to 'standard' unless an install profile is marked as a distribution. Additional info for the install profile may also be provided with additional arguments. The key is in the form [form name].[parameter name]
27      * @option db-url A Drupal 6 style database URL. Required for initial install, not re-install. If omitted and required, Drush prompts for this item.
28      * @option db-prefix An optional table prefix to use for initial install.
29      * @option db-su Account to use when creating a new database. Must have Grant permission (mysql only). Optional.
30      * @option db-su-pw Password for the "db-su" account. Optional.
31      * @option account-name uid1 name. Defaults to admin
32      * @option account-pass uid1 pass. Defaults to a randomly generated password. If desired, set a fixed password in config.yml.
33      * @option account-mail uid1 email. Defaults to admin@example.com
34      * @option locale A short language code. Sets the default site language. Language files must already be present.
35      * @option site-name Defaults to Site-Install
36      * @option site-mail From: for system mailings. Defaults to admin@example.com
37      * @option sites-subdir Name of directory under 'sites' which should be created.
38      * @option config-dir A path pointing to a full set of configuration which should be imported after installation.
39      * @usage drush si expert --locale=uk
40      *   (Re)install using the expert install profile. Set default language to Ukrainian.
41      * @usage drush si --db-url=mysql://root:pass@localhost:port/dbname
42      *   Install using the specified DB params.
43      * @usage drush si --db-url=sqlite://sites/example.com/files/.ht.sqlite
44      *   Install using SQLite
45      * @usage drush si --account-pass=mom
46      *   Re-install with specified uid1 password.
47      * @usage drush si standard install_configure_form.enable_update_status_emails=NULL
48      *   Disable email notification during install and later. If your server has no mail transfer agent, this gets rid of an error during install.
49      * @bootstrap root
50      * @kernel installer
51      * @aliases si,sin,site-install
52      *
53      */
54     public function install(array $profile, $options = ['db-url' => self::REQ, 'db-prefix' => self::REQ, 'db-su' => self::REQ, 'db-su-pw' => self::REQ, 'account-name' => 'admin', 'account-mail' => 'admin@example.com', 'site-mail' => 'admin@example.com', 'account-pass' => self::REQ, 'locale' => 'en', 'site-name' => 'Drush Site-Install', 'site-pass' => self::REQ, 'sites-subdir' => self::REQ, 'config-dir' => self::REQ])
55     {
56         $additional = $profile;
57         $profile = array_shift($additional) ?: '';
58         $form_options = [];
59         foreach ((array)$additional as $arg) {
60             list($key, $value) = explode('=', $arg, 2);
61
62             // Allow for numeric and NULL values to be passed in.
63             if (is_numeric($value)) {
64                 $value = intval($value);
65             } elseif ($value == 'NULL') {
66                 $value = null;
67             }
68
69             $form_options[$key] = $value;
70         }
71
72         $this->serverGlobals(Drush::bootstrapManager()->getUri());
73         $class_loader = Drush::service('loader');
74         $profile = $this->determineProfile($profile, $options, $class_loader);
75
76         $sql = SqlBase::create($options);
77         $db_spec = $sql->getDbSpec();
78
79         $account_pass = $options['account-pass'] ?: StringUtils::generatePassword();
80         $settings = [
81             'parameters' => [
82                 'profile' => $profile,
83                 'langcode' => $options['locale'],
84             ],
85             'forms' => [
86                 'install_settings_form' => [
87                     'driver' => $db_spec['driver'],
88                     $db_spec['driver'] => $db_spec,
89                     'op' => dt('Save and continue'),
90                 ],
91                 'install_configure_form' => [
92                     'site_name' => $options['site-name'],
93                     'site_mail' => $options['site-mail'],
94                     'account' => [
95                       'name' => $options['account-name'],
96                       'mail' => $options['account-mail'],
97                       'pass' => [
98                         'pass1' => $account_pass,
99                         'pass2' => $account_pass,
100                       ],
101                     ],
102                     'enable_update_status_module' => true,
103                     'enable_update_status_emails' => true,
104                     'clean_url' => true,
105                     'op' => dt('Save and continue'),
106                 ],
107             ],
108         ];
109
110         // Merge in the additional options.
111         foreach ($form_options as $key => $value) {
112             $current = &$settings['forms'];
113             foreach (explode('.', $key) as $param) {
114                 $current = &$current[$param];
115             }
116             $current = $value;
117         }
118
119         $msg = 'Starting Drupal installation. This takes a while.';
120         if (is_null($options['notify'])) {
121             $msg .= ' Consider using the --notify global option.';
122         }
123         $this->logger()->notice(dt($msg));
124
125         // Define some functions which alter away the install_finished task.
126         require_once Path::join(DRUSH_BASE_PATH, 'includes/site_install.inc');
127
128         require_once DRUSH_DRUPAL_CORE . '/includes/install.core.inc';
129         drush_op('install_drupal', $class_loader, $settings);
130         if (empty($options['account-pass'])) {
131             $this->logger()->success(dt('Installation complete.  User name: @name  User password: @pass', ['@name' => $options['account-name'], '@pass' => $account_pass]));
132         } else {
133             $this->logger()->success(dt('Installation complete.'));
134         }
135     }
136
137     protected function determineProfile($profile, $options, $class_loader)
138     {
139         // --config-dir fails with Standard profile and any other one that carries content entities.
140         // Force to minimal install profile.
141         if ($options['config-dir']) {
142             $this->logger()->info(dt("Using 'minimal' install profile since --config-dir option was provided."));
143             $profile = 'minimal';
144         }
145         if (empty($profile)) {
146             $boot = Drush::bootstrap();
147             $profile = $boot->getKernel()->getInstallProfile();
148         }
149
150         if (empty($profile)) {
151             // If there is an installation profile that acts as a distribution, use it.
152             // You can turn your installation profile into a distribution by providing a
153             // @code
154             //   distribution:
155             //     name: 'Distribution name'
156             // @endcode
157             // block in the profile's info YAML file.
158             // See https://www.drupal.org/node/2210443 for more information.
159             require_once DRUSH_DRUPAL_CORE . '/includes/install.core.inc';
160             $install_state = ['interactive' => false] + install_state_defaults();
161             try {
162                 install_begin_request($class_loader, $install_state);
163                 $profile = _install_select_profile($install_state);
164             } catch (\Exception $e) {
165                 // This is only a best effort to provide a better default, no harm done
166                 // if it fails.
167             }
168         }
169         if (empty($profile)) {
170             $profile = 'standard';
171         }
172         return $profile;
173     }
174
175     /**
176      * Post installation, run the configuration import.
177      *
178      * @hook post-command site-install
179      */
180     public function post($result, CommandData $commandData)
181     {
182         if ($config = $commandData->input()->getOption('config-dir')) {
183             // Set the destination site UUID to match the source UUID, to bypass a core fail-safe.
184             $source_storage = new FileStorage($config);
185             $options = ['yes' => true];
186             drush_invoke_process('@self', 'config-set', ['system.site', 'uuid', $source_storage->read('system.site')['uuid']], $options);
187             // Run a full configuration import.
188             drush_invoke_process('@self', 'config-import', [], ['source' => $config] + $options);
189         }
190     }
191
192     /**
193      * Check to see if there are any .yml files in the provided config directory.
194      */
195     protected function hasConfigFiles($config)
196     {
197         $files = glob("$config/*.yml");
198         return !empty($files);
199     }
200
201     /**
202      * @hook validate site-install
203      */
204     public function validate(CommandData $commandData)
205     {
206         if ($sites_subdir = $commandData->input()->getOption('sites-subdir')) {
207             $lower = strtolower($sites_subdir);
208             if ($sites_subdir != $lower) {
209                 $this->logger()->warning(dt('Only lowercase sites-subdir are valid. Switching to !lower.', ['!lower' => $lower]));
210                 $commandData->input()->setOption('sites-subdir', $lower);
211             }
212             // Make sure that we will bootstrap to the 'sites-subdir' site.
213             $bootstrapManager = Drush::bootstrapManager();
214             $bootstrapManager->setUri('http://' . $sites_subdir);
215         }
216
217         if ($config = $commandData->input()->getOption('config-dir')) {
218             if (!file_exists($config)) {
219                 throw new \Exception('The config source directory does not exist.');
220             }
221             if (!is_dir($config)) {
222                 throw new \Exception('The config source is not a directory.');
223             }
224             // Skip config import with a warning if specified config dir is empty.
225             if (!$this->hasConfigFiles($config)) {
226                 $this->logger()->warning(dt('Configuration import directory @config does not contain any configuration; will skip import.', ['@config' => $config]));
227                 $commandData->input()->setOption('config-dir', '');
228             }
229         }
230
231         try {
232             // Get AnnotationData. @todo Find a better way.
233             $annotationData = Drush::getApplication()->find('site:install')->getAnnotationData();
234             Drush::bootstrapManager()->bootstrapMax(DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION, $annotationData);
235             $sql = SqlBase::create($commandData->input()->getOptions());
236         } catch (\Exception $e) {
237             // Ask questions to get our data.
238             // TODO: we should only 'ask' in hook interact, never in hook validate
239             if ($commandData->input()->getOption('db-url') == '') {
240                 // Prompt for the db-url data if it was not provided via --db-url.
241                 $database = $this->io()->ask('Database name', 'drupal');
242                 $driver = $this->io()->ask('Database driver', 'mysql');
243                 $username = $this->io()->ask('Database username', 'drupal');
244                 $password = $this->io()->ask('Database password', 'drupal');
245                 $host = $this->io()->ask('Database host', '127.0.0.1');
246                 $port = $this->io()->ask('Database port', '3306');
247                 $db_url = "$driver://$username:$password@$host:$port/$database";
248                 $commandData->input()->setOption('db-url', $db_url);
249
250                 try {
251                     $sql = SqlBase::create($commandData->input()->getOptions());
252                 } catch (\Exception $e) {
253                     throw new \Exception(dt('Could not determine database connection parameters. Pass --db-url option.'));
254                 }
255             }
256         }
257     }
258
259     /**
260      * Perform setup tasks before installation.
261      *
262      * @hook pre-command site-install
263      *
264      */
265     public function pre(CommandData $commandData)
266     {
267         $sql = SqlBase::create($commandData->input()->getOptions());
268         $db_spec = $sql->getDbSpec();
269
270         $aliasRecord = $this->siteAliasManager()->getSelf();
271         $root = $aliasRecord->root();
272
273         $dir = $commandData->input()->getOption('sites-subdir');
274         if (!$dir) {
275             // We will allow the 'uri' from the site alias to provide
276             // a fallback name when '--sites-subdir' is not specified, but
277             // only if the uri and the folder name match, and only if
278             // the sites directory has already been created.
279             $dir = $this->getSitesSubdirFromUri($root, $aliasRecord->get('uri'));
280         }
281
282         if (!$dir) {
283             throw new \Exception(dt('Could not determine target sites directory for site to install. Use --sites-subdir to specify.'));
284         }
285
286         $sites_subdir = Path::join('sites', $dir);
287         $confPath = $sites_subdir;
288         $settingsfile = Path::join($confPath, 'settings.php');
289         $sitesfile = "sites/sites.php";
290         $default = realpath(Path::join($root, 'sites/default'));
291         $sitesfile_write = realpath($confPath) != $default && !file_exists($sitesfile);
292
293         if (!file_exists($settingsfile)) {
294             $msg[] = dt('create a @settingsfile file', ['@settingsfile' => $settingsfile]);
295         }
296         if ($sitesfile_write) {
297             $msg[] = dt('create a @sitesfile file', ['@sitesfile' => $sitesfile]);
298         }
299         if ($sql->dbExists()) {
300             $msg[] = dt("DROP all tables in your '@db' database.", ['@db' => $db_spec['database']]);
301         } else {
302             $msg[] = dt("CREATE the '@db' database.", ['@db' => $db_spec['database']]);
303         }
304
305         if (!$this->io()->confirm(dt('You are about to ') . implode(dt(' and '), $msg) . ' Do you want to continue?')) {
306             throw new UserAbortException();
307         }
308
309         // Can't install without sites subdirectory and settings.php.
310         if (!file_exists($confPath)) {
311             if (!drush_mkdir($confPath) && !Drush::simulate()) {
312                 throw new \Exception(dt('Failed to create directory @confPath', ['@confPath' => $confPath]));
313             }
314         } else {
315             $this->logger()->info(dt('Sites directory @subdir already exists - proceeding.', ['@subdir' => $confPath]));
316         }
317
318         if (!drush_file_not_empty($settingsfile)) {
319             if (!drush_op('copy', 'sites/default/default.settings.php', $settingsfile) && !Drush::simulate()) {
320                 throw new \Exception(dt('Failed to copy sites/default/default.settings.php to @settingsfile', ['@settingsfile' => $settingsfile]));
321             }
322         }
323
324         // Write an empty sites.php if we using multi-site.
325         if ($sitesfile_write) {
326             if (!drush_op('copy', 'sites/example.sites.php', $sitesfile) && !Drush::simulate()) {
327                 throw new \Exception(dt('Failed to copy sites/example.sites.php to @sitesfile', ['@sitesfile' => $sitesfile]));
328             }
329         }
330
331         // We need to be at least at DRUSH_BOOTSTRAP_DRUPAL_SITE to select the site uri to install to
332         define('MAINTENANCE_MODE', 'install');
333         $bootstrapManager = Drush::bootstrapManager();
334         $bootstrapManager->doBootstrap(DRUSH_BOOTSTRAP_DRUPAL_SITE);
335
336         if (!$sql->dropOrCreate()) {
337             throw new \Exception(dt('Failed to create database: @error', ['@error' => implode(drush_shell_exec_output())]));
338         }
339     }
340
341     /**
342      * Determine an appropriate site subdir name to use for the
343      * provided uri.
344      */
345     protected function getSitesSubdirFromUri($root, $uri)
346     {
347         $dir = strtolower($uri);
348         // Always accept simple uris (e.g. 'dev', 'stage', etc.)
349         if (preg_match('#^[a-z0-9_-]*$#', $dir)) {
350             return $dir;
351         }
352         // Strip off the protocol from the provided uri -- however,
353         // now we will require that the sites subdir already exist.
354         $dir = preg_replace('#[^/]*/*#', '', $dir);
355         if ($dir && file_exists(Path::join($root, $dir))) {
356             return $dir;
357         }
358         // Find the dir from sites.php file
359         $sites_file = $root . '/sites/sites.php';
360         if (file_exists($sites_file)) {
361             include $sites_file;
362             if (array_key_exists($uri, $sites)) {
363                 return $sites[$uri];
364             }
365         }
366         return false;
367     }
368
369     /**
370      * Fake the necessary HTTP headers that the Drupal installer still needs:
371      * @see https://github.com/drupal/drupal/blob/d260101f1ea8a6970df88d2f1899248985c499fc/core/includes/install.core.inc#L287
372      */
373     public function serverGlobals($drupal_base_url)
374     {
375         $drupal_base_url = parse_url($drupal_base_url);
376
377         // Fill in defaults.
378         $drupal_base_url += [
379             'scheme' => null,
380             'path' => '',
381             'host' => null,
382             'port' => null,
383         ];
384         $_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
385
386         if ($drupal_base_url['scheme'] == 'https') {
387               $_SERVER['HTTPS'] = 'on';
388         }
389
390         if ($drupal_base_url['port']) {
391               $_SERVER['HTTP_HOST'] .= ':' . $drupal_base_url['port'];
392         }
393         $_SERVER['SERVER_PORT'] = $drupal_base_url['port'];
394
395         $_SERVER['REQUEST_URI'] = $drupal_base_url['path'] . '/';
396
397         $_SERVER['PHP_SELF'] = $_SERVER['REQUEST_URI'] . 'index.php';
398         $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
399         $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
400         $_SERVER['REQUEST_METHOD']  = 'GET';
401
402         $_SERVER['SERVER_SOFTWARE'] = null;
403         $_SERVER['HTTP_USER_AGENT'] = null;
404         $_SERVER['SCRIPT_FILENAME'] = DRUPAL_ROOT . '/index.php';
405     }
406 }