$vdb = vmoodle_setup_DB($form);
 $res = $vdb->create_database($form->vdbname);
 if (!$res) {
     $erroritem->message = get_string('couldnotcreatedb', 'local_vmoodle');
     $erroritem->on = 'db';
     $errors[] = $erroritem;
 } else {
     $done[] = 'database';
     print_string('databasecreated', 'local_vmoodle');
     echo "<br/>";
 }
 // make a new connection so we can bind to database
 $vdb->dispose();
 $vdb = vmoodle_setup_DB($form);
 /// prepare a filter for absolute www roots
 $manifest = vmoodle_get_vmanifest($v);
 $filter[$manifest->templatehost] = $form->vhostname;
 /// Try to setup full datamodel loading database template
 if ($res = vmoodle_load_db_template($form, "{$CFG->dirroot}/local/vmoodle/{$v}_sql/vmoodle_master.{$form->vdbtype}.sql", $vdb, $filter)) {
     $errors[] = $res;
 } else {
     $done[] = 'databaseloaded';
     print_string('databaseloaded', 'local_vmoodle');
     echo "<br/>";
 }
 /// TODO run customisation SQL script
 $vars = get_object_vars($vmoodle);
 $vars['sessioncookie'] = strtoupper($vars->shortname);
 $vars['sessioncookie'] = preg_replace("/[-_]/", '', $vars['sessioncookie']);
 // strips out token damaging chars
 if ($res = vmoodle_load_db_template($form, "{$CFG->dirroot}/local/vmoodle/{$v}_sql/vmoodle_setup_template.{$form->vdbtype}.sql", $vdb, $vars)) {
/**
 * 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;
}
示例#3
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;
}