} else { /// try to create database $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']);
$return = (include $CFG->dirroot . '/local/vmoodle/controller.management.php'); if ($return == -1) { cli_error(get_string('cliprocesserror', 'local_vmoodle')); } if ($interactive) { $input = readline("Continue (y/n|r) ?\n"); if ($input == 'r' || $input == 'R') { $vmoodlestep--; } elseif ($input == 'n' || $input == 'N') { echo "finishing\n"; exit; } } } // Once all steps done on, this node, process extra settings from CSV file using a side connection $VDB = vmoodle_setup_DB($n); // special fix for deployed networks : // Fix the master node name in mnet_host // We need overseed the issue of loosing the name of the master node in the deploied instance // TODO : this is a turnaround quick fix. if ($remote_vhost = $VDB->get_record('mnet_host', array('wwwroot' => $CFG->wwwroot))) { global $SITE; $remote_vhost->name = $SITE->fullname; $VDB->update_record('mnet_host', $remote_vhost, 'id'); } if (!empty($n->config)) { $confiarr = (array) $n->config; foreach ($confiarr as $key => $value) { mtrace("Setting up main config {$key} to {$value}"); if ($oldrec = $VDB->get_record('config', array('name' => $key))) { $oldrec->value = $value;
} $handle = fopen($options['sql-file'], "r"); $contents = fread($handle, filesize($options['sql-file'])); fclose($handle); $requests = array_filter(explode(';', $contents)); if ($options['simulate']) { mtrace("Start simulating..."); } else { mtrace("Start processing..."); } mtrace('######################################################'); $i = 1; foreach ($allhosts as $h) { mtrace(">Execution for host {$i} : {$h->vhostname}"); if (!$options['simulate']) { $vdb = vmoodle_setup_DB($h); } foreach ($requests as $index => $req) { $requests[$index] = trim($req); mtrace('--'); mtrace($requests[$index]); if (!$options['simulate']) { $res = $vdb->execute_query($requests[$index], SQLSRV_CURSOR_STATIC); if ($res === false) { mtrace(' ** ERROR detected, exiting execution : '); mtrace(sqlsrv_errors()); die; } if ($vdb->get_last_request_type() == SQL_QUERY_SELECT) { if ($vdb->get_num_rows($res) > 0) { $resultset = $vdb->get_all_results_array($res);
/** * Test connection validation. * @see lib/moodleform#validation($data, $files) */ function validation($data, $files = null) { global $CFG, $DB; // Empty array. $errors = parent::validation($data, null); // Checks database connection again, after Javascript test. $database = new \stdClass(); $database->vdbtype = $data['vdbtype']; $database->vdbhost = $data['vdbhost']; $database->vdblogin = $data['vdblogin']; $database->vdbpass = $data['vdbpass']; $database->vdbname = $CFG->dbname; $database->vdbprefix = $data['vdbprefix']; if (!vmoodle_setup_DB($database)) { $errors['vdbhost'] = get_string('badconnection', 'local_vmoodle'); $errors['vdblogin'] = get_string('badconnection', 'local_vmoodle'); $errors['vdbpass'] = get_string('badconnection', 'local_vmoodle'); } // Checks if database's name doesn't finish with '_'. if ($data['vdbname'][strlen($data['vdbname']) - 1] == '_') { $errors['vdbname'] = get_string('baddatabasenamecoherence', 'local_vmoodle'); } // Checks if database's name doesn't finish with '_'. if (strstr($data['vdbname'], '-') !== false) { $errors['vdbname'] = get_string('badnohyphensindbname', 'local_vmoodle'); } // Checks if table's prefix doesn't begin with restricted values (which can evolve). $restrictedvalues = array('vmoodle_'); foreach ($restrictedvalues as $restrictedvalue) { if ($data['vdbprefix'] == $restrictedvalue) { $errors['vdbprefix'] = get_string('baddatabaseprefixvalue', 'local_vmoodle'); } } // ATTENTION Checks if user has entered a datapath with only one backslash between each folder // and/or file. if (isset($CFG->ostype) && $CFG->ostype == 'WINDOWS' && preg_match('#\\\\{3,}#', $data['vdatapath']) > 0) { $errors['vdatapath'] = get_string('badmoodledatapathbackslash', 'local_vmoodle'); return $errors; } // Test of values which have to be well-formed and can not be modified after. if ($this->isInAddMode()) { // Checks 'shortname', which must have no spaces. $shortname = $data['shortname']; if (strstr($shortname, ' ')) { $errors['shortname'] = get_string('badshortname', 'local_vmoodle'); } // Checks 'vhostname', if not already used. if ($this->isEqualToAnotherVhostname($data['vhostname'])) { // Check if the vhostname is deleted. $sql = "\n SELECT\n m.deleted\n FROM\n {local_vmoodle} b,\n {mnet_host} m\n WHERE\n b.vhostname = ?\n AND\n b.vhostname = m.wwwroot\n "; $resultsqlrequest = $DB->get_record_sql($sql, array($data['vhostname'])); if (!empty($resultsqlrequest)) { if ($resultsqlrequest->deleted == 0) { $errors['vhostname'] = get_string('badhostnamealreadyused', 'local_vmoodle'); } else { //Id the plateforme is deleted and the user want to reactivate the vhostname. if ($data['vtemplate'] == 0) { $sql = "\n SELECT\n id,\n vdatapath,\n vdbname\n FROM\n {local_vmoodle}\n WHERE\n vhostname = ?\n "; $resultsqlrequest = $DB->get_record_sql($sql, array($data['vhostname'])); // Checks if datapath and vdbname of vhostname are the same on the form. if ($resultsqlrequest->vdatapath != stripslashes($data['vdatapath']) && $resultsqlrequest->vdbname != $data['vdbname']) { $errors['vdatapath'] = get_string('errorreactivetemplate', 'local_vmoodle'); $errors['vdbname'] = get_string('errorreactivetemplate', 'local_vmoodle'); } } } } } // Checks 'vhostname' consistency, with a regular expression. $vhostname = $data['vhostname']; if (!preg_match('/^http(s)?:\\/\\//', $vhostname)) { $errors['vhostname'] = get_string('badvhostname', 'local_vmoodle'); } // Checks 'vdatapath', if not already used. if ($this->isEqualToAnotherDataRoot($data['vdatapath'])) { if ($data['vtemplate'] === 0) { } else { $errors['vdatapath'] = get_string('badmoodledatapathalreadyused', 'local_vmoodle'); } } // Checks 'vdbname', if not already used. if ($this->isEqualToAnotherDatabaseName($data) && $data['vtemplate'] != 0) { $errors['vdbname'] = get_string('baddatabasenamealreadyused', 'local_vmoodle'); } } return $errors; }
// but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Tests database connection. * * @package local_vmoodle * @category local * @author Moheissen Fabien (fabien.moheissen@gmail.com) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL */ // Loading $CFG configuration. require '../../../config.php'; require_once $CFG->dirroot . '/local/vmoodle/bootlib.php'; require_once $CFG->dirroot . '/local/vmoodle/lib.php'; // Retrieve parameters for database connection test. $database = new stdClass(); $database->vdbtype = required_param('vdbtype', PARAM_TEXT); $database->vdbhost = required_param('vdbhost', PARAM_TEXT); $database->vdblogin = required_param('vdblogin', PARAM_TEXT); $database->vdbpass = required_param('vdbpass', PARAM_TEXT); $database->vdbname = required_param('vdbname', PARAM_TEXT); // Works, but need to improve the style... if (vmoodle_setup_DB($database)) { echo get_string('connectionok', 'local_vmoodle'); } else { echo get_string('badconnection', 'local_vmoodle'); }
/** * 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; }