示例#1
0
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;
}
/**
 * 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));
        }
    }
}
示例#3
0
 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('&nbsp;&nbsp; <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;
 }
示例#4
0
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;
}
                 $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';
     }
 } else {
示例#6
0
    }
    // 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>&nbsp;&nbsp;Service ID&nbsp;&nbsp;</th><th>&nbsp;&nbsp;Service&nbsp;&nbsp;</th><th>&nbsp;&nbsp;Version&nbsp;&nbsp;</th><th>&nbsp;&nbsp;They Publish&nbsp;&nbsp;</th><th>&nbsp;&nbsp;They Subscribe&nbsp;&nbsp;</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);
            echo '<td>' . $service['humanname'] . '</td>';
示例#7
0
<?php 
    // For the demo, our 'remote' host is actually our local host.
    $wwwroot = $CFG->wwwroot;
    // Enter the complete path to the file that contains the function you want to
    // call on the remote server. In our example the function is in
    // mnet/testlib/
    // The function itself is added to that path to complete the $path_to_function
    // variable
    $path_to_function[0] = '_development/20070808/rpclib/fetch_user_image';
    $paramArray[0] = array();
    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);
    /*
    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;
    	    	default:
    	    		echo '<strong>'.$key.':</strong> '. $val."\n";
    	    		break;
 /**
  * Download a file
  * @global object $CFG
  * @param string $url the url of file
  * @param string $file save location
  * @return string the location of the file
  * @see curl package
  */
 public function get_file($url, $file = '')
 {
     global $CFG, $DB, $USER;
     ///set mnet environment and set the mnet host
     require_once $CFG->dirroot . '/mnet/xmlrpc/client.php';
     $this->ensure_environment();
     $host = $DB->get_record('mnet_host', array('id' => $this->options['peer']));
     //retrieve the host url
     $mnet_peer = new mnet_peer();
     $mnet_peer->set_wwwroot($host->wwwroot);
     ///create the client and set the method to call
     $client = new mnet_xmlrpc_client();
     $client->set_method('repository/remotemoodle/repository.class.php/retrieveFile');
     $client->add_param($USER->username);
     $client->add_param($url);
     ///call the method and manage host error
     if (!$client->send($mnet_peer)) {
         $message = " ";
         foreach ($client->error as $errormessage) {
             $message .= "ERROR: {$errormessage} . ";
         }
         echo json_encode(array('e' => $message));
         exit;
     }
     $services = $client->response;
     //service contains the file content in the first case of the array,
     //and the filename in the second
     //the content has been encoded in base64, need to decode it
     $content = base64_decode($services[0]);
     $file = $services[1];
     //filename
     ///create a temporary folder with a file
     $path = $this->prepare_file($file);
     ///fill the file with the content
     $fp = fopen($path, 'w');
     fwrite($fp, $content);
     fclose($fp);
     return $path;
 }
示例#9
0
 /**
  * This function confirms the remote (ID provider) host's mnet session
  * by communicating the token and UA over the XMLRPC transport layer, and
  * returns the local user record on success.
  *
  *   @param string $token           The random session token.
  *   @param string $remotewwwroot   The ID provider wwwroot.
  *   @return array The local user record.
  */
 function confirm_mnet_session($token, $remotewwwroot)
 {
     global $CFG, $MNET, $SESSION, $DB;
     require_once $CFG->dirroot . '/mnet/xmlrpc/client.php';
     // verify the remote host is configured locally before attempting RPC call
     if (!($remotehost = $DB->get_record('mnet_host', array('wwwroot' => $remotewwwroot, 'deleted' => 0)))) {
         print_error('notpermittedtoland', 'mnet');
     }
     // get the originating (ID provider) host info
     $remotepeer = new mnet_peer();
     $remotepeer->set_wwwroot($remotewwwroot);
     // set up the RPC request
     $mnetrequest = new mnet_xmlrpc_client();
     $mnetrequest->set_method('auth/mnet/auth.php/user_authorise');
     // set $token and $useragent parameters
     $mnetrequest->add_param($token);
     $mnetrequest->add_param(sha1($_SERVER['HTTP_USER_AGENT']));
     // Thunderbirds are go! Do RPC call and store response
     if ($mnetrequest->send($remotepeer) === true) {
         $remoteuser = (object) $mnetrequest->response;
     } else {
         foreach ($mnetrequest->error as $errormessage) {
             list($code, $message) = array_map('trim', explode(':', $errormessage, 2));
             if ($code == 702) {
                 $site = get_site();
                 print_error('mnet_session_prohibited', 'mnet', $remotewwwroot, format_string($site->fullname));
                 exit;
             }
             $message .= "ERROR {$code}:<br/>{$errormessage}<br/>";
         }
         print_error("rpcerror", '', '', $message);
     }
     unset($mnetrequest);
     if (empty($remoteuser) or empty($remoteuser->username)) {
         print_error('unknownerror', 'mnet');
         exit;
     }
     $firsttime = false;
     // get the local record for the remote user
     $localuser = $DB->get_record('user', array('username' => $remoteuser->username, 'mnethostid' => $remotehost->id));
     // add the remote user to the database if necessary, and if allowed
     // TODO: refactor into a separate function
     if (empty($localuser) || !$localuser->id) {
         if (empty($this->config->auto_add_remote_users)) {
             print_error('nolocaluser', 'mnet');
         }
         $remoteuser->mnethostid = $remotehost->id;
         $DB->insert_record('user', $remoteuser);
         $firsttime = true;
         if (!($localuser = $DB->get_record('user', array('username' => $remoteuser->username, 'mnethostid' => $remotehost->id)))) {
             print_error('nolocaluser', 'mnet');
         }
     }
     // check sso access control list for permission first
     if (!$this->can_login_remotely($localuser->username, $remotehost->id)) {
         print_error('sso_mnet_login_refused', 'mnet', '', array($localuser->username, $remotehost->name));
     }
     $session_gc_maxlifetime = 1440;
     // update the local user record with remote user data
     foreach ((array) $remoteuser as $key => $val) {
         if ($key == 'session.gc_maxlifetime') {
             $session_gc_maxlifetime = $val;
             continue;
         }
         // TODO: fetch image if it has changed
         if ($key == 'imagehash') {
             $dirname = make_user_directory($localuser->id, true);
             $filename = "{$dirname}/f1.jpg";
             $localhash = '';
             if (file_exists($filename)) {
                 $localhash = sha1(file_get_contents($filename));
             } elseif (!file_exists($dirname)) {
                 mkdir($dirname);
             }
             if ($localhash != $val) {
                 // fetch image from remote host
                 $fetchrequest = new mnet_xmlrpc_client();
                 $fetchrequest->set_method('auth/mnet/auth.php/fetch_user_image');
                 $fetchrequest->add_param($localuser->username);
                 if ($fetchrequest->send($remotepeer) === true) {
                     if (strlen($fetchrequest->response['f1']) > 0) {
                         $imagecontents = base64_decode($fetchrequest->response['f1']);
                         file_put_contents($filename, $imagecontents);
                         $localuser->picture = 1;
                     }
                     if (strlen($fetchrequest->response['f2']) > 0) {
                         $imagecontents = base64_decode($fetchrequest->response['f2']);
                         file_put_contents($dirname . '/f2.jpg', $imagecontents);
                     }
                 }
             }
         }
         if ($key == 'myhosts') {
             $localuser->mnet_foreign_host_array = array();
             foreach ($val as $rhost) {
                 $name = clean_param($rhost['name'], PARAM_ALPHANUM);
                 $url = clean_param($rhost['url'], PARAM_URL);
                 $count = clean_param($rhost['count'], PARAM_INT);
                 $url_is_local = stristr($url, $CFG->wwwroot);
                 if (!empty($name) && !empty($count) && empty($url_is_local)) {
                     $localuser->mnet_foreign_host_array[] = array('name' => $name, 'url' => $url, 'count' => $count);
                 }
             }
         }
         $localuser->{$key} = $val;
     }
     $localuser->mnethostid = $remotepeer->id;
     $DB->update_record('user', $localuser);
     // set up the session
     $mnet_session = $DB->get_record('mnet_session', array('userid' => $localuser->id, 'mnethostid' => $remotepeer->id, 'useragent' => sha1($_SERVER['HTTP_USER_AGENT'])));
     if ($mnet_session == false) {
         $mnet_session = new object();
         $mnet_session->mnethostid = $remotepeer->id;
         $mnet_session->userid = $localuser->id;
         $mnet_session->username = $localuser->username;
         $mnet_session->useragent = sha1($_SERVER['HTTP_USER_AGENT']);
         $mnet_session->token = $token;
         // Needed to support simultaneous sessions
         // and preserving DB rec uniqueness
         $mnet_session->confirm_timeout = time();
         $mnet_session->expires = time() + (int) $session_gc_maxlifetime;
         $mnet_session->session_id = session_id();
         $mnet_session->id = $DB->insert_record('mnet_session', $mnet_session);
     } else {
         $mnet_session->expires = time() + (int) $session_gc_maxlifetime;
         $DB->update_record('mnet_session', $mnet_session);
     }
     if (!$firsttime) {
         // repeat customer! let the IDP know about enrolments
         // we have for this user.
         // set up the RPC request
         $mnetrequest = new mnet_xmlrpc_client();
         $mnetrequest->set_method('auth/mnet/auth.php/update_enrolments');
         // pass username and an assoc array of "my courses"
         // with info so that the IDP can maintain mnet_enrol_assignments
         $mnetrequest->add_param($remoteuser->username);
         $fields = 'id, category, sortorder, fullname, shortname, idnumber, summary,
                    startdate, cost, currency, defaultrole, visible';
         $courses = get_my_courses($localuser->id, 'visible DESC,sortorder ASC', $fields);
         if (is_array($courses) && !empty($courses)) {
             // Second request to do the JOINs that we'd have done
             // inside get_my_courses() if we had been allowed
             $sql = "SELECT c.id,\n                               cc.name AS cat_name, cc.description AS cat_description,\n                               r.shortname as defaultrolename\n                          FROM {course} c\n                          JOIN {course_categories} cc ON c.category = cc.id\n                          LEFT OUTER JOIN {role} r  ON c.defaultrole = r.id\n                         WHERE c.id IN (" . join(',', array_keys($courses)) . ')';
             $extra = $DB->get_records_sql($sql);
             $keys = array_keys($courses);
             $defaultrolename = $DB->get_field('role', 'shortname', array('id' => $CFG->defaultcourseroleid));
             foreach ($keys as $id) {
                 if ($courses[$id]->visible == 0) {
                     unset($courses[$id]);
                     continue;
                 }
                 $courses[$id]->cat_id = $courses[$id]->category;
                 $courses[$id]->defaultroleid = $courses[$id]->defaultrole;
                 unset($courses[$id]->category);
                 unset($courses[$id]->defaultrole);
                 unset($courses[$id]->visible);
                 $courses[$id]->cat_name = $extra[$id]->cat_name;
                 $courses[$id]->cat_description = $extra[$id]->cat_description;
                 if (!empty($extra[$id]->defaultrolename)) {
                     $courses[$id]->defaultrolename = $extra[$id]->defaultrolename;
                 } else {
                     $courses[$id]->defaultrolename = $defaultrolename;
                 }
                 // coerce to array
                 $courses[$id] = (array) $courses[$id];
             }
         } else {
             // if the array is empty, send it anyway
             // we may be clearing out stale entries
             $courses = array();
         }
         $mnetrequest->add_param($courses);
         // Call 0800-RPC Now! -- we don't care too much if it fails
         // as it's just informational.
         if ($mnetrequest->send($remotepeer) === false) {
             // error_log(print_r($mnetrequest->error,1));
         }
     }
     return $localuser;
 }
     // emulate response
     $result = tracker_rpc_post_issue($USER->username, $CFG->wwwroot, $tracker->parent, json_encode($issue));
 } else {
     // tracker is remote, make an RPC call
     list($remoteid, $mnet_host) = explode('@', $tracker->parent);
     // get network tracker properties
     include_once $CFG->dirroot . '/mnet/xmlrpc/client.php';
     $userroot = get_field('mnet_host', 'wwwroot', 'id', $USER->mnethostid);
     $rpcclient = new mnet_xmlrpc_client();
     $rpcclient->set_method('mod/tracker/rpclib.php/tracker_rpc_post_issue');
     $rpcclient->add_param($USER->username, 'string');
     $rpcclient->add_param($userroot, 'string');
     $rpcclient->add_param($remoteid, 'int');
     $rpcclient->add_param(json_encode($issue), 'string');
     $parent_mnet = new mnet_peer();
     $parent_mnet->set_wwwroot($mnet_host);
     if ($rpcclient->send($parent_mnet)) {
         $result = $rpcclient->response;
     } else {
         $result = null;
     }
 }
 if ($result) {
     $response = json_decode($result);
     if ($response->status == RPC_SUCCESS) {
         $issue->status = TRANSFERED;
         $issue->followid = $response->followid;
         if (!update_record('tracker_issue', addslashes_recursive($issue))) {
             error("Could not update issue for cascade");
         }
     } else {
示例#11
0
function local_mahara_mnet_call()
{
    global $CFG, $MNET;
    if ($CFG->mnet_dispatcher_mode != 'strict') {
        return;
    }
    if (!($host = get_record('mnet_host', 'name', 'localmahara'))) {
        return;
    }
    require_once $CFG->dirroot . '/mnet/xmlrpc/client.php';
    if (empty($MNET)) {
        $MNET = new mnet_environment();
        $MNET->init();
    }
    $args = func_get_args();
    $method = array_shift($args);
    $mnet_peer = new mnet_peer();
    $mnet_peer->set_wwwroot($host->wwwroot);
    $client = new mnet_xmlrpc_client();
    $client->set_method($method);
    foreach ($args as $a) {
        $client->add_param($a);
    }
    $client->send($mnet_peer);
    return $client->response;
}
示例#12
0
$wantsurl = required_param('wantsurl', PARAM_LOCALURL);
$wantsremoteurl = optional_param('remoteurl', false, PARAM_BOOL);
$url = new moodle_url('/auth/mnet/jump.php', array('token' => $token, 'idp' => $remotewwwroot, 'wantsurl' => $wantsurl));
if ($wantsremoteurl !== false) {
    $url->param('remoteurl', $wantsremoteurl);
}
$PAGE->set_url($url);
$PAGE->set_context(context_system::instance());
$site = get_site();
if (!is_enabled_auth('mnet')) {
    print_error('mnetdisable');
}
// confirm the MNET session
$mnetauth = get_auth_plugin('mnet');
$remotepeer = new mnet_peer();
$remotepeer->set_wwwroot($remotewwwroot);
// this creates the local user account if necessary, or updates it if it already exists
$localuser = $mnetauth->confirm_mnet_session($token, $remotepeer);
// log in
$user = get_complete_user_data('id', $localuser->id, $localuser->mnethostid);
complete_user_login($user);
// now that we've logged in, set up the mnet session properly
$mnetauth->update_mnet_session($user, $token, $remotepeer);
if (!empty($localuser->mnet_foreign_host_array)) {
    $USER->mnet_foreign_host_array = $localuser->mnet_foreign_host_array;
}
// redirect
if ($wantsremoteurl) {
    redirect($remotewwwroot . $wantsurl);
}
redirect($CFG->wwwroot . $wantsurl);
示例#13
0
 public function callRemoteMethod($method, $parameters, $server = null)
 {
     global $CFG, $SynchServerController;
     require_once $CFG->dirroot . '/mnet/xmlrpc/client.php';
     // For the demo, our 'remote' host is actually our local host.
     $wwwroot = $CFG->wwwroot;
     //$method = 'synch/mnet/synch.php/getBackupById';
     // Get local server.
     $localServer = $SynchServerController->checkAndCreateLocalServer();
     global $Out;
     //$Out->print_r($localServer, '$localServer = ');
     // Cannot continue without a local server
     if (empty($localServer)) {
         return null;
     }
     if (empty($server)) {
         //$Out->append('Generating default remote server');
         //$server = new synch_modal_Server();
         //$server->mnetHostId = 1020000003;
         $server = $SynchServerController->getRemoteServer();
     }
     //$Out->print_r($server, '$server = ');
     // Cannot continue without a remote server to call
     if (empty($server) || synch_empty($server->mnetHostId)) {
         return null;
     }
     // mnet_peer pulls information about a remote host from the database.
     $mnet_peer = new mnet_peer();
     $mnet_peer->set_wwwroot($wwwroot);
     $mnethostid = $server->mnetHostId;
     $mnet_peer->set_id($mnethostid);
     // 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);
     // Set the time out to something decent in seconds
     //$mnet_request->set_timeout(600);
     //set_time_limit(120);
     // 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 ($parameters as $param) {
         $mnet_request->add_param($param[0], $param[1]);
     }
     // We send the request:
     $mnet_request->send($mnet_peer);
     return $mnet_request->response;
 }
/**
 * NOT WORKING
 * reimplementation of system.keyswapcall with capability of forcing the local renew
 *
 */
function mnetadmin_keyswap($function, $params)
{
    global $CFG, $MNET;
    $return = array();
    $wwwroot = $params[0];
    $pubkey = $params[1];
    $application = $params[2];
    $forcerenew = $params[3];
    if ($forcerenew == 0) {
        // standard keyswap for first key recording
        if (!empty($CFG->mnet_register_allhosts)) {
            $mnet_peer = new mnet_peer();
            $keyok = $mnet_peer->bootstrap($wwwroot, $pubkey, $application);
            if ($keyok) {
                $mnet_peer->commit();
            }
        }
    } else {
        $mnet_peer = new mnet_peer();
        // we can only renew hosts that we know something about.
        if ($mnet_peer->set_wwwroot($wwwroot)) {
            $mnet_peer->public_key = clean_param($pubkey, PARAM_PEM);
            $mnet_peer->public_key_expires = $mnet_peer->check_common_name($pubkey);
            $mnet_peer->updateparams->public_key = clean_param($pubkey, PARAM_PEM);
            $mnet_peer->updateparams->public_key_expires = $mnet_peer->check_common_name($pubkey);
            $mnet_peer->commit();
        } else {
            return false;
            // avoid giving our key to unkown hosts.
        }
    }
    return $MNET->public_key;
}
/**
 * require remote enrollement on a MNET satellite.
 * This XML-RPC call fetches for a remotely known course and enroll the user inside
 * This is essentially intended to use by foreign systems to slave the user management
 * in a MNET network.
 * @param string $callinguser The calling user.
 * @param string $targetuser The username or user identifier of the user to assign a role remotely.
 * @param string $useridfield The field used for identifying the user (id, idnumber or username).
 * @param string $courseidfield The identifying value of the remote course 
 * @param string $courseidentifier The identifying value of the remote course 
 * @param string $rolename The remote role name to be assigned as
 * @param string $starttime The starting date
 * @param string $endtime The enrollement ending date
 *
 */
function mnetadmin_rpc_remote_enrol($callinguser, $targetuser, $rolename, $whereroot, $courseidfield, $courseidentifier, $starttime = 0, $endtime = 0, $json_response = true)
{
    global $CFG, $USER, $DB;
    if (function_exists('debug_trace')) {
        debug_trace($CFG->wwwroot . ' >> mnetadmin_rpc_remote_enrol(' . json_encode($callinguser) . ", {$targetuser}, {$rolename}, {$whereroot}, {$courseidfield}, {$courseidentifier}, {$starttime} = 0, {$endtime} = 0, {$json_response} = true) ");
    }
    $extresponse = new stdclass();
    $extresponse->status = RPC_SUCCESS;
    $extresponse->errors = array();
    $extresponse->error = '';
    // Invoke local user and check his rights.
    if ($auth_response = invoke_local_user((array) $callinguser, 'local/vmoodle:execute')) {
        if ($json_response) {
            return $auth_response;
        } else {
            return json_decode($auth_response);
        }
    }
    if ($whereroot == $CFG->wwwroot) {
        if (function_exists('debug_trace')) {
            debug_trace("local enrol process for {$targetuser} as {$rolename} in {$courseidentifier} by {$courseidfield} from {$starttime} to {$endtime}");
        }
        // Getting remote_course definition.
        switch ($courseidfield) {
            case 'id':
                $course = $DB->get_record('course', array('id' => $courseidentifier));
                break;
            case 'shortname':
                $course = $DB->get_record('course', array('shortname' => $courseidentifier));
                break;
            case 'idnumber':
                $course = $DB->get_record('course', array('idnumber' => $courseidentifier));
                break;
        }
        if (!$course) {
            $extresponse->status = RPC_FAILURE_RECORD;
            $extresponse->errors[] = "Unkown course {$courseidentifier} based on {$courseidfield}.";
            $extresponse->error = "Unkown course {$courseidentifier} based on {$courseidfield}.";
            if (function_exists('debug_trace')) {
                debug_trace("Unkown course based on {$courseidfield} with {$courseidentifier} ");
            }
            if ($json_response) {
                return json_encode($extresponse);
            } else {
                return $extresponse;
            }
        }
        // Getting role if default.
        if (empty($rolename)) {
            $rolename = $course->defaultrolename;
        }
        if (function_exists('debug_trace')) {
            debug_trace("Bounce to mnetadmin_rpc_assignrole");
        }
        $extresponse = mnetadmin_rpc_assign_role($callinguser, $targetuser, $rolename, 'id', CONTEXT_COURSE, $course->id, $starttime, $endtime, $json_response);
        if (!$json_response) {
            return json_decode($extresponse);
        } else {
            return $extresponse;
        }
    } else {
        if (function_exists('debug_trace')) {
            debug_trace('remote source process');
        }
        // Make remote call.
        $userhostroot = $DB->get_field_select('mnet_host', 'wwwroot', " id = {$USER->mnethostid} AND deleted = 0 ");
        if (!$userhostroot) {
            $extresponse->error = 'Unkown user host root (or deleted).';
            if ($json_response) {
                return json_encode($extresponse);
            } else {
                return $extresponse;
            }
        }
        if (!$DB->record_exists('mnet_host', array('wwwroot' => $whereroot, 'deleted' => 0))) {
            $extresponse->error = '$whereroot is unknown host or deleted.';
            if ($json_response) {
                return json_encode($extresponse);
            } else {
                return $extresponse;
            }
        }
        $rpcclient = new mnet_xmlrpc_client();
        $rpcclient->set_method('local/vmoodle/plugins/roles/rpclib.php/mnetadmin_rpc_remote_enrol');
        $caller = new StdClass();
        $caller->username = $USER->username;
        $caller->remoteuserhostroot = $userhostroot;
        $caller->remotehostroot = $CFG->wwwroot;
        $rpcclient->add_param($caller, 'struct');
        // caller user
        $rpcclient->add_param($targetuser, 'string');
        $rpcclient->add_param($rolename, 'string');
        $rpcclient->add_param($whereroot, 'string');
        $rpcclient->add_param($courseidfield, 'string');
        $rpcclient->add_param($courseidentifier, 'string');
        $rpcclient->add_param($starttime, 'int');
        $rpcclient->add_param($endtime, 'int');
        $mnet_host = new mnet_peer();
        $mnet_host->set_wwwroot($whereroot);
        if (!$rpcclient->send($mnet_host)) {
            $extresponse->status = RPC_FAILURE;
            $extresponse->errors[] = 'REMOTE : ' . implode("<br/>\n", @$rpcclient->errors);
            $extresponse->error = 'REMOTE : ' . implode("<br/>\n", @$rpcclient->errors);
            if ($json_response) {
                return json_encode($extresponse);
            } else {
                return $extresponse;
            }
        }
        $response = json_decode($rpcclient->response);
        if ($response->status == 200) {
            $extresponse->message = 'remote enrol success';
            if ($json_response) {
                return json_encode($extresponse);
            } else {
                return $extresponse;
            }
        } else {
            $extresponse->status = RPC_FAILURE;
            $extresponse->errors = array();
            $extresponse->errors[] = 'Remote application errors : ';
            $extresponse->errors = array_merge($extresponse->errors, $response->errors);
            $extresponse->error = 'Remote application error.';
            if ($json_response) {
                return json_encode($extresponse);
            } else {
                return $extresponse;
            }
        }
    }
}