示例#1
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $this->writeCommandHeader($output, 'Current mail configuration.');
     $path = $this->getHelper('configuration')->getConfigurationPath();
     $path .= 'mail.conf.php';
     define('IS_WINDOWS_OS', strtolower(substr(php_uname(), 0, 3)) == 'win' ? true : false);
     if (isset($path) && is_file($path)) {
         $output->writeln('File: ' . $path);
         $lines = file($path);
         $list = array('SMTP_HOST', 'SMTP_PORT', 'SMTP_MAILER', 'SMTP_AUTH', 'SMTP_USER', 'SMTP_PASS');
         foreach ($lines as $line) {
             $match = array();
             if (preg_match("/platform_email\\['(.*)'\\]/", $line, $match)) {
                 if (in_array($match[1], $list)) {
                     eval($line);
                 }
             }
         }
         // @todo $platform_email is not set
         $output->writeln('Host:     ' . $platform_email['SMTP_HOST']);
         $output->writeln('Port:     ' . $platform_email['SMTP_PORT']);
         $output->writeln('Mailer:   ' . $platform_email['SMTP_MAILER']);
         $output->writeln('Auth SMTP:' . $platform_email['SMTP_AUTH']);
         $output->writeln('User:     '******'SMTP_USER']);
         $output->writeln('Pass:     '******'SMTP_PASS']);
     } else {
         $output->writeln("<comment>Nothing to print</comment>");
     }
 }
示例#2
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $output->writeln('Starting Chamilo SQL cli');
     $_configuration = $this->getConfigurationArray();
     $cmd = 'mysql -h ' . $_configuration['db_host'] . ' -u ' . $_configuration['db_user'] . ' -p' . $_configuration['db_password'] . ' ' . $_configuration['main_database'];
     $process = proc_open($cmd, array(0 => STDIN, 1 => STDOUT, 2 => STDERR), $pipes);
     $proc_status = proc_get_status($process);
     $exit_code = proc_close($process);
     return $proc_status["running"] ? $exit_code : $proc_status["exitcode"];
     /*$output->writeln('<comment>Starting Chamilo process</comment>');
       $output->writeln('<info>Chamilo process ended succesfully</info>');
       */
     /*
             $progress = $this->getHelperSet()->get('progress');
     
             $progress->start($output, 50);
             $i = 0;
             while ($i++ < 50) {
                 // ... do some work
     
                 // advance the progress bar 1 unit
                 $progress->advance();
             }
             $progress->finish();*/
     // Inside execute function
     //$output->getFormatter()->setStyle('fcbarcelona', new OutputFormatterStyle('red', 'blue', array('blink', 'bold', 'underscore')));
     //$output->writeln('<fcbarcelona>Messi for the win</fcbarcelona>');
 }
示例#3
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $_configuration = $this->getHelper('configuration')->getConfiguration();
     $connection = $this->getConnection($input);
     $lang = mysql_real_escape_string($input->getArgument('language'));
     $ls = "SELECT id, english_name, available FROM language WHERE english_name = '{$lang}'";
     $lq = mysql_query($ls);
     if ($lq === false) {
         $output->writeln('Error in query: ' . mysql_error());
         return null;
     }
     $num = mysql_num_rows($lq);
     if ($num < 1) {
         $output->writeln($lang . ' language not found in the database. Please make sure you use an existing language name.');
         return null;
     }
     $lr = mysql_fetch_assoc($lq);
     if ($lr['available'] == 1) {
         $output->writeln($lang . ' language is already enabled. Nothing to do.');
         return null;
     }
     // Everything is OK so far, enable the language
     $us = "UPDATE language SET available = 1 WHERE id = {$lr['id']}";
     $uq = mysql_query($us);
     if ($uq === false) {
         $output->writeln('Error in query: ' . mysql_error());
     } else {
         $output->writeln($lang . ' language has been enabled.');
     }
     return null;
 }
示例#4
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $dialog = $this->getHelperSet()->get('dialog');
     if (!$dialog->askConfirmation($output, '<question>Are you sure you want to drop all database in this portal? (y/N)</question>', false)) {
         return;
     }
     if (!$dialog->askConfirmation($output, '<question>Are you really sure? (y/N)</question>', false)) {
         return;
     }
     $_configuration = $this->getConfigurationArray();
     $connection = $this->getConnection($input);
     if ($connection) {
         $list = $_configuration = $this->getHelper('configuration')->getAllDatabases();
         $currentDatabases = $connection->getSchemaManager()->listDatabases();
         if (is_array($list)) {
             $output->writeln('<comment>Starting Chamilo drop database process.</comment>');
             foreach ($list as $db) {
                 if (in_array($db, $currentDatabases)) {
                     $output->writeln("Dropping DB: {$db}");
                     $connection->getSchemaManager()->dropDatabase($db);
                 } else {
                     $output->writeln("DB: {$db} was already dropped.");
                 }
             }
             $output->writeln('<comment>End drop database process.</comment>');
         }
     } else {
         $output->writeln("<comment>Can't established connection with the database. Probably it was already deleted.</comment>");
     }
 }
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $this->writeCommandHeader($output, 'Generating temp folders.');
     // Data folders
     $files = $this->getConfigurationHelper()->getTempFolderList();
     $this->createFolders($output, $files, 0777);
 }
示例#6
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $_configuration = $this->getConfigurationArray();
     $dump = 'mysqldump -h ' . $_configuration['db_host'] . ' -u ' . $_configuration['db_user'] . ' -p' . $_configuration['db_password'] . ' ' . $_configuration['main_database'];
     system($dump);
     return null;
 }
示例#7
0
 /**
  * Executes a command via CLI
  *
  * @param InputInterface $input
  * @param OutputInterface $output
  *
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $connection = $this->getConnection($input);
     $_configuration = $this->getConfigurationArray();
     $query = "SELECT selected_value FROM settings_current WHERE variable = 'chamilo_database_version'";
     $data = $connection->executeQuery($query);
     $data = $data->fetch();
     $chamiloVersion = $data['selected_value'];
     $databaseSetting = 'chamilo_database_version';
     if (empty($chamiloVersion)) {
         $query = "SELECT selected_value FROM settings_current WHERE variable = 'dokeos_database_version'";
         $data = $connection->executeQuery($query);
         $data = $data->fetch();
         $chamiloVersion = $data['selected_value'];
         $databaseSetting = 'dokeos_database_version';
     }
     $output->writeln('<comment>Chamilo $_configuration info:</comment>');
     $output->writeln('');
     $output->writeln('<comment>Chamilo $_configuration[root_web]:</comment> <info>' . $_configuration['root_web'] . '</info>');
     if (isset($_configuration['root_sys'])) {
         $output->writeln('<comment>Chamilo $_configuration[root_sys]:</comment> <info>' . $_configuration['root_sys'] . '</info>');
     }
     //$output->writeln('<comment>Chamilo $_configuration[db_driver]:</comment> <info>'.$_configuration['db_driver'].'</info>');
     $output->writeln('<comment>Chamilo $_configuration[main_database]:</comment> <info>' . $_configuration['main_database'] . '</info>');
     $output->writeln('<comment>Chamilo $_configuration[db_host]:</comment> <info>' . $_configuration['db_host'] . '</info>');
     $output->writeln('<comment>Chamilo $_configuration[db_user]:</comment> <info>' . $_configuration['db_user'] . '</info>');
     $output->writeln('<comment>Chamilo $_configuration[db_password]:</comment> <info>' . $_configuration['db_password'] . '</info>');
     if (isset($_configuration['db_port'])) {
         $output->writeln('<comment>Chamilo $_configuration[db_port]:</comment> <info>' . $_configuration['db_port'] . '</info>');
     }
     if (isset($_configuration['single_database'])) {
         $output->writeln('<comment>Chamilo $_configuration[single_database]:</comment> <info>' . $_configuration['single_database'] . '</info>');
     }
     if (isset($_configuration['db_prefix'])) {
         $output->writeln('<comment>Chamilo $_configuration[db_prefix]:</comment> <info>' . $_configuration['db_prefix'] . '</info>');
     }
     if (isset($_configuration['db_glue'])) {
         $output->writeln('<comment>Chamilo $_configuration[db_glue]:</comment> <info>' . $_configuration['db_glue'] . '</info>');
     }
     if (isset($_configuration['db_prefix'])) {
         $output->writeln('<comment>Chamilo $_configuration[table_prefix]:</comment> <info>' . $_configuration['table_prefix'] . '</info>');
     }
     $output->writeln('');
     if (empty($chamiloVersion)) {
         $output->writeln("<comment>Please check your Chamilo installation carefully the <info>'chamilo_database_version'</info> admin does not exists.</comment>");
     } else {
         //$output->writeln('<comment>Chamilo database settings:</comment>');
         //$output->writeln("<comment>Chamilo setting_current['".$databaseSetting."']:</comment> <info>".$chamiloVersion."</info>");
     }
     if (isset($_configuration['system_version'])) {
         $output->writeln('<comment>Chamilo $_configuration[system_version]:</comment> <info>' . $_configuration['system_version'] . '</info>');
     }
     if (!version_compare(substr($chamiloVersion, 0, 5), substr($_configuration['system_version'], 0, 5), '==')) {
         /*$output->writeln("<error>Please check carefully your Chamilo installation. </error>");
           $output->writeln("<comment>The configuration.php file and the 'chamilo_database_version' setting are not synced.</comment>");*/
     }
 }
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return bool|int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $this->writeCommandHeader($output, 'Cleaning folders in courses directory.');
     $dialog = $this->getHelperSet()->get('dialog');
     if (!$dialog->askConfirmation($output, '<question>Are you sure you want to clean this Chamilo install\'s courses files? (y/N)</question>', false)) {
         return;
     }
     $files = $this->getConfigurationHelper()->getCoursesFiles();
     $this->removeFiles($files, $output);
 }
示例#9
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $this->writeCommandHeader($output, "Cleaning config files.");
     $dialog = $this->getHelperSet()->get('dialog');
     if (!$dialog->askConfirmation($output, '<question>Are you sure you want to clean your config files? (y/N)</question>', false)) {
         return;
     }
     $files = $this->getConfigurationHelper()->getConfigFiles();
     $this->removeFiles($files, $output);
 }
示例#10
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $language = $input->getArgument('language');
     $tmpFolder = $input->getOption('tmp');
     $_configuration = $this->getHelper('configuration')->getConfiguration();
     $connection = $this->getConnection($input);
     if ($connection) {
         $lang = isset($language) ? $language : null;
         $lang = mysql_real_escape_string($lang);
         $q = mysql_query("SELECT * FROM language WHERE english_name = '{$lang}' ");
         $langInfo = mysql_fetch_array($q, MYSQL_ASSOC);
         if (!$langInfo) {
             $output->writeln("<comment>Language '{$lang}' is not registered in the Chamilo Database</comment>");
             $q = mysql_query("SELECT * FROM language WHERE parent_id IS NULL or parent_id = 0");
             $output->writeln("<comment>Available languages are: </comment>");
             while ($langRow = mysql_fetch_array($q, MYSQL_ASSOC)) {
                 $output->write($langRow['english_name'] . ", ");
             }
             $output->writeln(' ');
             $q = mysql_query("SELECT * FROM language WHERE parent_id <> 0");
             $output->writeln("<comment>Available sub languages are: </comment>");
             while ($langRow = mysql_fetch_array($q, MYSQL_ASSOC)) {
                 $output->write($langRow['english_name'] . ", ");
             }
             $output->writeln(' ');
             exit;
         } else {
             $output->writeln("<comment>Language</comment> <info>'{$lang}'</info> <comment>is registered in the Chamilo installation with iso code: </comment><info>{$langInfo['isocode']} </info>");
         }
         $langFolder = $_configuration['root_sys'] . 'main/lang/' . $lang;
         if (!is_dir($langFolder)) {
             $output->writeln("<comment>Language '{$lang}' does not exist in the path: {$langFolder}</comment>");
         }
         if (empty($tmpFolder)) {
             $tmpFolder = '/tmp/';
             $output->writeln("<comment>No temporary directory defined. Assuming /tmp/. Please make sure you have *enough space* left on that device");
         }
         if (!is_dir($tmpFolder)) {
             $output->writeln("<comment>Temporary directory: {$tmpFolder} is not a valid dir path, using /tmp/ </comment>");
             $tmpFolder = '/tmp/';
         }
         if ($langInfo) {
             $output->writeln("<comment>Creating translation package</comment>");
             $fileName = $tmpFolder . $langInfo['english_name'] . '.tar';
             $phar = new \PharData($fileName);
             $phar->buildFromDirectory($langFolder);
             $phar->setMetadata($langInfo);
             $output->writeln("<comment>File created:</comment> <info>{$fileName}</info>");
         }
     }
 }
示例#11
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $dumpPath = $input->getArgument('file');
     if (!is_dir($dumpPath) && file_exists($dumpPath)) {
         $_configuration = $this->getConfigurationArray();
         $output->writeln('<comment>Starting restoring database</comment>');
         $action = 'mysql -h ' . $_configuration['db_host'] . ' -u ' . $_configuration['db_user'] . ' -p' . $_configuration['db_password'] . ' ' . $_configuration['main_database'] . ' < ' . $dumpPath;
         system($action);
         $output->writeln('<info>Process ended succesfully</info>');
     } else {
         $output->writeln('<comment>File is not a valid SQL file: ' . $dumpPath . ' </comment>');
     }
 }
示例#12
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return bool|int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $this->writeCommandHeader($output, "Cleaning temp files.");
     $dialog = $this->getHelperSet()->get('dialog');
     if (PHP_SAPI == 'cli') {
         if ($input->isInteractive()) {
             if (!$dialog->askConfirmation($output, '<question>Are you sure you want to clean the Chamilo temp files? (y/N)</question>', false)) {
                 return;
             }
         }
     }
     $files = $this->getConfigurationHelper()->getTempFiles();
     $this->removeFiles($files, $output);
 }
示例#13
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $dialog = $this->getHelperSet()->get('dialog');
     if (!$dialog->askConfirmation($output, '<question>Are you sure you want to show the database connection info here? (y/N)</question>', false)) {
         return;
     }
     $_configuration = $this->getConfigurationArray();
     $output->writeln("Database connection details:");
     $output->writeln("Host:\t" . $_configuration['db_host']);
     $output->writeln("User:\t" . $_configuration['db_user']);
     $output->writeln("Pass:\t" . $_configuration['db_password']);
     $output->writeln("DB:\t" . $_configuration['main_database']);
     $output->writeln("Connection string (add password manually for increased security:");
     $output->writeln("mysql -h " . $_configuration['db_host'] . " -u " . $_configuration['db_user'] . " -p " . $_configuration['main_database'] . "\n");
 }
示例#14
0
 /**
  * @todo use doctrine
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $table = $input->getArgument('table');
     $_configuration = $this->getConfigurationArray();
     $connection = $this->getConnection($input);
     $tableExists = $connection->getSchemaManager()->tablesExist($table);
     if ($tableExists) {
         $sql = "SELECT COUNT(*) count FROM {$table}";
         $stmt = $connection->query($sql);
         $result = $stmt->fetch();
         $count = $result['count'];
         $output->writeln('<comment>Database/table/number of rows: </comment><info>' . $_configuration['main_database'] . '/' . $table . '/' . $count . '</info>');
     } else {
         $output->writeln("<comment>Table '{$table}' does not exists in the database: " . $_configuration['main_database']);
     }
 }
示例#15
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $_configuration = $this->getConfigurationArray();
     $connection = $this->getConnection($input);
     $parent = $input->getArgument('parent');
     $lang = $input->getArgument('sublanguage');
     $sql = "SELECT english_name FROM language WHERE english_name = ?";
     $statement = $connection->executeQuery($sql, array($lang));
     $count = $statement->rowCount();
     if ($count) {
         $output->writeln($lang . ' already exists in the database. Pick another English name.');
         return null;
     }
     $sql = "SELECT id, original_name, english_name, isocode, dokeos_folder\n                FROM language WHERE english_name = ?";
     $statement = $connection->prepare($sql);
     $statement->bindValue('1', $parent);
     $statement->execute();
     $count = $statement->rowCount();
     $parentData = $statement->fetch();
     if ($count < 1) {
         $output->writeln('The parent language ' . $parent . ' does not exist. Please choose a valid parent.');
         return null;
     }
     if (is_dir($_configuration['root_sys'] . 'main/lang/' . $lang)) {
         $output->writeln('The destination directory (' . $_configuration['root_sys'] . 'main/lang/' . $lang . ') already exists. Please choose another sub-language name.');
         return null;
     }
     // Everything is OK so far, insert the sub-language
     /*$sql = "INSERT INTO language ()
       VALUES ('{$parentData['original_name']}-2','$lang','{$parentData['isocode']}','$lang',0,{$parentData['id']})";*/
     $result = $connection->insert('language', array('original_name' => $parentData['original_name'] . "-2", 'english_name' => $lang, 'isocode' => $parentData['isocode'], 'dokeos_folder' => $lang, 'available' => 0, 'parent_id' => $parentData['id']));
     if ($result) {
         $output->writeln('Error in query: ' . mysql_error());
     } else {
         //permissions gathering, copied from main_api.lib.php::api_get_permissions_for_new_directories()
         //require_once $_configuration['root_sys'].'main/inc/lib/main_api.lib.php';
         //$perm = api_get_permissions_for_new_directories();
         // @todo Improve permissions to force creating as user www-data
         $r = @mkdir($_configuration['root_sys'] . 'main/lang/' . $lang, 0777);
         $output->writeln('Sub-language ' . $lang . ' of language ' . $parent . ' has been created but is disabled. Fill it, then enable to make available to users. Make sure you check the permissions for the newly created directory as well (' . $_configuration['root_sys'] . 'main/lang/' . $lang . ')');
     }
     return null;
 }
示例#16
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $_configuration = $this->getHelper('configuration')->getConfiguration();
     $connection = $this->getConnection($input);
     $av = mysql_real_escape_string($input->getArgument('availability'));
     $current = 'english';
     $ls = "SELECT selected_value FROM settings_current WHERE variable='platformLanguage'";
     $lq = mysql_query($ls);
     if ($lq === false) {
         $output->writeln('Error in query: ' . mysql_error());
         return null;
     } else {
         $lr = mysql_fetch_assoc($lq);
         //$output->writeln('Current default language is: '.$lr['selected_value']);
         $current = $lr['selected_value'];
     }
     $where = '';
     if ($av === '0') {
         $where = 'WHERE available = 0';
     } elseif ($av === '1') {
         $where = 'WHERE available = 1';
     }
     $ls = "SELECT english_name, available FROM language " . $where . " ORDER BY english_name";
     $lq = mysql_query($ls);
     if ($lq === false) {
         $output->writeln('Error in query: ' . mysql_error());
         return null;
     } else {
         $languages = array();
         $output->writeln("Language          | Enabled | Platform language");
         $output->writeln("-----------------------------------------------");
         while ($lr = mysql_fetch_assoc($lq)) {
             $pl = '';
             $l = strlen($lr['english_name']);
             if ($lr['english_name'] == $current) {
                 $pl = '*';
             }
             $output->writeln($lr['english_name'] . str_repeat(' ', 18 - $l) . "| " . $lr['available'] . "       | " . $pl);
         }
     }
     return null;
 }
示例#17
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $_configuration = $this->getHelper('configuration')->getConfiguration();
     $connection = $this->getConnection($input);
     $lang = mysql_real_escape_string($input->getArgument('language'));
     if (empty($lang)) {
         $ls = "SELECT selected_value FROM settings_current WHERE variable='platformLanguage'";
         $lq = mysql_query($ls);
         if ($lq === false) {
             $output->writeln('Error in query: ' . mysql_error());
             return null;
         } else {
             $lr = mysql_fetch_assoc($lq);
             $output->writeln('Current default language is: ' . $lr['selected_value']);
         }
     } else {
         $ls = "SELECT english_name FROM language ORDER BY english_name";
         $lq = mysql_query($ls);
         if ($lq === false) {
             $output->writeln('Error in query: ' . mysql_error());
             return null;
         } else {
             $languages = array();
             while ($lr = mysql_fetch_assoc($lq)) {
                 $languages[] = $lr['english_name'];
             }
             if (!in_array($lang, $languages)) {
                 $output->writeln($lang . ' must be available on your platform before you can set it as default');
                 return null;
             }
             $lu = "UPDATE settings_current set selected_value = '{$lang}' WHERE variable = 'platformLanguage'";
             $lq = mysql_query($lu);
             if ($lq === false) {
                 $output->writeln('Error in query: ' . mysql_error());
             } else {
                 $output->writeln('Language set to ' . $lang);
             }
         }
     }
     return null;
 }
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $this->writeCommandHeader($output, 'Setting permissions ...');
     $linuxUser = $input->getOption('linux-user');
     $linuxGroup = $input->getOption('linux-group');
     // All files
     $files = $this->getConfigurationHelper()->getSysFolders();
     $this->setPermissions($output, $files, 0777, $linuxUser, $linuxGroup, false);
     $files = $this->getConfigurationHelper()->getSysFiles();
     $this->setPermissions($output, $files, null, $linuxUser, $linuxGroup, false);
     // Data folders
     $files = $this->getConfigurationHelper()->getDataFolders();
     $this->setPermissions($output, $files, 0777, $linuxUser, $linuxGroup);
     // Config folders
     $files = $this->getConfigurationHelper()->getConfigFolders();
     $this->setPermissions($output, $files, 0555, $linuxUser, $linuxGroup);
     $files = $this->getConfigurationHelper()->getConfigFiles();
     $this->setPermissions($output, $files, 0555, $linuxUser, $linuxGroup);
     // Temp folders
     $files = $this->getConfigurationHelper()->getTempFolders();
     $this->setPermissions($output, $files, 0777, $linuxUser, $linuxGroup);
 }
示例#19
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $_configuration = $this->getConfigurationArray();
     $resultPath = $input->getArgument('result');
     $tmpFolder = $input->getOption('tmp');
     if (empty($tmpFolder)) {
         $output->writeln('<info>No temporary directory defined. Assuming /tmp/. Please make sure you have *enough space* left on that device</info>');
         $tmpFolder = '/tmp';
     }
     $deleteTemp = $input->getOption('del-archive');
     if ($deleteTemp) {
         //Calling command
         $command = $this->getApplication()->find('files:clean_temp_folder');
         $arguments = array('command' => 'files:clean_temp_folder');
         $input = new ArrayInput($arguments);
         $command->run($input, $output);
     } else {
         $output->writeln('<comment>Temp archives are not removed</comment>');
     }
     $cha_dir = realpath($_configuration['root_sys']);
     $output->writeln('<comment>Starting full backup</comment>');
     $f = $_configuration['db_user'];
     //backup the files (this requires root permissions)
     $bkp_dir = $tmpFolder . '/' . $f . '-' . date('Ymdhis');
     $err = @mkdir($bkp_dir);
     $tgz = $bkp_dir . '/' . $f . '.tgz';
     $sql = $bkp_dir . '/' . $f . '-db.sql';
     $err = @system('tar zcf ' . $tgz . ' ' . $cha_dir);
     $output->writeln('<comment>Generating mysqldump</comment>');
     $err = @system('mysqldump -h ' . $_configuration['db_host'] . ' -u ' . $_configuration['db_user'] . ' -p' . $_configuration['db_password'] . ' ' . $_configuration['main_database'] . ' --result-file=' . $sql);
     $output->writeln('<comment>Generating tarball </comment>');
     $err = @system('tar zcf ' . $resultPath . ' ' . $bkp_dir);
     $err = @system('rm -rf ' . $bkp_dir);
     $output->writeln('<comment>End Chamilo backup. File can be found here: ' . realpath($resultPath) . ' </comment>');
 }
示例#20
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return bool|int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     if ($input->isInteractive()) {
         $this->writeCommandHeader($output, 'Deleting URL');
         $list = $input->getOption('list');
         //1 if the option was set
         $connection = $this->getConnection($input);
         $sql = "SELECT * FROM access_url";
         $stmt = $connection->query($sql);
         $urls = array();
         while ($row = $stmt->fetch()) {
             $urls[$row['id']] = array('url' => $row['url'], 'active' => $row['active']);
         }
         if ($list) {
             if (count($urls) > 1) {
                 $output->writeln('ID' . "\t" . 'Active?' . "\t" . 'URL');
                 $preventDelete = '';
                 foreach ($urls as $id => $url) {
                     if ($id == 1) {
                         $preventDelete = '(cannot be deleted!)';
                     } else {
                         $preventDelete = '';
                     }
                     $output->writeln($id . "\t" . $url['active'] . "\t" . $url['url'] . "\t" . $preventDelete);
                 }
             } else {
                 $output->writeln('Only one URL. Please use another command to delete');
                 return;
             }
         }
         $show = $input->getOption('show');
         //1 if the option was set
         // Get all courses by URL
         $sql = "SELECT u.course_code, u.access_url_id, c.directory " . " FROM access_url_rel_course u, course c " . " WHERE u.course_code = c.code " . " ORDER BY access_url_id, course_code ASC";
         $stmt = $connection->query($sql);
         $urlCourses = array();
         $coursesUrl = array();
         $coursesDir = array();
         while ($row = $stmt->fetch()) {
             $urlCourses[$row['access_url_id']][] = $row['course_code'];
             $coursesUrl[$row['course_code']][] = $row['access_url_id'];
             $coursesDir[$row['course_code']] = $row['directory'];
         }
         $urlId = $input->getArgument('url');
         $du = $input->getOption('du');
         //1 if the option was set
         $sysPath = $this->getConfigurationHelper()->getSysPath();
         $coursesPath = $sysPath . 'courses/';
         $totalDiskUsage = 0;
         if ($show) {
             $output->writeln('');
             $count = count($urlCourses);
             if ($count > 0) {
                 $output->writeln('List of URLs vs courses');
                 $output->writeln('URL ID' . "\t" . 'Only in this URL?' . "\t" . ($du ? 'Size (KB)' . "\t\t" : '') . 'Course code');
                 foreach ($urlCourses as $url => $courses) {
                     if (!empty($urlId)) {
                         // if a URL was defined, skip other URLs
                         if ($url != $urlId) {
                             continue;
                         }
                     }
                     foreach ($courses as $code) {
                         $countUrl = count($coursesUrl[$code]);
                         $unique = $countUrl <= 1 ? 'yes' : 'no';
                         $diskUsage = '';
                         if ($du) {
                             $courseDir = $coursesPath . $coursesDir[$code];
                             if (!is_dir($courseDir)) {
                                 $size = 'N/A';
                             } else {
                                 $res = @exec('du -s ' . $courseDir);
                                 $res = preg_split('/\\s/', $res);
                                 $size = $res[0];
                                 if ($unique == 'yes') {
                                     $totalDiskUsage += $size;
                                 }
                             }
                         }
                         $output->writeln($url . "\t" . $unique . "\t\t\t" . ($du ? $size . "\t\t" : '') . $code);
                     }
                 }
             }
         }
         if ($du) {
             $output->writeln('Total size of courses only in this URL: ' . $totalDiskUsage);
         }
         if (!empty($urlId)) {
             $output->writeln('');
             if ($urlId == 1) {
                 $output->writeln('URL 1 cannot be deleted as it is the main URL');
                 return;
             }
             $output->writeln('Selected URL: ' . $urlId . ' (' . $urls[$urlId]['url'] . ')');
             if (!in_array($urlId, array_keys($urls))) {
                 $output->writeln('URL ' . $urlId . ' does not exist. ' . 'Please use the --list param to see the list of available URLs');
                 return;
             }
             $dialog = $this->getHelperSet()->get('dialog');
             if (!$dialog->askConfirmation($output, '<question>Are you sure you want to delete URL ' . $urlId . ' and all the courses that are used only in this URL? (y/N)</question>', false)) {
                 return;
             }
             // Now get the list of courses for that URL, and check, for each
             // course, whether it is used in just one or more URLs.
             // If the course is used in just the one URL that was scheduled
             // for deletion, then delete it and its relations with sessions.
             // If it is available in other URLs, only delete its relations
             // to the given URLs
             if (count($urlCourses) > 0 && isset($urlCourses[$urlId]) && count($urlCourses[$urlId]) > 0) {
                 foreach ($urlCourses[$urlId] as $courseCode) {
                     if (count($coursesUrl[$courseCode]) > 1) {
                         $output->writeln('Course ' . $courseCode . ' is used ' . 'by more than one URL (' . implode(',', $coursesUrl[$courseCode]) . ').');
                         $output->writeln('Deleting only references to given URL (' . $urlId . ')...');
                         $this->unlinkCourse($input, $output, $courseCode, $urlId);
                     } else {
                         // The course is only in the given URL
                         $output->writeln('Course ' . $courseCode . ' is only used ' . 'on this portal. Proceeding with deletion...');
                         $this->unlinkCourse($input, $output, $courseCode, $urlId);
                         $this->deleteCourse($input, $output, $courseCode);
                     }
                 }
             }
             // We removed all courses from that unique URL, so check if
             // there are any users left and delete the access URL reference
             $deleteUsers = $input->getOption('delete-users');
             //1 if the option was set
             if ($deleteUsers) {
                 // Check if some users are *only* in the given URL (if so,
                 // remove them)
                 $urlUsers = array();
                 $userUrls = array();
                 $sql = 'SELECT access_url_id, user_id FROM access_url_rel_user ORDER BY access_url_id, user_id';
                 $stmt = $connection->query($sql);
                 while ($row = $stmt->fetch()) {
                     $urlUsers[$row['access_url_id']][] = $row['user_id'];
                     $userUrls[$row['user_id']][] = $row['access_url_id'];
                 }
                 foreach ($userUrls as $user => $urls) {
                     if (count($urls) > 1) {
                         // user is in more than one URL, so only remove
                         // reference to this URL
                         $sql = "DELETE FROM access_url_rel_user where access_url_id = {$urlId} AND user_id = {$user}";
                         $connection->query($sql);
                     } else {
                         if ($urls[0] == $urlId) {
                             $output->writeln('User ' . $user . ' is only in URL ' . $urlId . ', deleting...');
                             // DELETE user
                             $this->deleteUser($input, $output, $user);
                         } else {
                             $output->writeln('User ' . $user . 'is in only one URL, but not this one. Skipping.');
                         }
                     }
                 }
             }
             // Everything removed. Delete URL
             $sql = 'DELETE FROM access_url WHERE id = ' . $urlId;
             $connection->query($sql);
         }
     }
 }
示例#21
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return bool|int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     if ($input->isInteractive()) {
         $this->writeCommandHeader($output, 'Looking for videos...');
         $confPath = $this->getConfigurationHelper()->getConfigurationFilePath();
         $sysPath = $this->getConfigurationHelper()->getSysPathFromConfigurationFile($confPath);
         $dir = $input->getArgument('source');
         //1 if the option was set
         if (substr($dir, 0, 1) != '/') {
             $dir = $sysPath . $dir;
         }
         if (!is_dir($dir)) {
             $output->writeln($dir . ' was not confirmed as a directory (if not starting with /, it is considered as relative to Chamilo\'s root folder)');
             return;
         }
         $this->ext = $input->getOption('ext');
         if (empty($this->ext)) {
             $this->ext = 'webm';
         }
         $this->origExt = $input->getOption('orig-ext');
         if (empty($this->origExt)) {
             $this->origExt = 'orig';
         }
         $fps = $input->getOption('fps');
         if (empty($fps)) {
             $fps = '24';
         }
         $bitRate = $input->getOption('bitrate');
         if (empty($bitRate)) {
             $bitRate = '512';
         }
         $vcodec = 'copy';
         if ($this->ext == 'webm') {
             $vcodec = 'libvpx';
         }
         // Find the files we want to treat, using Finder selectors
         $finder = new Finder();
         $filter = function (\SplFileInfo $file, $ext, $orig) {
             $combinedExt = '.' . $orig . '.' . $ext;
             $combinedExtLength = strlen($combinedExt);
             $extLength = strlen('.' . $ext);
             if (substr($file->getRealPath(), -$combinedExtLength) == $combinedExt) {
                 return false;
             }
             if (is_file(substr($file->getRealPath(), 0, -$extLength) . $combinedExt)) {
                 $this->excluded[] = $file;
                 return false;
             }
         };
         $finder->sortByName()->files()->in($dir)->name('*.' . $this->ext)->filter($filter, $this->ext, $this->origExt);
         // Print the list of matching files we found
         if (count($finder) > 0) {
             $output->writeln('Videos found for conversion: ');
             foreach ($finder as $file) {
                 $output->writeln($file->getRealpath());
             }
         } else {
             if (count($this->excluded) > 0) {
                 $output->writeln('The system has detected several videos already converted: ');
                 foreach ($this->excluded as $file) {
                     $output->writeln('- ' . $file->getRealPath());
                 }
             }
             $output->writeln('No video left to convert');
             return;
         }
         $dialog = $this->getHelperSet()->get('dialog');
         if (!$dialog->askConfirmation($output, '<question>All listed videos will be altered and a copy of the original will be taken with a .orig.webm extension. Are you sure you want to proceed? (y/N)</question>', false)) {
             return;
         }
         $fs = new Filesystem();
         $time = time();
         $counter = 0;
         $sizeNew = $sizeOrig = 0;
         foreach ($finder as $file) {
             $sizeOrig += $file->getSize();
             $origName = $file->getRealPath();
             $newName = substr($file->getRealPath(), 0, -4) . 'orig.webm';
             $fs->rename($origName, $newName);
             $out = array();
             $newNameCommand = preg_replace('/\\s/', '\\ ', $newName);
             $newNameCommand = preg_replace('/\\(/', '\\(', $newNameCommand);
             $newNameCommand = preg_replace('/\\)/', '\\)', $newNameCommand);
             $origNameCommand = preg_replace('/\\s/', '\\ ', $origName);
             $origNameCommand = preg_replace('/\\(/', '\\(', $origNameCommand);
             $origNameCommand = preg_replace('/\\)/', '\\)', $origNameCommand);
             $output->writeln('ffmpeg -i ' . $newNameCommand . ' -b ' . $bitRate . 'k -f ' . $this->ext . ' -vcodec ' . $vcodec . ' -acodec copy -r ' . $fps . ' ' . $origNameCommand);
             $exec = @system('ffmpeg -i ' . $newNameCommand . ' -b ' . $bitRate . 'k -f ' . $this->ext . ' -vcodec ' . $vcodec . ' -acodec copy -r ' . $fps . ' ' . $origNameCommand, $out);
             $sizeNew += filesize($origName);
             $counter++;
         }
     }
     $output->writeln('');
     $output->writeln('Done converting all videos from ' . $dir);
     $output->writeln('Total videos converted: ' . $counter . ' videos in ' . (time() - $time) . ' seconds');
     $output->writeln('Total size of old videos combined: ' . round($sizeOrig / (1024 * 1024)) . 'M');
     $output->writeln('Total size of all new videos combined: ' . round($sizeNew / (1024 * 1024)) . 'M');
     //$this->removeFiles($files, $output);
 }
示例#22
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return bool|int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $kb = $input->getOption('KB');
     //1 if the option was set
     $div = 1024 * 1024;
     $div2 = 1024;
     $unit = 'MB';
     if ($kb) {
         // Show results in KB instead of MB
         $div = 1024;
         $div2 = 1;
         $unit = 'KB';
     }
     $csv = $input->getOption('csv');
     //1 if the option was set
     if (!$csv) {
         $this->writeCommandHeader($output, 'Checking courses dir...');
     }
     $dialog = $this->getHelperSet()->get('dialog');
     if (!$csv && !$dialog->askConfirmation($output, '<question>This operation can take several hours on large volumes. Continue? (y/N)</question>', false)) {
         return;
     }
     $_configuration = $this->getConfigurationHelper()->getConfiguration();
     $connection = $this->getConnection();
     // Check whether we want to use multi-url
     $portals = array(1 => 'http://localhost/');
     $multi = $input->getOption('multi-url');
     //1 if the option was set
     if ($multi) {
         if (!$csv) {
             $output->writeln('Using multi-url mode');
         }
         $sql = "SELECT id, url FROM access_url ORDER BY url";
         $stmt = $connection->query($sql);
         while ($row = $stmt->fetch()) {
             $portals[$row['id']] = $row['url'];
         }
     }
     $globalCourses = array();
     $sql = "SELECT id, code, directory, disk_quota FROM course ORDER BY code";
     $stmt = $connection->query($sql);
     while ($row = $stmt->fetch()) {
         $globalCourses[$row['directory']] = array('code' => $row['code'], 'quota' => $row['disk_quota']);
     }
     $globalCoursesSizeSum = array();
     $sql = "SELECT directory, sum(size) as tSize\n            FROM c_document INNER JOIN course ON c_document.c_id = course.id\n            WHERE c_document.path NOT LIKE '%_DELETED'\n            GROUP BY directory";
     $stmt = $connection->query($sql);
     while ($row = $stmt->fetch()) {
         $globalCoursesSizeSum[$row['directory']] = $row['tSize'];
         $globalCourses[$row['directory']]['dbSize'] = $row['tSize'];
     }
     // Size for all portals combined
     $totalSize = $totalDbSize = 0;
     $finalList = array();
     $orphanList = array();
     $dirs = $this->getConfigurationHelper()->getDataFolders();
     $isDocumentOnly = $input->getOption('documents-only');
     $dirDoc = "";
     $docsOnly = "AllDiskFiles";
     if ($isDocumentOnly) {
         $dirDoc = "/document";
         $docsOnly = " DocFilesOnly";
     }
     $precision = $input->getOption('precision');
     if (version_compare($_configuration['system_version'], '10.0', '>=')) {
         $sql = " SELECT access_url_id, c.id as course_id, c.code, directory, disk_quota\n                FROM course c JOIN access_url_rel_course u\n                ON u.c_id = c.id\n                WHERE u.access_url_id = ? ";
     } else {
         $sql = " SELECT access_url_id, c.id as course_id, c.code, directory, disk_quota\n                FROM course c JOIN access_url_rel_course u\n                ON u.course_code = c.code\n                WHERE u.access_url_id = ? ";
     }
     /** @var TableHelper $table */
     $table = $this->getHelperSet()->get('table');
     $table->setHeaders(array('Portal', 'Code', $docsOnly . '(' . $unit . ')', 'DBDocs(' . $unit . ')', 'DBQuota(' . $unit . ')', 'UsedDiskVsDBQuota'));
     // browse all the portals
     foreach ($portals as $portalId => $portalName) {
         if (empty($portalId)) {
             continue;
         }
         $stmt = $connection->prepare($sql);
         $stmt->bindParam(1, $portalId);
         $stmt->execute();
         $localCourses = array();
         while ($row = $stmt->fetch()) {
             if (!empty($row['directory'])) {
                 $localCourses[$row['directory']] = array('code' => $row['code'], 'quota' => $row['disk_quota'], 'dbSize' => $globalCoursesSizeSum[$row['directory']]);
             }
         }
         // Size "local" to each course
         $localSize = $localDbSize = 0;
         if (count($dirs) > 0) {
             foreach ($dirs as $dir) {
                 $file = $dir->getFileName();
                 if (isset($localCourses[$file]['code']) && isset($globalCourses[$file]['code']) && isset($finalList[$globalCourses[$file]['code']])) {
                     // if this course has already been analysed, recover existing information
                     $size = $finalList[$globalCourses[$file]['code']]['size'];
                     $dbSize = $finalList[$globalCourses[$file]['code']]['dbSize'];
                     $table->addRow(array($portalName, $globalCourses[$file]['code'], round($size / $div2, $precision), round($dbSize / $div2, $precision), $finalList[$globalCourses[$file]['code']]['quota'], $finalList[$globalCourses[$file]['code']]['rate']));
                     $localSize += $size;
                     $localDbSize += $dbSize;
                 } else {
                     $res = exec('du -s ' . $dir->getRealPath() . $dirDoc);
                     $res = preg_split('/\\s/', $res);
                     $size = $res[0];
                     if (isset($localCourses[$file]['code'])) {
                         $localSize += $size;
                         //always add size to local portal (but only add to total size if new)
                         $code = $localCourses[$file]['code'];
                         $dbSize = round($localCourses[$file]['dbSize'] / $div2, $precision);
                         $localDbSize += $dbSize;
                         $quota = round($localCourses[$file]['quota'] / $div, 0);
                         $rate = '-';
                         if ($quota > 0) {
                             $rate = round(round($size / $div2, 2) / $quota * 100, 0);
                         }
                         $finalList[$code] = array('code' => $code, 'dir' => $file, 'size' => $size, 'dbSize' => $dbSize, 'quota' => $quota, 'rateVsDisk' => $rate);
                         //$finalListOrder[$code] = $size;
                         $totalSize += $size;
                         //only add to total if new course
                         $totalDbSize += $dbSize;
                         //only add to total if new course
                         $table->addRow(array($portalName, $code, round($size / $div2, $precision), round($dbSize / $div2, $precision), $finalList[$code]['quota'], $rate));
                     } elseif (!isset($globalCourses[$file]['code']) && !isset($orphanList[$file])) {
                         // only add to orphans if not in global list from db
                         $orphanList[$file] = array('size' => $size);
                     }
                 }
             }
         }
         //$output->writeln($portalName . ';Subtotal;' . round($localSize/$div2, $precision) . ';;;');
         $table->addRow(array($portalName, 'SubtotalWithoutOrphans', round($localSize / $div2, $precision), round($localDbSize / $div2, $precision)));
     }
     if (count($orphanList) > 0) {
         $table->addRow(array());
         $table->addRow(array('Portal', 'Code', $docsOnly . '(' . $unit . ')', 'DBDocs(' . $unit . ')', 'Quota(' . $unit . ')', 'UsedRatio'));
         //$output->writeln('CCC Code;Size' . $docsOnly . '(' . $unit . ');Quota(' . $unit . ');UsedRatio');
         foreach ($orphanList as $key => $orphan) {
             $size = $orphan['size'];
             $sizeToShow = !empty($orphan['size']) ? round($orphan['size'] / $div2, $precision) : 0;
             //$output->writeln($portalName . ';ORPHAN-DIR: ' . $key . ';' . $sizeToShow . ';;;');
             $table->addRow(array($portalName, 'ORPHAN-DIR: ' . $key, $sizeToShow));
             $totalSize += $size;
         }
     }
     //$output->writeln($portalName . ';Total size;' . round($totalSize/$div2, $precision) . ';;;');
     $table->addRow(array($portalName, 'Total size', round($totalSize / $div2, $precision), round($totalDbSize / $div2, $precision)));
     if ($csv) {
         $table->setPaddingChar(' ')->setHorizontalBorderChar('')->setVerticalBorderChar(' ')->setBorderFormat(';')->setPadType(STR_PAD_RIGHT);
     }
     $table->render($output);
 }
示例#23
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $source = $input->getArgument('source');
     $language = $input->getArgument('language');
     $destination = $input->getArgument('dest');
     $tgz = $input->getOption('tgz');
     $allowNew = $input->getOption('new');
     $_configuration = $this->getHelper('configuration')->getConfiguration();
     $baseDir = $_configuration['root_sys'];
     if (substr($baseDir, -1, 1) != '/') {
         $baseDir .= '/';
     }
     if (substr($source, -1, 1) != '/') {
         $source .= '/';
     }
     if (substr($destination, -1, 1) != '/') {
         $destination .= '/';
     }
     if (!is_dir($source)) {
         $output->writeln('The directory ' . $source . ' does not seem to exist. The source directory must exist and contain the language files, similar to e.g. /var/www/chamilo/main/lang/english');
         exit;
     }
     // Generate a folder name for saving the *partial* files in the original language - use suffix "_partial
     $origLang = substr(substr($source, 0, -1), strrpos(substr($source, 0, -1), '/')) . '_partial';
     if (!is_dir($destination)) {
         $output->writeln('The directory ' . $destination . ' does not seem to exist. The destination directory must exist in order for this script to write the results in a safe place');
         exit;
     }
     if (!is_writeable($destination)) {
         $output->writeln('The destination directory must be writeable. ' . $destination . ' seems not to be writeable now.');
         exit;
     }
     if (empty($language)) {
         $output->writeln('The destination language must be provided for this script to work. Received ' . $language . ', which could not be identified.');
         exit;
     }
     $langDir = $baseDir . 'main/lang/';
     $listDir = scandir($langDir);
     $langs = array();
     foreach ($listDir as $lang) {
         if (substr($lang, 0, 1) == '.') {
             continue;
         }
         if (!is_dir($langDir . $lang)) {
             continue;
         }
         $langs[] = $lang;
     }
     $new = false;
     if (!in_array($language, $langs)) {
         if (!$allowNew) {
             $output->writeln('The destination language must be expressed as one of the directories available in your Chamilo installation. If you are exporting for the creation of a new language, use the --new option to ignore this warning');
             exit;
         } else {
             $new = true;
         }
     }
     if (is_dir($destination . $language)) {
         if (!is_writeable($destination . $language)) {
             $output->writeln('Destination directory ' . $destination . $language . ' already exists but is not writeable. Please make sure whoever launches this script has privileges to write in there.');
             exit;
         }
         $output->writeln('Destination directory ' . $destination . $language . ' already exists. We recommend using an empty directory. Files in this directory will be overwritten if necessary. Sorry.');
     } elseif (!@mkdir($destination . $language)) {
         $output->writeln('For some reason, the directory creation returned an error for ' . $destination . $language);
         exit;
     }
     if (is_dir($destination . $origLang)) {
         if (!is_writeable($destination . $origLang)) {
             $output->writeln('Destination directory ' . $destination . $origLang . ' already exists but is not writeable. Please make sure whoever launches this script has privileges to write in there.');
             exit;
         }
         $output->writeln('Destination directory ' . $destination . $origLang . ' already exists. We recommend using an empty directory. Files in this directory will be overwritten if necessary. Sorry.');
     } elseif (!@mkdir($destination . $origLang)) {
         $output->writeln('For some reason, the directory creation returned an error for ' . $destination . $origLang);
         exit;
     }
     // Start working on those files!
     $listFiles = scandir($source);
     $countVars = 0;
     $countTranslatedVars = 0;
     $countWords = 0;
     $countTranslatedWords = 0;
     $fileString = '<?php' . "\n";
     foreach ($listFiles as $file) {
         if (substr($file, -1, 1) == '.') {
             continue;
         }
         $destFileLines = $fileString;
         $origFileLines = $fileString;
         $partialSourceFile = $langDir . $language . '/' . $file;
         $output->writeln('Source File 2 = ' . $partialSourceFile);
         $sourceVars = $this->_getLangVars($source . $file);
         $source2Vars = array();
         if (is_file($partialSourceFile)) {
             $source2Vars = $this->_getLangVars($partialSourceFile);
         }
         $source2Keys = array_keys($source2Vars);
         foreach ($sourceVars as $var => $val) {
             if (in_array($var, $source2Keys)) {
                 $destFileLines .= '$' . $var . '=' . $source2Vars[$var] . "\n";
                 $origFileLines .= '$' . $var . '=' . $val . "\n";
                 $countTranslatedVars++;
                 $countTranslatedWords += str_word_count($sourceVars[$var]);
             } else {
                 $destFileLines .= '$' . $var . '="";' . "\n";
                 $origFileLines .= '$' . $var . '=' . $val . "\n";
             }
             $countVars++;
             $countWords += str_word_count($sourceVars[$var]);
         }
         $output->writeln('Writing to file ' . $destination . $language . '/' . $file);
         $w = file_put_contents($destination . $language . '/' . $file, $destFileLines);
         $w = file_put_contents($destination . $origLang . '/' . $file, $origFileLines);
     }
     $output->writeln('Written translation files for packaging in ' . $destination . $language . '.');
     $output->writeln('Found ' . $countVars . ' variables, of which ' . $countTranslatedVars . ' were already translated (and ' . ($countVars - $countTranslatedVars) . ' are missing).');
     $output->writeln('In words, there are ' . $countWords . ' words in total, of which only ' . ($countWords - $countTranslatedWords) . ' still need translating.');
     if ($tgz) {
         $output->writeln('Compressing as .tar.gz...');
         chdir($destination);
         exec('tar zcf ' . $destination . $language . '.tar.gz ' . $language);
         $output->writeln('Written to ' . $destination . $language . '.tar.gz');
         $output->writeln('Removing work directory ' . $destination . $language);
         exec('rm -rf ' . $destination . $language);
     }
     $output->writeln('Finished exporting language package.');
     if (!$tgz) {
         $output->writeln('Please make sure you review your work directory for possible cleaning.');
     }
 }
示例#24
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return bool|int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     if ($input->isInteractive()) {
         $this->writeCommandHeader($output, 'Deleting courses');
         $courseId = $input->getOption('course-id');
         //1 if the option was set
         $courseCode = $input->getOption('course-code');
         //1 if the option was set
         $courseCategory = $input->getOption('course-category');
         //1 if the option was set
         $beforeDate = $input->getOption('before-date');
         //1 if the option was set
         $confirmDelete = $input->getOption('delete');
         //1 if the option was set
         $du = $input->getOption('show-disk-usage');
         //1 if the option was set
         $connection = $this->getConnection($input);
         if (empty($courseId) && empty($courseCode) && empty($courseCategory) && empty($beforeDate)) {
             $output->writeln('At least one search criteria (id, code, category or date) must be provided.');
             $output->writeln('Use "--help" param for details.');
             return;
         }
         // Check the courses that match the search criteria
         if (!empty($courseId)) {
             $courseId = intval($courseId);
             $sql = "SELECT id, code, category_code, creation_date\n                        FROM course\n                        WHERE id = {$courseId} ";
             if (!empty($beforeDate)) {
                 $output->writeln('ID-based course search: ' . $courseId . ' and date < ' . $beforeDate);
                 $sql .= " AND creation_date < '{$beforeDate}' ";
             } else {
                 $output->writeln('ID-based course search: ' . $courseId);
             }
             $sql .= " ORDER BY creation_date";
         } elseif (!empty($courseCode)) {
             $sql = "SELECT id, code, category_code, creation_date\n                        FROM course\n                        WHERE code = '{$courseCode}' ";
             if (!empty($beforeDate)) {
                 $output->writeln('Code-based course search: ' . $courseCode . ' and date < ' . $beforeDate);
                 $sql .= " AND creation_date < '{$beforeDate}' ";
             } else {
                 $output->writeln('Code-based course search: ' . $courseCode);
             }
             $sql .= " ORDER BY creation_date";
         } elseif (!empty($courseCategory)) {
             $sql = "SELECT id, code, category_code, creation_date\n                        FROM course\n                        WHERE category_code = '{$courseCategory}'";
             if (!empty($beforeDate)) {
                 $output->writeln('Category-based course search: ' . $courseCategory . ' and date < ' . $beforeDate);
                 $sql .= " AND creation_date < '{$beforeDate}' ";
             } else {
                 $output->writeln('Category-based course search: ' . $courseCategory);
             }
             $sql .= " ORDER BY creation_date";
         } elseif (!empty($beforeDate)) {
             $output->writeln('Category-based course search: ' . $beforeDate);
             $sql = "SELECT id, code, category_code, creation_date\n                        FROM course\n                        WHERE creation_date < '{$beforeDate}'\n                        ORDER BY creation_date";
         }
         $stmt = $connection->query($sql);
         $courses = array();
         $courseIdsString = '';
         while ($row = $stmt->fetch()) {
             $courses[$row['id']] = array('code' => $row['code'], 'category' => $row['category_code'], 'date' => $row['creation_date']);
             $courseIdsString .= $row['id'] . ', ';
         }
         $courseIdsString = substr($courseIdsString, 0, -2);
         if (count($courses) >= 1) {
             $output->writeln('ID' . "\t" . 'Code         ' . "\t\t" . 'Category' . "\t" . 'Creation date');
             foreach ($courses as $id => $course) {
                 $output->writeln($id . "\t" . $course['code'] . "\t\t" . (empty($course['category']) ? '--none--' : $course['category']) . "\t" . $course['date']);
             }
         } else {
             $output->writeln('No course found with that criteria. Bye bye.');
             return;
         }
         // Get courses vs URL match and measure disk usage
         $sql = "SELECT c.id, u.course_code, u.access_url_id, c.directory\n                    FROM access_url_rel_course u, course c\n                    WHERE u.course_code = c.code\n                    AND c.id IN ({$courseIdsString})\n                    ORDER BY access_url_id, course_code ASC";
         $stmt = $connection->query($sql);
         $urlCourses = array();
         $coursesUrl = array();
         $coursesDir = array();
         while ($row = $stmt->fetch()) {
             $urlCourses[$row['access_url_id']][] = $row['id'];
             $coursesUrl[$row['id']][] = $row['access_url_id'];
             $coursesDir[$row['id']] = $row['directory'];
         }
         $urls = array_keys($urlCourses);
         $sysPath = $this->getConfigurationHelper()->getSysPath();
         $coursesPath = $sysPath . 'courses/';
         $totalDiskUsage = 0;
         $output->writeln('');
         if ($du) {
             $output->writeln('Listing courses size (in KB)...');
         }
         $count = count($urlCourses);
         if ($count > 0) {
             foreach ($urlCourses as $url => $coursesList) {
                 foreach ($coursesList as $id) {
                     $countUrl = count($coursesUrl[$id]);
                     $unique = $countUrl <= 1 ? 'yes' : 'no';
                     $diskUsage = '';
                     if ($du) {
                         $courseDir = $coursesPath . $coursesDir[$id];
                         if (!is_dir($courseDir)) {
                             $size = 'N/A';
                         } else {
                             $res = @exec('du -s ' . $courseDir);
                             $res = preg_split('/\\s/', $res);
                             $size = $res[0];
                             $output->writeln($id . ":\t" . $size);
                             if ($unique == 'yes') {
                                 $totalDiskUsage += $size;
                             }
                         }
                     }
                 }
             }
         }
         if ($du) {
             $output->writeln('Total size of courses on disk (in KB): ' . $totalDiskUsage);
         }
         $output->writeln('');
         $dialog = $this->getHelperSet()->get('dialog');
         if (!$dialog->askConfirmation($output, '<question>Are you sure you want to clean the listed courses? (y/N)</question>', false)) {
             return;
         }
         if (count($urls) > 1) {
             $output->writeln('Detected multi-url. Courses will be unlinked from URLs before being erased.');
         }
         // Proceed with deletion, taking it by URL first
         // If the course is used in just the one URL
         // then delete it and its relations with sessions.
         // If it is available in other URLs, only delete its relations
         // to the given URLs
         foreach ($courses as $id => $course) {
             $cUrls = $coursesUrl[$id];
             if (count($cUrls) > 1) {
                 $output->writeln('Course ' . $course['code'] . ' is used ' . 'by more than one URL (' . implode(',', $coursesUrl[$id]) . ').');
             }
             foreach ($cUrls as $urlId) {
                 $output->writeln('Deleting references to course ID ' . $id . ' in URL (url ' . $urlId . ')...');
                 $this->unlinkCourse($input, $output, $course['code'], $urlId);
             }
             // Removal of the course linking in all URLs is over. Delete the
             // course itself
             $output->writeln('All references clear. Now deleting course ' . $id);
             $this->deleteCourse($intput, $output, $course['code']);
         }
     }
     $output->writeln('');
     $output->writeln('All done. ' . $totalDiskUsage . 'KB have been freed. Bye bye.');
     $output->writeln('');
 }
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return bool|int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $category = $input->getOption('category');
     $courseDirsList = array();
     if (!empty($category)) {
         $courseDirsList = '';
         $connection = $this->getConnection($input);
         // @todo escape the $category properly
         $sql = "SELECT directory FROM course WHERE category_code = '{$category}'";
         $stmt = $connection->query($sql);
         while ($row = $stmt->fetch()) {
             $courseDirsList[] = $row['directory'];
         }
     }
     $files = $this->getConfigurationHelper()->getDeletedDocuments($courseDirsList);
     if ($input->isInteractive()) {
         $this->writeCommandHeader($output, 'Cleaning deleted documents.');
         $list = $input->getOption('list');
         //1 if the option was set
         if ($list) {
             if (count($files) > 0) {
                 foreach ($files as $file) {
                     $output->writeln($file->getRealpath());
                 }
             } else {
                 $output->writeln('No file to be deleted in courses/ directory');
                 return;
             }
         }
         $stats = $input->getOption('size');
         //1 if the option was set
         if ($stats) {
             $size = 0;
             foreach ($files as $file) {
                 $size += $file->getSize();
             }
             $output->writeln('Total size used by deleted documents: ' . round((double) $size / 1024 / 1024, 2) . 'MB');
         }
         $dialog = $this->getHelperSet()->get('dialog');
         if (!$dialog->askConfirmation($output, '<question>Are you sure you want to clean the Chamilo deleted documents? (y/N)</question>', false)) {
             return;
         }
         $deleteFromDb = $input->getOption('from-db');
         if ($deleteFromDb) {
             $connection = $this->getConnection($input);
             $sql = "DELETE FROM c_document WHERE path LIKE '%_DELETED%'";
             $stmt = $connection->query($sql);
             /*
             while ($row = $stmt->fetch()) {
                 $sql2 = "SELECT id FROM c_item_property
                     WHERE c_id = " . $row['c_id'] . "
                         AND tool = 'document'
                         AND ref = ".$row['id'];
                 $stmt2 = $connection->query($sql2);
                 while ($row2 = $stmt2->fetch()) {
                     $output->writeln($row['c_id'] . ' ' . $row2['id']);
                 }
             
             }
             */
             $output->writeln('Deleted all database references in c_document.
                  Table c_item_property left untouched, to keep history.');
         }
     }
     $this->removeFiles($files, $output);
 }
示例#26
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $dialog = $this->getHelperSet()->get('dialog');
     $_configuration = $this->getHelper('configuration')->getConfiguration();
     $file = $input->getArgument('file');
     $connection = $this->getConnection($input);
     if (is_file($file) && is_readable($file)) {
         $phar = new \PharData($file);
         if ($phar->hasMetadata()) {
             $langInfo = $phar->getMetadata();
             if ($connection) {
                 $q = mysql_query("SELECT * FROM language WHERE dokeos_folder = '{$langInfo['dokeos_folder']}' ");
                 $langInfoFromDB = mysql_fetch_array($q, MYSQL_ASSOC);
                 $langFolderPath = $_configuration['root_sys'] . 'main/lang/' . $langInfoFromDB['dokeos_folder'];
                 if ($langInfoFromDB && $langFolderPath) {
                     //Overwrite lang files
                     if (!$dialog->askConfirmation($output, '<question>The ' . $langInfo['original_name'] . ' language already exists in Chamilo. Did you want to overwrite the contents? (y/N)</question>', false)) {
                         return;
                     }
                     if (is_writable($langFolderPath)) {
                         $output->writeln("Trying to save files here: {$langFolderPath}");
                         $phar->extractTo($langFolderPath, null, true);
                         // extract all files
                         $output->writeln("Files were copied.");
                     } else {
                         $output->writeln("<error>Make sure that this folder {$langFolderPath} has writable permissions or execute the script with sudo </error>");
                     }
                 } else {
                     //Check if parent_id exists
                     $parentId = '';
                     if (!empty($langInfo['parent_id'])) {
                         $sql = "select selected_value from settings_current where variable = 'allow_use_sub_language'";
                         $result = mysql_query($sql);
                         $subLanguageSetting = mysql_fetch_array($result, MYSQL_ASSOC);
                         $subLanguageSetting = $subLanguageSetting['selected_value'];
                         if ($subLanguageSetting == 'true') {
                             $q = mysql_query("SELECT * FROM language WHERE id = '{$langInfo['parent_id']}' ");
                             $parentLangInfoFromDB = mysql_fetch_array($q, MYSQL_ASSOC);
                             if ($parentLangInfoFromDB) {
                                 $output->writeln("Setting parent language: " . $parentLangInfoFromDB['original_name']);
                                 $parentId = $langInfo['parent_id'];
                             } else {
                                 $output->writeln("The lang parent_id = {$langInfo['parent_id']} does not exist in Chamilo. Try to import first the parent language.");
                                 exit;
                             }
                         } else {
                             $output->writeln("<comment>Please turn ON the sublanguage feature in this portal</comment>");
                             exit;
                         }
                     } else {
                         $output->writeln("Parent language was not provided");
                     }
                     $q = mysql_query("INSERT INTO language (original_name, english_name, isocode, dokeos_folder, available, parent_id) VALUES (\n                                '" . $langInfo['original_name'] . "',\n                                '" . $langInfo['english_name'] . "',\n                                '" . $langInfo['isocode'] . "',\n                                '" . $langInfo['dokeos_folder'] . "',\n                                '1',\n                                '" . $parentId . "')");
                     if ($q) {
                         $output->writeln("Language inserted in the DB");
                         $langFolderPath = $_configuration['root_sys'] . 'main/lang/' . $langInfo['dokeos_folder'];
                         $phar->extractTo($langFolderPath, null, true);
                         // extract all files
                         $output->writeln("<comment>Files were copied here {$langFolderPath} </comment>");
                     } else {
                         $output->writeln("An error ocurred while tring to create the language");
                     }
                 }
             }
         } else {
             $output->writeln("<comment>The file is not a valid Chamilo language package<comment>");
         }
     } else {
         $output->writeln("<comment>The file located in '{$file}' is not accessible<comment>");
     }
 }
示例#27
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $search = $input->getArgument('search');
     $replace = $input->getArgument('replace');
     $dryRun = $input->getOption('dry-run');
     if ($dryRun) {
         $output->writeln('');
         $output->writeln('<info>Running in --dry-run mode no changes or queries will be executed.</info>');
         $output->writeln('');
     }
     $this->writeCommandHeader($output, "Replacing URLs in these tables");
     $tables = $this->getTables();
     foreach ($tables as $table => $fields) {
         $output->write('<comment>' . $table . ': </comment>');
         $output->writeln(implode(', ', $fields));
     }
     $dialog = $this->getHelperSet()->get('dialog');
     $output->writeln('');
     if (!$dialog->askConfirmation($output, '<question>Are you sure you want to replace</question> <comment>' . $search . '</comment> with <comment>' . $replace . '</comment>? (y/N)', false)) {
         return;
     }
     $output->writeln('');
     $connection = $this->getConnection();
     // Replace URLs from Database:
     foreach ($tables as $table => $fields) {
         foreach ($fields as $field) {
             $sql = "UPDATE {$table} SET {$field} = REPLACE ({$field}, '{$search}', '{$replace}')";
             $output->writeln($sql);
             if (!$dryRun) {
                 $result = $connection->query($sql);
                 $count = $result->rowCount();
                 $output->writeln("<comment># {$count} row(s) modified.</comment>");
             } else {
                 $output->writeln("<comment>Nothing was changed.</comment>");
             }
         }
     }
     // Replacing documents.
     $output->writeln('');
     $this->writeCommandHeader($output, "Replacing documents matching this query:");
     $sql = "SELECT\n                    DISTINCT d.id, d.c_id, d.title, d.path, c.code, c.directory\n                FROM c_document d\n                INNER JOIN course c\n                ON d.c_id = c.id\n                WHERE\n                  filetype = 'file' AND\n                  (d.path LIKE '%.html' or d.path LIKE '%.htm')";
     $output->writeln('');
     $output->writeln(preg_replace('/\\s+/', ' ', $sql));
     $result = $connection->query($sql);
     $count = $result->rowCount();
     $output->writeln("<comment># {$count} html files found</comment>");
     $results = $result->fetchAll();
     $coursePath = $this->getCourseSysPath();
     $output->writeln('');
     if (!$dialog->askConfirmation($output, '<question>Are you sure you want to replace</question> <comment>' . $search . '</comment> with <comment>' . $replace . ' in those ' . $count . ' files</comment> ? (y/N)', false)) {
         return;
     }
     $output->writeln('');
     if (!empty($results)) {
         foreach ($results as $row) {
             $filePath = $coursePath . '/' . $row['directory'] . '/document' . $row['path'];
             $output->writeln($filePath);
             if (file_exists($filePath) && !empty($row['path'])) {
                 if (!$dryRun) {
                     $contents = file_get_contents($filePath);
                     $contents = str_replace($search, $replace, $contents);
                     $result = file_put_contents($filePath, $contents);
                     if ($result) {
                         $output->writeln("<comment>File Updated.</comment>");
                     } else {
                         $output->writeln("<error>Error!<error>");
                     }
                 } else {
                     $output->writeln("<comment>Nothing was changed.</comment>");
                 }
             } else {
                 $output->writeln("<error>File doesn't exists.</error>");
             }
         }
     } else {
         $output->writeln("<comment>No results found.</comment>");
     }
 }
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return bool|int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     parent::execute($input, $output);
     $add = $input->getOption('add-size');
     //1 if the option was set
     if (empty($add)) {
         $add = 100;
     }
     if ($add == 1) {
         $this->writeCommandHeader($output, 'Max space needs to be of at least 1MB for each course first');
         return;
     }
     $threshold = $input->getOption('threshold');
     if (empty($threshold)) {
         $threshold = 75;
     }
     $this->writeCommandHeader($output, 'Using threshold: ' . $threshold);
     $this->writeCommandHeader($output, 'Checking courses dir...');
     // Get database and path information
     $coursesPath = $this->getConfigurationHelper()->getSysPath();
     $connection = $this->getConnection($input);
     $_configuration = $this->getConfigurationHelper()->getConfiguration();
     $courseTable = $_configuration['main_database'] . '.course';
     $globalCourses = array();
     $sql = "SELECT c.id as cid, c.code as ccode, c.directory as cdir, c.disk_quota as cquota\n                FROM {$courseTable} c";
     $res = mysql_query($sql);
     if ($res && mysql_num_rows($res) > 0) {
         while ($row = mysql_fetch_assoc($res)) {
             $globalCourses[$row['cdir']] = array('id' => $row['cid'], 'code' => $row['ccode'], 'quota' => $row['cquota']);
         }
     }
     $dirs = $this->getConfigurationHelper()->getDataFolders();
     if (count($dirs) > 0) {
         foreach ($dirs as $dir) {
             $file = $dir->getFileName();
             $res = exec('du -s ' . $dir->getRealPath());
             // results are returned in KB (under Linux)
             $res = preg_split('/\\s/', $res);
             $size = round($res[0] / 1024, 1);
             // $size is stored in MB
             if (isset($globalCourses[$file]['code'])) {
                 $code = $globalCourses[$file]['code'];
                 $quota = round($globalCourses[$file]['quota'] / (1024 * 1024), 0);
                 //quota is originally in Bytes in DB. Store in MB
                 $rate = '-';
                 if ($quota > 0) {
                     $newAllowedSize = $quota;
                     $rate = round($size / $newAllowedSize * 100, 0);
                     //rate is a percentage of disk use vs allowed quota, in MB
                     $increase = false;
                     while ($rate > $threshold) {
                         // Typically 80 > 75 -> increase quota
                         //$output->writeln('...Rate '.$rate.' is larger than '.$threshold.', so increase allowed size');
                         // Current disk usage goes beyond threshold. Increase allowed size by 100MB
                         $newAllowedSize += $add;
                         //$output->writeln('....New allowed size is '.$newAllowedSize);
                         $rate = round($size / $newAllowedSize * 100, 0);
                         //$output->writeln('...Rate is now '.$rate);
                         $increase = true;
                     }
                     $newAllowedSize = $newAllowedSize * 1024 * 1024;
                     //$output->writeln('Allowed size is '.$newAllowedSize.' Bytes, or '.round($newAllowedSize/(1024*1024)));
                     $sql = "UPDATE {$courseTable} SET disk_quota = {$newAllowedSize} WHERE id = " . $globalCourses[$file]['id'];
                     $res = mysql_query($sql);
                     if ($increase) {
                         $output->writeln('Increased max size of ' . $globalCourses[$file]['code'] . '(' . $globalCourses[$file]['id'] . ') to ' . $newAllowedSize);
                     }
                 } else {
                     //Quota is 0 (unlimited?)
                 }
             }
         }
     }
     $output->writeln('Done increasing disk space');
 }