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