]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Command/InstallCommand.php
Add a check for the database connection
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Command / InstallCommand.php
CommitLineData
2e45e7be
J
1<?php
2
3namespace Wallabag\CoreBundle\Command;
4
5use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
619cc453
JB
6use Symfony\Component\Console\Helper\Table;
7use Symfony\Component\Console\Input\ArrayInput;
2e45e7be 8use Symfony\Component\Console\Input\InputInterface;
0bf99bb1 9use Symfony\Component\Console\Input\InputOption;
0bf99bb1 10use Symfony\Component\Console\Output\NullOutput;
619cc453 11use Symfony\Component\Console\Output\OutputInterface;
78507d28 12use Symfony\Component\Console\Question\ConfirmationQuestion;
619cc453 13use Symfony\Component\Console\Question\Question;
4d85d7e9 14use Wallabag\CoreBundle\Entity\Config;
d6ba77e8 15use Craue\ConfigBundle\Entity\Setting;
2e45e7be
J
16
17class InstallCommand extends ContainerAwareCommand
18{
0bf99bb1
J
19 /**
20 * @var InputInterface
21 */
22 protected $defaultInput;
23
24 /**
25 * @var OutputInterface
26 */
27 protected $defaultOutput;
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')
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
J
53 $this->defaultInput = $input;
54 $this->defaultOutput = $output;
55
56 $output->writeln('<info>Installing Wallabag...</info>');
2e45e7be
J
57 $output->writeln('');
58
59 $this
0bf99bb1
J
60 ->checkRequirements()
61 ->setupDatabase()
62 ->setupAdmin()
637dc4bb 63 ->setupConfig()
0bf99bb1 64 ->setupAsset()
2e45e7be
J
65 ;
66
67 $output->writeln('<info>Wallabag has been successfully installed.</info>');
0c6845a9 68 $output->writeln('<comment>Just execute `php bin/console server:run --env=prod` for using wallabag: http://localhost:8000</comment>');
2e45e7be
J
69 }
70
0bf99bb1 71 protected function checkRequirements()
2e45e7be 72 {
637dc4bb 73 $this->defaultOutput->writeln('<info><comment>Step 1 of 5.</comment> Checking system requirements.</info>');
2e45e7be 74
001a7bad 75 $rows = [];
2e45e7be 76
001a7bad
JB
77 // testing if database driver exists
78 $fulfilled = true;
c61b68e8 79 $label = '<comment>PDO Driver</comment>';
0e49487b
JB
80 $status = '<info>OK!</info>';
81 $help = '';
c61b68e8
JB
82
83 if (!extension_loaded($this->getContainer()->getParameter('database_driver'))) {
db847ca0
TC
84 $fulfilled = false;
85 $status = '<error>ERROR!</error>';
c61b68e8 86 $help = 'Database driver "'.$this->getContainer()->getParameter('database_driver').'" is not installed.';
db847ca0
TC
87 }
88
001a7bad
JB
89 $rows[] = [$label, $status, $help];
90
91 // testing if connection to the database can be etablished
92 $label = '<comment>Database connection</comment>';
93 $status = '<info>OK!</info>';
94 $help = '';
95
96 try {
97 $this->getContainer()->get('doctrine')->getManager()->getConnection()->connect();
98 } catch (\Exception $e) {
99 $fulfilled = false;
100 $status = '<error>ERROR!</error>';
101 $help = 'Can\'t connect to the database: '.$e->getMessage();
102 }
103
4d0ec0e7 104 $rows[] = [$label, $status, $help];
db847ca0
TC
105
106 foreach ($this->functionExists as $functionRequired) {
107 $label = '<comment>'.$functionRequired.'</comment>';
0e49487b
JB
108 $status = '<info>OK!</info>';
109 $help = '';
db847ca0 110
0e49487b 111 if (!function_exists($functionRequired)) {
fc6020b2
NL
112 $fulfilled = false;
113 $status = '<error>ERROR!</error>';
f2fcb65b 114 $help = 'You need the '.$functionRequired.' function activated';
fc6020b2 115 }
db847ca0 116
4d0ec0e7 117 $rows[] = [$label, $status, $help];
2e45e7be 118 }
0bf99bb1 119
78507d28
JB
120 $table = new Table($this->defaultOutput);
121 $table
4d0ec0e7 122 ->setHeaders(['Checked', 'Status', 'Recommendation'])
0bf99bb1 123 ->setRows($rows)
78507d28 124 ->render();
2e45e7be
J
125
126 if (!$fulfilled) {
0bf99bb1 127 throw new \RuntimeException('Some system requirements are not fulfilled. Please check output messages and fix them.');
2e45e7be
J
128 }
129
8a493541
JB
130 $this->defaultOutput->writeln('<info>Success! Your system can run Wallabag properly.</info>');
131
0bf99bb1 132 $this->defaultOutput->writeln('');
2e45e7be
J
133
134 return $this;
135 }
136
0bf99bb1 137 protected function setupDatabase()
2e45e7be 138 {
637dc4bb 139 $this->defaultOutput->writeln('<info><comment>Step 2 of 5.</comment> Setting up database.</info>');
2e45e7be 140
0bf99bb1
J
141 // user want to reset everything? Don't care about what is already here
142 if (true === $this->defaultInput->getOption('reset')) {
d5027625 143 $this->defaultOutput->writeln('Droping database, creating database and schema, clearing the cache');
2e45e7be 144
0bf99bb1 145 $this
4d0ec0e7 146 ->runCommand('doctrine:database:drop', ['--force' => true])
0bf99bb1
J
147 ->runCommand('doctrine:database:create')
148 ->runCommand('doctrine:schema:create')
d5027625 149 ->runCommand('cache:clear')
0bf99bb1 150 ;
2e45e7be 151
d5027625
JB
152 $this->defaultOutput->writeln('');
153
0bf99bb1
J
154 return $this;
155 }
2e45e7be 156
0bf99bb1
J
157 if (!$this->isDatabasePresent()) {
158 $this->defaultOutput->writeln('Creating database and schema, clearing the cache');
2e45e7be 159
0bf99bb1
J
160 $this
161 ->runCommand('doctrine:database:create')
162 ->runCommand('doctrine:schema:create')
163 ->runCommand('cache:clear')
164 ;
2e45e7be 165
d5027625
JB
166 $this->defaultOutput->writeln('');
167
0bf99bb1
J
168 return $this;
169 }
2e45e7be 170
78507d28
JB
171 $questionHelper = $this->getHelper('question');
172 $question = new ConfirmationQuestion('It appears that your database already exists. Would you like to reset it? (y/N)', false);
2e45e7be 173
78507d28 174 if ($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question)) {
0bf99bb1 175 $this->defaultOutput->writeln('Droping database, creating database and schema');
2e45e7be 176
0bf99bb1 177 $this
4d0ec0e7 178 ->runCommand('doctrine:database:drop', ['--force' => true])
0bf99bb1
J
179 ->runCommand('doctrine:database:create')
180 ->runCommand('doctrine:schema:create')
181 ;
182 } elseif ($this->isSchemaPresent()) {
78507d28
JB
183 $question = new ConfirmationQuestion('Seems like your database contains schema. Do you want to reset it? (y/N)', false);
184 if ($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question)) {
0bf99bb1 185 $this->defaultOutput->writeln('Droping schema and creating schema');
2e45e7be 186
0bf99bb1 187 $this
4d0ec0e7 188 ->runCommand('doctrine:schema:drop', ['--force' => true])
0bf99bb1
J
189 ->runCommand('doctrine:schema:create')
190 ;
191 }
2e45e7be 192 } else {
0bf99bb1
J
193 $this->defaultOutput->writeln('Creating schema');
194
195 $this
196 ->runCommand('doctrine:schema:create')
197 ;
2e45e7be
J
198 }
199
0bf99bb1
J
200 $this->defaultOutput->writeln('Clearing the cache');
201 $this->runCommand('cache:clear');
202
0bf99bb1
J
203 $this->defaultOutput->writeln('');
204
205 return $this;
2e45e7be
J
206 }
207
0bf99bb1 208 protected function setupAdmin()
2e45e7be 209 {
637dc4bb 210 $this->defaultOutput->writeln('<info><comment>Step 3 of 5.</comment> Administration setup.</info>');
0bf99bb1 211
78507d28 212 $questionHelper = $this->getHelperSet()->get('question');
3c39f5ac 213 $question = new ConfirmationQuestion('Would you like to create a new admin user (recommended) ? (Y/n)', true);
0bf99bb1 214
78507d28 215 if (!$questionHelper->ask($this->defaultInput, $this->defaultOutput, $question)) {
0bf99bb1
J
216 return $this;
217 }
218
2e45e7be
J
219 $em = $this->getContainer()->get('doctrine.orm.entity_manager');
220
ec3ce598
NL
221 $userManager = $this->getContainer()->get('fos_user.user_manager');
222 $user = $userManager->createUser();
78507d28
JB
223
224 $question = new Question('Username (default: wallabag) :', 'wallabag');
225 $user->setUsername($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question));
226
227 $question = new Question('Password (default: wallabag) :', 'wallabag');
228 $user->setPlainPassword($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question));
229
230 $question = new Question('Email:', '');
231 $user->setEmail($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question));
232
a1691859 233 $user->setEnabled(true);
8f06a8c4 234 $user->addRole('ROLE_SUPER_ADMIN');
2e45e7be
J
235
236 $em->persist($user);
237
0bd2cb1e 238 $config = new Config($user);
bc789687
JB
239 $config->setTheme($this->getContainer()->getParameter('wallabag_core.theme'));
240 $config->setItemsPerPage($this->getContainer()->getParameter('wallabag_core.items_on_page'));
241 $config->setRssLimit($this->getContainer()->getParameter('wallabag_core.rss_limit'));
bca54859 242 $config->setReadingSpeed($this->getContainer()->getParameter('wallabag_core.reading_speed'));
bc789687 243 $config->setLanguage($this->getContainer()->getParameter('wallabag_core.language'));
2e45e7be 244
4d85d7e9 245 $em->persist($config);
0bf99bb1 246
637dc4bb
JB
247 $this->defaultOutput->writeln('');
248
249 return $this;
250 }
251
252 protected function setupConfig()
253 {
254 $this->defaultOutput->writeln('<info><comment>Step 4 of 5.</comment> Config setup.</info>');
255 $em = $this->getContainer()->get('doctrine.orm.entity_manager');
256
d6ba77e8
JB
257 // cleanup before insert new stuff
258 $em->createQuery('DELETE FROM CraueConfigBundle:Setting')->execute();
259
260 $settings = [
d6ba77e8
JB
261 [
262 'name' => 'carrot',
263 'value' => '1',
264 'section' => 'entry',
265 ],
266 [
267 'name' => 'share_diaspora',
268 'value' => '1',
269 'section' => 'entry',
270 ],
271 [
272 'name' => 'diaspora_url',
273 'value' => 'http://diasporapod.com',
274 'section' => 'entry',
275 ],
276 [
277 'name' => 'share_shaarli',
278 'value' => '1',
279 'section' => 'entry',
280 ],
281 [
282 'name' => 'shaarli_url',
283 'value' => 'http://myshaarli.com',
284 'section' => 'entry',
285 ],
286 [
287 'name' => 'share_mail',
288 'value' => '1',
289 'section' => 'entry',
290 ],
291 [
292 'name' => 'share_twitter',
293 'value' => '1',
294 'section' => 'entry',
295 ],
296 [
297 'name' => 'export_epub',
298 'value' => '1',
299 'section' => 'export',
300 ],
301 [
302 'name' => 'export_mobi',
303 'value' => '1',
304 'section' => 'export',
305 ],
306 [
307 'name' => 'export_pdf',
308 'value' => '1',
309 'section' => 'export',
310 ],
a74a6ca2
JB
311 [
312 'name' => 'export_csv',
313 'value' => '1',
314 'section' => 'export',
315 ],
316 [
317 'name' => 'export_json',
318 'value' => '1',
319 'section' => 'export',
320 ],
321 [
322 'name' => 'export_txt',
323 'value' => '1',
324 'section' => 'export',
325 ],
326 [
327 'name' => 'export_xml',
328 'value' => '1',
329 'section' => 'export',
330 ],
d6ba77e8
JB
331 [
332 'name' => 'pocket_consumer_key',
1c7d6664 333 'value' => null,
d6ba77e8
JB
334 'section' => 'import',
335 ],
336 [
337 'name' => 'show_printlink',
338 'value' => '1',
339 'section' => 'entry',
340 ],
341 [
342 'name' => 'wallabag_support_url',
343 'value' => 'https://www.wallabag.org/pages/support.html',
344 'section' => 'misc',
345 ],
346 [
347 'name' => 'wallabag_url',
348 'value' => 'http://v2.wallabag.org',
349 'section' => 'misc',
350 ],
07643dde
NL
351 [
352 'name' => 'piwik_enabled',
353 'value' => '0',
354 'section' => 'analytics',
355 ],
356 [
357 'name' => 'piwik_host',
358 'value' => 'http://v2.wallabag.org',
359 'section' => 'analytics',
360 ],
361 [
362 'name' => 'piwik_site_id',
363 'value' => '1',
364 'section' => 'analytics',
365 ],
a4f42c59
JB
366 [
367 'name' => 'demo_mode_enabled',
368 'value' => '0',
369 'section' => 'misc',
370 ],
371 [
372 'name' => 'demo_mode_username',
373 'value' => 'wallabag',
374 'section' => 'misc',
375 ],
d6ba77e8
JB
376 ];
377
378 foreach ($settings as $setting) {
379 $newSetting = new Setting();
380 $newSetting->setName($setting['name']);
381 $newSetting->setValue($setting['value']);
382 $newSetting->setSection($setting['section']);
383 $em->persist($newSetting);
384 }
385
0bf99bb1
J
386 $em->flush();
387
388 $this->defaultOutput->writeln('');
389
390 return $this;
2e45e7be
J
391 }
392
0bf99bb1 393 protected function setupAsset()
2e45e7be 394 {
637dc4bb 395 $this->defaultOutput->writeln('<info><comment>Step 5 of 5.</comment> Installing assets.</info>');
0bf99bb1 396
2e45e7be 397 $this
0bf99bb1
J
398 ->runCommand('assets:install')
399 ->runCommand('assetic:dump')
2e45e7be
J
400 ;
401
0bf99bb1
J
402 $this->defaultOutput->writeln('');
403
404 return $this;
405 }
406
407 /**
4346a860 408 * Run a command.
0bf99bb1
J
409 *
410 * @param string $command
411 * @param array $parameters Parameters to this command (usually 'force' => true)
412 */
4d0ec0e7 413 protected function runCommand($command, $parameters = [])
0bf99bb1
J
414 {
415 $parameters = array_merge(
4d0ec0e7 416 ['command' => $command],
0bf99bb1 417 $parameters,
4d0ec0e7 418 [
0bf99bb1
J
419 '--no-debug' => true,
420 '--env' => $this->defaultInput->getOption('env') ?: 'dev',
4d0ec0e7 421 ]
0bf99bb1
J
422 );
423
424 if ($this->defaultInput->getOption('no-interaction')) {
4d0ec0e7 425 $parameters = array_merge($parameters, ['--no-interaction' => true]);
0bf99bb1
J
426 }
427
428 $this->getApplication()->setAutoExit(false);
429 $exitCode = $this->getApplication()->run(new ArrayInput($parameters), new NullOutput());
430
431 if (0 !== $exitCode) {
432 $this->getApplication()->setAutoExit(true);
433
434 $errorMessage = sprintf('The command "%s" terminated with an error code: %u.', $command, $exitCode);
435 $this->defaultOutput->writeln("<error>$errorMessage</error>");
436 $exception = new \Exception($errorMessage, $exitCode);
437
438 throw $exception;
439 }
440
441 // PDO does not always close the connection after Doctrine commands.
442 // See https://github.com/symfony/symfony/issues/11750.
443 $this->getContainer()->get('doctrine')->getManager()->getConnection()->close();
444
2e45e7be
J
445 return $this;
446 }
0bf99bb1
J
447
448 /**
4346a860 449 * Check if the database already exists.
0bf99bb1 450 *
4346a860 451 * @return bool
0bf99bb1
J
452 */
453 private function isDatabasePresent()
454 {
af43bd37
JB
455 $connection = $this->getContainer()->get('doctrine')->getManager()->getConnection();
456 $databaseName = $connection->getDatabase();
0bf99bb1
J
457
458 try {
af43bd37 459 $schemaManager = $connection->getSchemaManager();
0bf99bb1 460 } catch (\Exception $exception) {
54a2241e 461 // mysql & sqlite
0bf99bb1
J
462 if (false !== strpos($exception->getMessage(), sprintf("Unknown database '%s'", $databaseName))) {
463 return false;
464 }
465
54a2241e
JB
466 // pgsql
467 if (false !== strpos($exception->getMessage(), sprintf('database "%s" does not exist', $databaseName))) {
468 return false;
469 }
470
0bf99bb1
J
471 throw $exception;
472 }
473
732c2ad8
J
474 // custom verification for sqlite, since `getListDatabasesSQL` doesn't work for sqlite
475 if ('sqlite' == $schemaManager->getDatabasePlatform()->getName()) {
476 $params = $this->getContainer()->get('doctrine.dbal.default_connection')->getParams();
477
478 if (isset($params['path']) && file_exists($params['path'])) {
479 return true;
480 }
481
482 return false;
483 }
484
69c21157
JB
485 try {
486 return in_array($databaseName, $schemaManager->listDatabases());
443cff98 487 } catch (\Doctrine\DBAL\Exception\DriverException $e) {
69c21157
JB
488 // it means we weren't able to get database list, assume the database doesn't exist
489
490 return false;
491 }
0bf99bb1
J
492 }
493
494 /**
164bd801 495 * Check if the schema is already created.
4346a860 496 * If we found at least oen table, it means the schema exists.
0bf99bb1 497 *
4346a860 498 * @return bool
0bf99bb1
J
499 */
500 private function isSchemaPresent()
501 {
502 $schemaManager = $this->getContainer()->get('doctrine')->getManager()->getConnection()->getSchemaManager();
503
164bd801 504 return count($schemaManager->listTableNames()) > 0 ? true : false;
0bf99bb1 505 }
2e45e7be 506}