]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Command/InstallCommand.php
Add a check for the database connection
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Command / InstallCommand.php
1 <?php
2
3 namespace Wallabag\CoreBundle\Command;
4
5 use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
6 use Symfony\Component\Console\Helper\Table;
7 use Symfony\Component\Console\Input\ArrayInput;
8 use Symfony\Component\Console\Input\InputInterface;
9 use Symfony\Component\Console\Input\InputOption;
10 use Symfony\Component\Console\Output\NullOutput;
11 use Symfony\Component\Console\Output\OutputInterface;
12 use Symfony\Component\Console\Question\ConfirmationQuestion;
13 use Symfony\Component\Console\Question\Question;
14 use Wallabag\CoreBundle\Entity\Config;
15 use Craue\ConfigBundle\Entity\Setting;
16
17 class InstallCommand extends ContainerAwareCommand
18 {
19 /**
20 * @var InputInterface
21 */
22 protected $defaultInput;
23
24 /**
25 * @var OutputInterface
26 */
27 protected $defaultOutput;
28
29 /**
30 * @var array
31 */
32 protected $functionExists = [
33 'curl_exec',
34 'curl_multi_init',
35 ];
36
37 protected function configure()
38 {
39 $this
40 ->setName('wallabag:install')
41 ->setDescription('Wallabag installer.')
42 ->addOption(
43 'reset',
44 null,
45 InputOption::VALUE_NONE,
46 'Reset current database'
47 )
48 ;
49 }
50
51 protected function execute(InputInterface $input, OutputInterface $output)
52 {
53 $this->defaultInput = $input;
54 $this->defaultOutput = $output;
55
56 $output->writeln('<info>Installing Wallabag...</info>');
57 $output->writeln('');
58
59 $this
60 ->checkRequirements()
61 ->setupDatabase()
62 ->setupAdmin()
63 ->setupConfig()
64 ->setupAsset()
65 ;
66
67 $output->writeln('<info>Wallabag has been successfully installed.</info>');
68 $output->writeln('<comment>Just execute `php bin/console server:run --env=prod` for using wallabag: http://localhost:8000</comment>');
69 }
70
71 protected function checkRequirements()
72 {
73 $this->defaultOutput->writeln('<info><comment>Step 1 of 5.</comment> Checking system requirements.</info>');
74
75 $rows = [];
76
77 // testing if database driver exists
78 $fulfilled = true;
79 $label = '<comment>PDO Driver</comment>';
80 $status = '<info>OK!</info>';
81 $help = '';
82
83 if (!extension_loaded($this->getContainer()->getParameter('database_driver'))) {
84 $fulfilled = false;
85 $status = '<error>ERROR!</error>';
86 $help = 'Database driver "'.$this->getContainer()->getParameter('database_driver').'" is not installed.';
87 }
88
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
104 $rows[] = [$label, $status, $help];
105
106 foreach ($this->functionExists as $functionRequired) {
107 $label = '<comment>'.$functionRequired.'</comment>';
108 $status = '<info>OK!</info>';
109 $help = '';
110
111 if (!function_exists($functionRequired)) {
112 $fulfilled = false;
113 $status = '<error>ERROR!</error>';
114 $help = 'You need the '.$functionRequired.' function activated';
115 }
116
117 $rows[] = [$label, $status, $help];
118 }
119
120 $table = new Table($this->defaultOutput);
121 $table
122 ->setHeaders(['Checked', 'Status', 'Recommendation'])
123 ->setRows($rows)
124 ->render();
125
126 if (!$fulfilled) {
127 throw new \RuntimeException('Some system requirements are not fulfilled. Please check output messages and fix them.');
128 }
129
130 $this->defaultOutput->writeln('<info>Success! Your system can run Wallabag properly.</info>');
131
132 $this->defaultOutput->writeln('');
133
134 return $this;
135 }
136
137 protected function setupDatabase()
138 {
139 $this->defaultOutput->writeln('<info><comment>Step 2 of 5.</comment> Setting up database.</info>');
140
141 // user want to reset everything? Don't care about what is already here
142 if (true === $this->defaultInput->getOption('reset')) {
143 $this->defaultOutput->writeln('Droping database, creating database and schema, clearing the cache');
144
145 $this
146 ->runCommand('doctrine:database:drop', ['--force' => true])
147 ->runCommand('doctrine:database:create')
148 ->runCommand('doctrine:schema:create')
149 ->runCommand('cache:clear')
150 ;
151
152 $this->defaultOutput->writeln('');
153
154 return $this;
155 }
156
157 if (!$this->isDatabasePresent()) {
158 $this->defaultOutput->writeln('Creating database and schema, clearing the cache');
159
160 $this
161 ->runCommand('doctrine:database:create')
162 ->runCommand('doctrine:schema:create')
163 ->runCommand('cache:clear')
164 ;
165
166 $this->defaultOutput->writeln('');
167
168 return $this;
169 }
170
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);
173
174 if ($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question)) {
175 $this->defaultOutput->writeln('Droping database, creating database and schema');
176
177 $this
178 ->runCommand('doctrine:database:drop', ['--force' => true])
179 ->runCommand('doctrine:database:create')
180 ->runCommand('doctrine:schema:create')
181 ;
182 } elseif ($this->isSchemaPresent()) {
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)) {
185 $this->defaultOutput->writeln('Droping schema and creating schema');
186
187 $this
188 ->runCommand('doctrine:schema:drop', ['--force' => true])
189 ->runCommand('doctrine:schema:create')
190 ;
191 }
192 } else {
193 $this->defaultOutput->writeln('Creating schema');
194
195 $this
196 ->runCommand('doctrine:schema:create')
197 ;
198 }
199
200 $this->defaultOutput->writeln('Clearing the cache');
201 $this->runCommand('cache:clear');
202
203 $this->defaultOutput->writeln('');
204
205 return $this;
206 }
207
208 protected function setupAdmin()
209 {
210 $this->defaultOutput->writeln('<info><comment>Step 3 of 5.</comment> Administration setup.</info>');
211
212 $questionHelper = $this->getHelperSet()->get('question');
213 $question = new ConfirmationQuestion('Would you like to create a new admin user (recommended) ? (Y/n)', true);
214
215 if (!$questionHelper->ask($this->defaultInput, $this->defaultOutput, $question)) {
216 return $this;
217 }
218
219 $em = $this->getContainer()->get('doctrine.orm.entity_manager');
220
221 $userManager = $this->getContainer()->get('fos_user.user_manager');
222 $user = $userManager->createUser();
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
233 $user->setEnabled(true);
234 $user->addRole('ROLE_SUPER_ADMIN');
235
236 $em->persist($user);
237
238 $config = new Config($user);
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'));
242 $config->setReadingSpeed($this->getContainer()->getParameter('wallabag_core.reading_speed'));
243 $config->setLanguage($this->getContainer()->getParameter('wallabag_core.language'));
244
245 $em->persist($config);
246
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
257 // cleanup before insert new stuff
258 $em->createQuery('DELETE FROM CraueConfigBundle:Setting')->execute();
259
260 $settings = [
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 ],
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 ],
331 [
332 'name' => 'pocket_consumer_key',
333 'value' => null,
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 ],
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 ],
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 ],
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
386 $em->flush();
387
388 $this->defaultOutput->writeln('');
389
390 return $this;
391 }
392
393 protected function setupAsset()
394 {
395 $this->defaultOutput->writeln('<info><comment>Step 5 of 5.</comment> Installing assets.</info>');
396
397 $this
398 ->runCommand('assets:install')
399 ->runCommand('assetic:dump')
400 ;
401
402 $this->defaultOutput->writeln('');
403
404 return $this;
405 }
406
407 /**
408 * Run a command.
409 *
410 * @param string $command
411 * @param array $parameters Parameters to this command (usually 'force' => true)
412 */
413 protected function runCommand($command, $parameters = [])
414 {
415 $parameters = array_merge(
416 ['command' => $command],
417 $parameters,
418 [
419 '--no-debug' => true,
420 '--env' => $this->defaultInput->getOption('env') ?: 'dev',
421 ]
422 );
423
424 if ($this->defaultInput->getOption('no-interaction')) {
425 $parameters = array_merge($parameters, ['--no-interaction' => true]);
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
445 return $this;
446 }
447
448 /**
449 * Check if the database already exists.
450 *
451 * @return bool
452 */
453 private function isDatabasePresent()
454 {
455 $connection = $this->getContainer()->get('doctrine')->getManager()->getConnection();
456 $databaseName = $connection->getDatabase();
457
458 try {
459 $schemaManager = $connection->getSchemaManager();
460 } catch (\Exception $exception) {
461 // mysql & sqlite
462 if (false !== strpos($exception->getMessage(), sprintf("Unknown database '%s'", $databaseName))) {
463 return false;
464 }
465
466 // pgsql
467 if (false !== strpos($exception->getMessage(), sprintf('database "%s" does not exist', $databaseName))) {
468 return false;
469 }
470
471 throw $exception;
472 }
473
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
485 try {
486 return in_array($databaseName, $schemaManager->listDatabases());
487 } catch (\Doctrine\DBAL\Exception\DriverException $e) {
488 // it means we weren't able to get database list, assume the database doesn't exist
489
490 return false;
491 }
492 }
493
494 /**
495 * Check if the schema is already created.
496 * If we found at least oen table, it means the schema exists.
497 *
498 * @return bool
499 */
500 private function isSchemaPresent()
501 {
502 $schemaManager = $this->getContainer()->get('doctrine')->getManager()->getConnection()->getSchemaManager();
503
504 return count($schemaManager->listTableNames()) > 0 ? true : false;
505 }
506 }