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