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("encoding" => "utf-8"));
60 $ch = curl_init($uri . $application->xmlrpc_server_url
);
62 curl_setopt($ch, CURLOPT_TIMEOUT
, 60);
63 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
64 curl_setopt($ch, CURLOPT_POST
, true);
65 curl_setopt($ch, CURLOPT_USERAGENT
, 'Moodle');
66 curl_setopt($ch, CURLOPT_POSTFIELDS
, $rq);
67 curl_setopt($ch, CURLOPT_HTTPHEADER
, array("Content-Type: text/xml charset=UTF-8"));
68 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
69 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST
, 0);
72 if (!empty($CFG->proxyhost
) and !is_proxybypass($uri)) {
73 // SOCKS supported in PHP5 only
74 if (!empty($CFG->proxytype
) and ($CFG->proxytype
== 'SOCKS5')) {
75 if (defined('CURLPROXY_SOCKS5')) {
76 curl_setopt($ch, CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
79 print_error( 'socksnotsupported','mnet' );
83 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL
, false);
85 if (empty($CFG->proxyport
)) {
86 curl_setopt($ch, CURLOPT_PROXY
, $CFG->proxyhost
);
88 curl_setopt($ch, CURLOPT_PROXY
, $CFG->proxyhost
.':'.$CFG->proxyport
);
91 if (!empty($CFG->proxyuser
) and !empty($CFG->proxypassword
)) {
92 curl_setopt($ch, CURLOPT_PROXYUSERPWD
, $CFG->proxyuser
.':'.$CFG->proxypassword
);
93 if (defined('CURLOPT_PROXYAUTH')) {
94 // any proxy authentication if PHP 5.1
95 curl_setopt($ch, CURLOPT_PROXYAUTH
, CURLAUTH_BASIC | CURLAUTH_NTLM
);
100 $res = xmlrpc_decode(curl_exec($ch));
102 // check for curl errors
103 $curlerrno = curl_errno($ch);
105 debugging("Request for $uri failed with curl error $curlerrno");
108 // check HTTP error code
109 $info = curl_getinfo($ch);
110 if (!empty($info['http_code']) and ($info['http_code'] != 200)) {
111 debugging("Request for $uri failed with HTTP code ".$info['http_code']);
116 if (!is_array($res)) { // ! error
117 $public_certificate = $res;
118 $credentials=array();
119 if (strlen(trim($public_certificate))) {
120 $credentials = openssl_x509_parse($public_certificate);
121 $host = $credentials['subject']['CN'];
122 if (array_key_exists( 'subjectAltName', $credentials['subject'])) {
123 $host = $credentials['subject']['subjectAltName'];
125 if (strpos($uri, $host) !== false) {
126 mnet_set_public_key($uri, $public_certificate);
127 return $public_certificate;
130 debugging("Request for $uri returned public key for different URI - $host");
134 debugging("Request for $uri returned empty response");
138 debugging( "Request for $uri returned unexpected result");
144 * Store a URI's public key in a static variable, or retrieve the key for a URI
146 * @param string $uri The URI of a file on the remote computer, including its
148 * @param mixed $key A public key to store in the array OR null. If the key
149 * is null, the function will return the previously stored
150 * key for the supplied URI, should it exist.
151 * @return mixed A public key OR true/false.
153 function mnet_set_public_key($uri, $key = null) {
154 static $keyarray = array();
155 if (isset($keyarray[$uri]) && empty($key)) {
156 return $keyarray[$uri];
157 } elseif (!empty($key)) {
158 $keyarray[$uri] = $key;
165 * Sign a message and return it in an XML-Signature document
167 * This function can sign any content, but it was written to provide a system of
168 * signing XML-RPC request and response messages. The message will be base64
169 * encoded, so it does not need to be text.
171 * We compute the SHA1 digest of the message.
172 * We compute a signature on that digest with our private key.
173 * We link to the public key that can be used to verify our signature.
174 * We base64 the message data.
175 * We identify our wwwroot - this must match our certificate's CN
177 * The XML-RPC document will be parceled inside an XML-SIG document, which holds
178 * the base64_encoded XML as an object, the SHA1 digest of that document, and a
179 * signature of that document using the local private key. This signature will
180 * uniquely identify the RPC document as having come from this server.
182 * See the {@Link http://www.w3.org/TR/xmldsig-core/ XML-DSig spec} at the W3c
185 * @param string $message The data you want to sign
186 * @param resource $privatekey The private key to sign the response with
187 * @return string An XML-DSig document
189 function mnet_sign_message($message, $privatekey = null) {
191 $digest = sha1($message);
193 $mnet = get_mnet_environment();
194 // If the user hasn't supplied a private key (for example, one of our older,
195 // expired private keys, we get the current default private key and use that.
196 if ($privatekey == null) {
197 $privatekey = $mnet->get_private_key();
200 // The '$sig' value below is returned by reference.
201 // We initialize it first to stop my IDE from complaining.
203 $bool = openssl_sign($message, $sig, $privatekey); // TODO: On failure?
205 $message = '<?xml version="1.0" encoding="iso-8859-1"?>
207 <Signature Id="MoodleSignature" xmlns="http://www.w3.org/2000/09/xmldsig#">
209 <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
210 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
211 <Reference URI="#XMLRPC-MSG">
212 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
213 <DigestValue>'.$digest.'</DigestValue>
216 <SignatureValue>'.base64_encode($sig).'</SignatureValue>
218 <RetrievalMethod URI="'.$CFG->wwwroot
.'/mnet/publickey.php"/>
221 <object ID="XMLRPC-MSG">'.base64_encode($message).'</object>
222 <wwwroot>'.$mnet->wwwroot
.'</wwwroot>
223 <timestamp>'.time().'</timestamp>
229 * Encrypt a message and return it in an XML-Encrypted document
231 * This function can encrypt any content, but it was written to provide a system
232 * of encrypting XML-RPC request and response messages. The message will be
233 * base64 encoded, so it does not need to be text - binary data should work.
235 * We compute the SHA1 digest of the message.
236 * We compute a signature on that digest with our private key.
237 * We link to the public key that can be used to verify our signature.
238 * We base64 the message data.
239 * We identify our wwwroot - this must match our certificate's CN
241 * The XML-RPC document will be parceled inside an XML-SIG document, which holds
242 * the base64_encoded XML as an object, the SHA1 digest of that document, and a
243 * signature of that document using the local private key. This signature will
244 * uniquely identify the RPC document as having come from this server.
246 * See the {@Link http://www.w3.org/TR/xmlenc-core/ XML-ENC spec} at the W3c
249 * @param string $message The data you want to sign
250 * @param string $remote_certificate Peer's certificate in PEM format
251 * @return string An XML-ENC document
253 function mnet_encrypt_message($message, $remote_certificate) {
254 $mnet = get_mnet_environment();
256 // Generate a key resource from the remote_certificate text string
257 $publickey = openssl_get_publickey($remote_certificate);
259 if ( gettype($publickey) != 'resource' ) {
260 // Remote certificate is faulty.
265 $encryptedstring = '';
266 $symmetric_keys = array();
268 // passed by ref -> &$encryptedstring &$symmetric_keys
269 $bool = openssl_seal($message, $encryptedstring, $symmetric_keys, array($publickey));
270 $message = $encryptedstring;
271 $symmetrickey = array_pop($symmetric_keys);
273 $message = '<?xml version="1.0" encoding="iso-8859-1"?>
275 <EncryptedData Id="ED" xmlns="http://www.w3.org/2001/04/xmlenc#">
276 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#arcfour"/>
277 <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
278 <ds:RetrievalMethod URI="#EK" Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey"/>
279 <ds:KeyName>XMLENC</ds:KeyName>
282 <CipherValue>'.base64_encode($message).'</CipherValue>
285 <EncryptedKey Id="EK" xmlns="http://www.w3.org/2001/04/xmlenc#">
286 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
287 <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
288 <ds:KeyName>SSLKEY</ds:KeyName>
291 <CipherValue>'.base64_encode($symmetrickey).'</CipherValue>
294 <DataReference URI="#ED"/>
296 <CarriedKeyName>XMLENC</CarriedKeyName>
298 <wwwroot>'.$mnet->wwwroot
.'</wwwroot>
299 </encryptedMessage>';
304 * Get your SSL keys from the database, or create them (if they don't exist yet)
306 * Get your SSL keys from the database, or (if they don't exist yet) call
307 * mnet_generate_keypair to create them
309 * @param string $string The text you want to sign
310 * @return string The signature over that text
312 function mnet_get_keypair() {
314 static $keypair = null;
315 if (!is_null($keypair)) return $keypair;
316 if ($result = get_config('mnet', 'openssl')) {
317 list($keypair['certificate'], $keypair['keypair_PEM']) = explode('@@@@@@@@', $result);
318 $keypair['privatekey'] = openssl_pkey_get_private($keypair['keypair_PEM']);
319 $keypair['publickey'] = openssl_pkey_get_public($keypair['certificate']);
322 $keypair = mnet_generate_keypair();
328 * Generate public/private keys and store in the config table
330 * Use the distinguished name provided to create a CSR, and then sign that CSR
331 * with the same credentials. Store the keypair you create in the config table.
332 * If a distinguished name is not provided, create one using the fullname of
333 * 'the course with ID 1' as your organization name, and your hostname (as
334 * detailed in $CFG->wwwroot).
336 * @param array $dn The distinguished name of the server
337 * @return string The signature over that text
339 function mnet_generate_keypair($dn = null, $days=28) {
340 global $CFG, $USER, $DB;
342 // check if lifetime has been overriden
343 if (!empty($CFG->mnetkeylifetime
)) {
344 $days = $CFG->mnetkeylifetime
;
347 $host = strtolower($CFG->wwwroot
);
348 $host = preg_replace("~^http(s)?://~",'',$host);
349 $break = strpos($host.'/' , '/');
350 $host = substr($host, 0, $break);
353 $organization = $site->fullname
;
358 $province = 'Wellington';
359 $locality = 'Wellington';
360 $email = !empty($CFG->noreplyaddress
) ?
$CFG->noreplyaddress
: 'noreply@'.$_SERVER['HTTP_HOST'];
362 if(!empty($USER->country
)) {
363 $country = $USER->country
;
365 if(!empty($USER->city
)) {
366 $province = $USER->city
;
367 $locality = $USER->city
;
369 if(!empty($USER->email
)) {
370 $email = $USER->email
;
375 "countryName" => $country,
376 "stateOrProvinceName" => $province,
377 "localityName" => $locality,
378 "organizationName" => $organization,
379 "organizationalUnitName" => 'Moodle',
380 "commonName" => substr($CFG->wwwroot
, 0, 64),
381 "subjectAltName" => $CFG->wwwroot
,
382 "emailAddress" => $email
388 'stateOrProvinceName' => 128,
389 'localityName' => 128,
390 'organizationName' => 64,
391 'organizationalUnitName' => 64,
393 'emailAddress' => 128
396 foreach ($dnlimits as $key => $length) {
397 $dn[$key] = substr($dn[$key], 0, $length);
400 // ensure we remove trailing slashes
401 $dn["commonName"] = preg_replace(':/$:', '', $dn["commonName"]);
402 if (!empty($CFG->opensslcnf
)) { //allow specification of openssl.cnf especially for Windows installs
403 $new_key = openssl_pkey_new(array("config" => $CFG->opensslcnf
));
405 $new_key = openssl_pkey_new();
407 if ($new_key === false) {
408 // can not generate keys - missing openssl.cnf??
411 if (!empty($CFG->opensslcnf
)) { //allow specification of openssl.cnf especially for Windows installs
412 $csr_rsc = openssl_csr_new($dn, $new_key, array("config" => $CFG->opensslcnf
));
413 $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days, array("config" => $CFG->opensslcnf
));
415 $csr_rsc = openssl_csr_new($dn, $new_key, array('private_key_bits',2048));
416 $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days);
418 unset($csr_rsc); // Free up the resource
420 // We export our self-signed certificate to a string.
421 openssl_x509_export($selfSignedCert, $keypair['certificate']);
422 openssl_x509_free($selfSignedCert);
424 // Export your public/private key pair as a PEM encoded string. You
425 // can protect it with an optional passphrase if you wish.
426 if (!empty($CFG->opensslcnf
)) { //allow specification of openssl.cnf especially for Windows installs
427 $export = openssl_pkey_export($new_key, $keypair['keypair_PEM'], null, array("config" => $CFG->opensslcnf
));
429 $export = openssl_pkey_export($new_key, $keypair['keypair_PEM'] /* , $passphrase */);
431 openssl_pkey_free($new_key);
432 unset($new_key); // Free up the resource
438 function mnet_update_sso_access_control($username, $mnet_host_id, $accessctrl) {
441 $mnethost = $DB->get_record('mnet_host', array('id'=>$mnet_host_id));
442 if ($aclrecord = $DB->get_record('mnet_sso_access_control', array('username'=>$username, 'mnet_host_id'=>$mnet_host_id))) {
444 $aclrecord->accessctrl
= $accessctrl;
445 $DB->update_record('mnet_sso_access_control', $aclrecord);
446 add_to_log(SITEID
, 'admin/mnet', 'update', 'admin/mnet/access_control.php',
447 "SSO ACL: $accessctrl user '$username' from {$mnethost->name}");
450 $aclrecord = new stdClass();
451 $aclrecord->username
= $username;
452 $aclrecord->accessctrl
= $accessctrl;
453 $aclrecord->mnet_host_id
= $mnet_host_id;
454 $id = $DB->insert_record('mnet_sso_access_control', $aclrecord);
455 add_to_log(SITEID
, 'admin/mnet', 'add', 'admin/mnet/access_control.php',
456 "SSO ACL: $accessctrl user '$username' from {$mnethost->name}");
461 function mnet_get_peer_host ($mnethostid) {
464 if (!isset($hosts[$mnethostid])) {
465 $host = $DB->get_record('mnet_host', array('id' => $mnethostid));
466 $hosts[$mnethostid] = $host;
468 return $hosts[$mnethostid];
472 * Inline function to modify a url string so that mnet users are requested to
473 * log in at their mnet identity provider (if they are not already logged in)
474 * before ultimately being directed to the original url.
476 * @param string $jumpurl the url which user should initially be directed to.
477 * This is a URL associated with a moodle networking peer when it
478 * is fulfiling a role as an identity provider (IDP). Different urls for
479 * different peers, the jumpurl is formed partly from the IDP's webroot, and
480 * partly from a predefined local path within that webwroot.
481 * The result of the user hitting this jump url is that they will be asked
482 * to login (at their identity provider (if they aren't already)), mnet
483 * will prepare the necessary authentication information, then redirect
484 * them back to somewhere at the content provider(CP) moodle (this moodle)
485 * @param array $url array with 2 elements
486 * 0 - context the url was taken from, possibly just the url, possibly href="url"
487 * 1 - the destination url
488 * @return string the url the remote user should be supplied with.
490 function mnet_sso_apply_indirection ($jumpurl, $url) {
494 $urlparts = parse_url($url[1]);
496 if (isset($urlparts['path'])) {
497 $path = $urlparts['path'];
498 // if our wwwroot has a path component, need to strip that path from beginning of the
499 // 'localpart' to make it relative to moodle's wwwroot
500 $wwwrootpath = parse_url($CFG->wwwroot
, PHP_URL_PATH
);
501 if (!empty($wwwrootpath) and strpos($path, $wwwrootpath) === 0) {
502 $path = substr($path, strlen($wwwrootpath));
506 if (isset($urlparts['query'])) {
507 $localpart .= '?'.$urlparts['query'];
509 if (isset($urlparts['fragment'])) {
510 $localpart .= '#'.$urlparts['fragment'];
513 $indirecturl = $jumpurl . urlencode($localpart);
514 //If we matched on more than just a url (ie an html link), return the url to an href format
515 if ($url[0] != $url[1]) {
516 $indirecturl = 'href="'.$indirecturl.'"';
521 function mnet_get_app_jumppath ($applicationid) {
523 static $appjumppaths;
524 if (!isset($appjumppaths[$applicationid])) {
525 $ssojumpurl = $DB->get_field('mnet_application', 'sso_jump_url', array('id' => $applicationid));
526 $appjumppaths[$applicationid] = $ssojumpurl;
528 return $appjumppaths[$applicationid];
533 * Output debug information about mnet. this will go to the <b>error_log</b>.
535 * @param mixed $debugdata this can be a string, or array or object.
536 * @param int $debuglevel optional , defaults to 1. bump up for very noisy debug info
538 function mnet_debug($debugdata, $debuglevel=1) {
540 $setlevel = get_config('', 'mnet_rpcdebug');
541 if (empty($setlevel) ||
$setlevel < $debuglevel) {
544 if (is_object($debugdata)) {
545 $debugdata = (array)$debugdata;
547 if (is_array($debugdata)) {
548 mnet_debug('DUMPING ARRAY');
549 foreach ($debugdata as $key => $value) {
550 mnet_debug("$key: $value");
552 mnet_debug('END DUMPING ARRAY');
555 $prefix = 'MNET DEBUG ';
556 if (defined('MNET_SERVER')) {
557 $prefix .= " (server $CFG->wwwroot";
558 if ($peer = get_mnet_remote_client() && !empty($peer->wwwroot
)) {
559 $prefix .= ", remote peer " . $peer->wwwroot
;
563 $prefix .= " (client $CFG->wwwroot) ";
565 error_log("$prefix $debugdata");
569 * Return an array of information about all moodle's profile fields
570 * which ones are optional, which ones are forced.
571 * This is used as the basis of providing lists of profile fields to the administrator
572 * to pick which fields to import/export over MNET
574 * @return array(forced => array, optional => array)
576 function mnet_profile_field_options() {
584 'id', // makes no sense
585 'mnethostid', // makes no sense
586 'timecreated', // will be set to relative to the host anyway
587 'timemodified', // will be set to relative to the host anyway
588 'auth', // going to be set to 'mnet'
589 'deleted', // we should never get deleted users sent over, but don't send this anyway
590 'confirmed', // unconfirmed users can't log in to their home site, all remote users considered confirmed
591 'password', // no password for mnet users
592 'theme', // handled separately
593 'lastip', // will be set to relative to the host anyway
596 // these are the ones that user_not_fully_set_up will complain about
597 // and also special case ones
605 'session.gc_lifetime',
606 '_mnet_userpicture_timemodified',
607 '_mnet_userpicture_mimetype',
610 // these are the ones we used to send/receive (pre 2.0)
631 // get a random user record from the database to pull the fields off
632 $randomuser = $DB->get_record('user', array(), '*', IGNORE_MULTIPLE
);
633 foreach ($randomuser as $key => $discard) {
634 if (in_array($key, $excludes) ||
in_array($key, $forced)) {
637 $fields[$key] = $key;
641 'optional' => $fields,
649 * Returns information about MNet peers
651 * @param bool $withdeleted should the deleted peers be returned too
654 function mnet_get_hosts($withdeleted = false) {
657 $sql = "SELECT h.id, h.deleted, h.wwwroot, h.ip_address, h.name, h.public_key, h.public_key_expires,
658 h.transport, h.portno, h.last_connect_time, h.last_log_id, h.applicationid,
659 a.name as app_name, a.display_name as app_display_name, a.xmlrpc_server_url
661 JOIN {mnet_application} a ON h.applicationid = a.id
665 $sql .= " AND h.deleted = 0";
668 $sql .= " ORDER BY h.deleted, h.name, h.id";
670 return $DB->get_records_sql($sql, array($CFG->mnet_localhost_id
));
675 * return an array information about services enabled for the given peer.
676 * in two modes, fulldata or very basic data.
678 * @param mnet_peer $mnet_peer the peer to get information abut
679 * @param boolean $fulldata whether to just return which services are published/subscribed, or more information (defaults to full)
681 * @return array If $fulldata is false, an array is returned like:
683 * serviceid => boolean,
684 * serviceid => boolean,
686 * subscribe => array(
687 * serviceid => boolean,
688 * serviceid => boolean,
690 * If $fulldata is true, an array is returned like:
691 * servicename => array(
692 * apiversion => array(
696 * plugintype => string
697 * pluginname => string
698 * hostsubscribes => boolean
699 * hostpublishes => boolean
703 function mnet_get_service_info(mnet_peer
$mnet_peer, $fulldata=true) {
706 $requestkey = (!empty($fulldata) ?
'fulldata' : 'mydata');
708 static $cache = array();
709 if (array_key_exists($mnet_peer->id
, $cache)) {
710 return $cache[$mnet_peer->id
][$requestkey];
713 $id_list = $mnet_peer->id
;
714 if (!empty($CFG->mnet_all_hosts_id
)) {
715 $id_list .= ', '.$CFG->mnet_all_hosts_id
;
718 $concat = $DB->sql_concat('COALESCE(h2s.id,0) ', ' \'-\' ', ' svc.id', '\'-\'', 'r.plugintype', '\'-\'', 'r.pluginname');
733 {mnet_service2rpc} s2r,
737 {mnet_host2service} h2s
739 h2s.hostid in ($id_list) AND
740 h2s.serviceid = svc.id
743 s2r.serviceid = svc.id AND
748 $resultset = $DB->get_records_sql($query);
750 if (is_array($resultset)) {
751 $resultset = array_values($resultset);
753 $resultset = array();
756 require_once $CFG->dirroot
.'/mnet/xmlrpc/client.php';
758 $remoteservices = array();
759 if ($mnet_peer->id
!= $CFG->mnet_all_hosts_id
) {
760 // Create a new request object
761 $mnet_request = new mnet_xmlrpc_client();
763 // Tell it the path to the method that we want to execute
764 $mnet_request->set_method('system/listServices');
765 $mnet_request->send($mnet_peer);
766 if (is_array($mnet_request->response
)) {
767 foreach($mnet_request->response
as $service) {
768 $remoteservices[$service['name']][$service['apiversion']] = $service;
773 $myservices = array();
775 foreach($resultset as $result) {
776 $result->hostpublishes
= false;
777 $result->hostsubscribes
= false;
778 if (isset($remoteservices[$result->name
][$result->apiversion
])) {
779 if ($remoteservices[$result->name
][$result->apiversion
]['publish'] == 1) {
780 $result->hostpublishes
= true;
782 if ($remoteservices[$result->name
][$result->apiversion
]['subscribe'] == 1) {
783 $result->hostsubscribes
= true;
787 if (empty($myservices[$result->name
][$result->apiversion
])) {
788 $myservices[$result->name
][$result->apiversion
] = array('serviceid' => $result->serviceid
,
789 'name' => $result->name
,
790 'offer' => $result->offer
,
791 'apiversion' => $result->apiversion
,
792 'plugintype' => $result->plugintype
,
793 'pluginname' => $result->pluginname
,
794 'hostsubscribes' => $result->hostsubscribes
,
795 'hostpublishes' => $result->hostpublishes
799 // allhosts_publish allows us to tell the admin that even though he
800 // is disabling a service, it's still available to the host because
801 // he's also publishing it to 'all hosts'
802 if ($result->hostid
== $CFG->mnet_all_hosts_id
&& $CFG->mnet_all_hosts_id
!= $mnet_peer->id
) {
803 $myservices[$result->name
][$result->apiversion
]['allhosts_publish'] = $result->publish
;
804 $myservices[$result->name
][$result->apiversion
]['allhosts_subscribe'] = $result->subscribe
;
805 } elseif (!empty($result->hostid
)) {
806 $myservices[$result->name
][$result->apiversion
]['I_publish'] = $result->publish
;
807 $myservices[$result->name
][$result->apiversion
]['I_subscribe'] = $result->subscribe
;
809 $mydata['publish'][$result->serviceid
] = $result->publish
;
810 $mydata['subscribe'][$result->serviceid
] = $result->subscribe
;
814 $cache[$mnet_peer->id
]['fulldata'] = $myservices;
815 $cache[$mnet_peer->id
]['mydata'] = $mydata;
817 return $cache[$mnet_peer->id
][$requestkey];
821 * return an array of the profile fields to send
822 * with user information to the given mnet host.
824 * @param mnet_peer $peer the peer to send the information to
826 * @return array (like 'username', 'firstname', etc)
828 function mnet_fields_to_send(mnet_peer
$peer) {
829 return _mnet_field_helper($peer, 'export');
833 * return an array of the profile fields to import
834 * from the given host, when creating/updating user accounts
836 * @param mnet_peer $peer the peer we're getting the information from
838 * @return array (like 'username', 'firstname', etc)
840 function mnet_fields_to_import(mnet_peer
$peer) {
841 return _mnet_field_helper($peer, 'import');
845 * helper for {@see mnet_fields_to_import} and {@mnet_fields_to_send}
849 * @param mnet_peer $peer the peer object
850 * @param string $key 'import' or 'export'
852 * @return array (like 'username', 'firstname', etc)
854 function _mnet_field_helper(mnet_peer
$peer, $key) {
855 $tmp = mnet_profile_field_options();
856 $defaults = explode(',', get_config('moodle', 'mnetprofile' . $key . 'fields'));
857 if ('1' === get_config('mnet', 'host' . $peer->id
. $key . 'default')) {
858 return array_merge($tmp['forced'], $defaults);
860 $hostsettings = get_config('mnet', 'host' . $peer->id
. $key . 'fields');
861 if (false === $hostsettings) {
862 return array_merge($tmp['forced'], $defaults);
864 return array_merge($tmp['forced'], explode(',', $hostsettings));
869 * given a user object (or array) and a list of allowed fields,
870 * strip out all the fields that should not be included.
871 * This can be used both for outgoing data and incoming data.
873 * @param mixed $user array or object representing a database record
874 * @param array $fields an array of allowed fields (usually from mnet_fields_to_{send,import}
876 * @return mixed array or object, depending what type of $user object was passed (datatype is respected)
878 function mnet_strip_user($user, $fields) {
879 if (is_object($user)) {
880 $user = (array)$user;
881 $wasobject = true; // so we can cast back before we return
884 foreach ($user as $key => $value) {
885 if (!in_array($key, $fields)) {
889 if (!empty($wasobject)) {
890 $user = (object)$user;