/* // Save confirm message before redirection.
       $SESSION->vmoodle_ma['confirm_message'] = $message_object;
       header('Location: view.php?view=management');
       return -1; */
}
/********************* Just rough destroy without care (for bulk cleaning) ************/
if ($action == 'destroy') {
    // If there is submitted data from form or in session (no errors).
    if (isset($SESSION->vmoodledata)) {
        $submitteddata = $SESSION->vmoodledata;
    } else {
        $id = required_param('id', PARAM_INT);
        $submitteddata = $DB->get_record('local_vmoodle', array('id' => $id));
    }
    if ($submitteddata) {
        debug_trace('Destroying vmoodle host');
        vmoodle_destroy($submitteddata);
    }
}
/********************* Run an interactive cronlike trigger forcing key renew on all vmoodle ************/
if ($action == 'renewall') {
    // self renew
    echo $OUTPUT->header();
    echo '<pre>';
    $renewuri = $CFG->wwwroot . '/admin/cron.php?forcerenew=1';
    echo "Running on : {$renewuri}\n";
    echo "#############################\n";
    $ch = curl_init($renewuri);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, false);
/**
 * Enables or disables a plugin of a virtual platform.
 * @param string $user The calling user.
 * @param string $plugininfos a structure with info for each plugin to setup.
 */
function mnetadmin_rpc_set_plugins_states($user, $plugininfos, $json_response = true)
{
    global $CFG, $USER, $DB;
    // debug_trace("Plugin Set States: Entry point");
    // Creating response.
    $response = new Stdclass();
    $response->status = RPC_SUCCESS;
    $response->errors = array();
    $response->error = '';
    // Invoke local user and check his rights.
    if ($auth_response = invoke_local_user((array) $user, 'local/vmoodle:execute')) {
        if ($json_response) {
            // We could not have a credential.
            return $auth_response;
        } else {
            return json_decode($auth_response);
        }
    }
    // Getting plugin enable/disable method.
    if (!empty($plugininfos)) {
        foreach ($plugininfos as $plugin => $infos) {
            $actionclass = $infos['type'] . '_remote_control';
            // Ignore non implemented.
            if (!class_exists($actionclass)) {
                debug_trace("failing running remote action on {$actionclass}. Class not found");
                continue;
            }
            $control = new $actionclass($infos['type'], $plugin);
            $action = $infos['action'];
            $return = $control->action($action);
            if ($return !== 0) {
                $response->status = RPC_FAILURE;
                $response->errors[] = $return;
            }
            $response->value = 'done.';
        }
    }
    $response->error = implode(', ', $response->errors);
    // Returning response.
    if ($json_response) {
        return json_encode($response);
    } else {
        return $response;
    }
}
<?php

include '../../../config.php';
include $CFG->dirroot . '/mod/customlabel/lib.php';
$type = required_param('type', PARAM_ALPHA);
$selector = required_param('selector', PARAM_TEXT);
$constraints = required_param('constraints', PARAM_RAW);
$targetstr = required_param('targets', PARAM_TEXT);
$selection = optional_param('selection', null, PARAM_TEXT);
$constraintsarr = explode(',', $constraints);
debug_trace("type: {$type}\n{$selector}: {$selector}\nconstraints: {$constraints}\ntargets: {$targetstr}\nselection {$selection}");
// rebuild proper associative structure from flatten array
if (!empty($selection)) {
    $selected = json_decode(stripslashes($selection));
    $iskey = true;
    foreach ($selected as $sel) {
        if ($iskey) {
            $tmp = $sel;
            $iskey = false;
        } else {
            $preselection[$tmp] = $sel;
            if (is_array($sel)) {
                $constraintsarr = $constraintsarr + $sel;
            }
            $iskey = true;
        }
    }
}
if (!($targets = explode(',', $targetstr))) {
    exit;
}
/**
 * Get fields values of a virtual platform.
 * @param string $user The calling user.
 * @param string $command The sql command to run.
 * @param boolean $return true if the result of SQL should be returned, false otherwise. In that case query CANNOT be multiple
 */
function mnetadmin_rpc_run_sql_command($user, $command, $params, $return = false, $multiple = false)
{
    global $CFG, $USER, $vmcommands_constants, $DB;
    // Adding requirements.
    include_once $CFG->dirroot . '/local/vmoodle/lib.php';
    // Invoke local user and check his rights.
    // Creating response.
    $response = new StdClass();
    $response->status = RPC_SUCCESS;
    // Split multiple, non return commands, or save unique as first of array.
    if ($multiple == true && !$return) {
        $commands = explode(";\n", $command);
    } else {
        $commands[] = $command;
    }
    // Runnning commands.
    foreach ($commands as $command) {
        if (empty($command) || preg_match('/^\\s+$/s', $command)) {
            continue;
        }
        if ($return) {
            try {
                $record = $DB->get_record_sql($command, $params);
                $response->value = $record;
            } catch (Exception $e) {
                $response->errors[] = $DB->get_last_error();
                $response->error = $DB->get_last_error();
            }
        } else {
            try {
                debug_trace("Vmoodle Remote sql : {$command} " . serialize($params));
                if (!$DB->execute($command, $params)) {
                    $response->errors[] = 'No rows affected.';
                    $response->error = 'No rows affected.';
                }
            } catch (Exception $e) {
                $response->errors[] = $DB->get_last_error();
                $response->error = $DB->get_last_error();
            }
        }
    }
    // Returning response of last statement.
    if (!empty($response->errors)) {
        $response->status = RPC_FAILURE;
    } else {
        $response->status = RPC_SUCCESS;
    }
    return json_encode($response);
}
function vmoodle_destroy($vmoodledata)
{
    global $DB, $OUTPUT;
    if (!$vmoodledata) {
        return;
    }
    // Checks if paths commands have been properly defined in 'vconfig.php'.
    if ($vmoodledata->vdbtype == 'mysql') {
        $dropstatement = 'DROP DATABASE IF EXISTS';
    } elseif ($vmoodledata->vdbtype == 'mysqli') {
        $dropstatement = 'DROP DATABASE IF EXISTS';
    } elseif ($vmoodledata->vdbtype == 'postgres') {
        $dropstatement = 'DROP SCHEMA';
    }
    // Drop the database.
    $sql = "{$dropstatement} {$vmoodledata->vdbname}";
    debug_trace("destroy_database : executing drop sql");
    try {
        $DB->execute($sql);
    } catch (Exception $e) {
        echo $OUTPUT->notification('noexecutionfor', 'local_vmoodle', $sql);
    }
    // Destroy moodledata.
    $cmd = " rm -rf \"{$vmoodledata->vdatapath}\" ";
    exec($cmd);
    // Delete vmoodle instance.
    $DB->delete_records('local_vmoodle', array('vhostname' => $vmoodledata->vhostname));
    // Delete all related mnet_hosts info.
    $mnet_host = $DB->get_record('mnet_host', array('wwwroot' => $vmoodledata->vhostname));
    $DB->delete_records('mnet_host', array('wwwroot' => $mnet_host->wwwroot));
    $DB->delete_records('mnet_host2service', array('hostid' => $mnet_host->id));
    $DB->delete_records('mnetservice_enrol_courses', array('hostid' => $mnet_host->id));
    $DB->delete_records('mnetservice_enrol_enrolments', array('hostid' => $mnet_host->id));
    $DB->delete_records('mnet_log', array('hostid' => $mnet_host->id));
    $DB->delete_records('mnet_session', array('mnethostid' => $mnet_host->id));
    $DB->delete_records('mnet_sso_access_control', array('mnet_host_id' => $mnet_host->id));
}
/**
 * Purge internally all caches.
 * @param object $user The calling user, containing mnethostroot reference and hostroot reference.
 */
function mnetadmin_rpc_purge_caches($user, $json_response = true)
{
    global $CFG, $USER;
    debug_trace('RPC ' . json_encode($user));
    if ($auth_response = invoke_local_user((array) $user)) {
        if ($json_response) {
            return $auth_response;
        } else {
            return json_decode($auth_response);
        }
    }
    // Creating response.
    $response = new stdClass();
    $response->status = RPC_SUCCESS;
    purge_all_caches();
    debug_trace('RPC Bind : Sending response');
    // Returns response (success or failure).
    return json_encode($response);
}
/**
 * Adds a new peer to the known hosts, with its public key. Binding
 * an old record (deleted) will revive it.
 * @param string $username The calling user.
 * @param string $userhost The calling user's host.
 * @param string $remotehost The calling host.
 * @param array $new_peer The peer to add as a complete mnet_host record.
 */
function mnetadmin_rpc_bind_peer($username, $userhost, $remotehost, $new_peer, $servicestrategy)
{
    global $CFG, $USER, $DB;
    // Invoke distant user who makes the call and checks his rights.
    $user['username'] = $username;
    $user['remoteuserhostroot'] = $userhost;
    $user['remotehostroot'] = $remotehost;
    debug_trace('RPC ' . json_encode($user));
    invoke_local_user($user, 'local/vmoodle:managevmoodles');
    // Creating response.
    $response = new stdClass();
    $response->status = RPC_SUCCESS;
    // Add the new peer.
    $peerobj = (object) $new_peer;
    unset($peerobj->id);
    if ($oldpeer = $DB->get_record('mnet_host', array('wwwroot' => $peerobj->wwwroot))) {
        $peerobj->id = $oldpeer->id;
        if (!$DB->update_record('mnet_host', $peerobj)) {
            $response->status = RPC_FAILURE_RECORD;
            $response->errors[] = 'Error renewing the mnet record';
            $response->error = 'Error renewing the mnet record';
            return json_encode($response);
        }
    } else {
        if (!($peerobj->id = $DB->insert_record('mnet_host', $peerobj))) {
            $response->status = RPC_FAILURE_RECORD;
            $response->errors[] = 'Error recording the mnet record';
            $response->error = 'Error recording the mnet record';
            return json_encode($response);
        }
    }
    debug_trace('RPC : Binding service strategy');
    // bind the service strategy.
    if (!empty($servicestrategy)) {
        $DB->delete_records('mnet_host2service', array('hostid' => $peerobj->id));
        // eventually deletes something on the way
        foreach ($servicestrategy as $servicename => $servicestate) {
            $servicestate = (object) $servicestate;
            // ensure it is object
            $service = $DB->get_record('mnet_service', array('name' => $servicename));
            $host2service = new stdclass();
            $host2service->hostid = $peerobj->id;
            $host2service->serviceid = $service->id;
            $host2service->publish = 0 + $servicestate->publish;
            $host2service->subscribe = 0 + $servicestate->subscribe;
            $DB->insert_record('mnet_host2service', $host2service);
        }
    }
    debug_trace('RPC Bind : Sending response');
    // Returns response (success or failure).
    return json_encode($response);
}
/**
* a raster for xls printing of a report structure.
*
*/
function training_reports_print_xls(&$worksheet, &$structure, &$aggregate, &$done, &$row, &$xls_formats, $level = 1)
{
    if (empty($structure)) {
        $str = get_string('nostructure', 'report_trainingsessions');
        $worksheet->write_string($row, 1, $str);
        return;
    }
    // makes a blank dataobject.
    if (!isset($dataobject)) {
        $dataobject->elapsed = 0;
        $dataobject->events = 0;
        $dataobject->evaluating = 0;
        $dataobject->evaluatingevents = 0;
        $dataobject->preparing = 0;
        $dataobject->preparingevents = 0;
        $dataobject->executing = 0;
        $dataobject->executingevents = 0;
        $dataobject->mentored = 0;
        $dataobject->mentoredevents = 0;
        $dataobject->freerun = 0;
        $dataobject->freerunevents = 0;
    }
    if (is_array($structure)) {
        foreach ($structure as $element) {
            if (isset($element->instance) && empty($element->instance->visible)) {
                continue;
            }
            // non visible items should not be displayed
            $res = training_reports_print_xls($worksheet, $element, $aggregate, $done, $row, $xls_formats, $level);
            $dataobject->elapsed += $res->elapsed;
            $dataobject->events += $res->events;
            $dataobject->evaluating += $res->evaluating;
            $dataobject->evaluatingevents += $res->evaluatingevents;
            $dataobject->preparing += $res->preparing;
            $dataobject->preparingevents += $res->preparingevents;
            $dataobject->executing += $res->executing;
            $dataobject->executingevents += $res->executingevents;
            $dataobject->mentored += $res->mentored;
            $dataobject->mentoredevents += $res->mentoredevents;
            $dataobject->freerun += $res->freerun;
            $dataobject->freerunevents += $res->freerunevents;
        }
    } else {
        $format = isset($xls_formats['a' . $level]) ? $xls_formats['a' . $level] : $xls_formats['z'];
        $timeformat = $xls_formats['zt'];
        if (!isset($element->instance) || !empty($element->instance->visible)) {
            // non visible items should not be displayed
            if (!empty($structure->name)) {
                // write element title
                $indent = str_pad('', 3 * $level, ' ');
                $str = $indent . shorten_text($structure->name, 85);
                $worksheet->set_row($row, 18, $format);
                $worksheet->write_string($row, 0, $str, $format);
                $worksheet->write_blank($row, 1, $format);
                if (isset($structure->id) && !empty($aggregate[$structure->type][$structure->id])) {
                    $done++;
                    $dataobject = $aggregate[$structure->type][$structure->id];
                }
                $thisrow = $row;
                // saves the current row for post writing aggregates
                $row++;
                if (!empty($structure->subs)) {
                    debug_trace("with subs");
                    $res = training_reports_print_xls($worksheet, $structure->subs, $aggregate, $done, $row, $xls_formats, $level + 1);
                    $dataobject->elapsed += $res->elapsed;
                    $dataobject->events += $res->events;
                    $dataobject->preparing += $res->preparing;
                    $dataobject->preparingevents += $res->preparingevents;
                    $dataobject->executing += $res->executing;
                    $dataobject->executingevents += $res->executingevents;
                    $dataobject->evaluating += $res->evaluating;
                    $dataobject->evaluatingevents += $res->evaluatingevents;
                    $dataobject->mentored += $res->mentored;
                    $dataobject->mentoredevents += $res->mentoredevents;
                    $dataobject->freerun += $res->freerun;
                    $dataobject->freerunevents += $res->freerunevents;
                }
                $str = training_reports_format_time($dataobject->elapsed, 'xls');
                $worksheet->write_number($thisrow, 2, $str, $timeformat);
                $worksheet->write_number($thisrow, 3, $dataobject->events, $format);
                // plug here specific details
                if (!empty($dataobject->evaluating)) {
                    $str = training_reports_format_time($dataobject->evaluating, 'xls');
                    $worksheet->write_number($thisrow, 4, $str, $timeformat);
                    $worksheet->write_number($thisrow, 5, $dataobject->evaluatingevents, $format);
                } else {
                    $dataobject->evaluating = 0;
                    $dataobject->evaluatingevents = 0;
                }
                if (!empty($dataobject->preparing)) {
                    $str = training_reports_format_time($dataobject->preparing, 'xls');
                    $worksheet->write_number($thisrow, 6, $str, $timeformat);
                    $worksheet->write_number($thisrow, 7, $dataobject->preparingevents, $format);
                } else {
                    $dataobject->preparing = 0;
                    $dataobject->preparingevents = 0;
                }
                if (!empty($dataobject->executing)) {
                    $str = training_reports_format_time($dataobject->executing, 'xls');
                    $worksheet->write_number($thisrow, 8, $str, $timeformat);
                    $worksheet->write_number($thisrow, 9, $dataobject->executingevents, $format);
                } else {
                    $dataobject->executing = 0;
                    $dataobject->executingevents = 0;
                }
                // for trainees
                if (!empty($dataobject->mentored)) {
                    $str = training_reports_format_time($dataobject->mentored, 'xls');
                    $worksheet->write_number($thisrow, 10, $str, $timeformat);
                    $worksheet->write_number($thisrow, 11, $dataobject->mentoredevents, $format);
                } else {
                    $dataobject->mentored = 0;
                    $dataobject->mentoredevents = 0;
                }
                if (!empty($dataobject->freerun)) {
                    $str = training_reports_format_time($dataobject->freerun, 'xls');
                    $worksheet->write_number($thisrow, 12, $str, $timeformat);
                    $worksheet->write_number($thisrow, 13, $dataobject->freerunevents, $format);
                } else {
                    $dataobject->freerun = 0;
                    $dataobject->freerunevents = 0;
                }
            } else {
                // It is only a structural module that should not impact on level
                if (isset($structure->id) && !empty($aggregate[$structure->type][$structure->id])) {
                    $dataobject = $aggregate[$structure->type][$structure->id];
                }
                if (!empty($structure->subs)) {
                    $res = training_reports_print_xls($worksheet, $structure->subs, $aggregate, $done, $row, $xls_formats, $level);
                    $dataobject->elapsed += $res->elapsed;
                    $dataobject->events += $res->events;
                    $dataobject->preparing += $res->preparing;
                    $dataobject->preparingevents += $res->preparingevents;
                    $dataobject->executing += $res->executing;
                    $dataobject->executingevents += $res->executingevents;
                    $dataobject->evaluating += $res->evaluating;
                    $dataobject->evaluatingevents += $res->evaluatingevents;
                    $dataobject->mentored += $res->mentored;
                    $dataobject->mentoredevents += $res->mentoredevents;
                    $dataobject->freerun += $res->freerun;
                    $dataobject->freerunevents += $res->freerunevents;
                }
            }
        }
    }
    return $dataobject;
}
function rpc_check_context_target($contextlevel, $contextidentityfield, $contextidentity, &$response, $json_response)
{
    global $DB;
    // Check context target.
    switch ($contextlevel) {
        case CONTEXT_SYSTEM:
            $context = context_system::instance();
            break;
        case CONTEXT_COURSE:
            if (!preg_match('/id|shortname|idnumber/', $contextidentityfield)) {
                $response->status = RPC_FAILURE_RECORD;
                $response->errors[] = "This fieldname ({$contextidentityfield}) does\\'nt apply for this course context level.";
                $response->error = "This fieldname ({$contextidentityfield}) does\\'nt apply for this course context level.";
                if ($json_response) {
                    return json_encode($response);
                } else {
                    return $response;
                }
            }
            if (!($course = $DB->get_record('course', array($contextidentityfield => $contextidentity)))) {
                $response->status = RPC_FAILURE_RECORD;
                $response->errors[] = " Course Context {$contextidentity} not found based on {$contextidentityfield}.";
                $response->error = " Course Context {$contextidentity} not found based on {$contextidentityfield}.";
                if ($json_response) {
                    return json_encode($response);
                } else {
                    return $response;
                }
            }
            $context = context_course::instance($course->id);
            break;
        case CONTEXT_MODULE:
            if (!preg_match('/id|idnumber/', $contextidentityfield)) {
                $response->status = RPC_FAILURE_RECORD;
                $response->errors[] = " This fieldname ({$contextidentityfield}) does\\'nt apply for this module context level.";
                $response->error = " This fieldname ({$contextidentityfield}) does\\'nt apply for this module context level.";
            }
            if (!($cm = $DB->get_record('course_modules', array($contextidentityfield => $contextidentity)))) {
                $response->status = RPC_FAILURE_RECORD;
                $response->errors[] = " Course Module {$contextidentity} not found based on {$contextidentityfield}.";
                $response->error = " Course Module {$contextidentity} not found based on {$contextidentityfield}.";
            }
            if (!($context = context_module::instance($cm->id))) {
                $response->status = RPC_FAILURE_RECORD;
                $response->errors[] = 'Course Module context not found.';
                $response->error = 'Course Module context not found.';
            }
            break;
        case CONTEXT_USER:
            if (!preg_match('/id|username|email|idnumber', $contextidentityfield)) {
                $response->status = RPC_FAILURE_RECORD;
                $response->errors[] = " This fieldname ({$contextidentityfield}) does\\'nt apply for this user context level.";
                $response->error = " This fieldname ({$contextidentityfield}) does\\'nt apply for this user context level.";
            }
            if (!($user = $DB->get_record('user', array($contextidentityfield => $contextidentity)))) {
                $response->status = RPC_FAILURE_RECORD;
                $response->errors[] = " User {$contextidentity} not found based on {$contextidentityfield}. ";
                $response->error = " User {$contextidentity} not found based on {$contextidentityfield}. ";
            }
            if (!($context = context_user::instance($user->id))) {
                $response->status = RPC_FAILURE_RECORD;
                $response->errors[] = 'User context not found with userid ' . $user->id . '.';
                $response->error = 'User context not found with userid ' . $user->id . '.';
            }
            break;
        default:
            $response->status = RPC_FAILURE_RECORD;
            $response->errors[] = "Context level ({$contextlevel}) not implemented.";
            $response->error = "Context level ({$contextlevel}) not implemented.";
    }
    if (function_exists('debug_trace')) {
        debug_trace("Got context {$contextlevel}");
    }
    return $context;
}
Beispiel #10
0
function vmoodle_destroy($vmoodledata)
{
    global $CFG, $DB, $OUTPUT;
    if (!$vmoodledata) {
        return;
    }
    // Checks if paths commands have been properly defined in 'vconfig.php'.
    if ($vmoodledata->vdbtype == 'sqlsrv') {
        $sqldropstatement = "IF EXISTS(SELECT name FROM sys.databases WHERE name = '" . $vmoodledata->vdbname . "') DROP DATABASE " . $vmoodledata->vdbname;
    } elseif ($vmoodledata->vdbtype == 'mysql') {
        $sqldropstatement = 'DROP DATABASE IF EXISTS ' . $vmoodledata->vdbname;
    } elseif ($vmoodledata->vdbtype == 'mysqli') {
        $sqldropstatement = 'DROP DATABASE IF EXISTS ' . $vmoodledata->vdbname;
    } elseif ($vmoodledata->vdbtype == 'postgres') {
        $sqldropstatement = 'DROP SCHEMA ' . $vmoodledata->vdbname;
    } else {
        throw new moodle_exception('vmoodle_destroy', 'local_vmoodle', '', null, '[local/vmoodle/lib.php] vdbtype not implemented');
    }
    debug_trace("destroy_database : executing drop sql");
    try {
        $DB->execute($sqldropstatement);
    } catch (Exception $e) {
        echo $OUTPUT->notification('noexecutionfor', 'local_vmoodle', $sql);
    }
    // Destroy moodledata.
    if ($CFG->ostype == 'WINDOWS') {
        $cmd = 'rd "' . $vmoodledata->vdatapath . '" /S /Q';
    } else {
        $cmd = " rm -rf \"{$vmoodledata->vdatapath}\" ";
    }
    exec($cmd);
    // Delete vmoodle instance.
    $DB->delete_records('local_vmoodle', array('vhostname' => $vmoodledata->vhostname));
    // Delete all related mnet_hosts info.
    $mnet_host = $DB->get_record('mnet_host', array('wwwroot' => $vmoodledata->vhostname));
    if ($mnet_host) {
        $DB->delete_records('mnet_host', array('wwwroot' => $mnet_host->wwwroot));
        $DB->delete_records('mnet_host2service', array('hostid' => $mnet_host->id));
        $DB->delete_records('mnetservice_enrol_courses', array('hostid' => $mnet_host->id));
        $DB->delete_records('mnetservice_enrol_enrolments', array('hostid' => $mnet_host->id));
        $DB->delete_records('mnet_log', array('hostid' => $mnet_host->id));
        $DB->delete_records('mnet_session', array('mnethostid' => $mnet_host->id));
        $DB->delete_records('mnet_sso_access_control', array('mnet_host_id' => $mnet_host->id));
    }
}