3 * Library functions for mnet
5 * @author Donal McMullan donal@catalyst.net.nz
7 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
10 require_once $CFG->dirroot
.'/mnet/xmlrpc/xmlparser.php';
11 require_once $CFG->dirroot
.'/mnet/peer.php';
12 require_once $CFG->dirroot
.'/mnet/environment.php';
14 /// CONSTANTS ///////////////////////////////////////////////////////////
17 define('RPC_NOSUCHFILE', 1);
18 define('RPC_NOSUCHCLASS', 2);
19 define('RPC_NOSUCHFUNCTION', 3);
20 define('RPC_FORBIDDENFUNCTION', 4);
21 define('RPC_NOSUCHMETHOD', 5);
22 define('RPC_FORBIDDENMETHOD', 6);
25 * Strip extraneous detail from a URL or URI and return the hostname
27 * @param string $uri The URI of a file on the remote computer, optionally
28 * including its http:// prefix like
29 * http://www.example.com/index.html
30 * @return string Just the hostname
32 function mnet_get_hostname_from_uri($uri = null) {
33 $count = preg_match("@^(?:http[s]?://)?([A-Z0-9\-\.]+).*@i", $uri, $matches);
34 if ($count > 0) return $matches[1];
39 * Get the remote machine's SSL Cert
41 * @param string $uri The URI of a file on the remote computer, including
42 * its http:// or https:// prefix
43 * @return string A PEM formatted SSL Certificate.
45 function mnet_get_public_key($uri, $application=null) {
47 $mnet = get_mnet_environment();
48 // The key may be cached in the mnet_set_public_key function...
50 $key = mnet_set_public_key($uri);
55 if (empty($application)) {
56 $application = $DB->get_record('mnet_application', array('name'=>'moodle'));
59 $rq = xmlrpc_encode_request('system/keyswap', array($CFG->wwwroot
, $mnet->public_key
, $application->name
), array(
60 'encoding' => 'utf-8',
61 'escaping' => 'markup',
63 $ch = curl_init($uri . $application->xmlrpc_server_url
);
65 curl_setopt($ch, CURLOPT_TIMEOUT
, 60);
66 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
67 curl_setopt($ch, CURLOPT_POST
, true);
68 curl_setopt($ch, CURLOPT_USERAGENT
, 'Moodle');
69 curl_setopt($ch, CURLOPT_POSTFIELDS
, $rq);
70 curl_setopt($ch, CURLOPT_HTTPHEADER
, array("Content-Type: text/xml charset=UTF-8"));
71 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
72 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, 0);
75 if (!empty($CFG->proxyhost
) and !is_proxybypass($uri)) {
76 // SOCKS supported in PHP5 only
77 if (!empty($CFG->proxytype
) and ($CFG->proxytype
== 'SOCKS5')) {
78 if (defined('CURLPROXY_SOCKS5')) {
79 curl_setopt($ch, CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
82 print_error( 'socksnotsupported','mnet' );
86 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL
, false);
88 if (empty($CFG->proxyport
)) {
89 curl_setopt($ch, CURLOPT_PROXY
, $CFG->proxyhost
);
91 curl_setopt($ch, CURLOPT_PROXY
, $CFG->proxyhost
.':'.$CFG->proxyport
);
94 if (!empty($CFG->proxyuser
) and !empty($CFG->proxypassword
)) {
95 curl_setopt($ch, CURLOPT_PROXYUSERPWD
, $CFG->proxyuser
.':'.$CFG->proxypassword
);
96 if (defined('CURLOPT_PROXYAUTH')) {
97 // any proxy authentication if PHP 5.1
98 curl_setopt($ch, CURLOPT_PROXYAUTH
, CURLAUTH_BASIC | CURLAUTH_NTLM
);
103 $res = xmlrpc_decode(curl_exec($ch));
105 // check for curl errors
106 $curlerrno = curl_errno($ch);
108 debugging("Request for $uri failed with curl error $curlerrno");
111 // check HTTP error code
112 $info = curl_getinfo($ch);
113 if (!empty($info['http_code']) and ($info['http_code'] != 200)) {
114 debugging("Request for $uri failed with HTTP code ".$info['http_code']);
119 if (!is_array($res)) { // ! error
120 $public_certificate = $res;
121 $credentials=array();
122 if (strlen(trim($public_certificate))) {
123 $credentials = openssl_x509_parse($public_certificate);
124 $host = $credentials['subject']['CN'];
125 if (array_key_exists( 'subjectAltName', $credentials['subject'])) {
126 $host = $credentials['subject']['subjectAltName'];
128 if (strpos($uri, $host) !== false) {
129 mnet_set_public_key($uri, $public_certificate);
130 return $public_certificate;
133 debugging("Request for $uri returned public key for different URI - $host");
137 debugging("Request for $uri returned empty response");
141 debugging( "Request for $uri returned unexpected result");
147 * Store a URI's public key in a static variable, or retrieve the key for a URI
149 * @param string $uri The URI of a file on the remote computer, including its
151 * @param mixed $key A public key to store in the array OR null. If the key
152 * is null, the function will return the previously stored
153 * key for the supplied URI, should it exist.
154 * @return mixed A public key OR true/false.
156 function mnet_set_public_key($uri, $key = null) {
157 static $keyarray = array();
158 if (isset($keyarray[$uri]) && empty($key)) {
159 return $keyarray[$uri];
160 } elseif (!empty($key)) {
161 $keyarray[$uri] = $key;
168 * Sign a message and return it in an XML-Signature document
170 * This function can sign any content, but it was written to provide a system of
171 * signing XML-RPC request and response messages. The message will be base64
172 * encoded, so it does not need to be text.
174 * We compute the SHA1 digest of the message.
175 * We compute a signature on that digest with our private key.
176 * We link to the public key that can be used to verify our signature.
177 * We base64 the message data.
178 * We identify our wwwroot - this must match our certificate's CN
180 * The XML-RPC document will be parceled inside an XML-SIG document, which holds
181 * the base64_encoded XML as an object, the SHA1 digest of that document, and a
182 * signature of that document using the local private key. This signature will
183 * uniquely identify the RPC document as having come from this server.
185 * See the {@Link http://www.w3.org/TR/xmldsig-core/ XML-DSig spec} at the W3c
188 * @param string $message The data you want to sign
189 * @param resource $privatekey The private key to sign the response with
190 * @return string An XML-DSig document
192 function mnet_sign_message($message, $privatekey = null) {
194 $digest = sha1($message);
196 $mnet = get_mnet_environment();
197 // If the user hasn't supplied a private key (for example, one of our older,
198 // expired private keys, we get the current default private key and use that.
199 if ($privatekey == null) {
200 $privatekey = $mnet->get_private_key();
203 // The '$sig' value below is returned by reference.
204 // We initialize it first to stop my IDE from complaining.
206 $bool = openssl_sign($message, $sig, $privatekey); // TODO: On failure?
208 $message = '<?xml version="1.0" encoding="iso-8859-1"?>
210 <Signature Id="MoodleSignature" xmlns="http://www.w3.org/2000/09/xmldsig#">
212 <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
213 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
214 <Reference URI="#XMLRPC-MSG">
215 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
216 <DigestValue>'.$digest.'</DigestValue>
219 <SignatureValue>'.base64_encode($sig).'</SignatureValue>
221 <RetrievalMethod URI="'.$CFG->wwwroot
.'/mnet/publickey.php"/>
224 <object ID="XMLRPC-MSG">'.base64_encode($message).'</object>
225 <wwwroot>'.$mnet->wwwroot
.'</wwwroot>
226 <timestamp>'.time().'</timestamp>
232 * Encrypt a message and return it in an XML-Encrypted document
234 * This function can encrypt any content, but it was written to provide a system
235 * of encrypting XML-RPC request and response messages. The message will be
236 * base64 encoded, so it does not need to be text - binary data should work.
238 * We compute the SHA1 digest of the message.
239 * We compute a signature on that digest with our private key.
240 * We link to the public key that can be used to verify our signature.
241 * We base64 the message data.
242 * We identify our wwwroot - this must match our certificate's CN
244 * The XML-RPC document will be parceled inside an XML-SIG document, which holds
245 * the base64_encoded XML as an object, the SHA1 digest of that document, and a
246 * signature of that document using the local private key. This signature will
247 * uniquely identify the RPC document as having come from this server.
249 * See the {@Link http://www.w3.org/TR/xmlenc-core/ XML-ENC spec} at the W3c
252 * @param string $message The data you want to sign
253 * @param string $remote_certificate Peer's certificate in PEM format
254 * @return string An XML-ENC document
256 function mnet_encrypt_message($message, $remote_certificate) {
257 $mnet = get_mnet_environment();
259 // Generate a key resource from the remote_certificate text string
260 $publickey = openssl_get_publickey($remote_certificate);
262 if ($publickey === false) {
263 // Remote certificate is faulty.
268 $encryptedstring = '';
269 $symmetric_keys = array();
271 // passed by ref -> &$encryptedstring &$symmetric_keys
272 $bool = openssl_seal($message, $encryptedstring, $symmetric_keys, array($publickey), 'RC4');
273 $message = $encryptedstring;
274 $symmetrickey = array_pop($symmetric_keys);
276 $message = '<?xml version="1.0" encoding="iso-8859-1"?>
278 <EncryptedData Id="ED" xmlns="http://www.w3.org/2001/04/xmlenc#">
279 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#arcfour"/>
280 <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
281 <ds:RetrievalMethod URI="#EK" Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey"/>
282 <ds:KeyName>XMLENC</ds:KeyName>
285 <CipherValue>'.base64_encode($message).'</CipherValue>
288 <EncryptedKey Id="EK" xmlns="http://www.w3.org/2001/04/xmlenc#">
289 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
290 <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
291 <ds:KeyName>SSLKEY</ds:KeyName>
294 <CipherValue>'.base64_encode($symmetrickey).'</CipherValue>
297 <DataReference URI="#ED"/>
299 <CarriedKeyName>XMLENC</CarriedKeyName>
301 <wwwroot>'.$mnet->wwwroot
.'</wwwroot>
302 </encryptedMessage>';
307 * Get your SSL keys from the database, or create them (if they don't exist yet)
309 * Get your SSL keys from the database, or (if they don't exist yet) call
310 * mnet_generate_keypair to create them
312 * @param string $string The text you want to sign
313 * @return string The signature over that text
315 function mnet_get_keypair() {
317 static $keypair = null;
318 if (!is_null($keypair)) return $keypair;
319 if ($result = get_config('mnet', 'openssl')) {
320 list($keypair['certificate'], $keypair['keypair_PEM']) = explode('@@@@@@@@', $result);
321 $keypair['privatekey'] = openssl_pkey_get_private($keypair['keypair_PEM']);
322 $keypair['publickey'] = openssl_pkey_get_public($keypair['certificate']);
325 $keypair = mnet_generate_keypair();
331 * Generate public/private keys and store in the config table
333 * Use the distinguished name provided to create a CSR, and then sign that CSR
334 * with the same credentials. Store the keypair you create in the config table.
335 * If a distinguished name is not provided, create one using the fullname of
336 * 'the course with ID 1' as your organization name, and your hostname (as
337 * detailed in $CFG->wwwroot).
339 * @param array $dn The distinguished name of the server
340 * @return string The signature over that text
342 function mnet_generate_keypair($dn = null, $days=28) {
343 global $CFG, $USER, $DB;
345 // check if lifetime has been overriden
346 if (!empty($CFG->mnetkeylifetime
)) {
347 $days = $CFG->mnetkeylifetime
;
350 $host = strtolower($CFG->wwwroot
);
351 $host = preg_replace("~^http(s)?://~",'',$host);
352 $break = strpos($host.'/' , '/');
353 $host = substr($host, 0, $break);
356 $organization = $site->fullname
;
361 $province = 'Wellington';
362 $locality = 'Wellington';
363 $email = !empty($CFG->noreplyaddress
) ?
$CFG->noreplyaddress
: 'noreply@'.$_SERVER['HTTP_HOST'];
365 if(!empty($USER->country
)) {
366 $country = $USER->country
;
368 if(!empty($USER->city
)) {
369 $province = $USER->city
;
370 $locality = $USER->city
;
372 if(!empty($USER->email
)) {
373 $email = $USER->email
;
378 "countryName" => $country,
379 "stateOrProvinceName" => $province,
380 "localityName" => $locality,
381 "organizationName" => $organization,
382 "organizationalUnitName" => 'Moodle',
383 "commonName" => substr($CFG->wwwroot
, 0, 64),
384 "subjectAltName" => $CFG->wwwroot
,
385 "emailAddress" => $email
391 'stateOrProvinceName' => 128,
392 'localityName' => 128,
393 'organizationName' => 64,
394 'organizationalUnitName' => 64,
396 'emailAddress' => 128
399 foreach ($dnlimits as $key => $length) {
400 $dn[$key] = core_text
::substr($dn[$key], 0, $length);
403 // ensure we remove trailing slashes
404 $dn["commonName"] = preg_replace(':/$:', '', $dn["commonName"]);
405 if (!empty($CFG->opensslcnf
)) { //allow specification of openssl.cnf especially for Windows installs
406 $new_key = openssl_pkey_new(array("config" => $CFG->opensslcnf
));
408 $new_key = openssl_pkey_new();
410 if ($new_key === false) {
411 // can not generate keys - missing openssl.cnf??
414 if (!empty($CFG->opensslcnf
)) { //allow specification of openssl.cnf especially for Windows installs
415 $csr_rsc = openssl_csr_new($dn, $new_key, array("config" => $CFG->opensslcnf
));
416 $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days, array("config" => $CFG->opensslcnf
));
418 $csr_rsc = openssl_csr_new($dn, $new_key, array('private_key_bits',2048));
419 $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days);
421 unset($csr_rsc); // Free up the resource
423 // We export our self-signed certificate to a string.
424 openssl_x509_export($selfSignedCert, $keypair['certificate']);
425 // TODO: Remove this block once PHP 8.0 becomes required.
426 if (PHP_MAJOR_VERSION
< 8) {
427 openssl_x509_free($selfSignedCert);
430 // Export your public/private key pair as a PEM encoded string. You
431 // can protect it with an optional passphrase if you wish.
432 if (!empty($CFG->opensslcnf
)) { //allow specification of openssl.cnf especially for Windows installs
433 $export = openssl_pkey_export($new_key, $keypair['keypair_PEM'], null, array("config" => $CFG->opensslcnf
));
435 $export = openssl_pkey_export($new_key, $keypair['keypair_PEM'] /* , $passphrase */);
437 // TODO: Remove this block once PHP 8.0 becomes required.
438 if (PHP_MAJOR_VERSION
< 8) {
439 openssl_pkey_free($new_key);
441 unset($new_key); // Free up the resource
447 function mnet_update_sso_access_control($username, $mnet_host_id, $accessctrl) {
450 $mnethost = $DB->get_record('mnet_host', array('id'=>$mnet_host_id));
451 if ($aclrecord = $DB->get_record('mnet_sso_access_control', array('username'=>$username, 'mnet_host_id'=>$mnet_host_id))) {
453 $aclrecord->accessctrl
= $accessctrl;
454 $DB->update_record('mnet_sso_access_control', $aclrecord);
456 // Trigger access control updated event.
458 'objectid' => $aclrecord->id
,
459 'context' => context_system
::instance(),
461 'username' => $username,
462 'hostname' => $mnethost->name
,
463 'accessctrl' => $accessctrl
466 $event = \core\event\mnet_access_control_updated
::create($params);
467 $event->add_record_snapshot('mnet_host', $mnethost);
471 $aclrecord = new stdClass();
472 $aclrecord->username
= $username;
473 $aclrecord->accessctrl
= $accessctrl;
474 $aclrecord->mnet_host_id
= $mnet_host_id;
475 $aclrecord->id
= $DB->insert_record('mnet_sso_access_control', $aclrecord);
477 // Trigger access control created event.
479 'objectid' => $aclrecord->id
,
480 'context' => context_system
::instance(),
482 'username' => $username,
483 'hostname' => $mnethost->name
,
484 'accessctrl' => $accessctrl
487 $event = \core\event\mnet_access_control_created
::create($params);
488 $event->add_record_snapshot('mnet_host', $mnethost);
494 function mnet_get_peer_host ($mnethostid) {
497 if (!isset($hosts[$mnethostid])) {
498 $host = $DB->get_record('mnet_host', array('id' => $mnethostid));
499 $hosts[$mnethostid] = $host;
501 return $hosts[$mnethostid];
505 * Inline function to modify a url string so that mnet users are requested to
506 * log in at their mnet identity provider (if they are not already logged in)
507 * before ultimately being directed to the original url.
509 * @param string $jumpurl the url which user should initially be directed to.
510 * This is a URL associated with a moodle networking peer when it
511 * is fulfiling a role as an identity provider (IDP). Different urls for
512 * different peers, the jumpurl is formed partly from the IDP's webroot, and
513 * partly from a predefined local path within that webwroot.
514 * The result of the user hitting this jump url is that they will be asked
515 * to login (at their identity provider (if they aren't already)), mnet
516 * will prepare the necessary authentication information, then redirect
517 * them back to somewhere at the content provider(CP) moodle (this moodle)
518 * @param array $url array with 2 elements
519 * 0 - context the url was taken from, possibly just the url, possibly href="url"
520 * 1 - the destination url
521 * @return string the url the remote user should be supplied with.
523 function mnet_sso_apply_indirection ($jumpurl, $url) {
527 $urlparts = parse_url($url[1]);
529 if (isset($urlparts['path'])) {
530 $path = $urlparts['path'];
531 // if our wwwroot has a path component, need to strip that path from beginning of the
532 // 'localpart' to make it relative to moodle's wwwroot
533 $wwwrootpath = parse_url($CFG->wwwroot
, PHP_URL_PATH
);
534 if (!empty($wwwrootpath) and strpos($path, $wwwrootpath) === 0) {
535 $path = substr($path, strlen($wwwrootpath));
539 if (isset($urlparts['query'])) {
540 $localpart .= '?'.$urlparts['query'];
542 if (isset($urlparts['fragment'])) {
543 $localpart .= '#'.$urlparts['fragment'];
546 $indirecturl = $jumpurl . urlencode($localpart);
547 //If we matched on more than just a url (ie an html link), return the url to an href format
548 if ($url[0] != $url[1]) {
549 $indirecturl = 'href="'.$indirecturl.'"';
554 function mnet_get_app_jumppath ($applicationid) {
556 static $appjumppaths;
557 if (!isset($appjumppaths[$applicationid])) {
558 $ssojumpurl = $DB->get_field('mnet_application', 'sso_jump_url', array('id' => $applicationid));
559 $appjumppaths[$applicationid] = $ssojumpurl;
561 return $appjumppaths[$applicationid];
566 * Output debug information about mnet. this will go to the <b>error_log</b>.
568 * @param mixed $debugdata this can be a string, or array or object.
569 * @param int $debuglevel optional , defaults to 1. bump up for very noisy debug info
571 function mnet_debug($debugdata, $debuglevel=1) {
573 $setlevel = get_config('', 'mnet_rpcdebug');
574 if (empty($setlevel) ||
$setlevel < $debuglevel) {
577 if (is_object($debugdata)) {
578 $debugdata = (array)$debugdata;
580 if (is_array($debugdata)) {
581 mnet_debug('DUMPING ARRAY');
582 foreach ($debugdata as $key => $value) {
583 mnet_debug("$key: $value");
585 mnet_debug('END DUMPING ARRAY');
588 $prefix = 'MNET DEBUG ';
589 if (defined('MNET_SERVER')) {
590 $prefix .= " (server $CFG->wwwroot";
591 if ($peer = get_mnet_remote_client() && !empty($peer->wwwroot
)) {
592 $prefix .= ", remote peer " . $peer->wwwroot
;
596 $prefix .= " (client $CFG->wwwroot) ";
598 error_log("$prefix $debugdata");
602 * Return an array of information about all moodle's profile fields
603 * which ones are optional, which ones are forced.
604 * This is used as the basis of providing lists of profile fields to the administrator
605 * to pick which fields to import/export over MNET
607 * @return array(forced => array, optional => array)
609 function mnet_profile_field_options() {
617 'id', // makes no sense
618 'mnethostid', // makes no sense
619 'timecreated', // will be set to relative to the host anyway
620 'timemodified', // will be set to relative to the host anyway
621 'auth', // going to be set to 'mnet'
622 'deleted', // we should never get deleted users sent over, but don't send this anyway
623 'confirmed', // unconfirmed users can't log in to their home site, all remote users considered confirmed
624 'password', // no password for mnet users
625 'theme', // handled separately
626 'lastip', // will be set to relative to the host anyway
629 // these are the ones that user_not_fully_set_up will complain about
630 // and also special case ones
638 'session.gc_lifetime',
639 '_mnet_userpicture_timemodified',
640 '_mnet_userpicture_mimetype',
643 // these are the ones we used to send/receive (pre 2.0)
664 // get a random user record from the database to pull the fields off
665 $randomuser = $DB->get_record('user', array(), '*', IGNORE_MULTIPLE
);
666 foreach ($randomuser as $key => $discard) {
667 if (in_array($key, $excludes) ||
in_array($key, $forced)) {
670 $fields[$key] = $key;
674 'optional' => $fields,
682 * Returns information about MNet peers
684 * @param bool $withdeleted should the deleted peers be returned too
687 function mnet_get_hosts($withdeleted = false) {
690 $sql = "SELECT h.id, h.deleted, h.wwwroot, h.ip_address, h.name, h.public_key, h.public_key_expires,
691 h.transport, h.portno, h.last_connect_time, h.last_log_id, h.applicationid,
692 a.name as app_name, a.display_name as app_display_name, a.xmlrpc_server_url
694 JOIN {mnet_application} a ON h.applicationid = a.id
698 $sql .= " AND h.deleted = 0";
701 $sql .= " ORDER BY h.deleted, h.name, h.id";
703 return $DB->get_records_sql($sql, array($CFG->mnet_localhost_id
));
708 * return an array information about services enabled for the given peer.
709 * in two modes, fulldata or very basic data.
711 * @param mnet_peer $mnet_peer the peer to get information abut
712 * @param boolean $fulldata whether to just return which services are published/subscribed, or more information (defaults to full)
714 * @return array If $fulldata is false, an array is returned like:
716 * serviceid => boolean,
717 * serviceid => boolean,
719 * subscribe => array(
720 * serviceid => boolean,
721 * serviceid => boolean,
723 * If $fulldata is true, an array is returned like:
724 * servicename => array(
725 * apiversion => array(
729 * plugintype => string
730 * pluginname => string
731 * hostsubscribes => boolean
732 * hostpublishes => boolean
736 function mnet_get_service_info(mnet_peer
$mnet_peer, $fulldata=true) {
739 $requestkey = (!empty($fulldata) ?
'fulldata' : 'mydata');
741 static $cache = array();
742 if (array_key_exists($mnet_peer->id
, $cache)) {
743 return $cache[$mnet_peer->id
][$requestkey];
746 $id_list = $mnet_peer->id
;
747 if (!empty($CFG->mnet_all_hosts_id
)) {
748 $id_list .= ', '.$CFG->mnet_all_hosts_id
;
751 $concat = $DB->sql_concat('COALESCE(h2s.id,0) ', ' \'-\' ', ' svc.id', '\'-\'', 'r.plugintype', '\'-\'', 'r.pluginname');
766 {mnet_service2rpc} s2r,
770 {mnet_host2service} h2s
772 h2s.hostid in ($id_list) AND
773 h2s.serviceid = svc.id
776 s2r.serviceid = svc.id AND
781 $resultset = $DB->get_records_sql($query);
783 if (is_array($resultset)) {
784 $resultset = array_values($resultset);
786 $resultset = array();
789 require_once $CFG->dirroot
.'/mnet/xmlrpc/client.php';
791 $remoteservices = array();
792 if ($mnet_peer->id
!= $CFG->mnet_all_hosts_id
) {
793 // Create a new request object
794 $mnet_request = new mnet_xmlrpc_client();
796 // Tell it the path to the method that we want to execute
797 $mnet_request->set_method('system/listServices');
798 $mnet_request->send($mnet_peer);
799 if (is_array($mnet_request->response
)) {
800 foreach($mnet_request->response
as $service) {
801 $remoteservices[$service['name']][$service['apiversion']] = $service;
806 $myservices = array();
808 foreach($resultset as $result) {
809 $result->hostpublishes
= false;
810 $result->hostsubscribes
= false;
811 if (isset($remoteservices[$result->name
][$result->apiversion
])) {
812 if ($remoteservices[$result->name
][$result->apiversion
]['publish'] == 1) {
813 $result->hostpublishes
= true;
815 if ($remoteservices[$result->name
][$result->apiversion
]['subscribe'] == 1) {
816 $result->hostsubscribes
= true;
820 if (empty($myservices[$result->name
][$result->apiversion
])) {
821 $myservices[$result->name
][$result->apiversion
] = array('serviceid' => $result->serviceid
,
822 'name' => $result->name
,
823 'offer' => $result->offer
,
824 'apiversion' => $result->apiversion
,
825 'plugintype' => $result->plugintype
,
826 'pluginname' => $result->pluginname
,
827 'hostsubscribes' => $result->hostsubscribes
,
828 'hostpublishes' => $result->hostpublishes
832 // allhosts_publish allows us to tell the admin that even though he
833 // is disabling a service, it's still available to the host because
834 // he's also publishing it to 'all hosts'
835 if ($result->hostid
== $CFG->mnet_all_hosts_id
&& $CFG->mnet_all_hosts_id
!= $mnet_peer->id
) {
836 $myservices[$result->name
][$result->apiversion
]['allhosts_publish'] = $result->publish
;
837 $myservices[$result->name
][$result->apiversion
]['allhosts_subscribe'] = $result->subscribe
;
838 } elseif (!empty($result->hostid
)) {
839 $myservices[$result->name
][$result->apiversion
]['I_publish'] = $result->publish
;
840 $myservices[$result->name
][$result->apiversion
]['I_subscribe'] = $result->subscribe
;
842 $mydata['publish'][$result->serviceid
] = $result->publish
;
843 $mydata['subscribe'][$result->serviceid
] = $result->subscribe
;
847 $cache[$mnet_peer->id
]['fulldata'] = $myservices;
848 $cache[$mnet_peer->id
]['mydata'] = $mydata;
850 return $cache[$mnet_peer->id
][$requestkey];
854 * return an array of the profile fields to send
855 * with user information to the given mnet host.
857 * @param mnet_peer $peer the peer to send the information to
859 * @return array (like 'username', 'firstname', etc)
861 function mnet_fields_to_send(mnet_peer
$peer) {
862 return _mnet_field_helper($peer, 'export');
866 * return an array of the profile fields to import
867 * from the given host, when creating/updating user accounts
869 * @param mnet_peer $peer the peer we're getting the information from
871 * @return array (like 'username', 'firstname', etc)
873 function mnet_fields_to_import(mnet_peer
$peer) {
874 return _mnet_field_helper($peer, 'import');
878 * helper for {@see mnet_fields_to_import} and {@mnet_fields_to_send}
882 * @param mnet_peer $peer the peer object
883 * @param string $key 'import' or 'export'
885 * @return array (like 'username', 'firstname', etc)
887 function _mnet_field_helper(mnet_peer
$peer, $key) {
888 $tmp = mnet_profile_field_options();
889 $defaults = explode(',', get_config('moodle', 'mnetprofile' . $key . 'fields'));
890 if ('1' === get_config('mnet', 'host' . $peer->id
. $key . 'default')) {
891 return array_merge($tmp['forced'], $defaults);
893 $hostsettings = get_config('mnet', 'host' . $peer->id
. $key . 'fields');
894 if (false === $hostsettings) {
895 return array_merge($tmp['forced'], $defaults);
897 return array_merge($tmp['forced'], explode(',', $hostsettings));
902 * given a user object (or array) and a list of allowed fields,
903 * strip out all the fields that should not be included.
904 * This can be used both for outgoing data and incoming data.
906 * @param mixed $user array or object representing a database record
907 * @param array $fields an array of allowed fields (usually from mnet_fields_to_{send,import}
909 * @return mixed array or object, depending what type of $user object was passed (datatype is respected)
911 function mnet_strip_user($user, $fields) {
912 if (is_object($user)) {
913 $user = (array)$user;
914 $wasobject = true; // so we can cast back before we return
917 foreach ($user as $key => $value) {
918 if (!in_array($key, $fields)) {
922 if (!empty($wasobject)) {
923 $user = (object)$user;