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