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