Esempio n. 1
0
 function init()
 {
     global $CFG;
     if (empty($CFG->mnet_dispatcher_mode)) {
         set_config('mnet_dispatcher_mode', 'off');
     }
     // Bootstrap the object data on first load.
     if (empty($CFG->mnet_localhost_id)) {
         $this->wwwroot = $CFG->wwwroot;
         if (empty($_SERVER['SERVER_ADDR'])) {
             // SERVER_ADDR is only returned by Apache-like webservers
             $my_hostname = mnet_get_hostname_from_uri($CFG->wwwroot);
             $my_ip = gethostbyname($my_hostname);
             // Returns unmodified hostname on failure. DOH!
             if ($my_ip == $my_hostname) {
                 $this->ip_address = 'UNKNOWN';
             } else {
                 $this->ip_address = $my_ip;
             }
         } else {
             $this->ip_address = $_SERVER['SERVER_ADDR'];
         }
         $this->id = insert_record('mnet_host', $this, true);
         set_config('mnet_localhost_id', $this->id);
         $this->get_keypair();
     } else {
         $hostobject = get_record('mnet_host', 'id', $CFG->mnet_localhost_id);
         if (is_object($hostobject)) {
             $temparr = get_object_vars($hostobject);
             foreach ($temparr as $key => $value) {
                 $this->{$key} = $value;
             }
             unset($hostobject, $temparr);
         } else {
             return false;
         }
         // Unless this is an install/upgrade, generate the SSL keys.
         if (empty($this->public_key)) {
             $this->get_keypair();
         }
     }
     // We need to set up a record that represents 'all hosts'. Any rights
     // granted to this host will be conferred on all hosts.
     if (empty($CFG->mnet_all_hosts_id)) {
         $hostobject = new stdClass();
         $hostobject->wwwroot = '';
         $hostobject->ip_address = '';
         $hostobject->public_key = '';
         $hostobject->public_key_expires = '';
         $hostobject->last_connect_time = '0';
         $hostobject->last_log_id = '0';
         $hostobject->deleted = 0;
         $hostobject->name = 'All Hosts';
         $hostobject->id = insert_record('mnet_host', $hostobject, true);
         set_config('mnet_all_hosts_id', $hostobject->id);
         $CFG->mnet_all_hosts_id = $hostobject->id;
         unset($hostobject);
     }
 }
Esempio n. 2
0
 function bootstrap($wwwroot, $pubkey = null, $application)
 {
     if (substr($wwwroot, -1, 1) == '/') {
         $wwwroot = substr($wwwroot, 0, -1);
     }
     if (!$this->set_wwwroot($wwwroot)) {
         $hostname = mnet_get_hostname_from_uri($wwwroot);
         // Get the IP address for that host - if this fails, it will
         // return the hostname string
         $ip_address = gethostbyname($hostname);
         // Couldn't find the IP address?
         if ($ip_address === $hostname && !preg_match('/^\\d+\\.\\d+\\.\\d+.\\d+$/', $hostname)) {
             $this->error[] = array('code' => 2, 'text' => get_string("noaddressforhost", 'mnet'));
             return false;
         }
         $this->name = stripslashes($wwwroot);
         $this->updateparams->name = $wwwroot;
         // TODO: In reality, this will be prohibitively slow... need another
         // default - maybe blank string
         $homepage = file_get_contents($wwwroot);
         if (!empty($homepage)) {
             $count = preg_match("@<title>(.*)</title>@siU", $homepage, $matches);
             if ($count > 0) {
                 $this->name = $matches[1];
                 $this->updateparams->name = addslashes($matches[1]);
             }
         }
         $this->wwwroot = stripslashes($wwwroot);
         $this->updateparams->wwwroot = $wwwroot;
         $this->ip_address = $ip_address;
         $this->updateparams->ip_address = $ip_address;
         $this->deleted = 0;
         $this->updateparams->deleted = 0;
         $this->application = get_record('mnet_application', 'name', $application);
         if (empty($this->application)) {
             $this->application = get_record('mnet_application', 'name', 'moodle');
         }
         $this->applicationid = $this->application->id;
         $this->updateparams->applicationid = $this->application->id;
         if (empty($pubkey)) {
             $pubkeytemp = clean_param(mnet_get_public_key($this->wwwroot, $this->application), PARAM_PEM);
         } else {
             $pubkeytemp = clean_param($pubkey, PARAM_PEM);
         }
         $this->public_key_expires = $this->check_common_name($pubkeytemp);
         if ($this->public_key_expires == false) {
             return false;
         }
         $this->updateparams->public_key_expires = $this->public_key_expires;
         $this->updateparams->public_key = $pubkeytemp;
         $this->public_key = $pubkeytemp;
         $this->last_connect_time = 0;
         $this->updateparams->last_connect_time = 0;
         $this->last_log_id = 0;
         $this->updateparams->last_log_id = 0;
     }
     return true;
 }
Esempio n. 3
0
 function bootstrap($wwwroot, $pubkey = null, $application)
 {
     global $DB;
     if (substr($wwwroot, -1, 1) == '/') {
         $wwwroot = substr($wwwroot, 0, -1);
     }
     // If a peer record already exists for this address,
     // load that info and return
     if ($this->set_wwwroot($wwwroot)) {
         return true;
     }
     $hostname = mnet_get_hostname_from_uri($wwwroot);
     // Get the IP address for that host - if this fails, it will return the hostname string
     $ip_address = gethostbyname($hostname);
     // Couldn't find the IP address?
     if ($ip_address === $hostname && !preg_match('/^\\d+\\.\\d+\\.\\d+.\\d+$/', $hostname)) {
         throw new moodle_exception('noaddressforhost', 'mnet', '', $hostname);
     }
     $this->name = $wwwroot;
     // TODO: In reality, this will be prohibitively slow... need another
     // default - maybe blank string
     $homepage = download_file_content($wwwroot);
     if (!empty($homepage)) {
         $count = preg_match("@<title>(.*)</title>@siU", $homepage, $matches);
         if ($count > 0) {
             $this->name = $matches[1];
         }
     }
     $this->wwwroot = $wwwroot;
     $this->ip_address = $ip_address;
     $this->deleted = 0;
     $this->application = $DB->get_record('mnet_application', array('name' => $application));
     if (empty($this->application)) {
         $this->application = $DB->get_record('mnet_application', array('name' => 'moodle'));
     }
     $this->applicationid = $this->application->id;
     if (empty($pubkey)) {
         $this->public_key = clean_param(mnet_get_public_key($this->wwwroot, $this->application), PARAM_PEM);
     } else {
         $this->public_key = clean_param($pubkey, PARAM_PEM);
     }
     $this->public_key_expires = $this->check_common_name($this->public_key);
     $this->last_connect_time = 0;
     $this->last_log_id = 0;
     if ($this->public_key_expires == false) {
         $this->public_key == '';
         return false;
     }
     $this->bootstrapped = true;
 }
Esempio n. 4
0
 function replace_keys()
 {
     global $DB, $CFG;
     $keypair = mnet_generate_keypair();
     if (empty($keypair)) {
         error_log('Can not generate keypair, sorry');
         return;
     }
     $this->keypair = array();
     $this->keypair = $keypair;
     $this->public_key = $this->keypair['certificate'];
     $details = openssl_x509_parse($this->public_key);
     $this->public_key_expires = $details['validTo_time_t'];
     $this->wwwroot = $CFG->wwwroot;
     if (empty($_SERVER['SERVER_ADDR'])) {
         // SERVER_ADDR is only returned by Apache-like webservers
         $my_hostname = mnet_get_hostname_from_uri($CFG->wwwroot);
         $my_ip = gethostbyname($my_hostname);
         // Returns unmodified hostname on failure. DOH!
         if ($my_ip == $my_hostname) {
             $this->ip_address = 'UNKNOWN';
         } else {
             $this->ip_address = $my_ip;
         }
     } else {
         $this->ip_address = $_SERVER['SERVER_ADDR'];
     }
     set_config('openssl', implode('@@@@@@@@', $this->keypair), 'mnet');
     $DB->update_record('mnet_host', $this);
     error_log('New public key has been generated. It expires ' . date('Y/m/d h:i:s', $this->public_key_expires));
 }
 function replace_keys()
 {
     global $CFG;
     $this->keypair = array();
     $this->keypair = mnet_generate_keypair();
     $this->public_key = $this->keypair['certificate'];
     $this->wwwroot = $CFG->wwwroot;
     $details = openssl_x509_parse($this->public_key);
     $this->public_key_expires = $details['validTo_time_t'];
     if (empty($_SERVER['SERVER_ADDR'])) {
         // SERVER_ADDR is only returned by Apache-like webservers
         $my_hostname = mnet_get_hostname_from_uri($CFG->wwwroot);
         $my_ip = gethostbyname($my_hostname);
         // Returns unmodified hostname on failure. DOH!
         if ($my_ip == $my_hostname) {
             $this->ip_address = 'UNKNOWN';
         } else {
             $this->ip_address = $my_ip;
         }
     } else {
         $this->ip_address = $_SERVER['SERVER_ADDR'];
     }
     set_config('openssl', implode('@@@@@@@@', $this->keypair), 'mnet');
     // clone the proper object and then unset anything that isn't required to go into the database
     // most fields don't matter but things that are arrays, will break things.
     $dbobject = (object) clone $this;
     unset($dbobject->keypair);
     update_record('mnet_host', addslashes_object($dbobject));
     error_log('New public key has been generated. It expires ' . date('Y/m/d h:i:s', $this->public_key_expires));
 }
 function bootstrap($wwwroot, $pubkey = null, $application, $force = false, $localname = '')
 {
     global $DB;
     if (substr($wwwroot, -1, 1) == '/') {
         $wwwroot = substr($wwwroot, 0, -1);
     }
     if (!$this->set_wwwroot($wwwroot)) {
         $hostname = mnet_get_hostname_from_uri($wwwroot);
         // Get the IP address for that host - if this fails, it will
         // return the hostname string
         $ip_address = gethostbyname($hostname);
         // Couldn't find the IP address?
         if ($ip_address === $hostname && !preg_match('/^\\d+\\.\\d+\\.\\d+.\\d+$/', $hostname)) {
             $this->errors[] = 'ErrCode 2 - ' . get_string("noaddressforhost", 'mnet');
             return false;
         }
         if (empty($localname)) {
             $this->name = stripslashes($wwwroot);
             $this->updateparams->name = $wwwroot;
         } else {
             $this->name = $localname;
             $this->updateparams->name = $localname;
         }
         // TODO: In reality, this will be prohibitively slow... need another
         // default - maybe blank string
         $homepage = file_get_contents($wwwroot);
         if (!empty($homepage)) {
             $count = preg_match("@<title>(.*)</title>@siU", $homepage, $matches);
             if ($count > 0) {
                 $this->name = $matches[1];
                 $this->updateparams->name = str_replace("'", "''", $matches[1]);
             }
         } else {
             // debug_trace("Missing remote real name guessing, no other side response");
         }
         // debug_trace("final name : ".$this->name);
         $this->wwwroot = stripslashes($wwwroot);
         $this->updateparams->wwwroot = $wwwroot;
         $this->ip_address = $ip_address;
         $this->updateparams->ip_address = $ip_address;
         $this->deleted = 0;
         $this->updateparams->deleted = 0;
         $this->application = $DB->get_record('mnet_application', array('name' => $application));
         if (empty($this->application)) {
             $this->application = $DB->get_record('mnet_application', array('name' => 'moodle'));
         }
         $this->applicationid = $this->application->id;
         $this->updateparams->applicationid = $this->application->id;
         // start bootstraping as usual through the system command
         $pubkeytemp = clean_param(mnet_get_public_key($this->wwwroot, $this->application), PARAM_PEM);
         if (empty($pubkey)) {
             // This is the key difference : force the exchange using vmoodle RPC keyswap !!
             if (empty($pubkeytemp)) {
                 $pubkeytemp = clean_param(mnet_get_public_key($this->wwwroot, $this->application, $force), PARAM_PEM);
             }
         } else {
             $pubkeytemp = clean_param($pubkey, PARAM_PEM);
         }
         $this->public_key_expires = $this->check_common_name($pubkeytemp);
         if ($this->public_key_expires == false) {
             return false;
         }
         $this->updateparams->public_key_expires = $this->public_key_expires;
         $this->updateparams->public_key = $pubkeytemp;
         $this->public_key = $pubkeytemp;
         $this->last_connect_time = 0;
         $this->updateparams->last_connect_time = 0;
         $this->last_log_id = 0;
         $this->updateparams->last_log_id = 0;
     }
     return true;
 }
Esempio n. 7
0
/**
 * Loads a complete database dump from a template, and does some update.
 * @uses $CFG
 * @param object $vmoodledata All the Host_form data.
 * @param object $this_as_host The mnet_host record that represents the master.
 * @return bool If true, fixing database from template was sucessful, otherwise false.
 */
function vmoodle_fix_database($vmoodledata, $this_as_host)
{
    global $CFG, $SITE;
    // debug_trace('fixing_database ; IN');
    $manifest = vmoodle_get_vmanifest($vmoodledata->vtemplate);
    $hostname = mnet_get_hostname_from_uri($CFG->wwwroot);
    $cfgipaddress = gethostbyname($hostname);
    // SQL files paths.
    $temporarysetup_path = $CFG->dataroot . '/vmoodle/' . $vmoodledata->vtemplate . '_sql/vmoodle_setup_template.temp.sql';
    // debug_trace('fixing_database ; opening setup script file');
    if (!($FILE = fopen($temporarysetup_path, 'wb'))) {
        print_error('couldnotwritethesetupscript', 'local_vmoodle');
        return false;
    }
    $PREFIX = $vmoodledata->vdbprefix;
    $vmoodledata->description = str_replace("'", "''", $vmoodledata->description);
    // Setup moodle name and description.
    fwrite($FILE, "UPDATE {$PREFIX}course SET fullname='{$vmoodledata->name}', shortname='{$vmoodledata->shortname}', summary='{$vmoodledata->description}' WHERE category = 0 AND id = 1;\n");
    // Setup a suitable cookie name.
    $cookiename = clean_param($vmoodledata->shortname, PARAM_ALPHANUM);
    fwrite($FILE, "UPDATE {$PREFIX}config SET value='{$cookiename}' WHERE name = 'sessioncookie';\n\n");
    // Delete all logs.
    fwrite($FILE, "DELETE FROM {$PREFIX}log;\n\n");
    fwrite($FILE, "DELETE FROM {$PREFIX}mnet_log;\n\n");
    fwrite($FILE, "DELETE FROM {$PREFIX}mnet_session;\n\n");
    // purge mnet logs and sessions
    /*
     * we need :
     * clean host to service
     * clean mnet_hosts unless All Hosts and self record
     * rebind self record to new wwwroot, ip and cleaning public key
     */
    fwrite($FILE, "--\n-- Cleans all mnet tables but keeping service configuration in place \n--\n");
    // We first remove all services. Services will be next rebuild based on template or minimal strategy.
    // We expect all service declaraton are ok in the template DB as the template comes from homothetic installation.
    fwrite($FILE, "DELETE FROM {$PREFIX}mnet_host2service;\n\n");
    // We first remove all services. Services will be next rebuild based on template or minimal strategy.
    fwrite($FILE, "DELETE FROM {$PREFIX}mnet_host WHERE wwwroot != '' AND wwwroot != '{$manifest['templatewwwroot']}';\n\n");
    $vmoodlenodename = str_replace("'", "''", $vmoodledata->name);
    fwrite($FILE, "UPDATE {$PREFIX}mnet_host SET id = 1, wwwroot = '{$vmoodledata->vhostname}', name = '{$vmoodlenodename}' , public_key = '', public_key_expires = 0, ip_address = '{$cfgipaddress}'  WHERE wwwroot = '{$manifest['templatewwwroot']}';\n\n");
    fwrite($FILE, "UPDATE {$PREFIX}config SET value = 1 WHERE name = 'mnet_localhost_id';\n\n");
    // ensure consistance
    fwrite($FILE, "UPDATE {$PREFIX}user SET deleted = 1 WHERE auth = 'mnet' AND username != 'admin';\n\n");
    // disable all mnet users
    /* 
     * this is necessary when using a template from another location or deployment target as
     * the salt may have changed. We would like that all primary admins be the same techn admin.
     */
    $localadmin = get_admin();
    fputs($FILE, "--\n-- Force physical admin with same credentials than in master.  \n--\n");
    fwrite($FILE, "UPDATE {$PREFIX}user SET password = '******' WHERE auth = 'manual' AND username = '******';\n\n");
    if ($vmoodledata->mnet == -1) {
        // NO MNET AT ALL.
        /*
         * we need :
         * disable mnet
         */
        fputs($FILE, "UPDATE {$PREFIX}config SET value = 'off' WHERE name = 'mnet_dispatcher_mode';\n\n");
    } else {
        // ALL OTHER CASES.
        /*
         * we need : 
         * enable mnet
         * push our master identity in mnet_host table
         */
        fputs($FILE, "UPDATE {$PREFIX}config SET value = 'strict' WHERE name = 'mnet_dispatcher_mode';\n\n");
        fputs($FILE, "INSERT INTO {$PREFIX}mnet_host (wwwroot, ip_address, name, public_key, applicationid, public_key_expires) VALUES ('{$this_as_host->wwwroot}', '{$this_as_host->ip_address}', '{$SITE->fullname}', '{$this_as_host->public_key}', {$this_as_host->applicationid}, '{$this_as_host->public_key_expires}');\n\n");
        fputs($FILE, "--\n-- Enable the service 'mnetadmin, sso_sp and sso_ip' with host which creates this host.  \n--\n");
        fputs($FILE, "INSERT INTO {$PREFIX}mnet_host2service VALUES (null, (SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'), (SELECT id FROM {$PREFIX}mnet_service WHERE name LIKE 'mnetadmin'), 1, 0);\n\n");
        fputs($FILE, "INSERT INTO {$PREFIX}mnet_host2service VALUES (null, (SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'), (SELECT id FROM {$PREFIX}mnet_service WHERE name LIKE 'sso_sp'), 1, 0);\n\n");
        fputs($FILE, "INSERT INTO {$PREFIX}mnet_host2service VALUES (null, (SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'), (SELECT id FROM {$PREFIX}mnet_service WHERE name LIKE 'sso_idp'), 0, 1);\n\n");
        fputs($FILE, "--\n-- Insert master host user admin.  \n--\n");
        fputs($FILE, "INSERT INTO {$PREFIX}user (auth, confirmed, policyagreed, deleted, mnethostid, username, password) VALUES ('mnet', 1, 0, 0, (SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'), 'admin', '');\n\n");
        fputs($FILE, "--\n-- Links role and capabilites for master host admin.  \n--\n");
        $roleid = "(SELECT id FROM {$PREFIX}role WHERE shortname LIKE 'manager')";
        $contextid = 1;
        $userid = "(SELECT id FROM {$PREFIX}user WHERE auth LIKE 'mnet' AND username = '******' AND mnethostid = (SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'))";
        $timemodified = time();
        $modifierid = $userid;
        $component = "''";
        $itemid = 0;
        $sortorder = 1;
        fputs($FILE, "INSERT INTO {$PREFIX}role_assignments(id,roleid,contextid,userid,timemodified,modifierid,component,itemid,sortorder) VALUES (0, {$roleid}, {$contextid}, {$userid}, {$timemodified}, {$modifierid}, {$component}, {$itemid}, {$sortorder});\n\n");
        fputs($FILE, "--\n-- Add new network admin to local siteadmins.  \n--\n");
        $adminidsql = "(SELECT id FROM {$PREFIX}user WHERE auth LIKE 'mnet' AND username = '******' AND mnethostid = (SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'))";
        fputs($FILE, "UPDATE {$PREFIX}config SET value = CONCAT(value, ',', {$adminidsql}) WHERE name = 'siteadmins';\n");
        fputs($FILE, "--\n-- Create a disposable key for renewing new host's keys.  \n--\n");
        fputs($FILE, "INSERT INTO {$PREFIX}config (name, value) VALUES ('bootstrap_init', '{$this_as_host->wwwroot}');\n");
    }
    fclose($FILE);
    // debug_trace('fixing_database ; setup script written');
    $sqlcmd = vmoodle_get_database_dump_cmd($vmoodledata);
    // Make final commands to execute, depending on the database type.
    $import = $sqlcmd . $temporarysetup_path;
    // Prints log messages in the page and in 'cmd.log'.
    // debug_trace("fixing_database ; executing $import ");
    // Ensure utf8 is correctly handled by php exec().
    // @see http://stackoverflow.com/questions/10028925/call-a-program-via-shell-exec-with-utf-8-text-input
    // this is required only with PHP exec through a web access.
    if (!CLI_SCRIPT) {
        putenv('LANG=en_US.utf-8');
    }
    // Execute the command.
    exec($import, $output, $return);
    // debug_trace(implode("\n", $output)."\n");
    // Remove temporary files.
    //    if(!unlink($temporarysetup_path)){
    //        return false;
    //    }
    // End.
    return true;
}
Esempio n. 8
0
/**
 * Loads a complete database dump from a template, and does some update.
 * @uses $CFG
 * @param object $vmoodledata All the Host_form data.
 * @param object $this_as_host The mnet_host record that represents the master.
 * @return bool If true, fixing database from template was sucessful, otherwise false.
 */
function vmoodle_fix_database($vmoodledata, $this_as_host)
{
    global $CFG, $SITE;
    // debug_trace('fixing_database ; IN');
    $manifest = vmoodle_get_vmanifest($vmoodledata->vtemplate);
    $hostname = mnet_get_hostname_from_uri($CFG->wwwroot);
    $cfgipaddress = gethostbyname($hostname);
    // SQL files paths.
    $temporarysetup_path = $CFG->dataroot . '/vmoodle/' . $vmoodledata->vtemplate . '_sql/vmoodle_setup_template.temp.sql';
    // debug_trace('fixing_database ; opening setup script file');
    if (!($FILE = fopen($temporarysetup_path, 'wb'))) {
        print_error('couldnotwritethesetupscript', 'local_vmoodle');
        return false;
    }
    $PREFIX = $vmoodledata->vdbprefix;
    $vmoodledata->description = str_replace("'", "''", $vmoodledata->description);
    $vmoodledata->name = str_replace("'", "''", $vmoodledata->name);
    $requestsList = array();
    // Setup moodle name and description.
    $requestsList[0] = "UPDATE {$PREFIX}course SET fullname='{$vmoodledata->name}', shortname='{$vmoodledata->shortname}', summary='{$vmoodledata->description}' WHERE category = 0 AND id = 1";
    fwrite($FILE, $requestsList[0] . ";\n");
    // Setup a suitable cookie name.
    $cookiename = clean_param($vmoodledata->shortname, PARAM_ALPHANUM);
    $requestsList[1] = "UPDATE {$PREFIX}config SET value='{$cookiename}' WHERE name = 'sessioncookie'";
    fwrite($FILE, $requestsList[1] . ";\n\n");
    // Delete all logs.
    $requestsList[2] = "DELETE FROM {$PREFIX}log";
    fwrite($FILE, $requestsList[2] . ";\n\n");
    $requestsList[3] = "DELETE FROM {$PREFIX}mnet_log";
    fwrite($FILE, $requestsList[3] . ";\n\n");
    $requestsList[4] = "DELETE FROM {$PREFIX}mnet_session";
    fwrite($FILE, $requestsList[4] . ";\n\n");
    // purge mnet logs and sessions
    /*
     * we need :
     * clean host to service
     * clean mnet_hosts unless All Hosts and self record
     * rebind self record to new wwwroot, ip and cleaning public key
     */
    fwrite($FILE, "--\n-- Cleans all mnet tables but keeping service configuration in place \n--\n");
    // We first remove all services. Services will be next rebuild based on template or minimal strategy.
    // We expect all service declaraton are ok in the template DB as the template comes from homothetic installation.
    $requestsList[5] = "DELETE FROM {$PREFIX}mnet_host2service";
    fwrite($FILE, $requestsList[5] . ";\n\n");
    // We first remove all services. Services will be next rebuild based on template or minimal strategy.
    $requestsList[6] = "DELETE FROM {$PREFIX}mnet_host WHERE wwwroot != '' AND wwwroot != '{$manifest['templatewwwroot']}'";
    fwrite($FILE, $requestsList[6] . ";\n\n");
    $vmoodlenodename = str_replace("'", "''", $vmoodledata->name);
    // Into mnet_host table id which refer to self must be "1" (cannot be forced into sqlserver but shall already be fixed to "1" into the snapshoted node)
    $requestsList[7] = "UPDATE {$PREFIX}mnet_host SET wwwroot = '{$vmoodledata->vhostname}', name = '{$vmoodlenodename}' , public_key = '', public_key_expires = 0, ip_address = '{$cfgipaddress}'  WHERE wwwroot = '{$manifest['templatewwwroot']}'";
    fwrite($FILE, $requestsList[7] . ";\n\n");
    $requestsList[8] = "UPDATE {$PREFIX}config SET value = 1 WHERE name = 'mnet_localhost_id'";
    fwrite($FILE, $requestsList[8] . ";\n\n");
    // ensure consistance
    $requestsList[9] = "UPDATE {$PREFIX}user SET deleted = 1 WHERE auth = 'mnet' AND username != 'admin'";
    fwrite($FILE, $requestsList[9] . ";\n\n");
    // disable all mnet users
    /* 
     * this is necessary when using a template from another location or deployment target as
     * the salt may have changed. We would like that all primary admins be the same techn admin.
     */
    $localadmin = get_admin();
    fputs($FILE, "--\n-- Force physical admin with same credentials than in master.  \n--\n");
    $requestsList[10] = "UPDATE {$PREFIX}user SET password = '******' WHERE auth = 'manual' AND username = '******'";
    fwrite($FILE, $requestsList[10] . ";\n\n");
    if ($vmoodledata->mnet == -1) {
        // NO MNET AT ALL.
        /*
         * we need :
         * disable mnet
         */
        $requestsList[11] = "UPDATE {$PREFIX}config SET value = 'off' WHERE name = 'mnet_dispatcher_mode'";
        fputs($FILE, $requestsList[11] . ";\n\n");
    } else {
        // ALL OTHER CASES.
        /*
         * we need : 
         * enable mnet
         * push our master identity in mnet_host table
         */
        $requestsList[12] = "UPDATE {$PREFIX}config SET value = 'strict' WHERE name = 'mnet_dispatcher_mode'";
        fputs($FILE, $requestsList[12] . ";\n\n");
        $requestsList[13] = "INSERT INTO {$PREFIX}mnet_host (wwwroot, ip_address, name, public_key, applicationid, public_key_expires) VALUES ('{$this_as_host->wwwroot}', '{$this_as_host->ip_address}', '{$SITE->fullname}', '{$this_as_host->public_key}', {$this_as_host->applicationid}, '{$this_as_host->public_key_expires}')";
        fputs($FILE, $requestsList[13] . ";\n\n");
        fputs($FILE, "--\n-- Enable the service 'mnetadmin, sso_sp and sso_ip' with host which creates this host.  \n--\n");
        $requestsList[14] = "INSERT INTO {$PREFIX}mnet_host2service (hostid,serviceid,publish,subscribe) VALUES ((SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'), (SELECT id FROM {$PREFIX}mnet_service WHERE name LIKE 'mnetadmin'), 1, 0)";
        fputs($FILE, $requestsList[14] . ";\n\n");
        $requestsList[15] = "INSERT INTO {$PREFIX}mnet_host2service (hostid,serviceid,publish,subscribe) VALUES ((SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'), (SELECT id FROM {$PREFIX}mnet_service WHERE name LIKE 'sso_sp'), 1, 0)";
        fputs($FILE, $requestsList[15] . ";\n\n");
        $requestsList[16] = "INSERT INTO {$PREFIX}mnet_host2service (hostid,serviceid,publish,subscribe) VALUES ((SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'), (SELECT id FROM {$PREFIX}mnet_service WHERE name LIKE 'sso_idp'), 0, 1)";
        fputs($FILE, $requestsList[16] . ";\n\n");
        fputs($FILE, "--\n-- Insert master host user admin.  \n--\n");
        $requestsList[17] = "INSERT INTO {$PREFIX}user (auth, confirmed, policyagreed, deleted, mnethostid, username, password) VALUES ('mnet', 1, 0, 0, (SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'), 'admin', '')";
        fputs($FILE, $requestsList[17] . ";\n\n");
        fputs($FILE, "--\n-- Links role and capabilites for master host admin.  \n--\n");
        $roleid = "(SELECT id FROM {$PREFIX}role WHERE shortname LIKE 'manager')";
        $contextid = 1;
        $userid = "(SELECT id FROM {$PREFIX}user WHERE auth LIKE 'mnet' AND username = '******' AND mnethostid = (SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'))";
        $timemodified = time();
        $modifierid = $userid;
        $component = "''";
        $itemid = 0;
        $sortorder = 1;
        $requestsList[18] = "INSERT INTO {$PREFIX}role_assignments(roleid,contextid,userid,timemodified,modifierid,component,itemid,sortorder) VALUES ({$roleid}, {$contextid}, {$userid}, {$timemodified}, {$modifierid}, {$component}, {$itemid}, {$sortorder})";
        fputs($FILE, $requestsList[18] . ";\n\n");
        fputs($FILE, "--\n-- Add new network admin to local siteadmins.  \n--\n");
        $adminidsql = "(SELECT id FROM {$PREFIX}user WHERE auth LIKE 'mnet' AND username = '******' AND mnethostid = (SELECT id FROM {$PREFIX}mnet_host WHERE wwwroot LIKE '{$this_as_host->wwwroot}'))";
        if ($vmoodledata->vdbtype == 'sqlsrv') {
            $requestsList[19] = "UPDATE {$PREFIX}config SET value = value+','+CAST({$adminidsql} AS nvarchar(max)) WHERE name = 'siteadmins'";
        } else {
            $requestsList[19] = "UPDATE {$PREFIX}config SET value = CONCAT(value, ',', {$adminidsql}) WHERE name = 'siteadmins'";
        }
        fputs($FILE, $requestsList[19] . ";\n");
        fputs($FILE, "--\n-- Create a disposable key for renewing new host's keys.  \n--\n");
        $requestsList[20] = "DELETE FROM {$PREFIX}config WHERE name = 'bootstrap_init'";
        $requestsList[21] = "INSERT INTO {$PREFIX}config (name, value) VALUES ('bootstrap_init', '{$this_as_host->wwwroot}')";
        fputs($FILE, $requestsList[20] . ";\n");
    }
    fclose($FILE);
    // debug_trace('fixing_database ; setup script written');
    $vdb = vmoodle_setup_DB($vmoodledata);
    $transaction = $vdb->start_delegated_transaction();
    foreach ($requestsList as $req) {
        $vdb->execute_query($req);
    }
    $transaction->allow_commit();
    // INSERT into config table must be allowed by unique constraint on column "name" - impossible to check in a transaction
    /*if($lastrequest)
      $vdb->execute_query($lastrequest);*/
    return true;
}