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