function mnet_get_externalprofilefields($hostid) { /// Setup MNET environment global $MNET, $CFG; if (empty($MNET)) { $MNET = new mnet_environment(); $MNET->init(); } /// Setup the server $host = get_record('mnet_host', 'id', $hostid); //we retrieve the server(host) from the 'mnet_host' table if (empty($host)) { error('Invalid Hostid'); } $mnet_peer = new mnet_peer(); //we create a new mnet_peer (server/host) $mnet_peer->set_wwwroot($host->wwwroot); //we set this mnet_peer with the host http address $client = new mnet_xmlrpc_client(); //create a new client $client->set_method('auth/mnet/auth.php/get_user_profile_fields'); //tell it which method we're going to call $client->send($mnet_peer); //Call the server if (!empty($client->response['faultString'])) { error("Mnet error:" . $client->response['faultString']); } return $client->response; }
function refresh_key() { global $CFG; // set up an RPC request require_once $CFG->dirroot . '/mnet/xmlrpc/client.php'; $mnetrequest = new mnet_xmlrpc_client(); // Use any method - listServices is pretty lightweight. $mnetrequest->set_method('system/listServices'); // Do RPC call and store response if ($mnetrequest->send($this) === true) { // Ok - we actually don't care about the result $temp = new mnet_peer(); $temp->set_id($this->id); if ($this->public_key != $temp->public_key) { $newkey = clean_param($temp->public_key, PARAM_PEM); if (!empty($newkey)) { $this->public_key = $newkey; $this->updateparams->public_key = $newkey; $this->commit(); return true; } } } return false; }
/** * Execute the command. * @param mixed $hosts The host where run the command (may be wwwroot or an array). * @throws Command_Exception. */ public function run($hosts) { global $CFG, $USER; // Adding constants. require_once $CFG->dirroot . '/local/vmoodle/rpclib.php'; // Checking capabilities. if (!has_capability('local/vmoodle:execute', \context_system::instance())) { throw new Command_Exception('insuffisantcapabilities'); } // Getting role $table = $this->getParameter('table')->getValue(); // Creating XMLRPC client to read role configuration $rpc_client = new \local_vmoodle\XmlRpc_Client(); $rpc_client->set_method('local/vmoodle/plugins/roles/rpclib.php/mnetadmin_rpc_get_role_allow_table'); $rpc_client->add_param($table, 'string'); $rpc_client->add_param('', 'string'); // get for all roles // Initializing responses $responses = array(); // Creating peers. $mnet_hosts = array(); foreach ($hosts as $host => $name) { $mnet_host = new \mnet_peer(); if ($mnet_host->bootstrap($host, null, 'moodle')) { $mnet_hosts[] = $mnet_host; } else { $responses[$host] = (object) array('status' => MNET_FAILURE, 'error' => get_string('couldnotcreateclient', 'local_vmoodle', $host)); } } // Sending requests. foreach ($mnet_hosts as $mnet_host) { // Sending request. if (!$rpc_client->send($mnet_host)) { $response = new \StdClass(); $response->status = MNET_FAILURE; $response->errors[] = implode('<br/>', $rpc_client->getErrors($mnet_host)); if (debugging()) { echo '<pre>'; var_dump($rpc_client); echo '</pre>'; } } else { $response = json_decode($rpc_client->response); } // Recording response. $responses[$mnet_host->wwwroot] = $response; // Recording capabilities. if ($response->status == RPC_SUCCESS) { $this->capabilities[$mnet_host->wwwroot] = $response->value; } } // Saving results. $this->results = $responses + $this->results; // Processing results. $this->_process(); }
/** * Execute the command. * @param mixed $host The hosts where run the command (may be wwwroot or an array). * @throws Command_SetConfig_Exception */ public function run($hosts) { global $CFG, $USER; // Adding constants. require_once $CFG->dirroot . '/local/vmoodle/rpclib.php'; // Checking host. if (!is_array($hosts)) { $hosts = array($hosts => 'Unnamed host'); } // Checking capabilities. if (!has_capability('local/vmoodle:execute', \context_system::instance())) { throw new Command_SetConfig_Exception('insuffisantcapabilities'); } // Initializing responses. $responses = array(); // Creating peers. $mnet_hosts = array(); foreach ($hosts as $host => $name) { $mnet_host = new \mnet_peer(); if ($mnet_host->bootstrap($host, null, 'moodle')) { $mnet_hosts[] = $mnet_host; } else { $responses[$host] = (object) array('status' => MNET_FAILURE, 'error' => get_string('couldnotcreateclient', 'local_vmoodle', $host)); } } // Getting command. $command = $this->isReturned(); // Creating XMLRPC client. $rpc_client = new \local_vmoodle\XmlRpc_Client(); $rpc_client->set_method('local/vmoodle/plugins/generic/rpclib.php/mnetadmin_rpc_set_config'); $rpc_client->add_param($this->getParameter('key')->getValue(), 'string'); $rpc_client->add_param($this->getParameter('value')->getValue(), 'string'); $rpc_client->add_param(null, 'string'); $rpc_client->add_param($command, 'boolean'); // Sending requests. foreach ($mnet_hosts as $mnet_host) { // Sending request. if (!$rpc_client->send($mnet_host)) { $response = new StdClass(); $response->status = MNET_FAILURE; $response->errors[] = implode('<br/>', $rpc_client->getErrors($mnet_host)); if (debugging()) { echo '<pre>'; var_dump($rpc_client); echo '</pre>'; } } else { $response = json_decode($rpc_client->response); } // Recording response. $responses[$mnet_host->wwwroot] = $response; } // Saving results. $this->results = $responses + $this->results; }
/** * Get fields values of a virtual platform via MNET service. * @param string $host The virtual platform to aim. * @param string $table The table to read. * @param mixed $select The value of id or alternative field. * @param string $fields The fileds to retrieve (optional). * @throws Vmoodle_Command_Sql_Exception. */ function vmoodle_get_field($host, $table, $select, $fields = '*') { global $CFG, $USER, $DB; // Checking capabilities. if (!has_capability('local/vmoodle:execute', context_system::instance())) { throw new Command_Sql_Exception('unsiffisantcapability'); } // Checking host. if (!$DB->get_record('mnet_host', array('wwwroot' => $host))) { throw new Command_Sql_Exception('invalidhost'); } // Checking table. if (empty($table) || !is_string($table)) { throw new Command_Sql_Exception('invalidtable'); } // Checking select. if (empty($select) || !is_array($select) && !is_int($select)) { throw new Command_Sql_Exception('invalidselect'); } if (!is_array($select)) { $select = array('id' => $select); } // Checking field. if (empty($fields)) { throw new Command_Sql_Exception('invalidfields'); } if (!is_array($fields)) { $fields = array($fields); } // Creating peer. $mnet_host = new mnet_peer(); if (!$mnet_host->bootstrap($host, null, 'moodle')) { return (object) array('status' => MNET_FAILURE, 'error' => get_string('couldnotcreateclient', 'vmoodleadminset_sql', $host)); } // Creating XMLRPC client. $rpc_client = new \bock_vmoodle\XmlRpc_Client(); $rpc_client->add_param($table, 'string'); $rpc_client->add_param($fields, 'array'); $rpc_client->add_param($select, 'array'); // Sending request. if (!$rpc_client->send($mnet_host)) { if (debugging()) { echo '<pre>'; var_dump($rpc_client); echo '</pre>'; } } // Returning result. return $rpc_client->response; }
/** * fetches remotely a configuration value * @param object $mnethost a mnet host record. * @param string $configkey the configuration key * @param string $module the module (frankenstyle). If empty, will fetch into the global config scope. */ function vmoodle_get_remote_config($mnethost, $configkey, $module = '') { global $CFG, $USER, $DB, $OUTPUT; if (empty($mnethost)) { return ''; } if (!isset($USER)) { $user = $DB->get_record('user', array('username' => 'guest')); } else { if (empty($USER->id)) { $user = $DB->get_record('user', array('username' => 'guest')); } else { $user = $DB->get_record('user', array('id' => $USER->id)); } } if (!($userhost = $DB->get_record('mnet_host', array('id' => $user->mnethostid)))) { return ''; } $user->remoteuserhostroot = $userhost->wwwroot; $user->remotehostroot = $CFG->wwwroot; // get the sessions for each vmoodle that have same ID Number $rpcclient = new mnet_xmlrpc_client(); $rpcclient->set_method('local/vmoodle/plugins/generic/rpclib.php/dataexchange_rpc_fetch_config'); $rpcclient->add_param($user, 'struct'); $rpcclient->add_param($configkey, 'string'); $rpcclient->add_param($module, 'string'); $mnet_host = new mnet_peer(); if (empty($mnet_host)) { return; } $mnet_host->set_wwwroot($mnethost->wwwroot); if ($rpcclient->send($mnet_host)) { $response = json_decode($rpcclient->response); if ($response->status == 200) { return $response->value; } else { if (debugging()) { echo $OUTPUT->notification('Remote RPC error ' . implode('<br/>', $response->errors)); } } } else { if (debugging()) { echo $OUTPUT->notification('Remote RPC failure ' . implode('<br/', $rpcclient->error)); } } }
function call($paramArray = null) { global $CFG; // For the demo, our 'remote' host is actually our local host. $wwwroot = $CFG->wwwroot; // mnet_peer pulls information about a remote host from the database. $mnet_peer = new mnet_peer(); $mnet_peer->set_wwwroot($wwwroot); //$mnethostid = 1010000003; //$mnethostid = 1010000001; //$mnet_peer->set_id($mnethostid); $method = 'synch/mnet/synch.php/testResponse'; //$paramArray = array(); // Create a new request object $mnet_request = new mnet_xmlrpc_client(); // Tell it the path to the method that we want to execute $mnet_request->set_method($method); global $Out; //$Out->print_r($paramArray, '$paramArray = '); if (!empty($paramArray)) { // Add parameters for your function. The mnet_concatenate_strings takes three // parameters, like mnet_concatenate_strings($string1, $string2, $string3) // PHP is weakly typed, so you can get away with calling most things strings, // unless it's non-scalar (i.e. an array or object or something). foreach ($paramArray as $param) { $mnet_request->add_param($param[0], $param[1]); } } //$Out->print_r($mnet_request->params, '$mnet_request->params = '); if (false && count($mnet_request->params)) { $Out->append('Your parameters are:<br />'); while (list($key, $val) = each($mnet_request->params)) { $Out->append(' <strong>' . $key . ':</strong> ' . $val . "<br/>\n"); } } // We send the request: $mnet_request->send($mnet_peer); //$Out->append('$mnet_request->response = '.$mnet_request->response); //$Out->flush(); return $mnet_request->response; }
function refresh_key() { // set up an RPC request $mnetrequest = new mnet_xmlrpc_client(); // Use any method - listServices is pretty lightweight. $mnetrequest->set_method('system/listServices'); // Do RPC call and store response if ($mnetrequest->send($this) === true) { // Ok - we actually don't care about the result $temp = new mnet_peer(); $temp->set_id($this->id); if ($this->public_key != $temp->public_key) { $newkey = param_clean($temp->public_key, PARAM_PEM); if (!empty($newkey)) { $this->public_key = $newkey; return true; } } } return false; }
} $PAGE->set_url('/admin/mnet/peers.php'); admin_externalpage_setup($adminsection); if (!extension_loaded('openssl')) { print_error('requiresopenssl', 'mnet'); } if (!function_exists('curl_init')) { print_error('nocurl', 'mnet'); } if (!function_exists('xmlrpc_encode_request')) { print_error('xmlrpc-missing', 'mnet'); } if (!isset($CFG->mnet_dispatcher_mode)) { set_config('mnet_dispatcher_mode', 'off'); } $mnet_peer = new mnet_peer(); $simpleform = new mnet_simple_host_form(); // the one that goes on the bottom of the main page $reviewform = null; // set up later in different code branches, so mnet_peer can be passed to the constructor // if the first form has been submitted, bootstrap the peer and load up the review form if ($formdata = $simpleform->get_data()) { // ensure we remove trailing slashes $formdata->wwwroot = trim($formdata->wwwroot); $formdata->wwwroot = rtrim($formdata->wwwroot, '/'); // ensure the wwwroot starts with a http or https prefix if (strtolower(substr($formdata->wwwroot, 0, 4)) != 'http') { $formdata->wwwroot = 'http://' . $formdata->wwwroot; } $mnet_peer->set_applicationid($formdata->applicationid); $application = $DB->get_field('mnet_application', 'name', array('id' => $formdata->applicationid));
function taoview_call_mnet($viewtype) { /// Setup MNET environment global $MNET, $CFG; if (empty($MNET)) { $MNET = new mnet_environment(); $MNET->init(); } /// Setup the server $host = get_record('mnet_host', 'name', 'localmahara'); //we retrieve the server(host) from the 'mnet_host' table if (empty($host)) { error('Mahara not configured'); } $a = new stdclass(); $a->link = $CFG->wwwroot . '/auth/mnet/jump.php?hostid=' . $host->id . '&wantsurl=local/taoview.php?view=' . $viewtype; echo '<div class="taoviwdesc">'; print_string('toaddartefacts', 'local', $a); echo '</div>'; $mnet_peer = new mnet_peer(); //we create a new mnet_peer (server/host) $mnet_peer->set_wwwroot($host->wwwroot); //we set this mnet_peer with the host http address $client = new mnet_xmlrpc_client(); //create a new client $client->set_method('local/mahara/rpclib.php/get_artefacts_by_viewtype'); //tell it which method we're going to call $client->add_param($viewtype); $client->send($mnet_peer); //Call the server if (!empty($client->response['faultString'])) { error("Mahara error:" . $artefacts['faultString']); } return $client->response; }
/** * Work out the theme this page should use. * * This depends on numerous $CFG settings, and the properties of this page. * * @return string the name of the theme that should be used on this page. */ protected function resolve_theme() { global $CFG, $USER, $SESSION; if (empty($CFG->themeorder)) { $themeorder = array('course', 'category', 'session', 'user', 'site'); } else { $themeorder = $CFG->themeorder; // Just in case, make sure we always use the site theme if nothing else matched. $themeorder[] = 'site'; } $mnetpeertheme = ''; if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id) { require_once($CFG->dirroot.'/mnet/peer.php'); $mnetpeer = new mnet_peer(); $mnetpeer->set_id($USER->mnethostid); if ($mnetpeer->force_theme == 1 && $mnetpeer->theme != '') { $mnetpeertheme = $mnetpeer->theme; } } foreach ($themeorder as $themetype) { switch ($themetype) { case 'course': if (!empty($CFG->allowcoursethemes) && !empty($this->_course->theme) && $this->devicetypeinuse == 'default') { return $this->_course->theme; } case 'category': if (!empty($CFG->allowcategorythemes) && $this->devicetypeinuse == 'default') { $categories = $this->categories; foreach ($categories as $category) { if (!empty($category->theme)) { return $category->theme; } } } case 'session': if (!empty($SESSION->theme)) { return $SESSION->theme; } case 'user': if (!empty($CFG->allowuserthemes) && !empty($USER->theme) && $this->devicetypeinuse == 'default') { if ($mnetpeertheme) { return $mnetpeertheme; } else { return $USER->theme; } } case 'site': if ($mnetpeertheme) { return $mnetpeertheme; } // First try for the device the user is using. $devicetheme = get_selected_theme_for_device_type($this->devicetypeinuse); if (!empty($devicetheme)) { return $devicetheme; } // Next try for the default device (as a fallback) $devicetheme = get_selected_theme_for_device_type('default'); if (!empty($devicetheme)) { return $devicetheme; } // The default device theme isn't set up - use the overall default theme. return theme_config::DEFAULT_THEME; } } }
continue; } // Skip localhost if ($host->wwwroot == $CFG->wwwroot) { continue; } // Skip non-moodle hosts if ($host->applicationid != 1 && $host->applicationid != 2) { continue; } //TODO: get rid of magic numbers. echo '<p><a href="testclient.php?hostid=' . $host->id . '">' . $host->wwwroot . "</a></p>\n"; } if (!empty($_GET['hostid']) && array_key_exists($_GET['hostid'], $hosts)) { $host = $hosts[$_GET['hostid']]; $mnet_peer = new mnet_peer(); $mnet_peer->set_wwwroot($host->wwwroot); $mnet_request = new mnet_xmlrpc_client(); // Tell it the path to the method that we want to execute $mnet_request->set_method('system/listServices'); $mnet_request->send($mnet_peer); $services = $mnet_request->response; $yesno = array('No', 'Yes'); $servicenames = array(); echo '<hr /><br /><h3>Services available on host: ' . $host->wwwroot . '</h3><table><tr valign="top"><th> Service ID </th><th> Service </th><th> Version </th><th> They Publish </th><th> They Subscribe </th><th></th></tr>'; foreach ($services as $id => $service) { $sql = 'select c.id, c.parent_type, c.parent from ' . $CFG->prefix . 'mnet_service2rpc a,' . $CFG->prefix . 'mnet_service b, ' . $CFG->prefix . 'mnet_rpc c where a.serviceid = b.id and b.name=\'' . addslashes($service['name']) . '\' and c.id = a.rpcid '; echo '<tr valign="top"> <td>' . $service['name'] . '</td>'; if ($detail = get_record_sql($sql)) { $service['humanname'] = get_string($service['name'] . '_name', $detail->parent_type . '_' . $detail->parent);
print_error("hostexists", 'mnet', 'peers.php?step=update&hostid=' . $mnet_peer->id, $mnet_peer->id); } } if ('input' == $form->step) { include './mnet_review.html'; } elseif ('commit' == $form->step) { $bool = $mnet_peer->commit(); if ($bool) { redirect('peers.php?step=update&hostid=' . $mnet_peer->id, get_string('changessaved')); } else { print_error('invalidaction', 'error', 'index.php'); } } } } elseif (is_int($hostid)) { $mnet_peer = new mnet_peer(); $mnet_peer->set_id($hostid); $currentkey = mnet_get_public_key($mnet_peer->wwwroot, $mnet_peer->application); if ($currentkey == $mnet_peer->public_key) { unset($currentkey); } $form = new stdClass(); if ($hostid != $CFG->mnet_all_hosts_id) { $credentials = $mnet_peer->check_credentials($mnet_peer->public_key); include './mnet_review.html'; } else { include './mnet_review_allhosts.html'; } } else { $hosts = $DB->get_records_sql(' SELECT h.id,
/** * Does Foo * * @param int $mnethostid The id of the remote mnethost * @return array Whether the user can login from the remote host */ function req_unenrol_user($userid, $courseid) { global $CFG; global $USER; global $MNET; require_once $CFG->dirroot . '/mnet/xmlrpc/client.php'; // in case the remote host doesn't have it $username = get_field('user', 'username', 'id', $userid); $course = get_record('mnet_enrol_course', 'id', $courseid); // get the Service Provider info $mnet_sp = new mnet_peer(); $mnet_sp->set_id($course->hostid); // set up the RPC request $mnetrequest = new mnet_xmlrpc_client(); $mnetrequest->set_method('enrol/mnet/enrol.php/unenrol_user'); $mnetrequest->add_param($username); $mnetrequest->add_param($course->remoteid); // TODO - prevent removal of enrolments that are not of // type mnet... // Thunderbirds are go! Do RPC call and store response if ($mnetrequest->send($mnet_sp) === true) { if ($mnetrequest->response == true) { // remove enrolment cached in mnet_enrol_assignments delete_records_select('mnet_enrol_assignments', "userid={$userid} AND courseid={$course->id}"); return true; } } return false; }
* @copyright 2007 Martin Langhoff * @copyright 2010 Penny Leach * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ require_once dirname(dirname(dirname(__FILE__))) . '/config.php'; require_once $CFG->libdir . '/adminlib.php'; $step = optional_param('step', 'verify', PARAM_ALPHA); $hostid = required_param('hostid', PARAM_INT); require_login(); $context = get_context_instance(CONTEXT_SYSTEM); require_capability('moodle/site:config', $context, $USER->id, true, "nopermissions"); $mnet = get_mnet_environment(); $PAGE->set_url('/admin/mnet/delete.php'); admin_externalpage_setup('mnetpeer' . $hostid); require_sesskey(); $mnet_peer = new mnet_peer(); $mnet_peer->set_id($hostid); if ('verify' == $step) { echo $OUTPUT->header(); echo $OUTPUT->heading(get_string('deleteaserver', 'mnet')); if ($live_users = $mnet_peer->count_live_sessions() > 0) { echo $OUTPUT->notification(get_string('usersareonline', 'mnet', $live_users)); } $yesurl = new moodle_url('/admin/mnet/delete.php', array('hostid' => $mnet_peer->id, 'step' => 'delete')); $nourl = new moodle_url('/admin/mnet/peers.php'); echo $OUTPUT->confirm(get_string('reallydeleteserver', 'mnet') . ': ' . $mnet_peer->name, $yesurl, $nourl); echo $OUTPUT->footer(); } elseif ('delete' == $step) { $mnet_peer->delete(); redirect(new moodle_url('/admin/mnet/peers.php'), get_string('hostdeleted', 'mnet'), 5); }
/** * The IdP uses this function to kill child sessions on other hosts * * @param string $username Username for session to kill * @param string $useragent SHA1 hash of user agent to look for * @return string A plaintext report of what has happened */ function kill_children($username, $useragent) { global $CFG, $USER, $DB; $remoteclient = null; if (defined('MNET_SERVER')) { $remoteclient = get_mnet_remote_client(); } require_once $CFG->dirroot . '/mnet/xmlrpc/client.php'; $userid = $DB->get_field('user', 'id', array('mnethostid' => $CFG->mnet_localhost_id, 'username' => $username)); $returnstring = ''; $mnetsessions = $DB->get_records('mnet_session', array('userid' => $userid, 'useragent' => $useragent)); if (false == $mnetsessions) { $returnstring .= "Could find no remote sessions\n"; $mnetsessions = array(); } foreach ($mnetsessions as $mnetsession) { // If this script is being executed by a remote peer, that means the user has clicked // logout on that peer, and the session on that peer can be deleted natively. // Skip over it. if (isset($remoteclient->id) && $mnetsession->mnethostid == $remoteclient->id) { continue; } $returnstring .= "Deleting session\n"; $mnet_peer = new mnet_peer(); $mnet_peer->set_id($mnetsession->mnethostid); $mnet_request = new mnet_xmlrpc_client(); $mnet_request->set_method('auth/mnet/auth.php/kill_child'); // set $token and $useragent parameters $mnet_request->add_param($username); $mnet_request->add_param($useragent); if ($mnet_request->send($mnet_peer) === false) { debugging("Server side error has occured on host {$mnetsession->mnethostid}: " . join("\n", $mnet_request->error)); } } $ignore = $DB->delete_records('mnet_session', array('useragent' => $useragent, 'userid' => $userid)); if (isset($remoteclient) && isset($remoteclient->id)) { session_kill_user($userid); } return $returnstring; }
mtrace("forced mode"); } if ($havetorenew || $force) { mtrace("Local key will expire very soon. Renew MNET keys now !!...\n"); // renew local key $mnet->replace_keys(); // send new key using key exchange transportation // make a key and exchange it with all known and active peers $mnet_peers = $DB->get_records('mnet_host', array('deleted' => 0)); if ($mnet_peers) { foreach ($mnet_peers as $peer) { if ($peer->id == $CFG->mnet_all_hosts_id || $peer->id == $CFG->mnet_localhost_id) { continue; } $application = $DB->get_record('mnet_application', array('id' => $peer->applicationid)); $mnet_peer = new mnet_peer(); $mnet_peer->set_wwwroot($peer->wwwroot); // get the sessions for each vmoodle that have same ID Number // we use a force parameter to force fetching the key remotely anyway $currentkey = mnet_get_public_key($mnet_peer->wwwroot, $application, 1); if ($currentkey) { $mnet_peer->public_key = clean_param($currentkey, PARAM_PEM); $mnet_peer->updateparams = new StdClass(); $mnet_peer->updateparams->public_key = clean_param($currentkey, PARAM_PEM); $mnet_peer->public_key_expires = $mnet_peer->check_common_name($currentkey); $mnet_peer->updateparams->public_key_expires = $mnet_peer->check_common_name($currentkey); $mnet_peer->commit(); mtrace('My key renewed at ' . $peer->wwwroot . ' till ' . userdate($mnet_peer->public_key_expires)); $trace .= userdate(time()) . ' KEY RENEW from ' . $CFG->wwwroot . ' to ' . $peer->wwwroot . " suceeded\n"; } else { mtrace('Failed renewing key with ' . $peer->wwwroot . "\n");
admin_externalpage_setup('mnetpeers'); $context = get_context_instance(CONTEXT_SYSTEM); require_capability('moodle/site:config', $context, $USER->id, true, "nopermissions"); if (!($site = get_site())) { print_error('nosite', '', '', NULL, true); } /// Initialize variables. $hostid = required_param('hostid', PARAM_INT); $stradministration = get_string('administration'); $strconfiguration = get_string('configuration'); $strmnetedithost = get_string('reviewhostdetails', 'mnet'); $strmnetsettings = get_string('mnetsettings', 'mnet'); $strmnetservices = get_string('mnetservices', 'mnet'); $strmnetthemes = get_string('mnetthemes', 'mnet'); $strmnetlog = get_string('mnetlog', 'mnet'); $mnet_peer = new mnet_peer(); if (is_int($hostid)) { $mnet_peer->set_id($hostid); } $choose = optional_param("choose", '', PARAM_FILE); // set this theme as default $stradministration = get_string("administration"); $strconfiguration = get_string("configuration"); $strthemes = get_string("themes"); $strpreview = get_string("preview"); $strchoose = get_string("choose"); $strinfo = get_string("info"); $strtheme = get_string("theme"); $strthemesaved = get_string("themesaved"); $strscreenshot = get_string("screenshot"); $stroldtheme = get_string("oldtheme");
/** * Send the request to the server - decode and return the response * * @param object $mnet_peer A mnet_peer object with details of the * remote host we're connecting to * @return mixed A PHP variable, as returned by the * remote function */ function send($mnet_peer) { global $CFG, $MNET; $this->uri = $mnet_peer->wwwroot . $mnet_peer->application->xmlrpc_server_url; // Initialize with the target URL $ch = curl_init($this->uri); $system_methods = array('system/listMethods', 'system/methodSignature', 'system/methodHelp', 'system/listServices'); if (in_array($this->method, $system_methods)) { // Executing any system method is permitted. } else { $id_list = $mnet_peer->id; if (!empty($CFG->mnet_all_hosts_id)) { $id_list .= ', ' . $CFG->mnet_all_hosts_id; } // At this point, we don't care if the remote host implements the // method we're trying to call. We just want to know that: // 1. The method belongs to some service, as far as OUR host knows // 2. We are allowed to subscribe to that service on this mnet_peer // Find methods that we subscribe to on this host $sql = "\n SELECT\n r.id\n FROM\n {$CFG->prefix}mnet_rpc r,\n {$CFG->prefix}mnet_service2rpc s2r,\n {$CFG->prefix}mnet_host2service h2s\n WHERE\n r.xmlrpc_path = '{$this->method}' AND\n s2r.rpcid = r.id AND\n s2r.serviceid = h2s.serviceid AND\n h2s.subscribe = '1' AND\n h2s.hostid in ({$id_list})"; if (!record_exists_sql($sql)) { global $USER; $this->error[] = '7:User with ID ' . $USER->id . ' attempted to call unauthorised method ' . $this->method . ' on host ' . $mnet_peer->wwwroot; return false; } } $this->requesttext = xmlrpc_encode_request($this->method, $this->params, array("encoding" => "utf-8", "escaping" => "markup")); $rq = $this->requesttext; $rq = mnet_sign_message($this->requesttext); $this->signedrequest = $rq; $rq = mnet_encrypt_message($rq, $mnet_peer->public_key); $this->encryptedrequest = $rq; curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_USERAGENT, 'Moodle'); curl_setopt($ch, CURLOPT_POSTFIELDS, $rq); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/xml charset=UTF-8")); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); $timestamp_send = time(); $this->rawresponse = curl_exec($ch); $timestamp_receive = time(); if ($this->rawresponse === false) { $this->error[] = curl_errno($ch) . ':' . curl_error($ch); return false; } $this->rawresponse = trim($this->rawresponse); $mnet_peer->touch(); $crypt_parser = new mnet_encxml_parser(); $crypt_parser->parse($this->rawresponse); if ($crypt_parser->payload_encrypted) { $key = array_pop($crypt_parser->cipher); $data = array_pop($crypt_parser->cipher); $crypt_parser->free_resource(); // Initialize payload var $payload = ''; // &$payload $isOpen = openssl_open(base64_decode($data), $payload, base64_decode($key), $MNET->get_private_key()); if (!$isOpen) { // Decryption failed... let's try our archived keys $openssl_history = get_config('mnet', 'openssl_history'); if (empty($openssl_history)) { $openssl_history = array(); set_config('openssl_history', serialize($openssl_history), 'mnet'); } else { $openssl_history = unserialize($openssl_history); } foreach ($openssl_history as $keyset) { $keyresource = openssl_pkey_get_private($keyset['keypair_PEM']); $isOpen = openssl_open(base64_decode($data), $payload, base64_decode($key), $keyresource); if ($isOpen) { // It's an older code, sir, but it checks out break; } } } if (!$isOpen) { trigger_error("None of our keys could open the payload from host {$mnet_peer->wwwroot} with id {$mnet_peer->id}."); $this->error[] = '3:No key match'; return false; } if (strpos(substr($payload, 0, 100), '<signedMessage>')) { $sig_parser = new mnet_encxml_parser(); $sig_parser->parse($payload); } else { $this->error[] = '2:Payload not signed: ' . $payload; return false; } } else { if (!empty($crypt_parser->remoteerror)) { $this->error[] = '4: remote server error: ' . $crypt_parser->remoteerror; } else { if (!empty($crypt_parser->error)) { $crypt_parser_error = $crypt_parser->error[0]; $message = '3:XML Parse error in payload: ' . $crypt_parser_error['string'] . "\n"; if (array_key_exists('lineno', $crypt_parser_error)) { $message .= 'At line number: ' . $crypt_parser_error['lineno'] . "\n"; } if (array_key_exists('line', $crypt_parser_error)) { $message .= 'Which reads: ' . $crypt_parser_error['line'] . "\n"; } $this->error[] = $message; } else { $this->error[] = '1:Payload not encrypted '; } } $crypt_parser->free_resource(); return false; } // Margin of error is the time it took the request to complete. $margin_of_error = $timestamp_receive - $timestamp_send; // Guess the time gap between sending the request and the remote machine // executing the time() function. Marginally better than nothing. $hysteresis = $margin_of_error / 2; $remote_timestamp = $sig_parser->remote_timestamp - $hysteresis; $time_offset = $remote_timestamp - $timestamp_send; if ($time_offset > 0) { $threshold = get_config('mnet', 'drift_threshold'); if (empty($threshold)) { // We decided 15 seconds was a pretty good arbitrary threshold // for time-drift between servers, but you can customize this in // the config_plugins table. It's not advised though. set_config('drift_threshold', 15, 'mnet'); $threshold = 15; } if ($time_offset > $threshold) { $this->error[] = '6:Time gap with ' . $mnet_peer->name . ' (' . $time_offset . ' seconds) is greater than the permitted maximum of ' . $threshold . ' seconds'; return false; } } $this->xmlrpcresponse = base64_decode($sig_parser->data_object); $this->response = xmlrpc_decode($this->xmlrpcresponse); curl_close($ch); // xmlrpc errors are pushed onto the $this->error stack if (is_array($this->response) && array_key_exists('faultCode', $this->response)) { // The faultCode 7025 means we tried to connect with an old SSL key // The faultString is the new key - let's save it and try again // The re_key attribute stops us from getting into a loop if ($this->response['faultCode'] == 7025 && empty($mnet_peer->re_key)) { $record = new stdClass(); $record->id = $mnet_peer->id; if ($this->response['faultString'] == clean_param($this->response['faultString'], PARAM_PEM)) { $record->public_key = $this->response['faultString']; $details = openssl_x509_parse($record->public_key); if (is_array($details) && isset($details['validTo_time_t'])) { $record->public_key_expires = $details['validTo_time_t']; update_record('mnet_host', $record); $mnet_peer2 = new mnet_peer(); $mnet_peer2->set_id($record->id); $mnet_peer2->re_key = true; $this->send($mnet_peer2); } else { $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString']; } } else { $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString']; } } else { if (!empty($CFG->mnet_rpcdebug)) { $guidance = get_string('error' . $this->response['faultCode'], 'mnet'); } else { $guidance = ''; } $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString']; } } // ok, it's signed, but is it signed with the right certificate ? // do this *after* we check for an out of date key $verified = openssl_verify($this->xmlrpcresponse, base64_decode($sig_parser->signature), $mnet_peer->public_key); if ($verified != 1) { $this->error[] = 'Invalid signature'; } return empty($this->error); }
/** * This function is used to generate and display Mnet selector form * * @global stdClass $USER * @global stdClass $CFG * @global stdClass $SITE * @global moodle_database $DB * @global core_renderer $OUTPUT * @global stdClass $SESSION * @uses CONTEXT_SYSTEM * @uses COURSE_MAX_COURSES_PER_DROPDOWN * @uses CONTEXT_COURSE * @uses SEPARATEGROUPS * @param int $hostid host id * @param stdClass $course course instance * @param int $selecteduser id of the selected user * @param string $selecteddate Date selected * @param string $modname course_module->id * @param string $modid number or 'site_errors' * @param string $modaction an action as recorded in the logs * @param int $selectedgroup Group to display * @param int $showcourses whether to show courses if we're over our limit. * @param int $showusers whether to show users if we're over our limit. * @param string $logformat Format of the logs (downloadascsv, showashtml, downloadasods, downloadasexcel) * @return void */ function report_log_print_mnet_selector_form($hostid, $course, $selecteduser = 0, $selecteddate = 'today', $modname = "", $modid = 0, $modaction = '', $selectedgroup = -1, $showcourses = 0, $showusers = 0, $logformat = 'showashtml') { global $USER, $CFG, $SITE, $DB, $OUTPUT, $SESSION; require_once $CFG->dirroot . '/mnet/peer.php'; $mnet_peer = new mnet_peer(); $mnet_peer->set_id($hostid); $sql = "SELECT DISTINCT course, hostid, coursename FROM {mnet_log}"; $courses = $DB->get_records_sql($sql); $remotecoursecount = count($courses); // first check to see if we can override showcourses and showusers $numcourses = $remotecoursecount + $DB->count_records('course'); if ($numcourses < COURSE_MAX_COURSES_PER_DROPDOWN && !$showcourses) { $showcourses = 1; } $sitecontext = get_context_instance(CONTEXT_SYSTEM); // Context for remote data is always SITE // Groups for remote data are always OFF if ($hostid == $CFG->mnet_localhost_id) { $context = get_context_instance(CONTEXT_COURSE, $course->id); /// Setup for group handling. if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) { $selectedgroup = -1; $showgroups = false; } else { if ($course->groupmode) { $showgroups = true; } else { $selectedgroup = 0; $showgroups = false; } } if ($selectedgroup === -1) { if (isset($SESSION->currentgroup[$course->id])) { $selectedgroup = $SESSION->currentgroup[$course->id]; } else { $selectedgroup = groups_get_all_groups($course->id, $USER->id); if (is_array($selectedgroup)) { $selectedgroup = array_shift(array_keys($selectedgroup)); $SESSION->currentgroup[$course->id] = $selectedgroup; } else { $selectedgroup = 0; } } } } else { $context = $sitecontext; } // Get all the possible users $users = array(); // Define limitfrom and limitnum for queries below // If $showusers is enabled... don't apply limitfrom and limitnum $limitfrom = empty($showusers) ? 0 : ''; $limitnum = empty($showusers) ? COURSE_MAX_USERS_PER_DROPDOWN + 1 : ''; // If looking at a different host, we're interested in all our site users if ($hostid == $CFG->mnet_localhost_id && $course->id != SITEID) { $courseusers = get_enrolled_users($context, '', $selectedgroup, 'u.id, u.firstname, u.lastname, u.idnumber', 'lastname ASC, firstname ASC', $limitfrom, $limitnum); } else { // this may be a lot of users :-( $courseusers = $DB->get_records('user', array('deleted' => 0), 'lastaccess DESC', 'id, firstname, lastname, idnumber', $limitfrom, $limitnum); } if (count($courseusers) < COURSE_MAX_USERS_PER_DROPDOWN && !$showusers) { $showusers = 1; } if ($showusers) { if ($courseusers) { foreach ($courseusers as $courseuser) { $users[$courseuser->id] = fullname($courseuser, has_capability('moodle/site:viewfullnames', $context)); } } $users[$CFG->siteguest] = get_string('guestuser'); } // Get all the hosts that have log records $sql = "select distinct\n h.id,\n h.name\n from\n {mnet_host} h,\n {mnet_log} l\n where\n h.id = l.hostid\n order by\n h.name"; if ($hosts = $DB->get_records_sql($sql)) { foreach ($hosts as $host) { $hostarray[$host->id] = $host->name; } } $hostarray[$CFG->mnet_localhost_id] = $SITE->fullname; asort($hostarray); $dropdown = array(); foreach ($hostarray as $hostid => $name) { $courses = array(); $sites = array(); if ($CFG->mnet_localhost_id == $hostid) { if (has_capability('report/log:view', $sitecontext) && $showcourses) { if ($ccc = $DB->get_records("course", null, "fullname", "id,shortname,fullname,category")) { foreach ($ccc as $cc) { if ($cc->id == SITEID) { $sites["{$hostid}/{$cc->id}"] = format_string($cc->fullname) . ' (' . get_string('site') . ')'; } else { $courses["{$hostid}/{$cc->id}"] = format_string(get_course_display_name_for_list($cc)); } } } } } else { if (has_capability('report/log:view', $sitecontext) && $showcourses) { $sql = "SELECT DISTINCT course, coursename FROM {mnet_log} where hostid = ?"; if ($ccc = $DB->get_records_sql($sql, array($hostid))) { foreach ($ccc as $cc) { if (1 == $cc->course) { // TODO: this might be wrong - site course may have another id $sites["{$hostid}/{$cc->course}"] = $cc->coursename . ' (' . get_string('site') . ')'; } else { $courses["{$hostid}/{$cc->course}"] = $cc->coursename; } } } } } asort($courses); $dropdown[] = array($name => $sites + $courses); } $activities = array(); $selectedactivity = ""; /// Casting $course->modinfo to string prevents one notice when the field is null if ($modinfo = unserialize((string) $course->modinfo)) { $section = 0; $sections = get_all_sections($course->id); foreach ($modinfo as $mod) { if ($mod->mod == "label") { continue; } if ($mod->section > 0 and $section != $mod->section) { $activities["section/{$mod->section}"] = '--- ' . get_section_name($course, $sections[$mod->section]) . ' ---'; } $section = $mod->section; $mod->name = strip_tags(format_string($mod->name, true)); if (textlib::strlen($mod->name) > 55) { $mod->name = textlib::substr($mod->name, 0, 50) . "..."; } if (!$mod->visible) { $mod->name = "(" . $mod->name . ")"; } $activities["{$mod->cm}"] = $mod->name; if ($mod->cm == $modid) { $selectedactivity = "{$mod->cm}"; } } } if (has_capability('report/log:view', $sitecontext) && !$course->category) { $activities["site_errors"] = get_string("siteerrors"); if ($modid === "site_errors") { $selectedactivity = "site_errors"; } } $strftimedate = get_string("strftimedate"); $strftimedaydate = get_string("strftimedaydate"); asort($users); // Prepare the list of action options. $actions = array('view' => get_string('view'), 'add' => get_string('add'), 'update' => get_string('update'), 'delete' => get_string('delete'), '-view' => get_string('allchanges')); // Get all the possible dates // Note that we are keeping track of real (GMT) time and user time // User time is only used in displays - all calcs and passing is GMT $timenow = time(); // GMT // What day is it now for the user, and when is midnight that day (in GMT). $timemidnight = $today = usergetmidnight($timenow); // Put today up the top of the list $dates = array("0" => get_string('alldays'), "{$timemidnight}" => get_string("today") . ", " . userdate($timenow, $strftimedate)); if (!$course->startdate or $course->startdate > $timenow) { $course->startdate = $course->timecreated; } $numdates = 1; while ($timemidnight > $course->startdate and $numdates < 365) { $timemidnight = $timemidnight - 86400; $timenow = $timenow - 86400; $dates["{$timemidnight}"] = userdate($timenow, $strftimedaydate); $numdates++; } if ($selecteddate === "today") { $selecteddate = $today; } echo "<form class=\"logselectform\" action=\"{$CFG->wwwroot}/report/log/index.php\" method=\"get\">\n"; echo "<div>\n"; //invisible fieldset here breaks wrapping echo "<input type=\"hidden\" name=\"chooselog\" value=\"1\" />\n"; echo "<input type=\"hidden\" name=\"showusers\" value=\"{$showusers}\" />\n"; echo "<input type=\"hidden\" name=\"showcourses\" value=\"{$showcourses}\" />\n"; if (has_capability('report/log:view', $sitecontext) && $showcourses) { $cid = empty($course->id) ? '1' : $course->id; echo html_writer::label(get_string('selectacoursesite'), 'menuhost_course', false, array('class' => 'accesshide')); echo html_writer::select($dropdown, "host_course", $hostid . '/' . $cid); } else { $courses = array(); $courses[$course->id] = get_course_display_name_for_list($course) . (empty($course->category) ? ' (' . get_string('site') . ') ' : ''); echo html_writer::label(get_string('selectacourse'), 'menuid', false, array('class' => 'accesshide')); echo html_writer::select($courses, "id", $course->id, false); if (has_capability('report/log:view', $sitecontext)) { $a = new stdClass(); $a->url = "{$CFG->wwwroot}/report/log/index.php?chooselog=0&group={$selectedgroup}&user={$selecteduser}" . "&id={$course->id}&date={$selecteddate}&modid={$selectedactivity}&showcourses=1&showusers={$showusers}"; print_string('logtoomanycourses', 'moodle', $a); } } if ($showgroups) { if ($cgroups = groups_get_all_groups($course->id)) { foreach ($cgroups as $cgroup) { $groups[$cgroup->id] = $cgroup->name; } } else { $groups = array(); } echo html_writer::label(get_string('selectagroup'), 'menugroup', false, array('class' => 'accesshide')); echo html_writer::select($groups, "group", $selectedgroup, get_string("allgroups")); } if ($showusers) { echo html_writer::label(get_string('participantslist'), 'menuuser', false, array('class' => 'accesshide')); echo html_writer::select($users, "user", $selecteduser, get_string("allparticipants")); } else { $users = array(); if (!empty($selecteduser)) { $user = $DB->get_record('user', array('id' => $selecteduser)); $users[$selecteduser] = fullname($user); } else { $users[0] = get_string('allparticipants'); } echo html_writer::label(get_string('participantslist'), 'menuuser', false, array('class' => 'accesshide')); echo html_writer::select($users, "user", $selecteduser, false); $a->url = "{$CFG->wwwroot}/report/log/index.php?chooselog=0&group={$selectedgroup}&user={$selecteduser}" . "&id={$course->id}&date={$selecteddate}&modid={$selectedactivity}&showusers=1&showcourses={$showcourses}"; print_string('logtoomanyusers', 'moodle', $a); } echo html_writer::label(get_string('date'), 'menudate', false, array('class' => 'accesshide')); echo html_writer::select($dates, "date", $selecteddate, false); echo html_writer::label(get_string('showreports'), 'menumodid', false, array('class' => 'accesshide')); echo html_writer::select($activities, "modid", $selectedactivity, get_string("allactivities")); echo html_writer::label(get_string('actions'), 'menumodaction', false, array('class' => 'accesshide')); echo html_writer::select($actions, 'modaction', $modaction, get_string("allactions")); $logformats = array('showashtml' => get_string('displayonpage'), 'downloadascsv' => get_string('downloadtext'), 'downloadasods' => get_string('downloadods'), 'downloadasexcel' => get_string('downloadexcel')); echo html_writer::label(get_string('logsformat', 'report_log'), 'menulogformat', false, array('class' => 'accesshide')); echo html_writer::select($logformats, 'logformat', $logformat, false); echo '<input type="submit" value="' . get_string('gettheselogs') . '" />'; echo '</div>'; echo '</form>'; }
$temp_member = new mnet_peer(); $temp_member->set_wwwroot($subnetwork_host->wwwroot); // RPC error. if (!$rpc_client->send($temp_member)) { echo $OUTPUT->notification(implode('<br />', $rpc_client->getErrors($temp_member))); if (debugging()) { echo '<pre>'; var_dump($rpc_client); echo '</pre>'; } } } $rpc_client = new \local_vmoodle\XmlRpc_Client(); $rpc_client->set_method('local/vmoodle/rpclib.php/mnetadmin_rpc_disconnect_from_subnetwork'); $rpc_client->add_param($subnetwork_hosts, 'array'); $deleted_peer = new mnet_peer(); $deleted_peer->set_wwwroot($vmoodle_host->wwwroot); // RPC error. if (!$rpc_client->send($deleted_peer)) { echo $OUTPUT->notification(implode('<br />', $rpc_client->getErrors($deleted_peer))); if (debugging()) { echo '<pre>'; var_dump($rpc_client); echo '</pre>'; } } } // Every step was SUCCESS. $message_object->message = get_string('successdeletehost', 'local_vmoodle'); $message_object->style = 'notifysuccess'; }
function validation($data, $files) { $errors = array(); if ($data['oldpublickey'] == $data['public_key']) { return; } $mnet_peer = new mnet_peer(); // idiotic api $mnet_peer->wwwroot = $data['wwwroot']; // just hard-set this rather than bootstrap the object if (empty($data['public_key'])) { $errors['public_key'] = get_string('publickeyrequired', 'mnet'); } else { if (!($credentials = $mnet_peer->check_credentials($data['public_key']))) { $errmsg = ''; foreach ($mnet_peer->error as $err) { $errmsg .= $err['code'] . ': ' . $err['text'] . '<br />'; } $errors['public_key'] = get_string('invalidpubkey', 'mnet', $errmsg); } } unset($mnet_peer); return $errors; }
/** * Work out the theme this page should use. * * This depends on numerous $CFG settings, and the properties of this page. * * @return string the name of the theme that should be used on this page. */ protected function resolve_theme() { global $CFG, $USER, $SESSION; if (empty($CFG->themeorder)) { $themeorder = array('course', 'category', 'session', 'user', 'site'); } else { $themeorder = $CFG->themeorder; // Just in case, make sure we always use the site theme if nothing else matched. $themeorder[] = 'site'; } $mnetpeertheme = ''; if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id) { require_once $CFG->dirroot . '/mnet/peer.php'; $mnetpeer = new mnet_peer(); $mnetpeer->set_id($USER->mnethostid); if ($mnetpeer->force_theme == 1 && $mnetpeer->theme != '') { $mnetpeertheme = $mnetpeer->theme; } } $devicetheme = core_useragent::get_device_type_theme($this->devicetypeinuse); // The user is using another device than default, and we have a theme for that, we should use it. $hascustomdevicetheme = core_useragent::DEVICETYPE_DEFAULT != $this->devicetypeinuse && !empty($devicetheme); foreach ($themeorder as $themetype) { switch ($themetype) { case 'course': if (!empty($CFG->allowcoursethemes) && !empty($this->_course->theme) && !$hascustomdevicetheme) { return $this->_course->theme; } break; case 'category': if (!empty($CFG->allowcategorythemes) && !$hascustomdevicetheme) { $categories = $this->categories; foreach ($categories as $category) { if (!empty($category->theme)) { return $category->theme; } } } break; case 'session': if (!empty($SESSION->theme)) { return $SESSION->theme; } break; case 'user': if (!empty($CFG->allowuserthemes) && !empty($USER->theme) && !$hascustomdevicetheme) { if ($mnetpeertheme) { return $mnetpeertheme; } else { return $USER->theme; } } break; case 'site': if ($mnetpeertheme) { return $mnetpeertheme; } // First try for the device the user is using. if (!empty($devicetheme)) { return $devicetheme; } // Next try for the default device (as a fallback). $devicetheme = core_useragent::get_device_type_theme(core_useragent::DEVICETYPE_DEFAULT); if (!empty($devicetheme)) { return $devicetheme; } // The default device theme isn't set up - use the overall default theme. return theme_config::DEFAULT_THEME; } } // We should most certainly have resolved a theme by now. Something has gone wrong. debugging('Error resolving the theme to use for this page.', DEBUG_DEVELOPER); return theme_config::DEFAULT_THEME; }
/** * Returns the name of the current theme * * @uses $CFG * @uses $USER * @uses $SESSION * @uses $COURSE * @uses $SCRIPT * @return string */ function current_theme() { global $CFG, $USER, $SESSION, $COURSE, $SCRIPT; if (empty($CFG->themeorder)) { $themeorder = array('page', 'course', 'category', 'session', 'user', 'site'); } else { $themeorder = $CFG->themeorder; } if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id) { require_once $CFG->dirroot . '/mnet/peer.php'; $mnet_peer = new mnet_peer(); $mnet_peer->set_id($USER->mnethostid); } $theme = ''; foreach ($themeorder as $themetype) { if (!empty($theme)) { continue; } switch ($themetype) { case 'page': // Page theme is for special page-only themes set by code if (!empty($CFG->pagetheme)) { $theme = $CFG->pagetheme; } break; case 'course': if (!empty($CFG->allowcoursethemes) and !empty($COURSE->theme)) { $theme = $COURSE->theme; } break; case 'category': if (!empty($CFG->allowcategorythemes)) { /// Nasty hack to check if we're in a category page if ($SCRIPT == '/course/category.php') { global $id; if (!empty($id)) { $theme = current_category_theme($id); } /// Otherwise check if we're in a course that has a category theme set } else { if (!empty($COURSE->category)) { $theme = current_category_theme($COURSE->category); } } } break; case 'session': if (!empty($SESSION->theme)) { $theme = $SESSION->theme; } break; case 'user': if (!empty($CFG->allowuserthemes) and !empty($USER->theme)) { if (isloggedin() and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') { $theme = $mnet_peer->theme; } else { $theme = $USER->theme; } } break; case 'site': if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id && $mnet_peer->force_theme == 1 && $mnet_peer->theme != '') { $theme = $mnet_peer->theme; } else { $theme = $CFG->theme; } break; default: /// do nothing } } /// A final check in case 'site' was not included in $CFG->themeorder if (empty($theme)) { $theme = $CFG->theme; } return $theme; }
// enrol_config.php - allows admin to edit all enrollment variables // Yes, enrol is correct English spelling. require_once dirname(__FILE__) . "/../../config.php"; require_once $CFG->libdir . '/adminlib.php'; include_once $CFG->dirroot . '/mnet/xmlrpc/client.php'; if (!confirm_sesskey()) { error(get_string('confirmsesskeybad', 'error')); } admin_externalpage_setup('mnetenrol'); $CFG->pagepath = 'admin/mnet'; require_once "{$CFG->dirroot}/enrol/enrol.class.php"; /// Open the factory class $enrolment = enrolment_factory::factory('mnet'); $mnethostid = required_param('host', PARAM_INT); $courseid = required_param('courseid', PARAM_INT); $mnet_peer = new mnet_peer(); if (!$mnet_peer->set_id($mnethostid)) { print_error('hostcoursenotfound', 'mnet'); } $course = get_record('mnet_enrol_course', 'id', $courseid, 'hostid', $mnet_peer->id); if (empty($course)) { print_error('hostcoursenotfound', 'mnet'); } define("MAX_USERS_PER_PAGE", 5000); $add = optional_param('add', 0, PARAM_BOOL); $remove = optional_param('remove', 0, PARAM_BOOL); $showall = optional_param('showall', 0, PARAM_BOOL); $searchtext = optional_param('searchtext', '', PARAM_RAW); // search string $previoussearch = optional_param('previoussearch', 0, PARAM_BOOL); $userid = optional_param('userid', 0, PARAM_INT);
require_login(); $context = get_context_instance(CONTEXT_SYSTEM); require_capability('moodle/site:config', $context, $USER->id, true, "nopermissions"); if (!($site = get_site())) { print_error('nosite', '', '', NULL, true); } /// Initialize variables. // Step must be one of: // input Parse the details of a new host and fetch its public key // commit Save our changes (to a new OR existing host) $step = optional_param('step', 'verify', PARAM_ALPHA); $hostid = required_param('hostid', PARAM_INT); $warn = array(); if ($_SERVER['REQUEST_METHOD'] != 'POST') { redirect('index.php', get_string('postrequired', 'mnet'), 7); } require_sesskey(); if ('verify' == $step) { $mnet_peer = new mnet_peer(); $mnet_peer->set_id($hostid); $live_users = $mnet_peer->count_live_sessions(); if ($live_users > 0) { $warn[] = get_string('usersareonline', 'mnet', $live_users); } include 'delete.html'; } elseif ('delete' == $step) { $mnet_peer = new mnet_peer(); $mnet_peer->set_id($hostid); $mnet_peer->delete(); redirect('peers.php', get_string('hostdeleted', 'mnet'), 5); }
/** * Send request to unenrol our user from the remote course * * Updates our remote enrolments cache if the unenrolment was successful. * * @uses mnet_xmlrpc_client Invokes XML-RPC request * @param object $user our user * @param object $remotecourse record from mnetservice_enrol_courses table * @return true|string true if success, error message from the remote host otherwise */ public function req_unenrol_user(stdclass $user, stdclass $remotecourse) { global $CFG, $DB; require_once $CFG->dirroot . '/mnet/xmlrpc/client.php'; $peer = new mnet_peer(); $peer->set_id($remotecourse->hostid); $request = new mnet_xmlrpc_client(); $request->set_method('enrol/mnet/enrol.php/unenrol_user'); $request->add_param($user->username); $request->add_param($remotecourse->remoteid); if ($request->send($peer) === true) { if ($request->response === true) { // clear the cached information $DB->delete_records('mnetservice_enrol_enrolments', array('hostid' => $peer->id, 'userid' => $user->id, 'remotecourseid' => $remotecourse->remoteid, 'enroltype' => 'mnet')); return true; } else { return serialize(array('invalid response: ' . print_r($request->response, true))); } } else { return serialize($request->error); } }
/** * Accepts a public key from a new remote host and returns the public key for * this host. If 'register all hosts' is turned on, it will bootstrap a record * for the remote host in the mnet_host table (if it's not already there) * * @param string $function XML-RPC requires this but we don't... discard! * @param array $params Array of parameters * $params[0] is the remote wwwroot * $params[1] is the remote public key * @return string The XML-RPC response */ function mnet_keyswap($function, $params) { global $CFG; $return = array(); $mnet = get_mnet_environment(); if (!empty($CFG->mnet_register_allhosts)) { $mnet_peer = new mnet_peer(); @list($wwwroot, $pubkey, $application) = each($params); $keyok = $mnet_peer->bootstrap($wwwroot, $pubkey, $application); if ($keyok) { $mnet_peer->commit(); } } return $mnet->public_key; }
function print_mnet_log_selector_form($hostid, $course, $selecteduser = 0, $selecteddate = 'today', $modname = "", $modid = 0, $modaction = '', $selectedgroup = -1, $showcourses = 0, $showusers = 0, $logformat = 'showashtml') { global $USER, $CFG, $SITE; require_once $CFG->dirroot . '/mnet/peer.php'; $mnet_peer = new mnet_peer(); $mnet_peer->set_id($hostid); $sql = "select distinct course, hostid, coursename from {$CFG->prefix}mnet_log"; $courses = get_records_sql($sql); $remotecoursecount = count($courses); // first check to see if we can override showcourses and showusers $numcourses = $remotecoursecount + count_records_select("course", "", "COUNT(id)"); if ($numcourses < COURSE_MAX_COURSES_PER_DROPDOWN && !$showcourses) { $showcourses = 1; } $sitecontext = get_context_instance(CONTEXT_SYSTEM, SITEID); // Context for remote data is always SITE // Groups for remote data are always OFF if ($hostid == $CFG->mnet_localhost_id) { $context = get_context_instance(CONTEXT_COURSE, $course->id); /// Setup for group handling. if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) { $selectedgroup = get_current_group($course->id); $showgroups = false; } else { if ($course->groupmode) { $selectedgroup = $selectedgroup == -1 ? get_current_group($course->id) : $selectedgroup; $showgroups = true; } else { $selectedgroup = 0; $showgroups = false; } } } else { $context = $sitecontext; } // Get all the possible users $users = array(); // If looking at a different host, we're interested in all our site users if ($hostid == $CFG->mnet_localhost_id && $course->id != SITEID) { if ($selectedgroup) { // If using a group, only get users in that group. $courseusers = get_group_users($selectedgroup, 'u.lastname ASC', '', 'u.id, u.firstname, u.lastname, u.idnumber'); } else { $courseusers = get_course_users($course->id, '', '', 'u.id, u.firstname, u.lastname, u.idnumber'); } } else { $courseusers = get_site_users("u.lastaccess DESC", "u.id, u.firstname, u.lastname, u.idnumber"); } if (count($courseusers) < COURSE_MAX_USERS_PER_DROPDOWN && !$showusers) { $showusers = 1; } if ($showusers) { if ($courseusers) { foreach ($courseusers as $courseuser) { $users[$courseuser->id] = fullname($courseuser, has_capability('moodle/site:viewfullnames', $context)); } } if ($guest = get_guest()) { $users[$guest->id] = fullname($guest); } } // Get all the hosts that have log records $sql = "select distinct\n h.id,\n h.name\n from\n {$CFG->prefix}mnet_host h,\n {$CFG->prefix}mnet_log l\n where\n h.id = l.hostid\n order by\n h.name"; if ($hosts = get_records_sql($sql)) { foreach ($hosts as $host) { $hostarray[$host->id] = $host->name; } } $hostarray[$CFG->mnet_localhost_id] = $SITE->fullname; asort($hostarray); foreach ($hostarray as $hostid => $name) { $courses = array(); $sites = array(); if ($CFG->mnet_localhost_id == $hostid) { if (has_capability('moodle/site:viewreports', $sitecontext) && $showcourses) { if ($ccc = get_records("course", "", "", "fullname", "id,fullname,category")) { foreach ($ccc as $cc) { if ($cc->id == SITEID) { $sites["{$hostid}/{$cc->id}"] = format_string($cc->fullname) . ' (' . get_string('site') . ')'; } else { $courses["{$hostid}/{$cc->id}"] = format_string($cc->fullname); } } } } } else { if (has_capability('moodle/site:viewreports', $sitecontext) && $showcourses) { $sql = "select distinct course, coursename from {$CFG->prefix}mnet_log where hostid = '{$hostid}'"; if ($ccc = get_records_sql($sql)) { foreach ($ccc as $cc) { if (1 == $cc->course) { // TODO: this might be wrong - site course may have another id $sites["{$hostid}/{$cc->course}"] = $cc->coursename . ' (' . get_string('site') . ')'; } else { $courses["{$hostid}/{$cc->course}"] = $cc->coursename; } } } } } asort($courses); $dropdown[$name] = $sites + $courses; } $activities = array(); $selectedactivity = ""; /// Casting $course->modinfo to string prevents one notice when the field is null if ($modinfo = unserialize((string) $course->modinfo)) { $section = 0; if ($course->format == 'weeks') { // Bodgy $strsection = get_string("week"); } else { $strsection = get_string("topic"); } foreach ($modinfo as $mod) { if ($mod->mod == "label") { continue; } if ($mod->section > 0 and $section != $mod->section) { $activities["section/{$mod->section}"] = "-------------- {$strsection} {$mod->section} --------------"; } $section = $mod->section; $mod->name = strip_tags(format_string(urldecode($mod->name), true)); if (strlen($mod->name) > 55) { $mod->name = substr($mod->name, 0, 50) . "..."; } if (!$mod->visible) { $mod->name = "(" . $mod->name . ")"; } $activities["{$mod->cm}"] = $mod->name; if ($mod->cm == $modid) { $selectedactivity = "{$mod->cm}"; } } } if (has_capability('moodle/site:viewreports', $sitecontext) && !$course->category) { $activities["site_errors"] = get_string("siteerrors"); if ($modid === "site_errors") { $selectedactivity = "site_errors"; } } $strftimedate = get_string("strftimedate"); $strftimedaydate = get_string("strftimedaydate"); asort($users); // Prepare the list of action options. $actions = array('view' => get_string('view'), 'add' => get_string('add'), 'update' => get_string('update'), 'delete' => get_string('delete'), '-view' => get_string('allchanges')); // Get all the possible dates // Note that we are keeping track of real (GMT) time and user time // User time is only used in displays - all calcs and passing is GMT $timenow = time(); // GMT // What day is it now for the user, and when is midnight that day (in GMT). $timemidnight = $today = usergetmidnight($timenow); // Put today up the top of the list $dates = array("{$timemidnight}" => get_string("today") . ", " . userdate($timenow, $strftimedate)); if (!$course->startdate or $course->startdate > $timenow) { $course->startdate = $course->timecreated; } $numdates = 1; while ($timemidnight > $course->startdate and $numdates < 365) { $timemidnight = $timemidnight - 86400; $timenow = $timenow - 86400; $dates["{$timemidnight}"] = userdate($timenow, $strftimedaydate); $numdates++; } if ($selecteddate == "today") { $selecteddate = $today; } echo "<form class=\"logselectform\" action=\"{$CFG->wwwroot}/course/report/log/index.php\" method=\"get\">\n"; echo "<div>\n"; //invisible fieldset here breaks wrapping echo "<input type=\"hidden\" name=\"chooselog\" value=\"1\" />\n"; echo "<input type=\"hidden\" name=\"showusers\" value=\"{$showusers}\" />\n"; echo "<input type=\"hidden\" name=\"showcourses\" value=\"{$showcourses}\" />\n"; if (has_capability('moodle/site:viewreports', $sitecontext) && $showcourses) { $cid = empty($course->id) ? '1' : $course->id; choose_from_menu_nested($dropdown, "host_course", $hostid . '/' . $cid, ""); } else { $courses = array(); $courses[$course->id] = $course->fullname . (empty($course->category) ? ' (' . get_string('site') . ') ' : ''); choose_from_menu($courses, "id", $course->id, false); if (has_capability('moodle/site:viewreports', $sitecontext)) { $a = new object(); $a->url = "{$CFG->wwwroot}/course/report/log/index.php?chooselog=0&group={$selectedgroup}&user={$selecteduser}" . "&id={$course->id}&date={$selecteddate}&modid={$selectedactivity}&showcourses=1&showusers={$showusers}"; print_string('logtoomanycourses', 'moodle', $a); } } if ($showgroups) { if ($cgroups = groups_get_all_groups($course->id)) { foreach ($cgroups as $cgroup) { $groups[$cgroup->id] = $cgroup->name; } } else { $groups = array(); } choose_from_menu($groups, "group", $selectedgroup, get_string("allgroups")); } if ($showusers) { choose_from_menu($users, "user", $selecteduser, get_string("allparticipants")); } else { $users = array(); if (!empty($selecteduser)) { $user = get_record('user', 'id', $selecteduser); $users[$selecteduser] = fullname($user); } else { $users[0] = get_string('allparticipants'); } choose_from_menu($users, 'user', $selecteduser, false); $a->url = "{$CFG->wwwroot}/course/report/log/index.php?chooselog=0&group={$selectedgroup}&user={$selecteduser}" . "&id={$course->id}&date={$selecteddate}&modid={$selectedactivity}&showusers=1&showcourses={$showcourses}"; print_string('logtoomanyusers', 'moodle', $a); } choose_from_menu($dates, "date", $selecteddate, get_string("alldays")); choose_from_menu($activities, "modid", $selectedactivity, get_string("allactivities"), "", ""); choose_from_menu($actions, 'modaction', $modaction, get_string("allactions")); $logformats = array('showashtml' => get_string('displayonpage'), 'downloadascsv' => get_string('downloadtext'), 'downloadasods' => get_string('downloadods'), 'downloadasexcel' => get_string('downloadexcel')); choose_from_menu($logformats, 'logformat', $logformat, false); echo '<input type="submit" value="' . get_string('gettheselogs') . '" />'; echo '</div>'; echo '</form>'; }
$Out->print_r($session_decoded, '$session_decoded (1.1)= '); $Out->flush(); die(); */ $paramArray[0] = array(); $paramArray[1] = array(array('testing just to see if it is working correctly from the client', 'string')); //$paramArray[2] = array(array('1020000002-3', 'string')); $paramArray[2] = array(array('1010000009-3', 'string'), array($wwwroot, 'string'), array($session->id, 'string')); $paramArray[3] = array(array('1010000008-3', 'string'), array($wwwroot, 'string'), array($session->id, 'string'), array('backup-teco1-20071002-1631.1191339106.merge.zip', 'string')); $paramArray[4] = array(); $paramArray[5] = array(array('101-1', 'string'), array('2', 'string')); echo 'Your local wwwroot appears to be <strong>' . $wwwroot . "</strong>.<br />\n"; echo "We will use this as the local <em>and</em> remote hosts.<br /><br />\n"; flush(); // mnet_peer pulls information about a remote host from the database. $mnet_peer = new mnet_peer(); $mnet_peer->set_wwwroot($wwwroot); $mnethostid = 1020000003; $mnet_peer->set_id($mnethostid); /* echo "Your \$mnet_peer from the database looks like:<br />\n<pre>"; $h2 = get_object_vars($mnet_peer); while(list($key, $val) = each($h2)) { echo '<strong>'.$key.':</strong> '. gettype($val)."\n"; if(!is_numeric($key)){ switch (gettype($val)) { case 'object': echo '<pre>'.print_r($key).'</pre><br />'; echo '<pre>'.print_r($val).'</pre>'; break;