]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Command/InstallCommand.php
c78090539ae05f74234f846473148ce0adaaa404
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Command / InstallCommand.php
1 <?php
2
3 namespace Wallabag\CoreBundle\Command;
4
5 use Craue\ConfigBundle\Entity\Setting;
6 use FOS\UserBundle\Event\UserEvent;
7 use FOS\UserBundle\FOSUserEvents;
8 use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
9 use Symfony\Component\Console\Helper\Table;
10 use Symfony\Component\Console\Input\ArrayInput;
11 use Symfony\Component\Console\Input\InputInterface;
12 use Symfony\Component\Console\Input\InputOption;
13 use Symfony\Component\Console\Output\BufferedOutput;
14 use Symfony\Component\Console\Output\OutputInterface;
15 use Symfony\Component\Console\Question\ConfirmationQuestion;
16 use Symfony\Component\Console\Question\Question;
17
18 class InstallCommand extends ContainerAwareCommand
19 {
20 /**
21 * @var InputInterface
22 */
23 protected $defaultInput;
24
25 /**
26 * @var OutputInterface
27 */
28 protected $defaultOutput;
29
30 /**
31 * @var array
32 */
33 protected $functionExists = [
34 'curl_exec',
35 'curl_multi_init',
36 ];
37
38 protected function configure()
39 {
40 $this
41 ->setName('wallabag:install')
42 ->setDescription('wallabag installer.')
43 ->addOption(
44 'reset',
45 null,
46 InputOption::VALUE_NONE,
47 'Reset current database'
48 )
49 ;
50 }
51
52 protected function execute(InputInterface $input, OutputInterface $output)
53 {
54 $this->defaultInput = $input;
55 $this->defaultOutput = $output;
56
57 $output->writeln('<info>Installing wallabag...</info>');
58 $output->writeln('');
59
60 $this
61 ->checkRequirements()
62 ->setupDatabase()
63 ->setupAdmin()
64 ->setupConfig()
65 ->runMigrations()
66 ;
67
68 $output->writeln('<info>wallabag has been successfully installed.</info>');
69 $output->writeln('<comment>Just execute `php bin/console server:run --env=prod` for using wallabag: http://localhost:8000</comment>');
70 }
71
72 protected function checkRequirements()
73 {
74 $this->defaultOutput->writeln('<info><comment>Step 1 of 5.</comment> Checking system requirements.</info>');
75 $doctrineManager = $this->getContainer()->get('doctrine')->getManager();
76
77 $rows = [];
78
79 // testing if database driver exists
80 $fulfilled = true;
81 $label = '<comment>PDO Driver (%s)</comment>';
82 $status = '<info>OK!</info>';
83 $help = '';
84
85 if (!extension_loaded($this->getContainer()->getParameter('database_driver'))) {
86 $fulfilled = false;
87 $status = '<error>ERROR!</error>';
88 $help = 'Database driver "' . $this->getContainer()->getParameter('database_driver') . '" is not installed.';
89 }
90
91 $rows[] = [sprintf($label, $this->getContainer()->getParameter('database_driver')), $status, $help];
92
93 // testing if connection to the database can be etablished
94 $label = '<comment>Database connection</comment>';
95 $status = '<info>OK!</info>';
96 $help = '';
97
98 try {
99 $conn = $this->getContainer()->get('doctrine')->getManager()->getConnection();
100 $conn->connect();
101 } catch (\Exception $e) {
102 if (false === strpos($e->getMessage(), 'Unknown database')
103 && false === strpos($e->getMessage(), 'database "' . $this->getContainer()->getParameter('database_name') . '" does not exist')) {
104 $fulfilled = false;
105 $status = '<error>ERROR!</error>';
106 $help = 'Can\'t connect to the database: ' . $e->getMessage();
107 }
108 }
109
110 $rows[] = [$label, $status, $help];
111
112 // check MySQL & PostgreSQL version
113 $label = '<comment>Database version</comment>';
114 $status = '<info>OK!</info>';
115 $help = '';
116
117 // now check if MySQL isn't too old to handle utf8mb4
118 if ($conn->isConnected() && 'mysql' === $conn->getDatabasePlatform()->getName()) {
119 $version = $conn->query('select version()')->fetchColumn();
120 $minimalVersion = '5.5.4';
121
122 if (false === version_compare($version, $minimalVersion, '>')) {
123 $fulfilled = false;
124 $status = '<error>ERROR!</error>';
125 $help = 'Your MySQL version (' . $version . ') is too old, consider upgrading (' . $minimalVersion . '+).';
126 }
127 }
128
129 // testing if PostgreSQL > 9.1
130 if ($conn->isConnected() && 'postgresql' === $conn->getDatabasePlatform()->getName()) {
131 // return version should be like "PostgreSQL 9.5.4 on x86_64-apple-darwin15.6.0, compiled by Apple LLVM version 8.0.0 (clang-800.0.38), 64-bit"
132 $version = $doctrineManager->getConnection()->query('SELECT version();')->fetchColumn();
133
134 preg_match('/PostgreSQL ([0-9\.]+)/i', $version, $matches);
135
136 if (isset($matches[1]) & version_compare($matches[1], '9.2.0', '<')) {
137 $fulfilled = false;
138 $status = '<error>ERROR!</error>';
139 $help = 'PostgreSQL should be greater than 9.1 (actual version: ' . $matches[1] . ')';
140 }
141 }
142
143 $rows[] = [$label, $status, $help];
144
145 foreach ($this->functionExists as $functionRequired) {
146 $label = '<comment>' . $functionRequired . '</comment>';
147 $status = '<info>OK!</info>';
148 $help = '';
149
150 if (!function_exists($functionRequired)) {
151 $fulfilled = false;
152 $status = '<error>ERROR!</error>';
153 $help = 'You need the ' . $functionRequired . ' function activated';
154 }
155
156 $rows[] = [$label, $status, $help];
157 }
158
159 $table = new Table($this->defaultOutput);
160 $table
161 ->setHeaders(['Checked', 'Status', 'Recommendation'])
162 ->setRows($rows)
163 ->render();
164
165 if (!$fulfilled) {
166 throw new \RuntimeException('Some system requirements are not fulfilled. Please check output messages and fix them.');
167 }
168
169 $this->defaultOutput->writeln('<info>Success! Your system can run wallabag properly.</info>');
170
171 $this->defaultOutput->writeln('');
172
173 return $this;
174 }
175
176 protected function setupDatabase()
177 {
178 $this->defaultOutput->writeln('<info><comment>Step 2 of 5.</comment> Setting up database.</info>');
179
180 // user want to reset everything? Don't care about what is already here
181 if (true === $this->defaultInput->getOption('reset')) {
182 $this->defaultOutput->writeln('Dropping database, creating database and schema, clearing the cache');
183
184 $this
185 ->runCommand('doctrine:database:drop', ['--force' => true])
186 ->runCommand('doctrine:database:create')
187 ->runCommand('doctrine:schema:create')
188 ->runCommand('cache:clear')
189 ;
190
191 $this->defaultOutput->writeln('');
192
193 return $this;
194 }
195
196 if (!$this->isDatabasePresent()) {
197 $this->defaultOutput->writeln('Creating database and schema, clearing the cache');
198
199 $this
200 ->runCommand('doctrine:database:create')
201 ->runCommand('doctrine:schema:create')
202 ->runCommand('cache:clear')
203 ;
204
205 $this->defaultOutput->writeln('');
206
207 return $this;
208 }
209
210 $questionHelper = $this->getHelper('question');
211 $question = new ConfirmationQuestion('It appears that your database already exists. Would you like to reset it? (y/N)', false);
212
213 if ($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question)) {
214 $this->defaultOutput->writeln('Dropping database, creating database and schema');
215
216 $this
217 ->runCommand('doctrine:database:drop', ['--force' => true])
218 ->runCommand('doctrine:database:create')
219 ->runCommand('doctrine:schema:create')
220 ;
221 } elseif ($this->isSchemaPresent()) {
222 $question = new ConfirmationQuestion('Seems like your database contains schema. Do you want to reset it? (y/N)', false);
223 if ($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question)) {
224 $this->defaultOutput->writeln('Dropping schema and creating schema');
225
226 $this
227 ->runCommand('doctrine:schema:drop', ['--force' => true])
228 ->runCommand('doctrine:schema:create')
229 ;
230 }
231 } else {
232 $this->defaultOutput->writeln('Creating schema');
233
234 $this
235 ->runCommand('doctrine:schema:create')
236 ;
237 }
238
239 $this->defaultOutput->writeln('Clearing the cache');
240 $this->runCommand('cache:clear');
241
242 $this->defaultOutput->writeln('');
243
244 return $this;
245 }
246
247 protected function setupAdmin()
248 {
249 $this->defaultOutput->writeln('<info><comment>Step 3 of 5.</comment> Administration setup.</info>');
250
251 $questionHelper = $this->getHelperSet()->get('question');
252 $question = new ConfirmationQuestion('Would you like to create a new admin user (recommended) ? (Y/n)', true);
253
254 if (!$questionHelper->ask($this->defaultInput, $this->defaultOutput, $question)) {
255 return $this;
256 }
257
258 $em = $this->getContainer()->get('doctrine.orm.entity_manager');
259
260 $userManager = $this->getContainer()->get('fos_user.user_manager');
261 $user = $userManager->createUser();
262
263 $question = new Question('Username (default: wallabag) :', 'wallabag');
264 $user->setUsername($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question));
265
266 $question = new Question('Password (default: wallabag) :', 'wallabag');
267 $user->setPlainPassword($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question));
268
269 $question = new Question('Email:', '');
270 $user->setEmail($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question));
271
272 $user->setEnabled(true);
273 $user->addRole('ROLE_SUPER_ADMIN');
274
275 $em->persist($user);
276
277 // dispatch a created event so the associated config will be created
278 $event = new UserEvent($user);
279 $this->getContainer()->get('event_dispatcher')->dispatch(FOSUserEvents::USER_CREATED, $event);
280
281 $this->defaultOutput->writeln('');
282
283 return $this;
284 }
285
286 protected function setupConfig()
287 {
288 $this->defaultOutput->writeln('<info><comment>Step 4 of 5.</comment> Config setup.</info>');
289 $em = $this->getContainer()->get('doctrine.orm.entity_manager');
290
291 // cleanup before insert new stuff
292 $em->createQuery('DELETE FROM CraueConfigBundle:Setting')->execute();
293
294 foreach ($this->getContainer()->getParameter('wallabag_core.default_internal_settings') as $setting) {
295 $newSetting = new Setting();
296 $newSetting->setName($setting['name']);
297 $newSetting->setValue($setting['value']);
298 $newSetting->setSection($setting['section']);
299 $em->persist($newSetting);
300 }
301
302 $em->flush();
303
304 $this->defaultOutput->writeln('');
305
306 return $this;
307 }
308
309 protected function runMigrations()
310 {
311 $this->defaultOutput->writeln('<info><comment>Step 5 of 5.</comment> Run migrations.</info>');
312
313 $this
314 ->runCommand('doctrine:migrations:migrate', ['--no-interaction' => true]);
315
316 return $this;
317 }
318
319 /**
320 * Run a command.
321 *
322 * @param string $command
323 * @param array $parameters Parameters to this command (usually 'force' => true)
324 */
325 protected function runCommand($command, $parameters = [])
326 {
327 $parameters = array_merge(
328 ['command' => $command],
329 $parameters,
330 [
331 '--no-debug' => true,
332 '--env' => $this->defaultInput->getOption('env') ?: 'dev',
333 ]
334 );
335
336 if ($this->defaultInput->getOption('no-interaction')) {
337 $parameters = array_merge($parameters, ['--no-interaction' => true]);
338 }
339
340 $this->getApplication()->setAutoExit(false);
341
342 $output = new BufferedOutput();
343 $exitCode = $this->getApplication()->run(new ArrayInput($parameters), $output);
344
345 // PDO does not always close the connection after Doctrine commands.
346 // See https://github.com/symfony/symfony/issues/11750.
347 $this->getContainer()->get('doctrine')->getManager()->getConnection()->close();
348
349 if (0 !== $exitCode) {
350 $this->getApplication()->setAutoExit(true);
351
352 throw new \RuntimeException(
353 'The command "' . $command . "\" generates some errors: \n\n"
354 . $output->fetch());
355 }
356
357 return $this;
358 }
359
360 /**
361 * Check if the database already exists.
362 *
363 * @return bool
364 */
365 private function isDatabasePresent()
366 {
367 $connection = $this->getContainer()->get('doctrine')->getManager()->getConnection();
368 $databaseName = $connection->getDatabase();
369
370 try {
371 $schemaManager = $connection->getSchemaManager();
372 } catch (\Exception $exception) {
373 // mysql & sqlite
374 if (false !== strpos($exception->getMessage(), sprintf("Unknown database '%s'", $databaseName))) {
375 return false;
376 }
377
378 // pgsql
379 if (false !== strpos($exception->getMessage(), sprintf('database "%s" does not exist', $databaseName))) {
380 return false;
381 }
382
383 throw $exception;
384 }
385
386 // custom verification for sqlite, since `getListDatabasesSQL` doesn't work for sqlite
387 if ('sqlite' === $schemaManager->getDatabasePlatform()->getName()) {
388 $params = $this->getContainer()->get('doctrine.dbal.default_connection')->getParams();
389
390 if (isset($params['path']) && file_exists($params['path'])) {
391 return true;
392 }
393
394 return false;
395 }
396
397 try {
398 return in_array($databaseName, $schemaManager->listDatabases(), true);
399 } catch (\Doctrine\DBAL\Exception\DriverException $e) {
400 // it means we weren't able to get database list, assume the database doesn't exist
401
402 return false;
403 }
404 }
405
406 /**
407 * Check if the schema is already created.
408 * If we found at least oen table, it means the schema exists.
409 *
410 * @return bool
411 */
412 private function isSchemaPresent()
413 {
414 $schemaManager = $this->getContainer()->get('doctrine')->getManager()->getConnection()->getSchemaManager();
415
416 return count($schemaManager->listTableNames()) > 0 ? true : false;
417 }
418 }