Browse Source

The installation page now creates the database

Julio Montoya 11 years ago
parent
commit
eb35c2079e

+ 33 - 13
main/install/index.php

@@ -112,7 +112,7 @@ $app->match('/', function() use($app) {
             'choices'   => $languages,
             'required'  => true,
         ))
-        ->add('send', 'submit')
+        ->add('continue', 'submit')
         ->getForm();
 
      if ('POST' == $request->getMethod()) {
@@ -123,11 +123,10 @@ $app->match('/', function() use($app) {
     return $app['twig']->render('index.tpl', array('form' => $form->createView()));
 })->bind('welcome');
 
-
 $app->match('/requirements', function() use($app) {
     $request = $app['request'];
     $form = $app['form.factory']->createBuilder('form')
-        ->add('send', 'submit')
+        ->add('continue', 'submit')
         ->getForm();
 
     $req = display_requirements($app, 'new');
@@ -158,7 +157,13 @@ $app->match('/check-database', function() use($app) {
         $builder->add($key, $value['type'], $value['attributes']);
     }
 
-    $builder->add('send', 'submit');
+    /*$builder->add('create_database', 'choice', array(
+            'choices' => array('1' => 'Yes', '0' => 'No'),
+            'data' => 'Yes'
+        )
+    );*/
+
+    $builder->add('check', 'submit');
     $form = $builder->getForm();
 
     if ('POST' == $request->getMethod()) {
@@ -166,15 +171,30 @@ $app->match('/check-database', function() use($app) {
 
         if ($form->isValid()) {
             $parameters = $form->getData();
-            $config = new \Doctrine\DBAL\Configuration();
-            $conn = \Doctrine\DBAL\DriverManager::getConnection($parameters, $config);
+
+            /** @var \ChamiloLMS\Command\Database\InstallCommand $command */
+            $command = $app['console']->get('chamilo:install');
+            $command->setDatabaseSettings($parameters);
+
+            $connection = $command->getUserAccessConnectionToHost();
 
             try {
-                $connect = $conn->connect();
-                $sm = $conn->getSchemaManager();
+                $connect = $connection->connect();
+                $sm = $connection->getSchemaManager();
                 $databases = $sm->listDatabases();
-                if (in_array($parameters['database'], $databases)) {
-                    $app['session']->getFlashBag()->add('warning', 'The database is %s being used');
+
+                if (in_array($parameters['dbname'], $databases)) {
+                    $message = $app['translator']->trans(
+                        'The database %s being used and is going to be deleted!!',
+                        array('%s' => $parameters['dbname'])
+                    );
+                    $app['session']->getFlashBag()->add('warning', $message);
+                } else {
+                    $message = $app['translator']->trans(
+                        'A database %s is going to be created',
+                        array('%s' => $parameters['dbname'])
+                    );
+                    $app['session']->getFlashBag()->add('warning', $message);
                 }
 
                 $app['session']->getFlashBag()->add('success', 'Connection ok!');
@@ -223,7 +243,7 @@ $app->match('/portal-settings', function() use($app) {
         $builder->add($key, $value['type'], $value['attributes']);
     }
 
-    $builder->add('send', 'submit');
+    $builder->add('continue', 'submit');
     $form = $builder->getForm();
 
     if ('POST' == $request->getMethod()) {
@@ -252,7 +272,7 @@ $app->match('/admin-settings', function() use($app) {
     foreach ($data as $key => $value) {
         $builder->add($key, $value['type'], $value['attributes']);
     }
-    $builder->add('send', 'submit');
+    $builder->add('continue', 'submit');
     $form = $builder->getForm();
 
     if ('POST' == $request->getMethod()) {
@@ -279,7 +299,7 @@ $app->match('/resume', function() use($app) {
     if (!empty($portalSettings) && !empty($databaseSettings) && !empty($adminSettings)) {
 
         $form = $app['form.factory']->createBuilder('form', $data)
-            ->add('send', 'submit', array('label' => 'Continue'))
+            ->add('install', 'submit', array('label' => 'Continue'))
             ->getForm();
 
         if ('POST' == $request->getMethod()) {

+ 5 - 4
src/ChamiloLMS/Command/Database/CommonCommand.php

@@ -1,4 +1,5 @@
 <?php
+/* For licensing terms, see /license.txt */
 
 namespace ChamiloLMS\Command\Database;
 
@@ -124,7 +125,7 @@ class CommonCommand extends AbstractCommand
             'password' => array(
                 'attributes' => array(
                     'label' => 'Password',
-                    'data' =>  ''
+                    'data' =>  'admin'
                 ),
                 'type' => 'password'
             ),
@@ -218,11 +219,11 @@ class CommonCommand extends AbstractCommand
                         array(
                             'pdo_mysql' => 'pdo_mysql',
                             'pdo_sqlite' => 'pdo_sqlite',
-                            'pdo_pgsql' => 'pdo_pgsql',
-                            'pdo_oci' => 'pdo_oci',
+                            'pdo_pgsql' => 'pdo_pgsql'
+                            /*'pdo_oci' => 'pdo_oci',
                             'ibm_db2' => 'ibm_db2',
                             'pdo_ibm' => 'pdo_ibm',
-                            'pdo_sqlsrv' => 'pdo_sqlsrv'
+                            'pdo_sqlsrv' => 'pdo_sqlsrv'*/
                         ),
                     'data' => 'pdo_mysql'
                 ),

+ 136 - 84
src/ChamiloLMS/Command/Database/InstallCommand.php

@@ -1,4 +1,5 @@
 <?php
+/* For licensing terms, see /license.txt */
 
 namespace ChamiloLMS\Command\Database;
 
@@ -18,7 +19,6 @@ class InstallCommand extends CommonCommand
 {
     public $commandLine = true;
 
-
     /**
      * @return string
      */
@@ -128,16 +128,19 @@ class InstallCommand extends CommonCommand
             // Ask for portal settings
 
             $params = $this->getPortalSettingsParams();
+            $total = count($params);
             $portalSettings = array();
 
-            $output->writeln("<comment>Portal settings: </comment>");
+            $output->writeln("<comment>Portal settings (".$total.") </comment>");
 
+            $counter = 1;
             foreach ($params as $key => $value) {
                 $data = $dialog->ask(
                     $output,
-                    "Please enter the value of the $key (".$value['attributes']['data']."): ",
+                    "($counter/$total) Please enter the value of the $key (".$value['attributes']['data']."): ",
                     $value['attributes']['data']
                 );
+                $counter++;
                 $portalSettings[$key] = $data;
             }
             $this->setPortalSettings($portalSettings);
@@ -145,14 +148,16 @@ class InstallCommand extends CommonCommand
             // Ask for admin settings
             $output->writeln("<comment>Admin settings: </comment>");
             $params = $this->getAdminSettingsParams();
+            $total = count($params);
             $adminSettings = array();
 
             foreach ($params as $key => $value) {
                 $data = $dialog->ask(
                     $output,
-                    "Please enter the value of the $key (".$value['attributes']['data']."): ",
+                    "($counter/$total) Please enter the value of the $key (".$value['attributes']['data']."): ",
                     $value['attributes']['data']
                 );
+                $counter++;
                 $adminSettings[$key] = $data;
             }
             $this->setAdminSettings($adminSettings);
@@ -160,88 +165,129 @@ class InstallCommand extends CommonCommand
             // Ask for db settings
             $output->writeln("<comment>Database settings: </comment>");
             $params = $this->getDatabaseSettingsParams();
+            $total = count($params);
             $databaseSettings = array();
 
             foreach ($params as $key => $value) {
                 $data = $dialog->ask(
                     $output,
-                    "Please enter the value of the $key (".$value['attributes']['data']."): ",
+                    "($counter/$total) Please enter the value of the $key (".$value['attributes']['data']."): ",
                     $value['attributes']['data']
                 );
+                $counter++;
                 $databaseSettings[$key] = $data;
             }
             $this->setDatabaseSettings($databaseSettings);
         }
 
-        $testConnection = $this->testDatabaseConnection();
+        $databaseSettings = $this->getDatabaseSettings();
 
-        if ($testConnection) {
-            $output->writeln("<comment>Connection enabled for user: </comment><info>".$this->databaseSettings['user']);
+        $connectionToHost = $this->getUserAccessConnectionToHost();
+        $connectionToHostConnect = $connectionToHost->connect();
+        if ($connectionToHostConnect) {
+            $output->writeln("<comment>Connection enabled for user: </comment><info>".$databaseSettings['user']);
         } else {
-            $output->writeln("<error>No access to the database for user:</error><info>".$this->databaseSettings['user']."</info>");
+            $output->writeln("<error>No access to the database for user:</error><info>".$databaseSettings['user']."</info>");
+            return false;
         }
 
-        $configurationWasSaved = $this->writeConfiguration($version);
 
-        if ($configurationWasSaved) {
+        if ($this->commandLine) {
+            $databases = $connectionToHost->listDatabases();
+            if (in_array($databaseSettings['dbname'], $databases)) {
+                $dialog = $this->getHelperSet()->get('dialog');
 
-            // $app['chamilo.log'] = $app['log.path'].'/chamilo_install.log';
+                if (!$dialog->askConfirmation(
+                    $output,
+                    '<comment>The database '.$databaseSettings['dbname'].' exists and is going to be dropped! </comment></info> <question>Are you sure?</question>(y/N)',
+                    false
+                )
+                ) {
+                    return;
+                }
+            }
+        }
 
-            // Installing database
-            $result = $this->install($version, $output);
+        // When installing always drop the current database
 
-            if ($result) {
+        $sm = $connectionToHost->getSchemaManager();
+        $sm->dropAndCreateDatabase($databaseSettings['dbname']);
+        $connectionToDatabase = $this->getUserAccessConnectionToDatabase();
+        $connect = $connectionToDatabase->connect();
+        if ($connect) {
 
-                require_once $this->getRootSys().'main/inc/lib/database.constants.inc.php';
-                require_once $this->getRootSys().'main/inc/lib/main_api.lib.php';
+            $output->writeln("<comment>Connection to database '".$databaseSettings['dbname']."' established.</comment>");
 
-                // In order to use the Datbase class
-                $database = new \Database($this->getHelper('db')->getConnection());
+            $configurationWasSaved = $this->writeConfiguration($version);
 
-                $this->createAdminUser($output);
+            if ($configurationWasSaved) {
 
-                //@todo ask this during installation
+                // $app['chamilo.log'] = $app['log.path'].'/chamilo_install.log';
 
-                $adminInfo = $this->getAdminSettings();
-                $portalSettings = $this->getPortalSettings();
+                // Installing database
+                $result = $this->install($version, $output);
 
-                api_set_setting('emailAdministrator', $adminInfo['email']);
-                api_set_setting('administratorSurname', $adminInfo['lastname']);
-                api_set_setting('administratorName', $adminInfo['firstname']);
-                api_set_setting('platformLanguage', $adminInfo['language']);
+                if ($result) {
 
-                api_set_setting('allow_registration', '1');
-                api_set_setting('allow_registration_as_teacher', '1');
+                    require_once $this->getRootSys().'main/inc/lib/database.constants.inc.php';
+                    require_once $this->getRootSys().'main/inc/lib/main_api.lib.php';
 
-                api_set_setting('permissions_for_new_directories', $portalSettings['permissions_for_new_directories']);
-                api_set_setting('permissions_for_new_files', $portalSettings['permissions_for_new_files']);
+                    // In order to use the Database class
+                    $database = new \Database($this->getHelper('db')->getConnection());
 
-                api_set_setting('Institution', $portalSettings['institution']);
-                api_set_setting('InstitutionUrl', $portalSettings['institution_url']);
-                api_set_setting('siteName', $portalSettings['sitename']);
+                    $this->createAdminUser($output);
 
-                //$versionInfo = $this->getAvailableVersionInfo($version);
+                    //@todo ask this during installation
 
-                // Optional run Doctrine migrations from src/database/migrations
-                /* $command = $this->getApplication()->find('migrations:migrate');
-                $definition = $command->getDefinition();
+                    $adminInfo = $this->getAdminSettings();
+                    $portalSettings = $this->getPortalSettings();
 
-                $arguments = array(
-                    'command' => 'migrations:migrate',
-                    'version' => $versionInfo['hook_to_doctrine_version'],
-                    '--configuration' => $this->getMigrationConfigurationFile()
-                );
-                $output->writeln("<comment>Executing migrations:migrate ".$versionInfo['hook_to_doctrine_version']." --configuration=".$this->getMigrationConfigurationFile()."<comment>");
+                    api_set_setting('emailAdministrator', $adminInfo['email']);
+                    api_set_setting('administratorSurname', $adminInfo['lastname']);
+                    api_set_setting('administratorName', $adminInfo['firstname']);
+                    api_set_setting('platformLanguage', $adminInfo['language']);
 
-                $input = new ArrayInput($arguments, $definition);
-                $return = $command->run($input, $output);
-                */
-                //$output->writeln("<comment>Migration ended succesfully</comment>");
+                    api_set_setting('allow_registration', '1');
+                    api_set_setting('allow_registration_as_teacher', '1');
 
-                //$output->writeln("<comment>Chamilo was successfully installed. Go to your browser and enter:</comment> <info>".$newConfigurationArray['root_web']);
+                    api_set_setting('permissions_for_new_directories', $portalSettings['permissions_for_new_directories']);
+                    api_set_setting('permissions_for_new_files', $portalSettings['permissions_for_new_files']);
+
+                    api_set_setting('Institution', $portalSettings['institution']);
+                    api_set_setting('InstitutionUrl', $portalSettings['institution_url']);
+                    api_set_setting('siteName', $portalSettings['sitename']);
+
+                    //$versionInfo = $this->getAvailableVersionInfo($version);
+
+                    // Optional run Doctrine migrations from src/database/migrations
+                    /* $command = $this->getApplication()->find('migrations:migrate');
+                    $definition = $command->getDefinition();
+
+                    $arguments = array(
+                        'command' => 'migrations:migrate',
+                        'version' => $versionInfo['hook_to_doctrine_version'],
+                        '--configuration' => $this->getMigrationConfigurationFile()
+                    );
+                    $output->writeln("<comment>Executing migrations:migrate ".$versionInfo['hook_to_doctrine_version']." --configuration=".$this->getMigrationConfigurationFile()."<comment>");
+
+                    $input = new ArrayInput($arguments, $definition);
+                    $return = $command->run($input, $output);
+                    */
+                    //$output->writeln("<comment>Migration ended succesfully</comment>");
+
+                    //$output->writeln("<comment>Chamilo was successfully installed. Go to your browser and enter:</comment> <info>".$newConfigurationArray['root_web']);
+                    return true;
+                } else {
+                    $output->writeln("<comment>There was an error during installation.</comment>");
+                    return false;
+                }
+            } else {
+                $output->writeln("<comment>Configuration file was not saved</comment>");
+                return false;
             }
         } else {
-            $output->writeln("<comment>Configuration file was not saved</comment>");
+            $output->writeln("<comment>Can't create database '".$databaseSettings['dbname']."' </comment>");
+            return false;
         }
     }
 
@@ -255,7 +301,6 @@ class InstallCommand extends CommonCommand
      */
     public function createAdminUser($output)
     {
-
         //By default admin is = 1 so we update it
 
         $userInfo = $this->getAdminSettings();
@@ -285,7 +330,7 @@ class InstallCommand extends CommonCommand
         $config->setProxyDir(__DIR__ . '/Proxies');
         $config->setProxyNamespace('Proxies');
 
-        $em = \Doctrine\ORM\EntityManager::create($this->databaseSettings, $config);
+        $em = \Doctrine\ORM\EntityManager::create($this->getDatabaseSettings(), $config);
 
         // Fixes some errors
         $platform = $em->getConnection()->getDatabasePlatform();
@@ -313,10 +358,7 @@ class InstallCommand extends CommonCommand
      */
     public function install($version, $output)
     {
-        $this->setDoctrineSettings($this->databaseSettings);
-
-        $configurationPath = $this->getHelper('configuration')->getConfigurationPath(null);
-
+        $this->setDoctrineSettings();
         $sqlFolder = $this->getInstallationPath($version);
 
         $databaseMap = $this->getDatabaseMap();
@@ -361,8 +403,9 @@ class InstallCommand extends CommonCommand
                 }
             }
 
-            $output->writeln("<comment>Check your installation status with </comment><info>chamilo:status</info>");
-
+            if ($this->commandLine) {
+                $output->writeln("<comment>Check your installation status with </comment><info>chamilo:status</info>");
+            }
 
             return true;
         }
@@ -370,6 +413,40 @@ class InstallCommand extends CommonCommand
         return false;
     }
 
+     /**
+     *
+     * In step 3. Tests establishing connection to the database server.
+     * If it's a single database environment the function checks if the database exist.
+     * If the database doesn't exist we check the creation permissions.
+     *
+     * @return int      1 when there is no problem;
+     *                  0 when a new database is impossible to be created, then the single/multiple database configuration is impossible too
+     *                 -1 when there is no connection established.
+     */
+    public function testDatabaseConnection()
+    {
+        $conn = $this->testUserAccessConnection();
+        $connect = $conn->connect();
+        return $connect;
+    }
+
+    public function getUserAccessConnectionToHost()
+    {
+        $config = new \Doctrine\DBAL\Configuration();
+        $databaseConnection = $this->getDatabaseSettings();
+        $databaseConnection['dbname'] = null;
+        $conn = \Doctrine\DBAL\DriverManager::getConnection($databaseConnection, $config);
+        return $conn;
+    }
+
+    public function getUserAccessConnectionToDatabase()
+    {
+        $config = new \Doctrine\DBAL\Configuration();
+        $databaseConnection = $this->getDatabaseSettings();
+        $conn = \Doctrine\DBAL\DriverManager::getConnection($databaseConnection, $config);
+        return $conn;
+    }
+
     /**
      * Creates a course (only an insert in the DB)
      * @param string $databaseName
@@ -394,15 +471,6 @@ class InstallCommand extends CommonCommand
      */
     public function dropAndCreateDatabase($databaseName)
     {
-        /*
-        $command = $this->getApplication()->find('orm:schema-tool:create');
-        $arguments = array(
-            'command' => 'orm:schema-tool:create',
-        );
-        $input     = new ArrayInput($arguments);
-        $command->run($input, $output);
-        exit;
-        */
 
         $this->dropDatabase($databaseName);
         $result = \Database::query("CREATE DATABASE IF NOT EXISTS ".mysql_real_escape_string($databaseName)." DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci");
@@ -423,23 +491,7 @@ class InstallCommand extends CommonCommand
         \Database::query("DROP DATABASE ".mysql_real_escape_string($name)."");
     }
 
-    /**
-     *
-     * In step 3. Tests establishing connection to the database server.
-     * If it's a single database environment the function checks if the database exist.
-     * If the database doesn't exist we check the creation permissions.
-     *
-     * @return int      1 when there is no problem;
-     *                  0 when a new database is impossible to be created, then the single/multiple database configuration is impossible too
-     *                 -1 when there is no connection established.
-     */
-    public function testDatabaseConnection()
-    {
-        $config = new \Doctrine\DBAL\Configuration();
-        $conn = \Doctrine\DBAL\DriverManager::getConnection($this->databaseSettings, $config);
-        $connect = $conn->connect();
-        return $connect;
-    }
+
 
     /**
      * This function gets the hash in md5 or sha1 (it depends in the platform config) of a given password