Merge branch 'MDL-77321-401' of https://github.com/paulholden/moodle into MOODLE_401_...
[moodle.git] / mnet / lib.php
blob20a14a59c364a1b00d6553764baa16466ed44872
1 <?php
2 /**
3 * Library functions for mnet
5 * @author Donal McMullan donal@catalyst.net.nz
6 * @version 0.0.1
7 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
8 * @package mnet
9 */
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 ///////////////////////////////////////////////////////////
16 define('RPC_OK', 0);
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);
24 /**
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];
35 return false;
38 /**
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) {
46 global $CFG, $DB;
47 $mnet = get_mnet_environment();
48 // The key may be cached in the mnet_set_public_key function...
49 // check this first
50 $key = mnet_set_public_key($uri);
51 if ($key != false) {
52 return $key;
55 if (empty($application)) {
56 $application = $DB->get_record('mnet_application', array('name'=>'moodle'));
59 $params = [
60 new \PhpXmlRpc\Value($CFG->wwwroot),
61 new \PhpXmlRpc\Value($mnet->public_key),
62 new \PhpXmlRpc\Value($application->name),
64 $request = new \PhpXmlRpc\Request('system/keyswap', $params);
65 $request->request_charset_encoding = 'utf-8';
67 // Let's create a client to handle the request and the response easily.
68 $client = new \PhpXmlRpc\Client($uri . $application->xmlrpc_server_url);
69 $client->setUseCurl(\PhpXmlRpc\Client::USE_CURL_ALWAYS);
70 $client->setUserAgent('Moodle');
71 $client->return_type = 'xmlrpcvals'; // This (keyswap) is not encrypted, so we can expect proper xmlrpc in this case.
72 $client->request_charset_encoding = 'utf-8';
74 // TODO: Link this to DEBUG DEVELOPER or with MNET debugging...
75 // $client->setdebug(1); // See a good number of complete requests and responses.
77 $client->setSSLVerifyHost(0);
78 $client->setSSLVerifyPeer(false);
80 // TODO: It's curious that this service (keyswap) that needs
81 // a custom client, different from mnet_xmlrpc_client, because
82 // this is not encrypted / signed, does support proxies and the
83 // general one does not. Worth analysing if the support below
84 // should be added to it.
86 // Some curl options need to be set apart, accumulate them here.
87 $extracurloptions = [];
89 // Check for proxy.
90 if (!empty($CFG->proxyhost) && !is_proxybypass($uri)) {
91 // SOCKS supported in PHP5 only.
92 if (!empty($CFG->proxytype) && ($CFG->proxytype == 'SOCKS5')) {
93 if (defined('CURLPROXY_SOCKS5')) {
94 $extracurloptions[CURLOPT_PROXYTYPE] = CURLPROXY_SOCKS5;
95 } else {
96 throw new \moodle_exception( 'socksnotsupported', 'mnet');
100 $extracurloptions[CURLOPT_HTTPPROXYTUNNEL] = false;
102 // Configure proxy host, port, user, pass and auth.
103 $client->setProxy(
104 $CFG->proxyhost,
105 empty($CFG->proxyport) ? 0 : $CFG->proxyport,
106 empty($CFG->proxyuser) ? '' : $CFG->proxyuser,
107 empty($CFG->proxypassword) ? '' : $CFG->proxypassword,
108 defined('CURLOPT_PROXYAUTH') ? CURLAUTH_BASIC | CURLAUTH_NTLM : 1);
111 // Finally, add the extra curl options we may have accumulated.
112 $client->setCurlOptions($extracurloptions);
114 $response = $client->send($request, 60);
116 // Check curl / xmlrpc errors.
117 if ($response->faultCode()) {
118 debugging("Request for $uri failed with error {$response->faultCode()}: {$response->faultString()}");
119 return false;
122 // Check HTTP error code.
123 $status = $response->httpResponse()['status_code'];
124 if (!empty($status) && ($status != 200)) {
125 debugging("Request for $uri failed with HTTP code " . $status);
126 return false;
129 // Get the peer actual public key from the response.
130 $res = $response->value()->scalarval();
132 if (!is_array($res)) { // ! error
133 $public_certificate = $res;
134 $credentials=array();
135 if (strlen(trim($public_certificate))) {
136 $credentials = openssl_x509_parse($public_certificate);
137 $host = $credentials['subject']['CN'];
138 if (array_key_exists( 'subjectAltName', $credentials['subject'])) {
139 $host = $credentials['subject']['subjectAltName'];
141 if (strpos($uri, $host) !== false) {
142 mnet_set_public_key($uri, $public_certificate);
143 return $public_certificate;
145 else {
146 debugging("Request for $uri returned public key for different URI - $host");
149 else {
150 debugging("Request for $uri returned empty response");
153 else {
154 debugging( "Request for $uri returned unexpected result");
156 return false;
160 * Store a URI's public key in a static variable, or retrieve the key for a URI
162 * @param string $uri The URI of a file on the remote computer, including its
163 * https:// prefix
164 * @param mixed $key A public key to store in the array OR null. If the key
165 * is null, the function will return the previously stored
166 * key for the supplied URI, should it exist.
167 * @return mixed A public key OR true/false.
169 function mnet_set_public_key($uri, $key = null) {
170 static $keyarray = array();
171 if (isset($keyarray[$uri]) && empty($key)) {
172 return $keyarray[$uri];
173 } elseif (!empty($key)) {
174 $keyarray[$uri] = $key;
175 return true;
177 return false;
181 * Sign a message and return it in an XML-Signature document
183 * This function can sign any content, but it was written to provide a system of
184 * signing XML-RPC request and response messages. The message will be base64
185 * encoded, so it does not need to be text.
187 * We compute the SHA1 digest of the message.
188 * We compute a signature on that digest with our private key.
189 * We link to the public key that can be used to verify our signature.
190 * We base64 the message data.
191 * We identify our wwwroot - this must match our certificate's CN
193 * The XML-RPC document will be parceled inside an XML-SIG document, which holds
194 * the base64_encoded XML as an object, the SHA1 digest of that document, and a
195 * signature of that document using the local private key. This signature will
196 * uniquely identify the RPC document as having come from this server.
198 * See the {@Link http://www.w3.org/TR/xmldsig-core/ XML-DSig spec} at the W3c
199 * site
201 * @param string $message The data you want to sign
202 * @param resource $privatekey The private key to sign the response with
203 * @return string An XML-DSig document
205 function mnet_sign_message($message, $privatekey = null) {
206 global $CFG;
207 $digest = sha1($message);
209 $mnet = get_mnet_environment();
210 // If the user hasn't supplied a private key (for example, one of our older,
211 // expired private keys, we get the current default private key and use that.
212 if ($privatekey == null) {
213 $privatekey = $mnet->get_private_key();
216 // The '$sig' value below is returned by reference.
217 // We initialize it first to stop my IDE from complaining.
218 $sig = '';
219 $bool = openssl_sign($message, $sig, $privatekey); // TODO: On failure?
221 $message = '<?xml version="1.0" encoding="iso-8859-1"?>
222 <signedMessage>
223 <Signature Id="MoodleSignature" xmlns="http://www.w3.org/2000/09/xmldsig#">
224 <SignedInfo>
225 <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
226 <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
227 <Reference URI="#XMLRPC-MSG">
228 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
229 <DigestValue>'.$digest.'</DigestValue>
230 </Reference>
231 </SignedInfo>
232 <SignatureValue>'.base64_encode($sig).'</SignatureValue>
233 <KeyInfo>
234 <RetrievalMethod URI="'.$CFG->wwwroot.'/mnet/publickey.php"/>
235 </KeyInfo>
236 </Signature>
237 <object ID="XMLRPC-MSG">'.base64_encode($message).'</object>
238 <wwwroot>'.$mnet->wwwroot.'</wwwroot>
239 <timestamp>'.time().'</timestamp>
240 </signedMessage>';
241 return $message;
245 * Encrypt a message and return it in an XML-Encrypted document
247 * This function can encrypt any content, but it was written to provide a system
248 * of encrypting XML-RPC request and response messages. The message will be
249 * base64 encoded, so it does not need to be text - binary data should work.
251 * We compute the SHA1 digest of the message.
252 * We compute a signature on that digest with our private key.
253 * We link to the public key that can be used to verify our signature.
254 * We base64 the message data.
255 * We identify our wwwroot - this must match our certificate's CN
257 * The XML-RPC document will be parceled inside an XML-SIG document, which holds
258 * the base64_encoded XML as an object, the SHA1 digest of that document, and a
259 * signature of that document using the local private key. This signature will
260 * uniquely identify the RPC document as having come from this server.
262 * See the {@Link http://www.w3.org/TR/xmlenc-core/ XML-ENC spec} at the W3c
263 * site
265 * @param string $message The data you want to sign
266 * @param string $remote_certificate Peer's certificate in PEM format
267 * @return string An XML-ENC document
269 function mnet_encrypt_message($message, $remote_certificate) {
270 $mnet = get_mnet_environment();
272 // Generate a key resource from the remote_certificate text string
273 $publickey = openssl_get_publickey($remote_certificate);
275 if ($publickey === false) {
276 // Remote certificate is faulty.
277 return false;
280 // Initialize vars
281 $encryptedstring = '';
282 $symmetric_keys = array();
284 // passed by ref -> &$encryptedstring &$symmetric_keys
285 $bool = openssl_seal($message, $encryptedstring, $symmetric_keys, array($publickey), 'RC4');
286 $message = $encryptedstring;
287 $symmetrickey = array_pop($symmetric_keys);
289 $message = '<?xml version="1.0" encoding="iso-8859-1"?>
290 <encryptedMessage>
291 <EncryptedData Id="ED" xmlns="http://www.w3.org/2001/04/xmlenc#">
292 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#arcfour"/>
293 <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
294 <ds:RetrievalMethod URI="#EK" Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey"/>
295 <ds:KeyName>XMLENC</ds:KeyName>
296 </ds:KeyInfo>
297 <CipherData>
298 <CipherValue>'.base64_encode($message).'</CipherValue>
299 </CipherData>
300 </EncryptedData>
301 <EncryptedKey Id="EK" xmlns="http://www.w3.org/2001/04/xmlenc#">
302 <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
303 <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
304 <ds:KeyName>SSLKEY</ds:KeyName>
305 </ds:KeyInfo>
306 <CipherData>
307 <CipherValue>'.base64_encode($symmetrickey).'</CipherValue>
308 </CipherData>
309 <ReferenceList>
310 <DataReference URI="#ED"/>
311 </ReferenceList>
312 <CarriedKeyName>XMLENC</CarriedKeyName>
313 </EncryptedKey>
314 <wwwroot>'.$mnet->wwwroot.'</wwwroot>
315 </encryptedMessage>';
316 return $message;
320 * Get your SSL keys from the database, or create them (if they don't exist yet)
322 * Get your SSL keys from the database, or (if they don't exist yet) call
323 * mnet_generate_keypair to create them
325 * @param string $string The text you want to sign
326 * @return string The signature over that text
328 function mnet_get_keypair() {
329 global $CFG, $DB;
330 static $keypair = null;
331 if (!is_null($keypair)) return $keypair;
332 if ($result = get_config('mnet', 'openssl')) {
333 list($keypair['certificate'], $keypair['keypair_PEM']) = explode('@@@@@@@@', $result);
334 return $keypair;
335 } else {
336 $keypair = mnet_generate_keypair();
337 return $keypair;
342 * Generate public/private keys and store in the config table
344 * Use the distinguished name provided to create a CSR, and then sign that CSR
345 * with the same credentials. Store the keypair you create in the config table.
346 * If a distinguished name is not provided, create one using the fullname of
347 * 'the course with ID 1' as your organization name, and your hostname (as
348 * detailed in $CFG->wwwroot).
350 * @param array $dn The distinguished name of the server
351 * @return string The signature over that text
353 function mnet_generate_keypair($dn = null, $days=28) {
354 global $CFG, $USER, $DB;
356 // check if lifetime has been overriden
357 if (!empty($CFG->mnetkeylifetime)) {
358 $days = $CFG->mnetkeylifetime;
361 $host = strtolower($CFG->wwwroot);
362 $host = preg_replace("~^http(s)?://~",'',$host);
363 $break = strpos($host.'/' , '/');
364 $host = substr($host, 0, $break);
366 $site = get_site();
367 $organization = $site->fullname;
369 $keypair = array();
371 $country = 'NZ';
372 $province = 'Wellington';
373 $locality = 'Wellington';
374 $email = !empty($CFG->noreplyaddress) ? $CFG->noreplyaddress : 'noreply@'.$_SERVER['HTTP_HOST'];
376 if(!empty($USER->country)) {
377 $country = $USER->country;
379 if(!empty($USER->city)) {
380 $province = $USER->city;
381 $locality = $USER->city;
383 if(!empty($USER->email)) {
384 $email = $USER->email;
387 if (is_null($dn)) {
388 $dn = array(
389 "countryName" => $country,
390 "stateOrProvinceName" => $province,
391 "localityName" => $locality,
392 "organizationName" => $organization,
393 "organizationalUnitName" => 'Moodle',
394 "commonName" => substr($CFG->wwwroot, 0, 64),
395 "subjectAltName" => $CFG->wwwroot,
396 "emailAddress" => $email
400 $dnlimits = array(
401 'countryName' => 2,
402 'stateOrProvinceName' => 128,
403 'localityName' => 128,
404 'organizationName' => 64,
405 'organizationalUnitName' => 64,
406 'commonName' => 64,
407 'emailAddress' => 128
410 foreach ($dnlimits as $key => $length) {
411 $dn[$key] = core_text::substr($dn[$key], 0, $length);
414 // ensure we remove trailing slashes
415 $dn["commonName"] = preg_replace(':/$:', '', $dn["commonName"]);
416 if (!empty($CFG->opensslcnf)) { //allow specification of openssl.cnf especially for Windows installs
417 $new_key = openssl_pkey_new(array("config" => $CFG->opensslcnf));
418 } else {
419 $new_key = openssl_pkey_new();
421 if ($new_key === false) {
422 // can not generate keys - missing openssl.cnf??
423 return null;
425 if (!empty($CFG->opensslcnf)) { //allow specification of openssl.cnf especially for Windows installs
426 $csr_rsc = openssl_csr_new($dn, $new_key, array("config" => $CFG->opensslcnf));
427 $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days, array("config" => $CFG->opensslcnf));
428 } else {
429 $csr_rsc = openssl_csr_new($dn, $new_key, array('private_key_bits',2048));
430 $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days);
432 unset($csr_rsc); // Free up the resource
434 // We export our self-signed certificate to a string.
435 openssl_x509_export($selfSignedCert, $keypair['certificate']);
436 // TODO: Remove this block once PHP 8.0 becomes required.
437 if (PHP_MAJOR_VERSION < 8) {
438 openssl_x509_free($selfSignedCert);
441 // Export your public/private key pair as a PEM encoded string. You
442 // can protect it with an optional passphrase if you wish.
443 if (!empty($CFG->opensslcnf)) { //allow specification of openssl.cnf especially for Windows installs
444 $export = openssl_pkey_export($new_key, $keypair['keypair_PEM'], null, array("config" => $CFG->opensslcnf));
445 } else {
446 $export = openssl_pkey_export($new_key, $keypair['keypair_PEM'] /* , $passphrase */);
448 // TODO: Remove this block once PHP 8.0 becomes required.
449 if (PHP_MAJOR_VERSION < 8) {
450 openssl_pkey_free($new_key);
452 unset($new_key); // Free up the resource
454 return $keypair;
458 function mnet_update_sso_access_control($username, $mnet_host_id, $accessctrl) {
459 global $DB;
461 $mnethost = $DB->get_record('mnet_host', array('id'=>$mnet_host_id));
462 if ($aclrecord = $DB->get_record('mnet_sso_access_control', array('username'=>$username, 'mnet_host_id'=>$mnet_host_id))) {
463 // Update.
464 $aclrecord->accessctrl = $accessctrl;
465 $DB->update_record('mnet_sso_access_control', $aclrecord);
467 // Trigger access control updated event.
468 $params = array(
469 'objectid' => $aclrecord->id,
470 'context' => context_system::instance(),
471 'other' => array(
472 'username' => $username,
473 'hostname' => $mnethost->name,
474 'accessctrl' => $accessctrl
477 $event = \core\event\mnet_access_control_updated::create($params);
478 $event->add_record_snapshot('mnet_host', $mnethost);
479 $event->trigger();
480 } else {
481 // Insert.
482 $aclrecord = new stdClass();
483 $aclrecord->username = $username;
484 $aclrecord->accessctrl = $accessctrl;
485 $aclrecord->mnet_host_id = $mnet_host_id;
486 $aclrecord->id = $DB->insert_record('mnet_sso_access_control', $aclrecord);
488 // Trigger access control created event.
489 $params = array(
490 'objectid' => $aclrecord->id,
491 'context' => context_system::instance(),
492 'other' => array(
493 'username' => $username,
494 'hostname' => $mnethost->name,
495 'accessctrl' => $accessctrl
498 $event = \core\event\mnet_access_control_created::create($params);
499 $event->add_record_snapshot('mnet_host', $mnethost);
500 $event->trigger();
502 return true;
505 function mnet_get_peer_host ($mnethostid) {
506 global $DB;
507 static $hosts;
508 if (!isset($hosts[$mnethostid])) {
509 $host = $DB->get_record('mnet_host', array('id' => $mnethostid));
510 $hosts[$mnethostid] = $host;
512 return $hosts[$mnethostid];
516 * Inline function to modify a url string so that mnet users are requested to
517 * log in at their mnet identity provider (if they are not already logged in)
518 * before ultimately being directed to the original url.
520 * @param string $jumpurl the url which user should initially be directed to.
521 * This is a URL associated with a moodle networking peer when it
522 * is fulfiling a role as an identity provider (IDP). Different urls for
523 * different peers, the jumpurl is formed partly from the IDP's webroot, and
524 * partly from a predefined local path within that webwroot.
525 * The result of the user hitting this jump url is that they will be asked
526 * to login (at their identity provider (if they aren't already)), mnet
527 * will prepare the necessary authentication information, then redirect
528 * them back to somewhere at the content provider(CP) moodle (this moodle)
529 * @param array $url array with 2 elements
530 * 0 - context the url was taken from, possibly just the url, possibly href="url"
531 * 1 - the destination url
532 * @return string the url the remote user should be supplied with.
534 function mnet_sso_apply_indirection ($jumpurl, $url) {
535 global $USER, $CFG;
537 $localpart='';
538 $urlparts = parse_url($url[1]);
539 if($urlparts) {
540 if (isset($urlparts['path'])) {
541 $path = $urlparts['path'];
542 // if our wwwroot has a path component, need to strip that path from beginning of the
543 // 'localpart' to make it relative to moodle's wwwroot
544 $wwwrootpath = parse_url($CFG->wwwroot, PHP_URL_PATH);
545 if (!empty($wwwrootpath) && strpos($path, $wwwrootpath) === 0) {
546 $path = substr($path, strlen($wwwrootpath));
548 $localpart .= $path;
550 if (isset($urlparts['query'])) {
551 $localpart .= '?'.$urlparts['query'];
553 if (isset($urlparts['fragment'])) {
554 $localpart .= '#'.$urlparts['fragment'];
557 $indirecturl = $jumpurl . urlencode($localpart);
558 //If we matched on more than just a url (ie an html link), return the url to an href format
559 if ($url[0] != $url[1]) {
560 $indirecturl = 'href="'.$indirecturl.'"';
562 return $indirecturl;
565 function mnet_get_app_jumppath ($applicationid) {
566 global $DB;
567 static $appjumppaths;
568 if (!isset($appjumppaths[$applicationid])) {
569 $ssojumpurl = $DB->get_field('mnet_application', 'sso_jump_url', array('id' => $applicationid));
570 $appjumppaths[$applicationid] = $ssojumpurl;
572 return $appjumppaths[$applicationid];
577 * Output debug information about mnet. this will go to the <b>error_log</b>.
579 * @param mixed $debugdata this can be a string, or array or object.
580 * @param int $debuglevel optional , defaults to 1. bump up for very noisy debug info
582 function mnet_debug($debugdata, $debuglevel=1) {
583 global $CFG;
584 $setlevel = get_config('', 'mnet_rpcdebug');
585 if (empty($setlevel) || $setlevel < $debuglevel) {
586 return;
588 if (is_object($debugdata)) {
589 $debugdata = (array)$debugdata;
591 if (is_array($debugdata)) {
592 mnet_debug('DUMPING ARRAY');
593 foreach ($debugdata as $key => $value) {
594 mnet_debug("$key: $value");
596 mnet_debug('END DUMPING ARRAY');
597 return;
599 $prefix = 'MNET DEBUG ';
600 if (defined('MNET_SERVER')) {
601 $prefix .= " (server $CFG->wwwroot";
602 if ($peer = get_mnet_remote_client() && !empty($peer->wwwroot)) {
603 $prefix .= ", remote peer " . $peer->wwwroot;
605 $prefix .= ')';
606 } else {
607 $prefix .= " (client $CFG->wwwroot) ";
609 error_log("$prefix $debugdata");
613 * Return an array of information about all moodle's profile fields
614 * which ones are optional, which ones are forced.
615 * This is used as the basis of providing lists of profile fields to the administrator
616 * to pick which fields to import/export over MNET
618 * @return array(forced => array, optional => array)
620 function mnet_profile_field_options() {
621 global $DB;
622 static $info;
623 if (!empty($info)) {
624 return $info;
627 $excludes = array(
628 'id', // makes no sense
629 'mnethostid', // makes no sense
630 'timecreated', // will be set to relative to the host anyway
631 'timemodified', // will be set to relative to the host anyway
632 'auth', // going to be set to 'mnet'
633 'deleted', // we should never get deleted users sent over, but don't send this anyway
634 'confirmed', // unconfirmed users can't log in to their home site, all remote users considered confirmed
635 'password', // no password for mnet users
636 'theme', // handled separately
637 'lastip', // will be set to relative to the host anyway
640 // these are the ones that user_not_fully_set_up will complain about
641 // and also special case ones
642 $forced = array(
643 'username',
644 'email',
645 'firstname',
646 'lastname',
647 'auth',
648 'wwwroot',
649 'session.gc_lifetime',
650 '_mnet_userpicture_timemodified',
651 '_mnet_userpicture_mimetype',
654 // these are the ones we used to send/receive (pre 2.0)
655 $legacy = array(
656 'username',
657 'email',
658 'auth',
659 'deleted',
660 'firstname',
661 'lastname',
662 'city',
663 'country',
664 'lang',
665 'timezone',
666 'description',
667 'mailformat',
668 'maildigest',
669 'maildisplay',
670 'htmleditor',
671 'wwwroot',
672 'picture',
675 // get a random user record from the database to pull the fields off
676 $randomuser = $DB->get_record('user', array(), '*', IGNORE_MULTIPLE);
677 foreach ($randomuser as $key => $discard) {
678 if (in_array($key, $excludes) || in_array($key, $forced)) {
679 continue;
681 $fields[$key] = $key;
683 $info = array(
684 'forced' => $forced,
685 'optional' => $fields,
686 'legacy' => $legacy,
688 return $info;
693 * Returns information about MNet peers
695 * @param bool $withdeleted should the deleted peers be returned too
696 * @return array
698 function mnet_get_hosts($withdeleted = false) {
699 global $CFG, $DB;
701 $sql = "SELECT h.id, h.deleted, h.wwwroot, h.ip_address, h.name, h.public_key, h.public_key_expires,
702 h.transport, h.portno, h.last_connect_time, h.last_log_id, h.applicationid,
703 a.name as app_name, a.display_name as app_display_name, a.xmlrpc_server_url
704 FROM {mnet_host} h
705 JOIN {mnet_application} a ON h.applicationid = a.id
706 WHERE h.id <> ?";
708 if (!$withdeleted) {
709 $sql .= " AND h.deleted = 0";
712 $sql .= " ORDER BY h.deleted, h.name, h.id";
714 return $DB->get_records_sql($sql, array($CFG->mnet_localhost_id));
719 * return an array information about services enabled for the given peer.
720 * in two modes, fulldata or very basic data.
722 * @param mnet_peer $mnet_peer the peer to get information abut
723 * @param boolean $fulldata whether to just return which services are published/subscribed, or more information (defaults to full)
725 * @return array If $fulldata is false, an array is returned like:
726 * publish => array(
727 * serviceid => boolean,
728 * serviceid => boolean,
729 * ),
730 * subscribe => array(
731 * serviceid => boolean,
732 * serviceid => boolean,
734 * If $fulldata is true, an array is returned like:
735 * servicename => array(
736 * apiversion => array(
737 * name => string
738 * offer => boolean
739 * apiversion => int
740 * plugintype => string
741 * pluginname => string
742 * hostsubscribes => boolean
743 * hostpublishes => boolean
744 * ),
747 function mnet_get_service_info(mnet_peer $mnet_peer, $fulldata=true) {
748 global $CFG, $DB;
750 $requestkey = (!empty($fulldata) ? 'fulldata' : 'mydata');
752 static $cache = array();
753 if (array_key_exists($mnet_peer->id, $cache)) {
754 return $cache[$mnet_peer->id][$requestkey];
757 $id_list = $mnet_peer->id;
758 if (!empty($CFG->mnet_all_hosts_id)) {
759 $id_list .= ', '.$CFG->mnet_all_hosts_id;
762 $concat = $DB->sql_concat('COALESCE(h2s.id,0) ', ' \'-\' ', ' svc.id', '\'-\'', 'r.plugintype', '\'-\'', 'r.pluginname');
764 $query = "
765 SELECT DISTINCT
766 $concat as id,
767 svc.id as serviceid,
768 svc.name,
769 svc.offer,
770 svc.apiversion,
771 r.plugintype,
772 r.pluginname,
773 h2s.hostid,
774 h2s.publish,
775 h2s.subscribe
776 FROM
777 {mnet_service2rpc} s2r,
778 {mnet_rpc} r,
779 {mnet_service} svc
780 LEFT JOIN
781 {mnet_host2service} h2s
783 h2s.hostid in ($id_list) AND
784 h2s.serviceid = svc.id
785 WHERE
786 svc.offer = '1' AND
787 s2r.serviceid = svc.id AND
788 s2r.rpcid = r.id
789 ORDER BY
790 svc.name ASC";
792 $resultset = $DB->get_records_sql($query);
794 if (is_array($resultset)) {
795 $resultset = array_values($resultset);
796 } else {
797 $resultset = array();
800 require_once $CFG->dirroot.'/mnet/xmlrpc/client.php';
802 $remoteservices = array();
803 if ($mnet_peer->id != $CFG->mnet_all_hosts_id) {
804 // Create a new request object
805 $mnet_request = new mnet_xmlrpc_client();
807 // Tell it the path to the method that we want to execute
808 $mnet_request->set_method('system/listServices');
809 $mnet_request->send($mnet_peer);
810 if (is_array($mnet_request->response)) {
811 foreach($mnet_request->response as $service) {
812 $remoteservices[$service['name']][$service['apiversion']] = $service;
817 $myservices = array();
818 $mydata = array();
819 foreach($resultset as $result) {
820 $result->hostpublishes = false;
821 $result->hostsubscribes = false;
822 if (isset($remoteservices[$result->name][$result->apiversion])) {
823 if ($remoteservices[$result->name][$result->apiversion]['publish'] == 1) {
824 $result->hostpublishes = true;
826 if ($remoteservices[$result->name][$result->apiversion]['subscribe'] == 1) {
827 $result->hostsubscribes = true;
831 if (empty($myservices[$result->name][$result->apiversion])) {
832 $myservices[$result->name][$result->apiversion] = array('serviceid' => $result->serviceid,
833 'name' => $result->name,
834 'offer' => $result->offer,
835 'apiversion' => $result->apiversion,
836 'plugintype' => $result->plugintype,
837 'pluginname' => $result->pluginname,
838 'hostsubscribes' => $result->hostsubscribes,
839 'hostpublishes' => $result->hostpublishes
843 // allhosts_publish allows us to tell the admin that even though he
844 // is disabling a service, it's still available to the host because
845 // he's also publishing it to 'all hosts'
846 if ($result->hostid == $CFG->mnet_all_hosts_id && $CFG->mnet_all_hosts_id != $mnet_peer->id) {
847 $myservices[$result->name][$result->apiversion]['allhosts_publish'] = $result->publish;
848 $myservices[$result->name][$result->apiversion]['allhosts_subscribe'] = $result->subscribe;
849 } elseif (!empty($result->hostid)) {
850 $myservices[$result->name][$result->apiversion]['I_publish'] = $result->publish;
851 $myservices[$result->name][$result->apiversion]['I_subscribe'] = $result->subscribe;
853 $mydata['publish'][$result->serviceid] = $result->publish;
854 $mydata['subscribe'][$result->serviceid] = $result->subscribe;
858 $cache[$mnet_peer->id]['fulldata'] = $myservices;
859 $cache[$mnet_peer->id]['mydata'] = $mydata;
861 return $cache[$mnet_peer->id][$requestkey];
865 * return an array of the profile fields to send
866 * with user information to the given mnet host.
868 * @param mnet_peer $peer the peer to send the information to
870 * @return array (like 'username', 'firstname', etc)
872 function mnet_fields_to_send(mnet_peer $peer) {
873 return _mnet_field_helper($peer, 'export');
877 * return an array of the profile fields to import
878 * from the given host, when creating/updating user accounts
880 * @param mnet_peer $peer the peer we're getting the information from
882 * @return array (like 'username', 'firstname', etc)
884 function mnet_fields_to_import(mnet_peer $peer) {
885 return _mnet_field_helper($peer, 'import');
889 * helper for {@see mnet_fields_to_import} and {@mnet_fields_to_send}
891 * @access private
893 * @param mnet_peer $peer the peer object
894 * @param string $key 'import' or 'export'
896 * @return array (like 'username', 'firstname', etc)
898 function _mnet_field_helper(mnet_peer $peer, $key) {
899 $tmp = mnet_profile_field_options();
900 $defaults = explode(',', get_config('moodle', 'mnetprofile' . $key . 'fields'));
901 if ('1' === get_config('mnet', 'host' . $peer->id . $key . 'default')) {
902 return array_merge($tmp['forced'], $defaults);
904 $hostsettings = get_config('mnet', 'host' . $peer->id . $key . 'fields');
905 if (false === $hostsettings) {
906 return array_merge($tmp['forced'], $defaults);
908 return array_merge($tmp['forced'], explode(',', $hostsettings));
913 * given a user object (or array) and a list of allowed fields,
914 * strip out all the fields that should not be included.
915 * This can be used both for outgoing data and incoming data.
917 * @param mixed $user array or object representing a database record
918 * @param array $fields an array of allowed fields (usually from mnet_fields_to_{send,import}
920 * @return mixed array or object, depending what type of $user object was passed (datatype is respected)
922 function mnet_strip_user($user, $fields) {
923 if (is_object($user)) {
924 $user = (array)$user;
925 $wasobject = true; // so we can cast back before we return
928 foreach ($user as $key => $value) {
929 if (!in_array($key, $fields)) {
930 unset($user[$key]);
933 if (!empty($wasobject)) {
934 $user = (object)$user;
936 return $user;