]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/CoreBundle/Command/InstallCommand.php
Add a real configuration for CS-Fixer
[github/wallabag/wallabag.git] / src / Wallabag / CoreBundle / Command / InstallCommand.php
1 <?php
2
3 namespace Wallabag\CoreBundle\Command;
4
5 use Craue\ConfigBundle\Entity\Setting;
6 use FOS\UserBundle\Event\UserEvent;
7 use FOS\UserBundle\FOSUserEvents;
8 use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
9 use Symfony\Component\Console\Helper\Table;
10 use Symfony\Component\Console\Input\ArrayInput;
11 use Symfony\Component\Console\Input\InputInterface;
12 use Symfony\Component\Console\Input\InputOption;
13 use Symfony\Component\Console\Output\BufferedOutput;
14 use Symfony\Component\Console\Output\OutputInterface;
15 use Symfony\Component\Console\Question\ConfirmationQuestion;
16 use Symfony\Component\Console\Question\Question;
17 use Wallabag\CoreBundle\Entity\Config;
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 ->runMigrations()
67 ;
68
69 $output->writeln('<info>wallabag has been successfully installed.</info>');
70 $output->writeln('<comment>Just execute `php bin/console server:run --env=prod` for using wallabag: http://localhost:8000</comment>');
71 }
72
73 protected function checkRequirements()
74 {
75 $this->defaultOutput->writeln('<info><comment>Step 1 of 5.</comment> Checking system requirements.</info>');
76 $doctrineManager = $this->getContainer()->get('doctrine')->getManager();
77
78 $rows = [];
79
80 // testing if database driver exists
81 $fulfilled = true;
82 $label = '<comment>PDO Driver (%s)</comment>';
83 $status = '<info>OK!</info>';
84 $help = '';
85
86 if (!extension_loaded($this->getContainer()->getParameter('database_driver'))) {
87 $fulfilled = false;
88 $status = '<error>ERROR!</error>';
89 $help = 'Database driver "' . $this->getContainer()->getParameter('database_driver') . '" is not installed.';
90 }
91
92 $rows[] = [sprintf($label, $this->getContainer()->getParameter('database_driver')), $status, $help];
93
94 // testing if connection to the database can be etablished
95 $label = '<comment>Database connection</comment>';
96 $status = '<info>OK!</info>';
97 $help = '';
98
99 try {
100 $conn = $this->getContainer()->get('doctrine')->getManager()->getConnection();
101 $conn->connect();
102 } catch (\Exception $e) {
103 if (false === strpos($e->getMessage(), 'Unknown database')
104 && false === strpos($e->getMessage(), 'database "' . $this->getContainer()->getParameter('database_name') . '" does not exist')) {
105 $fulfilled = false;
106 $status = '<error>ERROR!</error>';
107 $help = 'Can\'t connect to the database: ' . $e->getMessage();
108 }
109 }
110
111 $rows[] = [$label, $status, $help];
112
113 // check MySQL & PostgreSQL version
114 $label = '<comment>Database version</comment>';
115 $status = '<info>OK!</info>';
116 $help = '';
117
118 // now check if MySQL isn't too old to handle utf8mb4
119 if ($conn->isConnected() && 'mysql' === $conn->getDatabasePlatform()->getName()) {
120 $version = $conn->query('select version()')->fetchColumn();
121 $minimalVersion = '5.5.4';
122
123 if (false === version_compare($version, $minimalVersion, '>')) {
124 $fulfilled = false;
125 $status = '<error>ERROR!</error>';
126 $help = 'Your MySQL version (' . $version . ') is too old, consider upgrading (' . $minimalVersion . '+).';
127 }
128 }
129
130 // testing if PostgreSQL > 9.1
131 if ($conn->isConnected() && 'postgresql' === $conn->getDatabasePlatform()->getName()) {
132 // 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"
133 $version = $doctrineManager->getConnection()->query('SELECT version();')->fetchColumn();
134
135 preg_match('/PostgreSQL ([0-9\.]+)/i', $version, $matches);
136
137 if (isset($matches[1]) & version_compare($matches[1], '9.2.0', '<')) {
138 $fulfilled = false;
139 $status = '<error>ERROR!</error>';
140 $help = 'PostgreSQL should be greater than 9.1 (actual version: ' . $matches[1] . ')';
141 }
142 }
143
144 $rows[] = [$label, $status, $help];
145
146 foreach ($this->functionExists as $functionRequired) {
147 $label = '<comment>' . $functionRequired . '</comment>';
148 $status = '<info>OK!</info>';
149 $help = '';
150
151 if (!function_exists($functionRequired)) {
152 $fulfilled = false;
153 $status = '<error>ERROR!</error>';
154 $help = 'You need the ' . $functionRequired . ' function activated';
155 }
156
157 $rows[] = [$label, $status, $help];
158 }
159
160 $table = new Table($this->defaultOutput);
161 $table
162 ->setHeaders(['Checked', 'Status', 'Recommendation'])
163 ->setRows($rows)
164 ->render();
165
166 if (!$fulfilled) {
167 throw new \RuntimeException('Some system requirements are not fulfilled. Please check output messages and fix them.');
168 }
169
170 $this->defaultOutput->writeln('<info>Success! Your system can run wallabag properly.</info>');
171
172 $this->defaultOutput->writeln('');
173
174 return $this;
175 }
176
177 protected function setupDatabase()
178 {
179 $this->defaultOutput->writeln('<info><comment>Step 2 of 5.</comment> Setting up database.</info>');
180
181 // user want to reset everything? Don't care about what is already here
182 if (true === $this->defaultInput->getOption('reset')) {
183 $this->defaultOutput->writeln('Dropping database, creating database and schema, clearing the cache');
184
185 $this
186 ->runCommand('doctrine:database:drop', ['--force' => true])
187 ->runCommand('doctrine:database:create')
188 ->runCommand('doctrine:schema:create')
189 ->runCommand('cache:clear')
190 ;
191
192 $this->defaultOutput->writeln('');
193
194 return $this;
195 }
196
197 if (!$this->isDatabasePresent()) {
198 $this->defaultOutput->writeln('Creating database and schema, clearing the cache');
199
200 $this
201 ->runCommand('doctrine:database:create')
202 ->runCommand('doctrine:schema:create')
203 ->runCommand('cache:clear')
204 ;
205
206 $this->defaultOutput->writeln('');
207
208 return $this;
209 }
210
211 $questionHelper = $this->getHelper('question');
212 $question = new ConfirmationQuestion('It appears that your database already exists. Would you like to reset it? (y/N)', false);
213
214 if ($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question)) {
215 $this->defaultOutput->writeln('Dropping database, creating database and schema');
216
217 $this
218 ->runCommand('doctrine:database:drop', ['--force' => true])
219 ->runCommand('doctrine:database:create')
220 ->runCommand('doctrine:schema:create')
221 ;
222 } elseif ($this->isSchemaPresent()) {
223 $question = new ConfirmationQuestion('Seems like your database contains schema. Do you want to reset it? (y/N)', false);
224 if ($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question)) {
225 $this->defaultOutput->writeln('Dropping schema and creating schema');
226
227 $this
228 ->runCommand('doctrine:schema:drop', ['--force' => true])
229 ->runCommand('doctrine:schema:create')
230 ;
231 }
232 } else {
233 $this->defaultOutput->writeln('Creating schema');
234
235 $this
236 ->runCommand('doctrine:schema:create')
237 ;
238 }
239
240 $this->defaultOutput->writeln('Clearing the cache');
241 $this->runCommand('cache:clear');
242
243 $this->defaultOutput->writeln('');
244
245 return $this;
246 }
247
248 protected function setupAdmin()
249 {
250 $this->defaultOutput->writeln('<info><comment>Step 3 of 5.</comment> Administration setup.</info>');
251
252 $questionHelper = $this->getHelperSet()->get('question');
253 $question = new ConfirmationQuestion('Would you like to create a new admin user (recommended) ? (Y/n)', true);
254
255 if (!$questionHelper->ask($this->defaultInput, $this->defaultOutput, $question)) {
256 return $this;
257 }
258
259 $em = $this->getContainer()->get('doctrine.orm.entity_manager');
260
261 $userManager = $this->getContainer()->get('fos_user.user_manager');
262 $user = $userManager->createUser();
263
264 $question = new Question('Username (default: wallabag) :', 'wallabag');
265 $user->setUsername($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question));
266
267 $question = new Question('Password (default: wallabag) :', 'wallabag');
268 $user->setPlainPassword($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question));
269
270 $question = new Question('Email:', '');
271 $user->setEmail($questionHelper->ask($this->defaultInput, $this->defaultOutput, $question));
272
273 $user->setEnabled(true);
274 $user->addRole('ROLE_SUPER_ADMIN');
275
276 $em->persist($user);
277
278 // dispatch a created event so the associated config will be created
279 $event = new UserEvent($user);
280 $this->getContainer()->get('event_dispatcher')->dispatch(FOSUserEvents::USER_CREATED, $event);
281
282 $this->defaultOutput->writeln('');
283
284 return $this;
285 }
286
287 protected function setupConfig()
288 {
289 $this->defaultOutput->writeln('<info><comment>Step 4 of 5.</comment> Config setup.</info>');
290 $em = $this->getContainer()->get('doctrine.orm.entity_manager');
291
292 // cleanup before insert new stuff
293 $em->createQuery('DELETE FROM CraueConfigBundle:Setting')->execute();
294
295 foreach ($this->getContainer()->getParameter('wallabag_core.default_internal_settings') as $setting) {
296 $newSetting = new Setting();
297 $newSetting->setName($setting['name']);
298 $newSetting->setValue($setting['value']);
299 $newSetting->setSection($setting['section']);
300 $em->persist($newSetting);
301 }
302
303 $em->flush();
304
305 $this->defaultOutput->writeln('');
306
307 return $this;
308 }
309
310 protected function runMigrations()
311 {
312 $this->defaultOutput->writeln('<info><comment>Step 5 of 5.</comment> Run migrations.</info>');
313
314 $this
315 ->runCommand('doctrine:migrations:migrate', ['--no-interaction' => true]);
316
317 return $this;
318 }
319
320 /**
321 * Run a command.
322 *
323 * @param string $command
324 * @param array $parameters Parameters to this command (usually 'force' => true)
325 */
326 protected function runCommand($command, $parameters = [])
327 {
328 $parameters = array_merge(
329 ['command' => $command],
330 $parameters,
331 [
332 '--no-debug' => true,
333 '--env' => $this->defaultInput->getOption('env') ?: 'dev',
334 ]
335 );
336
337 if ($this->defaultInput->getOption('no-interaction')) {
338 $parameters = array_merge($parameters, ['--no-interaction' => true]);
339 }
340
341 $this->getApplication()->setAutoExit(false);
342
343 $output = new BufferedOutput();
344 $exitCode = $this->getApplication()->run(new ArrayInput($parameters), $output);
345
346 // PDO does not always close the connection after Doctrine commands.
347 // See https://github.com/symfony/symfony/issues/11750.
348 $this->getContainer()->get('doctrine')->getManager()->getConnection()->close();
349
350 if (0 !== $exitCode) {
351 $this->getApplication()->setAutoExit(true);
352
353 throw new \RuntimeException(
354 'The command "' . $command . "\" generates some errors: \n\n"
355 . $output->fetch());
356 }
357
358 return $this;
359 }
360
361 /**
362 * Check if the database already exists.
363 *
364 * @return bool
365 */
366 private function isDatabasePresent()
367 {
368 $connection = $this->getContainer()->get('doctrine')->getManager()->getConnection();
369 $databaseName = $connection->getDatabase();
370
371 try {
372 $schemaManager = $connection->getSchemaManager();
373 } catch (\Exception $exception) {
374 // mysql & sqlite
375 if (false !== strpos($exception->getMessage(), sprintf("Unknown database '%s'", $databaseName))) {
376 return false;
377 }
378
379 // pgsql
380 if (false !== strpos($exception->getMessage(), sprintf('database "%s" does not exist', $databaseName))) {
381 return false;
382 }
383
384 throw $exception;
385 }
386
387 // custom verification for sqlite, since `getListDatabasesSQL` doesn't work for sqlite
388 if ('sqlite' === $schemaManager->getDatabasePlatform()->getName()) {
389 $params = $this->getContainer()->get('doctrine.dbal.default_connection')->getParams();
390
391 if (isset($params['path']) && file_exists($params['path'])) {
392 return true;
393 }
394
395 return false;
396 }
397
398 try {
399 return in_array($databaseName, $schemaManager->listDatabases(), true);
400 } catch (\Doctrine\DBAL\Exception\DriverException $e) {
401 // it means we weren't able to get database list, assume the database doesn't exist
402
403 return false;
404 }
405 }
406
407 /**
408 * Check if the schema is already created.
409 * If we found at least oen table, it means the schema exists.
410 *
411 * @return bool
412 */
413 private function isSchemaPresent()
414 {
415 $schemaManager = $this->getContainer()->get('doctrine')->getManager()->getConnection()->getSchemaManager();
416
417 return count($schemaManager->listTableNames()) > 0 ? true : false;
418 }
419 }