]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/CoreBundle/Command/InstallCommand.php
Merge pull request #3516 from wallabag/delete-id
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Command / InstallCommand.php
CommitLineData
2e45e7be
J
1<?php
2
3namespace Wallabag\CoreBundle\Command;
4
f808b016 5use Craue\ConfigBundle\Entity\Setting;
ca17abce
JB
6use FOS\UserBundle\Event\UserEvent;
7use FOS\UserBundle\FOSUserEvents;
2e45e7be 8use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
619cc453 9use Symfony\Component\Console\Input\ArrayInput;
2e45e7be 10use Symfony\Component\Console\Input\InputInterface;
0bf99bb1 11use Symfony\Component\Console\Input\InputOption;
39a19bdf 12use Symfony\Component\Console\Output\BufferedOutput;
619cc453 13use Symfony\Component\Console\Output\OutputInterface;
619cc453 14use Symfony\Component\Console\Question\Question;
e1b33efb 15use Symfony\Component\Console\Style\SymfonyStyle;
2e45e7be
J
16
17class InstallCommand extends ContainerAwareCommand
18{
0bf99bb1
J
19 /**
20 * @var InputInterface
21 */
22 protected $defaultInput;
23
24 /**
e1b33efb 25 * @var SymfonyStyle
0bf99bb1 26 */
e1b33efb 27 protected $io;
0bf99bb1 28
fc6020b2
NL
29 /**
30 * @var array
31 */
db847ca0 32 protected $functionExists = [
db847ca0
TC
33 'curl_exec',
34 'curl_multi_init',
fc6020b2
NL
35 ];
36
2e45e7be
J
37 protected function configure()
38 {
39 $this
40 ->setName('wallabag:install')
88d5d94d 41 ->setDescription('wallabag installer.')
0bf99bb1
J
42 ->addOption(
43 'reset',
44 null,
45 InputOption::VALUE_NONE,
46 'Reset current database'
47 )
2e45e7be
J
48 ;
49 }
50
51 protected function execute(InputInterface $input, OutputInterface $output)
52 {
0bf99bb1 53 $this->defaultInput = $input;
0bf99bb1 54
e1b33efb
NH
55 $this->io = new SymfonyStyle($input, $output);
56
57 $this->io->title('Wallabag installer');
2e45e7be
J
58
59 $this
0bf99bb1
J
60 ->checkRequirements()
61 ->setupDatabase()
62 ->setupAdmin()
637dc4bb 63 ->setupConfig()
2e45e7be
J
64 ;
65
e1b33efb 66 $this->io->success('Wallabag has been successfully installed.');
f565e108 67 $this->io->success('You can now configure your web server, see https://doc.wallabag.org');
2e45e7be
J
68 }
69
0bf99bb1 70 protected function checkRequirements()
2e45e7be 71 {
2680b0bc 72 $this->io->section('Step 1 of 4: Checking system requirements.');
e1b33efb 73
cffcce0c 74 $doctrineManager = $this->getContainer()->get('doctrine')->getManager();
2e45e7be 75
001a7bad 76 $rows = [];
2e45e7be 77
001a7bad
JB
78 // testing if database driver exists
79 $fulfilled = true;
a730cae3 80 $label = '<comment>PDO Driver (%s)</comment>';
0e49487b
JB
81 $status = '<info>OK!</info>';
82 $help = '';
c61b68e8
JB
83
84 if (!extension_loaded($this->getContainer()->getParameter('database_driver'))) {
db847ca0
TC
85 $fulfilled = false;
86 $status = '<error>ERROR!</error>';
f808b016 87 $help = 'Database driver "' . $this->getContainer()->getParameter('database_driver') . '" is not installed.';
db847ca0
TC
88 }
89
a730cae3 90 $rows[] = [sprintf($label, $this->getContainer()->getParameter('database_driver')), $status, $help];
001a7bad
JB
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 {
fc79f1ff
JB
98 $conn = $this->getContainer()->get('doctrine')->getManager()->getConnection();
99 $conn->connect();
001a7bad 100 } catch (\Exception $e) {
39a19bdf 101 if (false === strpos($e->getMessage(), 'Unknown database')
f808b016 102 && false === strpos($e->getMessage(), 'database "' . $this->getContainer()->getParameter('database_name') . '" does not exist')) {
f62c3faf
JB
103 $fulfilled = false;
104 $status = '<error>ERROR!</error>';
f808b016 105 $help = 'Can\'t connect to the database: ' . $e->getMessage();
f62c3faf 106 }
001a7bad
JB
107 }
108
4d0ec0e7 109 $rows[] = [$label, $status, $help];
db847ca0 110
68003139
JB
111 // check MySQL & PostgreSQL version
112 $label = '<comment>Database version</comment>';
cffcce0c
JB
113 $status = '<info>OK!</info>';
114 $help = '';
115
fc79f1ff 116 // now check if MySQL isn't too old to handle utf8mb4
68003139 117 if ($conn->isConnected() && 'mysql' === $conn->getDatabasePlatform()->getName()) {
fc79f1ff
JB
118 $version = $conn->query('select version()')->fetchColumn();
119 $minimalVersion = '5.5.4';
120
121 if (false === version_compare($version, $minimalVersion, '>')) {
122 $fulfilled = false;
68003139 123 $status = '<error>ERROR!</error>';
f808b016 124 $help = 'Your MySQL version (' . $version . ') is too old, consider upgrading (' . $minimalVersion . '+).';
fc79f1ff
JB
125 }
126 }
127
68003139
JB
128 // testing if PostgreSQL > 9.1
129 if ($conn->isConnected() && 'postgresql' === $conn->getDatabasePlatform()->getName()) {
cffcce0c
JB
130 // 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"
131 $version = $doctrineManager->getConnection()->query('SELECT version();')->fetchColumn();
132
133 preg_match('/PostgreSQL ([0-9\.]+)/i', $version, $matches);
134
135 if (isset($matches[1]) & version_compare($matches[1], '9.2.0', '<')) {
136 $fulfilled = false;
137 $status = '<error>ERROR!</error>';
f808b016 138 $help = 'PostgreSQL should be greater than 9.1 (actual version: ' . $matches[1] . ')';
cffcce0c
JB
139 }
140 }
141
142 $rows[] = [$label, $status, $help];
143
db847ca0 144 foreach ($this->functionExists as $functionRequired) {
f808b016 145 $label = '<comment>' . $functionRequired . '</comment>';
0e49487b
JB
146 $status = '<info>OK!</info>';
147 $help = '';
db847ca0 148
0e49487b 149 if (!function_exists($functionRequired)) {
fc6020b2
NL
150 $fulfilled = false;
151 $status = '<error>ERROR!</error>';
f808b016 152 $help = 'You need the ' . $functionRequired . ' function activated';
fc6020b2 153 }
db847ca0 154
4d0ec0e7 155 $rows[] = [$label, $status, $help];
2e45e7be 156 }
0bf99bb1 157
e1b33efb 158 $this->io->table(['Checked', 'Status', 'Recommendation'], $rows);
2e45e7be
J
159
160 if (!$fulfilled) {
0bf99bb1 161 throw new \RuntimeException('Some system requirements are not fulfilled. Please check output messages and fix them.');
2e45e7be
J
162 }
163
e1b33efb 164 $this->io->success('Success! Your system can run wallabag properly.');
2e45e7be
J
165
166 return $this;
167 }
168
0bf99bb1 169 protected function setupDatabase()
2e45e7be 170 {
2680b0bc 171 $this->io->section('Step 2 of 4: Setting up database.');
2e45e7be 172
0bf99bb1
J
173 // user want to reset everything? Don't care about what is already here
174 if (true === $this->defaultInput->getOption('reset')) {
e1b33efb 175 $this->io->text('Dropping database, creating database and schema, clearing the cache');
2e45e7be 176
0bf99bb1 177 $this
4d0ec0e7 178 ->runCommand('doctrine:database:drop', ['--force' => true])
0bf99bb1 179 ->runCommand('doctrine:database:create')
2680b0bc 180 ->runCommand('doctrine:migrations:migrate', ['--no-interaction' => true])
d5027625 181 ->runCommand('cache:clear')
0bf99bb1 182 ;
2e45e7be 183
e1b33efb 184 $this->io->newLine();
d5027625 185
0bf99bb1
J
186 return $this;
187 }
2e45e7be 188
0bf99bb1 189 if (!$this->isDatabasePresent()) {
e1b33efb 190 $this->io->text('Creating database and schema, clearing the cache');
2e45e7be 191
0bf99bb1
J
192 $this
193 ->runCommand('doctrine:database:create')
2680b0bc 194 ->runCommand('doctrine:migrations:migrate', ['--no-interaction' => true])
0bf99bb1
J
195 ->runCommand('cache:clear')
196 ;
2e45e7be 197
e1b33efb 198 $this->io->newLine();
d5027625 199
0bf99bb1
J
200 return $this;
201 }
2e45e7be 202
e1b33efb
NH
203 if ($this->io->confirm('It appears that your database already exists. Would you like to reset it?', false)) {
204 $this->io->text('Dropping database, creating database and schema...');
2e45e7be 205
0bf99bb1 206 $this
4d0ec0e7 207 ->runCommand('doctrine:database:drop', ['--force' => true])
0bf99bb1 208 ->runCommand('doctrine:database:create')
2680b0bc 209 ->runCommand('doctrine:migrations:migrate', ['--no-interaction' => true])
0bf99bb1
J
210 ;
211 } elseif ($this->isSchemaPresent()) {
e1b33efb
NH
212 if ($this->io->confirm('Seems like your database contains schema. Do you want to reset it?', false)) {
213 $this->io->text('Dropping schema and creating schema...');
2e45e7be 214
0bf99bb1 215 $this
4d0ec0e7 216 ->runCommand('doctrine:schema:drop', ['--force' => true])
2680b0bc 217 ->runCommand('doctrine:migrations:migrate', ['--no-interaction' => true])
0bf99bb1
J
218 ;
219 }
2e45e7be 220 } else {
e1b33efb 221 $this->io->text('Creating schema...');
0bf99bb1
J
222
223 $this
2680b0bc 224 ->runCommand('doctrine:migrations:migrate', ['--no-interaction' => true])
0bf99bb1 225 ;
2e45e7be
J
226 }
227
e1b33efb 228 $this->io->text('Clearing the cache...');
0bf99bb1
J
229 $this->runCommand('cache:clear');
230
e1b33efb
NH
231 $this->io->newLine();
232 $this->io->text('<info>Database successfully setup.</info>');
0bf99bb1
J
233
234 return $this;
2e45e7be
J
235 }
236
0bf99bb1 237 protected function setupAdmin()
2e45e7be 238 {
2680b0bc 239 $this->io->section('Step 3 of 4: Administration setup.');
0bf99bb1 240
e1b33efb 241 if (!$this->io->confirm('Would you like to create a new admin user (recommended)?', true)) {
0bf99bb1
J
242 return $this;
243 }
244
2e45e7be
J
245 $em = $this->getContainer()->get('doctrine.orm.entity_manager');
246
ec3ce598
NL
247 $userManager = $this->getContainer()->get('fos_user.user_manager');
248 $user = $userManager->createUser();
78507d28 249
e1b33efb 250 $user->setUsername($this->io->ask('Username', 'wallabag'));
78507d28 251
e1b33efb
NH
252 $question = new Question('Password', 'wallabag');
253 $question->setHidden(true);
254 $user->setPlainPassword($this->io->askQuestion($question));
78507d28 255
e1b33efb 256 $user->setEmail($this->io->ask('Email', ''));
78507d28 257
a1691859 258 $user->setEnabled(true);
8f06a8c4 259 $user->addRole('ROLE_SUPER_ADMIN');
2e45e7be
J
260
261 $em->persist($user);
262
ca17abce
JB
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);
0bf99bb1 266
e1b33efb 267 $this->io->text('<info>Administration successfully setup.</info>');
637dc4bb
JB
268
269 return $this;
270 }
271
272 protected function setupConfig()
273 {
2680b0bc 274 $this->io->section('Step 4 of 4: Config setup.');
637dc4bb
JB
275 $em = $this->getContainer()->get('doctrine.orm.entity_manager');
276
d6ba77e8
JB
277 // cleanup before insert new stuff
278 $em->createQuery('DELETE FROM CraueConfigBundle:Setting')->execute();
279
426bb453 280 foreach ($this->getContainer()->getParameter('wallabag_core.default_internal_settings') as $setting) {
d6ba77e8
JB
281 $newSetting = new Setting();
282 $newSetting->setName($setting['name']);
283 $newSetting->setValue($setting['value']);
284 $newSetting->setSection($setting['section']);
285 $em->persist($newSetting);
286 }
287
0bf99bb1
J
288 $em->flush();
289
e1b33efb 290 $this->io->text('<info>Config successfully setup.</info>');
0bf99bb1
J
291
292 return $this;
2e45e7be
J
293 }
294
0bf99bb1 295 /**
4346a860 296 * Run a command.
0bf99bb1
J
297 *
298 * @param string $command
299 * @param array $parameters Parameters to this command (usually 'force' => true)
300 */
4d0ec0e7 301 protected function runCommand($command, $parameters = [])
0bf99bb1
J
302 {
303 $parameters = array_merge(
4d0ec0e7 304 ['command' => $command],
0bf99bb1 305 $parameters,
4d0ec0e7 306 [
0bf99bb1
J
307 '--no-debug' => true,
308 '--env' => $this->defaultInput->getOption('env') ?: 'dev',
4d0ec0e7 309 ]
0bf99bb1
J
310 );
311
312 if ($this->defaultInput->getOption('no-interaction')) {
4d0ec0e7 313 $parameters = array_merge($parameters, ['--no-interaction' => true]);
0bf99bb1
J
314 }
315
316 $this->getApplication()->setAutoExit(false);
39a19bdf
JB
317
318 $output = new BufferedOutput();
319 $exitCode = $this->getApplication()->run(new ArrayInput($parameters), $output);
0bf99bb1 320
7ab5eb95 321 // PDO does not always close the connection after Doctrine commands.
322 // See https://github.com/symfony/symfony/issues/11750.
323 $this->getContainer()->get('doctrine')->getManager()->getConnection()->close();
324
0bf99bb1
J
325 if (0 !== $exitCode) {
326 $this->getApplication()->setAutoExit(true);
327
7ab5eb95 328 throw new \RuntimeException(
f808b016
JB
329 'The command "' . $command . "\" generates some errors: \n\n"
330 . $output->fetch());
0bf99bb1
J
331 }
332
2e45e7be
J
333 return $this;
334 }
0bf99bb1
J
335
336 /**
4346a860 337 * Check if the database already exists.
0bf99bb1 338 *
4346a860 339 * @return bool
0bf99bb1
J
340 */
341 private function isDatabasePresent()
342 {
af43bd37
JB
343 $connection = $this->getContainer()->get('doctrine')->getManager()->getConnection();
344 $databaseName = $connection->getDatabase();
0bf99bb1
J
345
346 try {
af43bd37 347 $schemaManager = $connection->getSchemaManager();
0bf99bb1 348 } catch (\Exception $exception) {
54a2241e 349 // mysql & sqlite
0bf99bb1
J
350 if (false !== strpos($exception->getMessage(), sprintf("Unknown database '%s'", $databaseName))) {
351 return false;
352 }
353
54a2241e
JB
354 // pgsql
355 if (false !== strpos($exception->getMessage(), sprintf('database "%s" does not exist', $databaseName))) {
356 return false;
357 }
358
0bf99bb1
J
359 throw $exception;
360 }
361
732c2ad8 362 // custom verification for sqlite, since `getListDatabasesSQL` doesn't work for sqlite
f62c3faf 363 if ('sqlite' === $schemaManager->getDatabasePlatform()->getName()) {
732c2ad8
J
364 $params = $this->getContainer()->get('doctrine.dbal.default_connection')->getParams();
365
366 if (isset($params['path']) && file_exists($params['path'])) {
367 return true;
368 }
369
370 return false;
371 }
372
69c21157 373 try {
f808b016 374 return in_array($databaseName, $schemaManager->listDatabases(), true);
443cff98 375 } catch (\Doctrine\DBAL\Exception\DriverException $e) {
69c21157
JB
376 // it means we weren't able to get database list, assume the database doesn't exist
377
378 return false;
379 }
0bf99bb1
J
380 }
381
382 /**
164bd801 383 * Check if the schema is already created.
4346a860 384 * If we found at least oen table, it means the schema exists.
0bf99bb1 385 *
4346a860 386 * @return bool
0bf99bb1
J
387 */
388 private function isSchemaPresent()
389 {
390 $schemaManager = $this->getContainer()->get('doctrine')->getManager()->getConnection()->getSchemaManager();
391
164bd801 392 return count($schemaManager->listTableNames()) > 0 ? true : false;
0bf99bb1 393 }
2e45e7be 394}