Browse Source

WIP vchamilo plugin - Force creation of master snapshot to setup a default template.

jmontoyaa 9 years ago
parent
commit
c023e350c3

+ 0 - 2
main/inc/lib/api.lib.php

@@ -4999,7 +4999,6 @@ function api_set_setting($var, $value, $subvar = null, $cat = null, $access_url
     } else {
         $select .= " AND access_url = 1 ";
     }
-
     $res = Database::query($select);
     if (Database::num_rows($res) > 0) {
         // Found item for this access_url.
@@ -5020,7 +5019,6 @@ function api_set_setting($var, $value, $subvar = null, $cat = null, $access_url
                 $select .= " AND category = '$cat'";
             }
             $res = Database::query($select);
-
             if (Database::num_rows($res) > 0) {
                 // We have a setting for access_url 1, but none for the current one, so create one.
                 $row = Database::fetch_array($res);

+ 3 - 1
main/inc/lib/display.lib.php

@@ -1918,7 +1918,9 @@ class Display
                 $html .= '</li>';
             }
             $html .= '</ul></div>';
+            $html .= '<br />';
         }
+
         return $html;
     }
 
@@ -2166,7 +2168,7 @@ class Display
         $link = Display::url($label.' ', $link_to_show, $linkAttributes);
         return  '<li class = "'.$class.'">'.$link.'</li>';
     }
-    
+
     /**
      * @param int $current
      * @param int $total

+ 1 - 1
main/inc/lib/plugin.class.php

@@ -403,7 +403,7 @@ class Plugin
                 $variable = $setting['name'];
                 $value ='';
                 if (isset($setting['init_value'])) {
-                    $value = ($setting['init_value']);
+                    $value = $setting['init_value'];
                 }
 
                 $type = 'textfield';

+ 4 - 2
plugin/vchamilo/index.php

@@ -6,13 +6,15 @@
 require_once api_get_path(LIBRARY_PATH) . 'plugin.class.php';
 require_once dirname(__FILE__).'/lib/vchamilo_plugin.class.php';
 
+api_protect_admin_script();
+
 global $VCHAMILO;
 
 $plugininstance = VChamiloPlugin::create();
 
-// See also the share_user_info plugin 
+// See also the share_user_info plugin
 
-$_template['show_message']   = true;
+$_template['show_message'] = true;
 $_template['title'] = $plugininstance->get_lang('hostlist');
 
 $tablename = Database::get_main_table('vchamilo');

+ 3 - 0
plugin/vchamilo/install.php

@@ -13,6 +13,8 @@
 
  */
 
+api_protect_admin_script();
+
 $table = 'vchamilo';
 $tablename = Database::get_main_table($table);
 $sql = "CREATE TABLE IF NOT EXISTS $tablename (
@@ -33,6 +35,7 @@ $sql = "CREATE TABLE IF NOT EXISTS $tablename (
   `lastcrongap` int(11),
   `lastcron` int(11),
   `croncount` int(11),
+  `template` varchar(255),
   PRIMARY KEY (`id`)
 ) DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
 ";

+ 2 - 2
plugin/vchamilo/lang/english.php

@@ -72,8 +72,8 @@ $strings['testdatapath'] = 'Test data location';
 $strings['trackingenabled'] = 'Tracking enabled';
 $strings['userpersonaldatabase'] = 'User personal database';
 $strings['vchamilo'] = 'Virtual Chamilo';
-$strings['vchamilosnapshot1'] = 'STEP 1 OF 3 : Directories for snapshot have been created. Continue with database dumping...';
-$strings['vchamilosnapshot2'] = 'STEP 2 OF 3 : Databases have been dumped. Continue with saving the exploitation files... beware this step can be long if a lot of content resides in the instance...';
+$strings['vchamilosnapshot1'] = 'STEP 1 OF 3 : Directories for snapshot have been created. Continue with database backup ...';
+$strings['vchamilosnapshot2'] = 'STEP 2 OF 3 : Databases have been backed up. Continue with saving files... beware this step can be long if a lot of content resides in the instance...';
 $strings['vchamilosnapshot3'] = 'STEP 3 OF 3 : Files saved.';
 $strings['withselection'] = 'With selection: ';
 $strings['yes'] = 'Yes';

+ 47 - 39
plugin/vchamilo/lib.php

@@ -204,7 +204,6 @@ function vchamilo_template_exists($template)
     // Find and checktemplate directory (files and SQL).
     $separator = DIRECTORY_SEPARATOR;
     $templatefoldername = 'plugin'.$separator.'vchamilo'.$separator.'templates';
-    $absolute_templatesdir = $_configuration['root_sys'].$templatefoldername;
     $relative_datadir = $templatefoldername.$separator.$template.'_sql';
     $absolute_datadir = $_configuration['root_sys'].$relative_datadir;
 
@@ -223,31 +222,23 @@ function vchamilo_drop_databases(&$vchamilo)
 
     if (is_array($vchamilo)) $vchamilo = (object)$vchamilo;
 
+    if (empty($vchamilo->main_database)) {
+        Display::addFlash(Display::return_message('No database found'));
+        return;
+    }
+
     // Drop databases you need to drop
     $sqls = array(" DROP DATABASE `{$vchamilo->main_database}` ");
 
-    if (!empty($vchamilo->statistics_database) && ($vchamilo->main_database != $vchamilo->statistics_database)) {
-        $sqls[] = " DROP DATABASE `{$vchamilo->statistics_database}` ";
-    };
-
-    if (!empty($vchamilo->user_personal_database) && ($vchamilo->user_personal_database != $vchamilo->statistics_database) && ($vchamilo->main_database != $vchamilo->user_personal_database)) {
-        $sqls[] = " DROP DATABASE `{$vchamilo->user_personal_database}` ";
-    }
+    Display::addFlash(Display::return_message("Dropping database: ".$vchamilo->main_database));
 
-    foreach($sqls as $sql){
+    foreach ($sqls as $sql){
         $res = Database::query($sql);
-        if (!$res){
-            $erroritem = new stdClass();
-            $erroritem->message = $plugininstance->get_lang('couldnotdropdb');
-            $erroritem->on = 'db';
-            $erroritems[] = $erroritem;
+        if (!$res) {
+            Display::addFlash(Display::return_message($plugininstance->get_lang('couldnotdropdb')));
         }
     }
 
-    if (!empty($erroritems)) {
-        return $erroritems;
-    }
-
     return false;
 }
 
@@ -320,7 +311,8 @@ function vchamilo_get_database_dump_cmd($vchamilodata)
     return $sqlcmd;
 }
 
-function vchamilo_load_db_template($vchamilo, $template) {
+function vchamilo_load_db_template($vchamilo, $template)
+{
     global $_configuration;
 
     // Make template directory (files and SQL).
@@ -480,24 +472,26 @@ function vchamilo_dump_databases($vchamilo, $outputfilerad)
     $pgm = !empty($mysqldumpcmd) ? stripslashes($mysqldumpcmd) : false ;
 
     if (!$pgm) {
-        $erroritem = new stdClass();
-        $erroritem->message = "Database dump command not available check here: ";
+        $message = "Database dump command not available check here: ";
         $url = api_get_path(WEB_CODE_PATH).'admin/configure_plugin.php?name=vchamilo';
-        $erroritem->message .= Display::url($url, $url);
-        return array($erroritem);
+        $message .= Display::url($url, $url);
+        Display::addFlash(Display::return_message($message));
+
+        return false;
     } else {
         $phppgm = str_replace("\\", '/', $pgm);
         $phppgm = str_replace("\"", '', $phppgm);
         $pgm = str_replace('/', DIRECTORY_SEPARATOR, $pgm);
 
-        if (!is_executable($phppgm)){
-            $erroritem = new stdClass();
-            $erroritem->message = "Database dump command $phppgm does not match any executable";
-            return array($erroritem);
+        if (!is_executable($phppgm)) {
+            $message = "Database dump command $phppgm does not match any executable";
+            Display::addFlash(Display::return_message($message));
+
+            return false;
         }
 
         // executing all commands
-        foreach($cmds as $cmd){
+        foreach ($cmds as $cmd){
 
             // Final command.
             $cmd = $pgm.' '.$cmd;
@@ -517,7 +511,7 @@ function vchamilo_dump_databases($vchamilo, $outputfilerad)
     }
 
     // End with success.
-    return 0;
+    return 1;
 }
 
 /**
@@ -560,38 +554,52 @@ function vchamilo_make_this()
 
 /**
  * Get available templates for defining a new virtual host.
- * @return        array        The availables templates, or EMPTY array.
+ * @return        array        The available templates, or EMPTY array.
  */
-function vchamilo_get_available_templates()
+function vchamilo_get_available_templates($addEmptyTemplate = true)
 {
     global $_configuration;
     global $plugininstance;
 
     $separator = DIRECTORY_SEPARATOR;
 
-    $templatefoldername    = 'plugin'.$separator.'vchamilo'.$separator.'templates';
-    $absolute_templatesdir = $_configuration['root_sys'].$templatefoldername;
+    $templatefoldername = 'plugin'.$separator.'vchamilo'.$separator.'templates';
+    $tempDir = $_configuration['root_sys'].$templatefoldername;
 
     // Scans the templates.
-    if (!is_dir($absolute_templatesdir)) {
-        mkdir($absolute_templatesdir, 0777, true);
+    if (!is_dir($tempDir)) {
+        mkdir($tempDir, 0777, true);
     }
 
     $finder = new \Symfony\Component\Finder\Finder();
-    $dirs = $finder->in($absolute_templatesdir)->depth('== 0');
+    $dirs = $finder->in($tempDir)->depth('== 0');
 
     // Retrieves template(s) name(s). Should be hostnames.
-    $templatesarray = array('' => $plugininstance->get_lang('emptysite'));
+    $templates = [];
+    if ($addEmptyTemplate) {
+        $templates = array('' => $plugininstance->get_lang('emptysite'));
+    }
+
+    $template = vchamilo_get_config('vchamilo', 'default_template');
+
     if ($dirs) {
         /** @var Symfony\Component\Finder\SplFileInfo $dir */
         foreach ($dirs as $dir) {
             if (is_dir($dir->getPathname())) {
-                $templatesarray[$dir->getRelativePathname()] = $dir->getRelativePathname();
+                // A template is considered when a dump.sql exists.
+                if (file_exists($dir->getPathname().'/dump.sql')) {
+
+                    $templateName = $dir->getRelativePathname();
+                    if ($templateName == $template) {
+                        $templateName .= ' (default)';
+                    }
+                    $templates[$dir->getRelativePathname()] = $templateName;
+                }
             }
         }
     }
 
-    return $templatesarray;
+    return $templates;
 }
 
 function vchamilo_print_error($errortrace, $return = false)

+ 3 - 5
plugin/vchamilo/plugin.php

@@ -79,17 +79,15 @@ $form->addElement(
     [$plugininstance->get_lang('homerealroot'), 'Example: '.api_get_path(SYS_PATH).'var/home/']
 );
 
+$form->addElement('header', $plugininstance->get_lang('mysqlcmds'));
+$form->addElement('text', 'cmd_mysql', [$plugininstance->get_lang('mysqlcmd'), 'Example: /usr/bin/mysql']);
+$form->addElement('text', 'cmd_mysqldump', [$plugininstance->get_lang('mysqldumpcmd'), 'Example: /usr/bin/mysqldump']);
 $form->addElement('header', $plugininstance->get_lang('proxysettings'));
 $form->addElement('text', 'httpproxyhost', $plugininstance->get_lang('httpproxyhost'));
 $form->addElement('text', 'httpproxyport', $plugininstance->get_lang('httpproxyport'));
 $form->addElement('text', 'httpproxybypass', $plugininstance->get_lang('httpproxybypass'));
 $form->addElement('text', 'httpproxyuser', $plugininstance->get_lang('httpproxyuser'));
 $form->addElement('text', 'httpproxypassword', $plugininstance->get_lang('httpproxypassword'));
-
-$form->addElement('header', $plugininstance->get_lang('mysqlcmds'));
-$form->addElement('text', 'cmd_mysql', [$plugininstance->get_lang('mysqlcmd'), 'Example: /usr/bin/mysql']);
-$form->addElement('text', 'cmd_mysqldump', [$plugininstance->get_lang('mysqldumpcmd'), 'Example: /usr/bin/mysqldump']);
-
 $form->addButtonSave($plugininstance->get_lang('Save'));
 
 $plugin_info['settings_form'] = $form;

+ 1 - 1
plugin/vchamilo/templates/README.txt

@@ -1,2 +1,2 @@
-This directory whould be http server writable for templates snapshot to be created.
+This directory would be http server writable for templates snapshot to be created.
 Set GID to web server group, or give write access to everyone.

+ 2 - 1
plugin/vchamilo/uninstall.php

@@ -1,9 +1,10 @@
 <?php
 /* PHP code to uninstall the plugin */
 
+api_protect_admin_script();
+
 $table = 'vchamilo';
 $tablename = Database::get_main_table($table);
 $sql = " DROP TABLE IF EXISTS $tablename ";
 
 Database::query($sql);
- 

+ 17 - 18
plugin/vchamilo/vcron.php

@@ -2,8 +2,8 @@
 
 /**
  * This file is a cron microclock script.
- * It will be used as replacement of setting individual 
- * cron lines for all virtual instances. 
+ * It will be used as replacement of setting individual
+ * cron lines for all virtual instances.
  *
  * Setup this vcron to run at the smallest period possible, as
  * it will schedule all availables vchamilos to be run as required.
@@ -11,7 +11,7 @@
  * or may be run more than one cron.
  *
  * If used on a big system with clustering, ensure hostnames are adressed
- * at the load balancer entry and not on physical hosts 
+ * at the load balancer entry and not on physical hosts
  *
  * @package plugin/vchamilo
  * @category plugins
@@ -49,17 +49,17 @@ if (!is_dir($_configuration['root_sys'].'plugin/vchamilo/log')) {
 *
 */
 function fire_vhost_cron($vhost) {
-    global $VCRON,$DB;
+    global $VCRON;
 
     if ($VCRON->TRACE_ENABLE) {
         $CRONTRACE = fopen($VCRON->TRACE, 'a');
     }
     $ch = curl_init($vhost->root_web.'/main/cron/run.php');
 
-    $http_proxy_host =     api_get_setting('vchamilo_httpproxyhost', 'vchamilo');
-    $http_proxy_port =     api_get_setting('vchamilo_httpproxyport', 'vchamilo');
-    $http_proxy_bypass =   api_get_setting('vchamilo_httpproxybypass', 'vchamilo');
-    $http_proxy_user =     api_get_setting('vchamilo_httpproxyuser', 'vchamilo');
+    $http_proxy_host = api_get_setting('vchamilo_httpproxyhost', 'vchamilo');
+    $http_proxy_port = api_get_setting('vchamilo_httpproxyport', 'vchamilo');
+    $http_proxy_bypass = api_get_setting('vchamilo_httpproxybypass', 'vchamilo');
+    $http_proxy_user = api_get_setting('vchamilo_httpproxyuser', 'vchamilo');
     $http_proxy_password = api_get_setting('vchamilo_httpproxypassword', 'vchamilo');
 
     curl_setopt($ch, CURLOPT_TIMEOUT, $VCRON->TIMEOUT);
@@ -118,7 +118,7 @@ function fire_vhost_cron($vhost) {
             fputs($CRONTRACE, "VCron start on $vhost->vhostname : ".api_time_to_hms($timestamp_send)."\n" );
             fputs($CRONTRACE, $rawresponse."\n");
             fputs($CRONTRACE, "VCron stop on $vhost->vhostname : ".api_time_to_hms($timestamp_receive)."\n#################\n\n" );
-            fclose($CRONTRACE);    
+            fclose($CRONTRACE);
         }
     }
     echo("VCron start on $vhost->root_web : ".api_time_to_hms($timestamp_send)."\n" );
@@ -127,7 +127,7 @@ function fire_vhost_cron($vhost) {
     $vhost->lastcrongap = time() - $vhost->lastcron;
     $vhost->lastcron = $timestamp_send;
     $vhost->croncount++;
-    
+
     $vhostid = $vhost->id;
     unset($vhost->id);
 
@@ -158,7 +158,7 @@ function exec_vhost_cron($vhost) {
             fputs($CRONTRACE, "VCron start on $vhost->root_web : $timestamp_send\n" );
             fputs($CRONTRACE, $rawresponse."\n");
             fputs($CRONTRACE, "VCron stop on $vhost->root_web : $timestamp_receive\n#################\n\n" );
-            fclose($CRONTRACE);    
+            fclose($CRONTRACE);
         }
     }
 
@@ -183,11 +183,10 @@ function exec_vhost_cron($vhost) {
  * @param string $url url to check
  * @return boolean true if we should bypass the proxy
  */
-function is_proxybypass( $url ) {
-    global $CFG;
-
-    $http_proxy_host   = api_get_setting('vchamilo_httpproxyhost', 'vchamilo');
-    $http_proxy_port   = api_get_setting('vchamilo_httpproxyport', 'vchamilo');
+function is_proxybypass($url)
+{
+    $http_proxy_host = api_get_setting('vchamilo_httpproxyhost', 'vchamilo');
+    $http_proxy_port = api_get_setting('vchamilo_httpproxyport', 'vchamilo');
     $http_proxy_bypass = api_get_setting('vchamilo_httpproxybypass', 'vchamilo');
 
     // sanity check
@@ -196,12 +195,12 @@ function is_proxybypass( $url ) {
     }
 
     // get the host part out of the url
-    if (!$host = parse_url( $url, PHP_URL_HOST )) {
+    if (!$host = parse_url($url, PHP_URL_HOST)) {
         return false;
     }
 
     // get the possible bypass hosts into an array
-    $matches = explode(',', $http_proxy_bypass );
+    $matches = explode(',', $http_proxy_bypass);
 
     // check for a match
     // (IPs need to match the left hand side and hosts the right of the url,

+ 12 - 5
plugin/vchamilo/views/editinstance.controller.php

@@ -2,6 +2,8 @@
 
 require_once api_get_path(LIBRARY_PATH).'fileManage.lib.php';
 
+api_protect_admin_script();
+
 if (!defined('CHAMILO_INTERNAL')) die('You cannot use this script this way');
 
 if ($data->what == 'addinstance' || $data->what == 'registerinstance') {
@@ -19,15 +21,18 @@ if ($data->what == 'addinstance' || $data->what == 'registerinstance') {
     $data->lastcrongap = 0;
     $data->croncount = 0;
 
-    if (isset($data->template)) {
+    if (!empty($data->template)) {
         $template = $data->template;
-        unset($data->template);
+    } else {
+        $template = '';
     }
 
     $mainDatabase = api_get_configuration_value('main_database');
 
     if ($mainDatabase == $data->main_database) {
-        Display::addFlash(Display::return_message('You cannot use the same database as the chamilo master', 'error'));
+        Display::addFlash(
+            Display::return_message('You cannot use the same database as the chamilo master', 'error')
+        );
         return ;
     }
 
@@ -171,8 +176,10 @@ if ($data->what == 'addinstance' || $data->what == 'registerinstance') {
     $settingstable = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
     $sitename = Database::escape_string($data->sitename);
     $institution = Database::escape_string($data->institution);
-    $sqls[] = "UPDATE {$settingstable} SET selected_value = '{$sitename}' WHERE variable = 'siteName' AND category = 'Platform' ";
-    $sqls[] = "UPDATE {$settingstable} SET selected_value = '{$institution}' WHERE variable = 'institution' AND category = 'Platform' ";
+    $sqls[] = "UPDATE {$settingstable} SET selected_value = '{$sitename}' 
+               WHERE variable = 'siteName' AND category = 'Platform' ";
+    $sqls[] = "UPDATE {$settingstable} SET selected_value = '{$institution}' 
+               WHERE variable = 'institution' AND category = 'Platform' ";
     $accessurltable = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
     $sqls[] = "UPDATE {$accessurltable} SET url = '{$data->root_web}' WHERE id = '1' ";
 

+ 17 - 20
plugin/vchamilo/views/editinstance.php

@@ -10,6 +10,9 @@ require_once api_get_path(SYS_PLUGIN_PATH).'vchamilo/lib.php';
 require_once api_get_path(SYS_PLUGIN_PATH).'vchamilo/lib/vchamilo_plugin.class.php';
 require_once api_get_path(SYS_PLUGIN_PATH).'vchamilo/views/editinstance_form.php';
 
+// security
+api_protect_admin_script();
+
 $htmlHeadXtra[] = '<script src="'.api_get_path(WEB_PLUGIN_PATH).'vchamilo/js/host_form.js" type="text/javascript" language="javascript"></script>';
 
 // get parameters
@@ -19,52 +22,46 @@ $registeronly = isset($_REQUEST['registeronly']) ? $_REQUEST['registeronly'] : 0
 $plugininstance = VChamiloPlugin::create();
 $thisurl = api_get_path(WEB_PLUGIN_PATH).'vchamilo/views/manage.php';
 
-$course_real_root = vchamilo_get_config('vchamilo', 'course_real_root');
+$coursePath = vchamilo_get_config('vchamilo', 'course_real_root');
 $homePath = vchamilo_get_config('vchamilo', 'home_real_root');
 
-if (empty($course_real_root) || empty($homePath)) {
+if (empty($coursePath) || empty($homePath)) {
     api_not_allowed(true, 'You have to setup the course real root');
 }
 
-// security
-api_protect_admin_script();
-
 if ($id) {
     $mode = 'update';
 } else {
     $mode = $registeronly ? 'register' : 'add' ;
 }
 
-$form = new InstanceForm($plugininstance, $mode);
-$form->definition();
+$vhost = [];
+if ($id) {
+    $sql = "SELECT * FROM vchamilo WHERE id = $id";
+    $result = Database::query($sql);
+    $vhost = Database::fetch_array($result, 'ASSOC');
+}
+
+$form = new InstanceForm($plugininstance, $mode, $vhost);
 
-$actions = '';
-$message = '';
 if ($data = $form->get_data()) {
     include api_get_path(SYS_PLUGIN_PATH).'vchamilo/views/editinstance.controller.php';
 }
 
 if ($id) {
-    $sql = "SELECT * FROM vchamilo WHERE id = $id";
-    $result = Database::query($sql);
-    $vhost = Database::fetch_array($result);
     $vhost['vid'] = $vhost['id'];
     unset($vhost['id']);
     $form->set_data($vhost);
 } else {
-    $data = array();
-    $data['db_host'] = 'localhost';
-    $data['single_database'] = 1;
-    $data['registeronly'] = $registeronly;
-    $form->set_data($data);
+    $vhost['db_host'] = 'localhost';
+    $vhost['registeronly'] = $registeronly;
+    $form->set_data($vhost);
 }
 
 $content = $form->return_form();
 
 $interbreadcrumb[] = array('url' => 'manage.php', 'name' => get_lang('VChamilo'));
 
-$tpl = new Template(get_lang('Instances'), true, true, false, true, false);
-$tpl->assign('actions', $actions);
-$tpl->assign('message', $message);
+$tpl = new Template(get_lang('Instance'), true, true, false, true, false);
 $tpl->assign('content', $content);
 $tpl->display_one_col_template();

+ 28 - 60
plugin/vchamilo/views/editinstance_form.php

@@ -268,7 +268,7 @@ abstract class ChamiloForm
      * @param mixed $default_values object or array of default values
      * @param bool $slashed true if magic quotes applied to data values
      */
-    public function set_data($default_values, $slashed=false)
+    public function set_data($default_values, $slashed = false)
     {
         if (is_object($default_values)) {
             $default_values = (array)$default_values;
@@ -336,15 +336,14 @@ abstract class ChamiloForm
 class InstanceForm extends ChamiloForm
 {
     public $_plugin;
+    public $instance;
 
     /**
      * InstanceForm constructor.
      * @param $plugin
      * @param string $mode
-     * @param null $returnurl
-     * @param null $cancelurl
      */
-    public function __construct($plugin, $mode = 'add', $returnurl = null, $cancelurl = null)
+    public function __construct($plugin, $mode = 'add', $instance = [])
     {
         global $_configuration;
 
@@ -356,6 +355,8 @@ class InstanceForm extends ChamiloForm
 
         $cancelurl = $_configuration['root_web'].'plugin/vchamilo/views/manage.php';
         parent::__construct($mode, $returnurl, $cancelurl);
+        $this->instance = $instance;
+        $this->definition();
     }
 
     /**
@@ -382,8 +383,7 @@ class InstanceForm extends ChamiloForm
         $cform->addElement('text', 'sitename', $this->_plugin->get_lang('sitename'));
         $cform->applyFilter('sitename', 'trim');
 
-        // Shortname.
-        $elementInstitution = $cform->addElement(
+        $cform->addElement(
             'text',
             'institution',
             $this->_plugin->get_lang('institution')
@@ -400,7 +400,6 @@ class InstanceForm extends ChamiloForm
         $cform->applyFilter('root_web', 'trim');
 
         if ($this->_mode == 'update') {
-            $elementInstitution->freeze();
             $elementWeb->freeze();
         }
 
@@ -428,20 +427,6 @@ class InstanceForm extends ChamiloForm
         // Database name.
         $cform->addElement('text', 'main_database', $this->_plugin->get_lang('maindatabase'));
 
-        // Table's prefix.
-        //$cform->addElement('text', 'table_prefix', $this->_plugin->get_lang('tableprefix'));
-
-        // Db's prefix.
-        //$cform->addElement('text', 'db_prefix', $this->_plugin->get_lang('dbprefix'));
-        //$cform->addElement('header', $this->_plugin->get_lang('datalocation'));
-
-        /*$cform->addElement(
-            'text',
-            'course_folder',
-            $this->_plugin->get_lang('coursefolder'),
-            array('id' => 'id_vdatapath')
-        );*/
-
         // Button for testing database connection.
         $cform->addElement(
             'button',
@@ -454,18 +439,6 @@ class InstanceForm extends ChamiloForm
             'onclick="opencnxpopup(\''.$_configuration['root_web'].'\'); return false;"'
         );
 
-        // Button for testing datapath.
-        /*$cform->addElement(
-            'button',
-            'testdatapath',
-            $this->_plugin->get_lang('testdatapath'),
-            'check',
-            'default',
-            'default',
-            '',
-            'onclick="opendatapathpopup(\''.$_configuration['root_web'].'\'); return true;"'
-        );*/
-
         /*
          * Template selection.
          */
@@ -476,38 +449,33 @@ class InstanceForm extends ChamiloForm
 
             // Template choice
             $cform->addElement('select', 'template', $this->_plugin->get_lang('template'), $templateoptions);
+        } else {
+            if ($this->instance) {
+                $cform->addLabel($this->_plugin->get_lang('template'), $this->instance->template);
+            }
         }
 
         $submitstr = $this->_plugin->get_lang('savechanges');
-        $cancelstr = $this->_plugin->get_lang('cancel');
-        $this->add_action_buttons(true, $submitstr, $cancelstr);
+        $this->add_action_buttons(true, $submitstr);
 
         // Rules for the add mode.
-        if ($this->is_in_add_mode()) {
-            $cform->addRule('sitename', $this->_plugin->get_lang('sitenameinputerror'), 'required', null, 'client');
-            $cform->addRule(
-                'institution',
-                $this->_plugin->get_lang('institutioninputerror'),
-                'required',
-                null,
-                'client'
-            );
-            $cform->addRule('root_web', $this->_plugin->get_lang('rootwebinputerror'), 'required', null, 'client');
-            $cform->addRule(
-                'main_database',
-                $this->_plugin->get_lang('databaseinputerror'),
-                'required',
-                null,
-                'client'
-            );
-            /*$cform->addRule(
-                'course_folder',
-                $this->_plugin->get_lang('coursefolderinputerror'),
-                'required',
-                null,
-                'client'
-            );*/
-        }
+
+        $cform->addRule('sitename', $this->_plugin->get_lang('sitenameinputerror'), 'required', null, 'client');
+        $cform->addRule(
+            'institution',
+            $this->_plugin->get_lang('institutioninputerror'),
+            'required',
+            null,
+            'client'
+        );
+        $cform->addRule('root_web', $this->_plugin->get_lang('rootwebinputerror'), 'required', null, 'client');
+        $cform->addRule(
+            'main_database',
+            $this->_plugin->get_lang('databaseinputerror'),
+            'required',
+            null,
+            'client'
+        );
     }
 
     /**

+ 54 - 50
plugin/vchamilo/views/manage.controller.php

@@ -23,14 +23,7 @@ if ($action == 'deleteinstances' || $action == 'disableinstances') {
     Display::addFlash(Display::return_message("Disabling instance"));
     // Make it not visible.
     $vidlist = implode("','", $_REQUEST['vids']);
-    $sql = "
-        UPDATE 
-            {$table}
-        SET
-            visible = 0
-        WHERE
-            id IN ('$vidlist')
-    ";
+    $sql = "UPDATE $table SET visible = 0 WHERE id IN ('$vidlist')";
     Database::query($sql);
     vchamilo_redirect(api_get_path(WEB_PLUGIN_PATH).'vchamilo/views/manage.php');
 }
@@ -38,22 +31,13 @@ if ($action == 'enableinstances') {
 
     Display::addFlash(Display::return_message("Enabling instance"));
     $vidlist = implode("','", $_REQUEST['vids']);
-    $sql = "
-        UPDATE 
-            {$table}
-        SET
-            visible = 1
-        WHERE
-            id IN ('$vidlist')
-    ";
+    $sql = " UPDATE $table SET  visible = 1 WHERE id IN ('$vidlist') ";
     Database::query($sql);
     vchamilo_redirect(api_get_path(WEB_PLUGIN_PATH).'vchamilo/views/manage.php');
 }
 
 if ($action == 'fulldeleteinstances') {
 
-    Display::addFlash(Display::return_message("Destroying instance"));
-
     // Removes everything.
     if (empty($automation)) {
         $vidlist = implode("','", $_REQUEST['vids']);
@@ -61,38 +45,39 @@ if ($action == 'fulldeleteinstances') {
     } else {
         $todelete = Database::select('*', 'vchamilo', array('where' => array("root_web = '{$n->root_web}' " => array())));
     }
+    if ($todelete) {
+        foreach ($todelete as $fooid => $instance) {
+            $slug = $instance['slug'];
 
-    foreach ($todelete as $fooid => $instance) {
-        $slug = $instance['slug'];
+            Display::addFlash(Display::return_message("Removing instance: ".$instance->root_web));
 
-        Display::addFlash(Display::return_message("Dropping instance databases"));
-        vchamilo_drop_databases($instance);
+            vchamilo_drop_databases($instance);
 
-        // Remove all files and eventual symlinks
+            // Remove all files and eventual symlinks
 
-        $absalternatecourse = vchamilo_get_config('vchamilo', 'course_real_root');
-        $coursedir = $absalternatecourse.$slug;
+            $absalternatecourse = vchamilo_get_config('vchamilo', 'course_real_root');
+            $coursedir = $absalternatecourse.$slug;
 
-        Display::addFlash(Display::return_message("Deleting $coursedir"));
+            Display::addFlash(Display::return_message("Deleting $coursedir"));
 
-        if ($absalternatehome = vchamilo_get_config('vchamilo', 'home_real_root')) {
-            $homedir = str_replace('//', '/', $absalternatehome.'/'.$slug);
+            if ($absalternatehome = vchamilo_get_config('vchamilo', 'home_real_root')) {
+                $homedir = str_replace('//', '/', $absalternatehome.'/'.$slug);
 
-            Display::addFlash(Display::return_message("Deleting $homedir"));
-            removeDir($homedir);
-        }
+                Display::addFlash(Display::return_message("Deleting $homedir"));
+                removeDir($homedir);
+            }
 
-        // delete archive
-        if ($absalternatearchive = vchamilo_get_config('vchamilo', 'archive_real_root')){
-            $archivedir = str_replace('//', '/', $absalternatearchive.'/'.$slug);
+            // delete archive
+            if ($absalternatearchive = vchamilo_get_config('vchamilo', 'archive_real_root')) {
+                $archivedir = str_replace('//', '/', $absalternatearchive.'/'.$slug);
 
-            Display::addFlash(Display::return_message("Deleting $archivedir"));
-            removeDir($archivedir);
-        }
+                Display::addFlash(Display::return_message("Deleting $archivedir"));
+                removeDir($archivedir);
+            }
 
-        Display::addFlash(Display::return_message("Removing vchamilo record"));
-        $sql = "DELETE FROM {$table} WHERE id = {$instance->id}";
-        Database::query($sql);
+            $sql = "DELETE FROM {$table} WHERE id = {$instance->id}";
+            Database::query($sql);
+        }
     }
 }
 
@@ -122,6 +107,9 @@ if ($action == 'snapshotinstance') {
     $absolute_sqldir = $backupDir.'dump.sql';
 
     if (!is_dir($backupDir)) {
+        Display::addFlash(
+            Display::return_message('Directory created: '.$backupDir)
+        );
         mkdir($backupDir, 0777, true);
     }
 
@@ -145,7 +133,7 @@ if ($action == 'snapshotinstance') {
 
             $tpl = new Template(get_lang('Snapshot'), true, true, false, true, false);
             $tpl->assign('actions', '');
-            $tpl->assign('message', $plugininstance->get_lang('vchamilosnapshot1'));
+            $tpl->assign('message', '<h4>'.$plugininstance->get_lang('vchamilosnapshot1').'</h4>');
             $tpl->assign('content', $content);
             $tpl->display_one_col_template();
 
@@ -180,14 +168,11 @@ if ($action == 'snapshotinstance') {
         if ($vchamilostep == 1) {
             // Auto dump the databases in a master template folder.
             // this will create three files : dump.sql
-            $errors = vchamilo_dump_databases($vchamilo, $absolute_sqldir);
+            $result = vchamilo_dump_databases($vchamilo, $absolute_sqldir);
 
             if (empty($fullautomation)) {
-                if(!empty($errors)) {
+                if (!$result) {
                     $actionurl = $_configuration['root_web'].'/plugin/vchamilo/views/manage.php';
-
-                    $message = vchamilo_print_error($errors, true);
-
                     $content .= '<p><form name"single" action="'.$actionurl.'">';
                     $content .= '<input type="submit" name="go_btn" value="'.$plugininstance->get_lang('cancel').'" />';
                     $content .= '</form></p>';
@@ -197,7 +182,7 @@ if ($action == 'snapshotinstance') {
                     $message = $plugininstance->get_lang('vchamilosnapshot2');
 
                     Display::addFlash(
-                        Display::return_message('mysql dump: '.$absolute_sqldir)
+                        Display::return_message('Database file created: '.$absolute_sqldir)
                     );
 
                     $content .= '<form name"single" action="'.$actionurl.'">';
@@ -210,7 +195,7 @@ if ($action == 'snapshotinstance') {
 
                 $tpl = new Template(get_lang('Snapshot'), true, true, false, true, false);
                 $tpl->assign('actions', '');
-                $tpl->assign('message', $message);
+                $tpl->assign('message', '<h4>'.$message.'</h4>');
                 $tpl->assign('content', $content);
                 $tpl->display_one_col_template();
 
@@ -218,10 +203,10 @@ if ($action == 'snapshotinstance') {
             }
         }
 
-        Display::addFlash(Display::return_message("Copying from $homePath to {$absolute_datadir}/home "));
+        Display::addFlash(Display::return_message("Copying from '$homePath' to '{$absolute_datadir}/home' "));
         copyDirTo($homePath, $absolute_datadir.'/home/', false);
 
-        Display::addFlash(Display::return_message("Copying from $coursePath to $absolute_datadir/courses "));
+        Display::addFlash(Display::return_message("Copying from '$coursePath' to '$absolute_datadir/courses' "));
         copyDirTo($coursePath, $absolute_datadir.'/courses/', false);
         /*Display::addFlash(Display::return_message("Copying from $archivePath to {$absolute_datadir}/archive "));
         copyDirTo($varchivepath, $absolute_datadir.'/archive', false);*/
@@ -239,6 +224,25 @@ if ($action == 'snapshotinstance') {
         if (empty($fullautomation)) {
             Display::addFlash(Display::return_message($plugininstance->get_lang('successfinishedcapture'), 'success'));
 
+            if (empty($vid)) {
+                $template = vchamilo_get_config('vchamilo', 'default_template');
+                if (empty($template)) {
+                    Display::addFlash(Display::return_message('Set default template as <b>'.$vhost->slug.'</b>', 'success', false));
+                    $params = [
+                        'subkey' => 'vchamilo',
+                        'title' => 'default_template',
+                        'type' => 'setting',
+                        'category' => 'Plugins',
+                        'variable' => 'vchamilo_default_template',
+                        'selected_value' => $vhost->slug,
+                        'access_url_changeable' => 0
+                    ];
+                    api_set_setting_simple($params);
+                } else {
+                    Display::addFlash(Display::return_message('Default template is: <b>'.$vhost->slug.'</b>', 'success', false));
+                }
+            }
+
             $actionurl = $_configuration['root_web'].'/plugin/vchamilo/views/manage.php';
             $content .= '<form name"single" action="'.$actionurl.'">';
             $content .= '<input class="btn btn-primary" type="submit" name="go_btn" value="'.$plugininstance->get_lang('backtoindex').'" />';

+ 23 - 11
plugin/vchamilo/views/manage.php

@@ -5,22 +5,21 @@ require_once '../../../main/inc/global.inc.php';
 require_once api_get_path(SYS_PLUGIN_PATH).'vchamilo/lib.php';
 require_once api_get_path(SYS_PLUGIN_PATH).'vchamilo/lib/vchamilo_plugin.class.php';
 
+// security
+api_protect_admin_script();
+
 $action = isset($_GET['what']) ? $_GET['what'] : '';
 define('CHAMILO_INTERNAL', true);
 
 $plugininstance = VChamiloPlugin::create();
 $thisurl = api_get_path(WEB_PLUGIN_PATH).'vchamilo/views/manage.php';
 
-api_protect_admin_script();
-
 require_js('host_list.js', 'vchamilo');
 
 if ($action) {
     require_once api_get_path(SYS_PLUGIN_PATH).'vchamilo/views/manage.controller.php';
 }
 
-$content = Display::page_header('VChamilo Instances');
-
 $query = "SELECT * FROM vchamilo";
 $result = Database::query($query);
 $instances = array();
@@ -28,6 +27,16 @@ while ($instance = Database::fetch_object($result)) {
     $instances[$instance->id] = $instance;
 }
 
+$templates = vchamilo_get_available_templates(false);
+
+if (empty($templates)) {
+    $url = api_get_path(WEB_PLUGIN_PATH).'vchamilo/views/manage.php?what=snapshotinstance';
+    $url = Display::url($url, $url);
+    Display::addFlash(
+        Display::return_message('You need to create a snapshot of master first here:'.$url, 'info', false)
+    );
+}
+
 $table = new HTML_Table(array('class' => 'data_table'));
 $column = 0;
 $row = 0;
@@ -117,6 +126,8 @@ $items = [
     ]
 ];
 
+$content = Display::page_header('VChamilo Instances');
+
 $content .= Display::actions($items);
 $content .= '<form action="'.$thisurl.'">';
 $content .= $table->toHtml();
@@ -124,23 +135,24 @@ $content .= $table->toHtml();
 $selectionoptions = array('<option value="0" selected="selected">'.$plugininstance->get_lang('choose').'</option>');
 $selectionoptions[] = '<option value="deleteinstances">'.$plugininstance->get_lang('deleteinstances').'</option>';
 $selectionoptions[] = '<option value="enableinstances">'.$plugininstance->get_lang('enableinstances').'</option>';
-$selectionoptions[] = '<option value="fulldeleteinstances">'.$plugininstance->get_lang('destroyinstances').'</option>';
+$selectionoptions[] = '<option value="fulldeleteinstances">'.$plugininstance->get_lang(
+        'destroyinstances'
+    ).'</option>';
 $selectionoptions[] = '<option value="clearcache">'.$plugininstance->get_lang('clearcache').'</option>';
 $selectionoptions[] = '<option value="setconfigvalue">'.$plugininstance->get_lang('setconfigvalue').'</option>';
 $selectionaction = '<select name="what" onchange="this.form.submit()">'.implode('', $selectionoptions).'</select>';
 
-$content .=  '<div class"vchamilo-right"><div></div><div>
+$content .= '<div class"vchamilo-right"><div></div><div>
 <a href="javascript:selectallhosts()">'.$plugininstance->get_lang('selectall').'</a> - 
 <a href="javascript:deselectallhosts()">'.$plugininstance->get_lang('selectnone').'</a> - 
 &nbsp; - '.$plugininstance->get_lang('withselection').' '.$selectionaction.'</div></div>';
 
-$content .=  '</form>';
+$content .= '</form>';
 
-$actions = '';
-$message = '';
+if (empty($templates)) {
+    $content = '';
+}
 
 $tpl = new Template(get_lang('VChamilo'), true, true, false, true, false);
-$tpl->assign('actions', $actions);
-$tpl->assign('message', $message);
 $tpl->assign('content', $content);
 $tpl->display_one_col_template();

+ 2 - 0
plugin/vchamilo/views/manage.testcnx.php

@@ -12,6 +12,8 @@ require_once '../../../main/inc/global.inc.php';
 require_once api_get_path(SYS_PLUGIN_PATH).'vchamilo/lib/vchamilo_plugin.class.php';
 require_once api_get_path(SYS_PLUGIN_PATH).'vchamilo/lib.php';
 
+api_protect_admin_script();
+
 $plugininstance = VChamiloPlugin::create();
 
 // Retrieve parameters for database connection test.

+ 2 - 0
plugin/vchamilo/views/manage.testdatapath.php

@@ -12,6 +12,8 @@ require_once '../../../main/inc/global.inc.php';
 require_once api_get_path(SYS_PLUGIN_PATH).'vchamilo/lib/vchamilo_plugin.class.php';
 require_once api_get_path(SYS_PLUGIN_PATH).'vchamilo/lib.php';
 
+api_protect_admin_script();
+
 $plugininstance = VChamiloPlugin::create();
 
 // Retrieve parameters for database connection test.

+ 2 - 1
plugin/vchamilo/views/syncparams.controller.php

@@ -1,10 +1,11 @@
 <?php
 
+api_protect_admin_script();
+
 $sql = "SELECT * FROM vchamilo";
 $result = Database::query($sql);
 $vchamilos = Database::store_result($result);
 
-
 // propagate in all known vchamilos a setting
 if ($action == 'syncall') {
     $keys = array_keys($_REQUEST);

+ 2 - 2
plugin/vchamilo/views/syncparams.php

@@ -3,6 +3,8 @@
 $cidReset = true;
 require_once '../../../main/inc/global.inc.php';
 
+api_protect_admin_script();
+
 require_once api_get_path(SYS_PLUGIN_PATH).'vchamilo/lib.php';
 require_once api_get_path(SYS_PLUGIN_PATH).'vchamilo/lib/vchamilo_plugin.class.php';
 
@@ -12,8 +14,6 @@ define('CHAMILO_INTERNAL', true);
 $plugininstance = VChamiloPlugin::create();
 $thisurl = api_get_path(WEB_PLUGIN_PATH).'vchamilo/views/manage.php';
 
-api_protect_admin_script();
-
 if ($action){
     require_once(api_get_path(SYS_PLUGIN_PATH).'vchamilo/views/syncparams.controller.php');
 }