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