182167a4c45eedff0e136c870744779c843be1f5
[yaffs-website] / web / core / lib / Drupal / Core / Command / ServerCommand.php
1 <?php
2
3 namespace Drupal\Core\Command;
4
5 use Drupal\Core\Database\ConnectionNotDefinedException;
6 use Drupal\Core\DrupalKernel;
7 use Drupal\Core\DrupalKernelInterface;
8 use Drupal\Core\Site\Settings;
9 use Drupal\user\Entity\User;
10 use Symfony\Component\Console\Command\Command;
11 use Symfony\Component\Console\Input\InputInterface;
12 use Symfony\Component\Console\Input\InputOption;
13 use Symfony\Component\Console\Output\OutputInterface;
14 use Symfony\Component\Console\Style\SymfonyStyle;
15 use Symfony\Component\HttpFoundation\Request;
16 use Symfony\Component\Process\PhpExecutableFinder;
17 use Symfony\Component\Process\PhpProcess;
18 use Symfony\Component\Process\Process;
19
20 /**
21  * Runs the PHP webserver for a Drupal site for local testing/development.
22  *
23  * @internal
24  *   This command makes no guarantee of an API for Drupal extensions.
25  */
26 class ServerCommand extends Command {
27
28   /**
29    * The class loader.
30    *
31    * @var object
32    */
33   protected $classLoader;
34
35   /**
36    * Constructs a new ServerCommand command.
37    *
38    * @param object $class_loader
39    *   The class loader.
40    */
41   public function __construct($class_loader) {
42     parent::__construct('server');
43     $this->classLoader = $class_loader;
44   }
45
46   /**
47    * {@inheritdoc}
48    */
49   protected function configure() {
50     $this->setDescription('Starts up a webserver for a site.')
51       ->addOption('host', NULL, InputOption::VALUE_OPTIONAL, 'Provide a host for the server to run on.', '127.0.0.1')
52       ->addOption('port', NULL, InputOption::VALUE_OPTIONAL, 'Provide a port for the server to run on. Will be determined automatically if none supplied.')
53       ->addOption('suppress-login', 's', InputOption::VALUE_NONE, 'Disable opening a login URL in a browser.')
54       ->addUsage('--host localhost --port 8080')
55       ->addUsage('--host my-site.com --port 80');
56   }
57
58   /**
59    * {@inheritdoc}
60    */
61   protected function execute(InputInterface $input, OutputInterface $output) {
62     $io = new SymfonyStyle($input, $output);
63
64     $host = $input->getOption('host');
65     $port = $input->getOption('port');
66     if (!$port) {
67       $port = $this->findAvailablePort($host);
68     }
69     if (!$port) {
70       $io->getErrorStyle()->error('Unable to automatically determine a port. Use the --port to hardcode an available port.');
71     }
72
73     try {
74       $kernel = $this->boot();
75     }
76     catch (ConnectionNotDefinedException $e) {
77       $io->getErrorStyle()->error("No installation found. Use the 'install' command.");
78       return 1;
79     }
80     return $this->start($host, $port, $kernel, $input, $io);
81   }
82
83   /**
84    * Boots up a Drupal environment.
85    *
86    * @return \Drupal\Core\DrupalKernelInterface
87    *   The Drupal kernel.
88    *
89    * @throws \Exception
90    *   Exception thrown if kernel does not boot.
91    */
92   protected function boot() {
93     $kernel = new DrupalKernel('prod', $this->classLoader, FALSE);
94     $kernel::bootEnvironment();
95     $kernel->setSitePath($this->getSitePath());
96     Settings::initialize($kernel->getAppRoot(), $kernel->getSitePath(), $this->classLoader);
97     $kernel->boot();
98     // Some services require a request to work. For example, CommentManager.
99     // This is needed as generating the URL fires up entity load hooks.
100     $kernel->getContainer()
101       ->get('request_stack')
102       ->push(Request::createFromGlobals());
103
104     return $kernel;
105   }
106
107   /**
108    * Finds an available port.
109    *
110    * @param string $host
111    *   The host to find a port on.
112    *
113    * @return int|false
114    *   The available port or FALSE, if no available port found,
115    */
116   protected function findAvailablePort($host) {
117     $port = 8888;
118     while ($port >= 8888 && $port <= 9999) {
119       $connection = @fsockopen($host, $port);
120       if (is_resource($connection)) {
121         // Port is being used.
122         fclose($connection);
123       }
124       else {
125         // Port is available.
126         return $port;
127       }
128       $port++;
129     }
130     return FALSE;
131   }
132
133   /**
134    * Opens a URL in your system default browser.
135    *
136    * @param string $url
137    *   The URL to browser to.
138    * @param \Symfony\Component\Console\Style\SymfonyStyle $io
139    *   The IO.
140    */
141   protected function openBrowser($url, SymfonyStyle $io) {
142     $is_windows = defined('PHP_WINDOWS_VERSION_BUILD');
143     if ($is_windows) {
144       // Handle escaping ourselves.
145       $cmd = 'start "web" "' . $url . '""';
146     }
147     else {
148       $url = escapeshellarg($url);
149     }
150
151     $is_linux = (new Process('which xdg-open'))->run();
152     $is_osx = (new Process('which open'))->run();
153     if ($is_linux === 0) {
154       $cmd = 'xdg-open ' . $url;
155     }
156     elseif ($is_osx === 0) {
157       $cmd = 'open ' . $url;
158     }
159
160     if (empty($cmd)) {
161       $io->getErrorStyle()
162         ->error('No suitable browser opening command found, open yourself: ' . $url);
163       return;
164     }
165
166     if ($io->isVerbose()) {
167       $io->writeln("<info>Browser command:</info> $cmd");
168     }
169
170     // Need to escape double quotes in the command so the PHP will work.
171     $cmd = str_replace('"', '\"', $cmd);
172     // Sleep for 2 seconds before opening the browser. This allows the command
173     // to start up the PHP built-in webserver in the meantime. We use a
174     // PhpProcess so that Windows powershell users also get a browser opened
175     // for them.
176     $php = "<?php sleep(2); passthru(\"$cmd\"); ?>";
177     $process = new PhpProcess($php);
178     $process->start();
179     return;
180   }
181
182   /**
183    * Gets a one time login URL for user 1.
184    *
185    * @return string
186    *   The one time login URL for user 1.
187    */
188   protected function getOneTimeLoginUrl() {
189     $user = User::load(1);
190     \Drupal::moduleHandler()->load('user');
191     return user_pass_reset_url($user);
192   }
193
194   /**
195    * Starts up a webserver with a running Drupal.
196    *
197    * @param string $host
198    *   The hostname of the webserver.
199    * @param int $port
200    *   The port to start the webserver on.
201    * @param \Drupal\Core\DrupalKernelInterface $kernel
202    *   The Drupal kernel.
203    * @param \Symfony\Component\Console\Input\InputInterface $input
204    *   The input.
205    * @param \Symfony\Component\Console\Style\SymfonyStyle $io
206    *   The IO.
207    *
208    * @return int
209    *   The exit status of the PHP in-built webserver command.
210    */
211   protected function start($host, $port, DrupalKernelInterface $kernel, InputInterface $input, SymfonyStyle $io) {
212     $finder = new PhpExecutableFinder();
213     $binary = $finder->find();
214     if ($binary === FALSE) {
215       throw new \RuntimeException('Unable to find the PHP binary.');
216     }
217
218     $io->writeln("<info>Drupal development server started:</info> <http://{$host}:{$port}>");
219     $io->writeln('<info>This server is not meant for production use.</info>');
220     $one_time_login = "http://$host:$port{$this->getOneTimeLoginUrl()}/login";
221     $io->writeln("<info>One time login url:</info> <$one_time_login>");
222     $io->writeln('Press Ctrl-C to quit the Drupal development server.');
223
224     if (!$input->getOption('suppress-login')) {
225       if ($this->openBrowser("$one_time_login?destination=" . urlencode("/"), $io) === 1) {
226         $io->error('Error while opening up a one time login URL');
227       }
228     }
229
230     // Use the Process object to construct an escaped command line.
231     $process = new Process([
232       $binary,
233       '-S',
234       $host . ':' . $port,
235       '.ht.router.php',
236     ], $kernel->getAppRoot(), [], NULL, NULL);
237     if ($io->isVerbose()) {
238       $io->writeln("<info>Server command:</info> {$process->getCommandLine()}");
239     }
240
241     // Carefully manage output so we can display output only in verbose mode.
242     $descriptors = [];
243     $descriptors[0] = STDIN;
244     $descriptors[1] = ['pipe', 'w'];
245     $descriptors[2] = ['pipe', 'w'];
246     $server = proc_open($process->getCommandLine(), $descriptors, $pipes, $kernel->getAppRoot());
247     if (is_resource($server)) {
248       if ($io->isVerbose()) {
249         // Write a blank line so that server output and the useful information are
250         // visually separated.
251         $io->writeln('');
252       }
253       $server_status = proc_get_status($server);
254       while ($server_status['running']) {
255         if ($io->isVerbose()) {
256           fpassthru($pipes[2]);
257         }
258         sleep(1);
259         $server_status = proc_get_status($server);
260       }
261     }
262     return proc_close($server);
263   }
264
265   /**
266    * Gets the site path.
267    *
268    * Defaults to 'sites/default'. For testing purposes this can be overridden
269    * using the DRUPAL_DEV_SITE_PATH environment variable.
270    *
271    * @return string
272    *   The site path to use.
273    */
274   protected function getSitePath() {
275     return getenv('DRUPAL_DEV_SITE_PATH') ?: 'sites/default';
276   }
277
278 }