Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
/**
3
 * Library functions for mnet
4
 *
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';
13
 
14
/// CONSTANTS ///////////////////////////////////////////////////////////
15
 
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);
23
 
24
/**
25
 * Strip extraneous detail from a URL or URI and return the hostname
26
 *
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
31
 */
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;
36
}
37
 
38
/**
39
 * Get the remote machine's SSL Cert
40
 *
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.
44
 */
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;
53
    }
54
 
55
    if (empty($application)) {
56
        $application = $DB->get_record('mnet_application', array('name'=>'moodle'));
57
    }
58
 
59
    $params = [
60
        new \PhpXmlRpc\Value($CFG->wwwroot),
61
        new \PhpXmlRpc\Value($mnet->public_key),
62
        new \PhpXmlRpc\Value($application->name),
63
    ];
64
    $request = new \PhpXmlRpc\Request('system/keyswap', $params);
65
 
66
    // Let's create a client to handle the request and the response easily.
67
    $client = new \PhpXmlRpc\Client($uri . $application->xmlrpc_server_url);
68
    $client->setOption('use_curl', \PhpXmlRpc\Client::USE_CURL_ALWAYS);
69
    $client->setOption('user_agent', 'Moodle');
70
    $client->return_type = 'xmlrpcvals'; // This (keyswap) is not encrypted, so we can expect proper xmlrpc in this case.
71
    $client->setOption('request_charset_encoding', 'utf-8');
72
    $client->setOption('accepted_charset_encodings', ['utf-8']);
73
 
74
    // TODO: Link this to DEBUG DEVELOPER or with MNET debugging...
75
    // $client->setdebug(1); // See a good number of complete requests and responses.
76
 
77
    $client->setOption('verifyhost', 0);
78
    $client->setOption('verifypeer', false);
79
 
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.
85
 
86
    // Some curl options need to be set apart, accumulate them here.
87
    $extracurloptions = [];
88
 
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');
97
            }
98
        }
99
 
100
        $extracurloptions[CURLOPT_HTTPPROXYTUNNEL] = false;
101
 
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);
109
    }
110
 
111
    // Finally, add the extra curl options we may have accumulated.
112
    $client->setCurlOptions($extracurloptions);
113
 
114
    $response = $client->send($request, 60);
115
 
116
    // Check curl / xmlrpc errors.
117
    if ($response->faultCode()) {
118
        debugging("Request for $uri failed with error {$response->faultCode()}: {$response->faultString()}");
119
        return false;
120
    }
121
 
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;
127
    }
128
 
129
    // Get the peer actual public key from the response.
130
    $res = $response->value()->scalarval();
131
 
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'];
140
            }
141
            if (strpos($uri, $host) !== false) {
142
                mnet_set_public_key($uri, $public_certificate);
143
                return $public_certificate;
144
            }
145
            else {
146
                debugging("Request for $uri returned public key for different URI - $host");
147
            }
148
        }
149
        else {
150
            debugging("Request for $uri returned empty response");
151
        }
152
    }
153
    else {
154
        debugging( "Request for $uri returned unexpected result");
155
    }
156
    return false;
157
}
158
 
159
/**
160
 * Store a URI's public key in a static variable, or retrieve the key for a URI
161
 *
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.
168
 */
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;
176
    }
177
    return false;
178
}
179
 
180
/**
181
 * Sign a message and return it in an XML-Signature document
182
 *
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.
186
 *
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
192
 *
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.
197
 *
198
 * See the {@Link http://www.w3.org/TR/xmldsig-core/ XML-DSig spec} at the W3c
199
 * site
200
 *
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
204
 */
205
function mnet_sign_message($message, $privatekey = null) {
206
    global $CFG;
207
    $digest = sha1($message);
208
 
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();
214
    }
215
 
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);
220
 
221
    // Avoid passing null values to base64_encode.
222
    if ($bool === false) {
223
        throw new \moodle_exception('opensslsignerror');
224
    }
225
 
226
    $message = '<?xml version="1.0" encoding="iso-8859-1"?>
227
    <signedMessage>
228
        <Signature Id="MoodleSignature" xmlns="http://www.w3.org/2000/09/xmldsig#">
229
            <SignedInfo>
230
                <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
231
                <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
232
                <Reference URI="#XMLRPC-MSG">
233
                    <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
234
                    <DigestValue>'.$digest.'</DigestValue>
235
                </Reference>
236
            </SignedInfo>
237
            <SignatureValue>'.base64_encode($sig).'</SignatureValue>
238
            <KeyInfo>
239
                <RetrievalMethod URI="'.$CFG->wwwroot.'/mnet/publickey.php"/>
240
            </KeyInfo>
241
        </Signature>
242
        <object ID="XMLRPC-MSG">'.base64_encode($message).'</object>
243
        <wwwroot>'.$mnet->wwwroot.'</wwwroot>
244
        <timestamp>'.time().'</timestamp>
245
    </signedMessage>';
246
    return $message;
247
}
248
 
249
/**
250
 * Encrypt a message and return it in an XML-Encrypted document
251
 *
252
 * This function can encrypt any content, but it was written to provide a system
253
 * of encrypting XML-RPC request and response messages. The message will be
254
 * base64 encoded, so it does not need to be text - binary data should work.
255
 *
256
 * We compute the SHA1 digest of the message.
257
 * We compute a signature on that digest with our private key.
258
 * We link to the public key that can be used to verify our signature.
259
 * We base64 the message data.
260
 * We identify our wwwroot - this must match our certificate's CN
261
 *
262
 * The XML-RPC document will be parceled inside an XML-SIG document, which holds
263
 * the base64_encoded XML as an object, the SHA1 digest of that document, and a
264
 * signature of that document using the local private key. This signature will
265
 * uniquely identify the RPC document as having come from this server.
266
 *
267
 * See the {@Link http://www.w3.org/TR/xmlenc-core/ XML-ENC spec} at the W3c
268
 * site
269
 *
270
 * @param  string   $message              The data you want to sign
271
 * @param  string   $remote_certificate   Peer's certificate in PEM format
272
 * @return string                         An XML-ENC document
273
 */
274
function mnet_encrypt_message($message, $remote_certificate) {
275
    $mnet = get_mnet_environment();
276
 
277
    // Generate a key resource from the remote_certificate text string
278
    $publickey = openssl_get_publickey($remote_certificate);
279
 
280
    if ($publickey === false) {
281
        // Remote certificate is faulty.
282
        return false;
283
    }
284
 
285
    // Initialize vars
286
    $encryptedstring = '';
287
    $symmetric_keys = array();
288
 
289
    //        passed by ref ->     &$encryptedstring &$symmetric_keys
290
    $bool = openssl_seal($message, $encryptedstring, $symmetric_keys, array($publickey), 'RC4');
291
 
292
    // Avoid passing null values to base64_encode.
293
    if ($bool === false) {
294
        throw new \moodle_exception('opensslsealerror');
295
    }
296
 
297
    $message = $encryptedstring;
298
    $symmetrickey = array_pop($symmetric_keys);
299
 
300
    $message = '<?xml version="1.0" encoding="iso-8859-1"?>
301
    <encryptedMessage>
302
        <EncryptedData Id="ED" xmlns="http://www.w3.org/2001/04/xmlenc#">
303
            <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#arcfour"/>
304
            <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
305
                <ds:RetrievalMethod URI="#EK" Type="http://www.w3.org/2001/04/xmlenc#EncryptedKey"/>
306
                <ds:KeyName>XMLENC</ds:KeyName>
307
            </ds:KeyInfo>
308
            <CipherData>
309
                <CipherValue>'.base64_encode($message).'</CipherValue>
310
            </CipherData>
311
        </EncryptedData>
312
        <EncryptedKey Id="EK" xmlns="http://www.w3.org/2001/04/xmlenc#">
313
            <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5"/>
314
            <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
315
                <ds:KeyName>SSLKEY</ds:KeyName>
316
            </ds:KeyInfo>
317
            <CipherData>
318
                <CipherValue>'.base64_encode($symmetrickey).'</CipherValue>
319
            </CipherData>
320
            <ReferenceList>
321
                <DataReference URI="#ED"/>
322
            </ReferenceList>
323
            <CarriedKeyName>XMLENC</CarriedKeyName>
324
        </EncryptedKey>
325
        <wwwroot>'.$mnet->wwwroot.'</wwwroot>
326
    </encryptedMessage>';
327
    return $message;
328
}
329
 
330
/**
331
 * Get your SSL keys from the database, or create them (if they don't exist yet)
332
 *
333
 * Get your SSL keys from the database, or (if they don't exist yet) call
334
 * mnet_generate_keypair to create them
335
 *
336
 * @param   string  $string     The text you want to sign
337
 * @return  string              The signature over that text
338
 */
339
function mnet_get_keypair() {
340
    global $CFG, $DB;
341
    static $keypair = null;
342
    if (!is_null($keypair)) return $keypair;
343
    if ($result = get_config('mnet', 'openssl')) {
344
        list($keypair['certificate'], $keypair['keypair_PEM']) = explode('@@@@@@@@', $result);
345
        return $keypair;
346
    } else {
347
        $keypair = mnet_generate_keypair();
348
        return $keypair;
349
    }
350
}
351
 
352
/**
353
 * Generate public/private keys and store in the config table
354
 *
355
 * Use the distinguished name provided to create a CSR, and then sign that CSR
356
 * with the same credentials. Store the keypair you create in the config table.
357
 * If a distinguished name is not provided, create one using the fullname of
358
 * 'the course with ID 1' as your organization name, and your hostname (as
359
 * detailed in $CFG->wwwroot).
360
 *
361
 * @param   array  $dn  The distinguished name of the server
362
 * @return  string      The signature over that text
363
 */
364
function mnet_generate_keypair($dn = null, $days=28) {
365
    global $CFG, $USER, $DB;
366
 
367
    // check if lifetime has been overriden
368
    if (!empty($CFG->mnetkeylifetime)) {
369
        $days = $CFG->mnetkeylifetime;
370
    }
371
 
372
    $host = strtolower($CFG->wwwroot);
373
    $host = preg_replace("~^http(s)?://~",'',$host);
374
    $break = strpos($host.'/' , '/');
375
    $host   = substr($host, 0, $break);
376
 
377
    $site = get_site();
378
    $organization = $site->fullname;
379
 
380
    $keypair = array();
381
 
382
    $country  = 'NZ';
383
    $province = 'Wellington';
384
    $locality = 'Wellington';
385
    $email    = !empty($CFG->noreplyaddress) ? $CFG->noreplyaddress : 'noreply@'.$_SERVER['HTTP_HOST'];
386
 
387
    if(!empty($USER->country)) {
388
        $country  = $USER->country;
389
    }
390
    if(!empty($USER->city)) {
391
        $province = $USER->city;
392
        $locality = $USER->city;
393
    }
394
    if(!empty($USER->email)) {
395
        $email    = $USER->email;
396
    }
397
 
398
    if (is_null($dn)) {
399
        $dn = array(
400
           "countryName" => $country,
401
           "stateOrProvinceName" => $province,
402
           "localityName" => $locality,
403
           "organizationName" => $organization,
404
           "organizationalUnitName" => 'Moodle',
405
           "commonName" => substr($CFG->wwwroot, 0, 64),
406
           "subjectAltName" => $CFG->wwwroot,
407
           "emailAddress" => $email
408
        );
409
    }
410
 
411
    $dnlimits = array(
412
           'countryName'            => 2,
413
           'stateOrProvinceName'    => 128,
414
           'localityName'           => 128,
415
           'organizationName'       => 64,
416
           'organizationalUnitName' => 64,
417
           'commonName'             => 64,
418
           'emailAddress'           => 128
419
    );
420
 
421
    foreach ($dnlimits as $key => $length) {
422
        $dn[$key] = core_text::substr($dn[$key], 0, $length);
423
    }
424
 
425
    // ensure we remove trailing slashes
426
    $dn["commonName"] = preg_replace(':/$:', '', $dn["commonName"]);
427
    if (!empty($CFG->opensslcnf)) { //allow specification of openssl.cnf especially for Windows installs
428
        $new_key = openssl_pkey_new(array("config" => $CFG->opensslcnf));
429
    } else {
430
        $new_key = openssl_pkey_new();
431
    }
432
    if ($new_key === false) {
433
        // can not generate keys - missing openssl.cnf??
434
        return null;
435
    }
436
    if (!empty($CFG->opensslcnf)) { //allow specification of openssl.cnf especially for Windows installs
437
        $csr_rsc = openssl_csr_new($dn, $new_key, array("config" => $CFG->opensslcnf));
438
        $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days, array("config" => $CFG->opensslcnf));
439
    } else {
440
        $csr_rsc = openssl_csr_new($dn, $new_key, array('private_key_bits',2048));
441
        $selfSignedCert = openssl_csr_sign($csr_rsc, null, $new_key, $days);
442
    }
443
    unset($csr_rsc); // Free up the resource
444
 
445
    // We export our self-signed certificate to a string.
446
    openssl_x509_export($selfSignedCert, $keypair['certificate']);
447
 
448
    // Export your public/private key pair as a PEM encoded string. You
449
    // can protect it with an optional passphrase if you wish.
450
    if (!empty($CFG->opensslcnf)) { //allow specification of openssl.cnf especially for Windows installs
451
        $export = openssl_pkey_export($new_key, $keypair['keypair_PEM'], null, array("config" => $CFG->opensslcnf));
452
    } else {
453
        $export = openssl_pkey_export($new_key, $keypair['keypair_PEM'] /* , $passphrase */);
454
    }
455
    unset($new_key); // Free up the resource
456
 
457
    return $keypair;
458
}
459
 
460
 
461
function mnet_update_sso_access_control($username, $mnet_host_id, $accessctrl) {
462
    global $DB;
463
 
464
    $mnethost = $DB->get_record('mnet_host', array('id'=>$mnet_host_id));
465
    if ($aclrecord = $DB->get_record('mnet_sso_access_control', array('username'=>$username, 'mnet_host_id'=>$mnet_host_id))) {
466
        // Update.
467
        $aclrecord->accessctrl = $accessctrl;
468
        $DB->update_record('mnet_sso_access_control', $aclrecord);
469
 
470
        // Trigger access control updated event.
471
        $params = array(
472
            'objectid' => $aclrecord->id,
473
            'context' => context_system::instance(),
474
            'other' => array(
475
                'username' => $username,
476
                'hostname' => $mnethost->name,
477
                'accessctrl' => $accessctrl
478
            )
479
        );
480
        $event = \core\event\mnet_access_control_updated::create($params);
481
        $event->add_record_snapshot('mnet_host', $mnethost);
482
        $event->trigger();
483
    } else {
484
        // Insert.
485
        $aclrecord = new stdClass();
486
        $aclrecord->username = $username;
487
        $aclrecord->accessctrl = $accessctrl;
488
        $aclrecord->mnet_host_id = $mnet_host_id;
489
        $aclrecord->id = $DB->insert_record('mnet_sso_access_control', $aclrecord);
490
 
491
        // Trigger access control created event.
492
        $params = array(
493
            'objectid' => $aclrecord->id,
494
            'context' => context_system::instance(),
495
            'other' => array(
496
                'username' => $username,
497
                'hostname' => $mnethost->name,
498
                'accessctrl' => $accessctrl
499
            )
500
        );
501
        $event = \core\event\mnet_access_control_created::create($params);
502
        $event->add_record_snapshot('mnet_host', $mnethost);
503
        $event->trigger();
504
    }
505
    return true;
506
}
507
 
508
function mnet_get_peer_host ($mnethostid) {
509
    global $DB;
510
    static $hosts;
511
    if (!isset($hosts[$mnethostid])) {
512
        $host = $DB->get_record('mnet_host', array('id' => $mnethostid));
513
        $hosts[$mnethostid] = $host;
514
    }
515
    return $hosts[$mnethostid];
516
}
517
 
518
/**
519
 * Inline function to modify a url string so that mnet users are requested to
520
 * log in at their mnet identity provider (if they are not already logged in)
521
 * before ultimately being directed to the original url.
522
 *
523
 * @param string $jumpurl the url which user should initially be directed to.
524
 *     This is a URL associated with a moodle networking peer when it
525
 *     is fulfiling a role as an identity provider (IDP). Different urls for
526
 *     different peers, the jumpurl is formed partly from the IDP's webroot, and
527
 *     partly from a predefined local path within that webwroot.
528
 *     The result of the user hitting this jump url is that they will be asked
529
 *     to login (at their identity provider (if they aren't already)), mnet
530
 *     will prepare the necessary authentication information, then redirect
531
 *     them back to somewhere at the content provider(CP) moodle (this moodle)
532
 * @param array $url array with 2 elements
533
 *     0 - context the url was taken from, possibly just the url, possibly href="url"
534
 *     1 - the destination url
535
 * @return string the url the remote user should be supplied with.
536
 */
537
function mnet_sso_apply_indirection ($jumpurl, $url) {
538
    global $USER, $CFG;
539
 
540
    $localpart='';
541
    $urlparts = parse_url($url[1]);
542
    if($urlparts) {
543
        if (isset($urlparts['path'])) {
544
            $path = $urlparts['path'];
545
            // if our wwwroot has a path component, need to strip that path from beginning of the
546
            // 'localpart' to make it relative to moodle's wwwroot
547
            $wwwrootpath = parse_url($CFG->wwwroot, PHP_URL_PATH);
548
            if (!empty($wwwrootpath) && strpos($path, $wwwrootpath) === 0) {
549
                $path = substr($path, strlen($wwwrootpath));
550
            }
551
            $localpart .= $path;
552
        }
553
        if (isset($urlparts['query'])) {
554
            $localpart .= '?'.$urlparts['query'];
555
        }
556
        if (isset($urlparts['fragment'])) {
557
            $localpart .= '#'.$urlparts['fragment'];
558
        }
559
    }
560
    $indirecturl = $jumpurl . urlencode($localpart);
561
    //If we matched on more than just a url (ie an html link), return the url to an href format
562
    if ($url[0] != $url[1]) {
563
        $indirecturl = 'href="'.$indirecturl.'"';
564
    }
565
    return $indirecturl;
566
}
567
 
568
function mnet_get_app_jumppath ($applicationid) {
569
    global $DB;
570
    static $appjumppaths;
571
    if (!isset($appjumppaths[$applicationid])) {
572
        $ssojumpurl = $DB->get_field('mnet_application', 'sso_jump_url', array('id' => $applicationid));
573
        $appjumppaths[$applicationid] = $ssojumpurl;
574
    }
575
    return $appjumppaths[$applicationid];
576
}
577
 
578
 
579
/**
580
 * Output debug information about mnet.  this will go to the <b>error_log</b>.
581
 *
582
 * @param mixed $debugdata this can be a string, or array or object.
583
 * @param int   $debuglevel optional , defaults to 1. bump up for very noisy debug info
584
 */
585
function mnet_debug($debugdata, $debuglevel=1) {
586
    global $CFG;
587
    $setlevel = get_config('', 'mnet_rpcdebug');
588
    if (empty($setlevel) || $setlevel < $debuglevel) {
589
        return;
590
    }
591
    if (is_object($debugdata)) {
592
        $debugdata = (array)$debugdata;
593
    }
594
    if (is_array($debugdata)) {
595
        mnet_debug('DUMPING ARRAY');
596
        foreach ($debugdata as $key => $value) {
597
            mnet_debug("$key: $value");
598
        }
599
        mnet_debug('END DUMPING ARRAY');
600
        return;
601
    }
602
    $prefix = 'MNET DEBUG ';
603
    if (defined('MNET_SERVER')) {
604
        $prefix .= " (server $CFG->wwwroot";
605
        if ($peer = get_mnet_remote_client() && !empty($peer->wwwroot)) {
606
            $prefix .= ", remote peer " . $peer->wwwroot;
607
        }
608
        $prefix .= ')';
609
    } else {
610
        $prefix .= " (client $CFG->wwwroot) ";
611
    }
612
    error_log("$prefix $debugdata");
613
}
614
 
615
/**
616
 * Return an array of information about all moodle's profile fields
617
 * which ones are optional, which ones are forced.
618
 * This is used as the basis of providing lists of profile fields to the administrator
619
 * to pick which fields to import/export over MNET
620
 *
621
 * @return array(forced => array, optional => array)
622
 */
623
function mnet_profile_field_options() {
624
    global $DB;
625
    static $info;
626
    if (!empty($info)) {
627
        return $info;
628
    }
629
 
630
    $excludes = array(
631
        'id',              // makes no sense
632
        'mnethostid',      // makes no sense
633
        'timecreated',     // will be set to relative to the host anyway
634
        'timemodified',    // will be set to relative to the host anyway
635
        'auth',            // going to be set to 'mnet'
636
        'deleted',         // we should never get deleted users sent over, but don't send this anyway
637
        'confirmed',       // unconfirmed users can't log in to their home site, all remote users considered confirmed
638
        'password',        // no password for mnet users
639
        'theme',           // handled separately
640
        'lastip',          // will be set to relative to the host anyway
641
    );
642
 
643
    // these are the ones that user_not_fully_set_up will complain about
644
    // and also special case ones
645
    $forced = array(
646
        'username',
647
        'email',
648
        'firstname',
649
        'lastname',
650
        'auth',
651
        'wwwroot',
652
        'session.gc_lifetime',
653
        '_mnet_userpicture_timemodified',
654
        '_mnet_userpicture_mimetype',
655
    );
656
 
657
    // these are the ones we used to send/receive (pre 2.0)
658
    $legacy = array(
659
        'username',
660
        'email',
661
        'auth',
662
        'deleted',
663
        'firstname',
664
        'lastname',
665
        'city',
666
        'country',
667
        'lang',
668
        'timezone',
669
        'description',
670
        'mailformat',
671
        'maildigest',
672
        'maildisplay',
673
        'htmleditor',
674
        'wwwroot',
675
        'picture',
676
    );
677
 
678
    // get a random user record from the database to pull the fields off
679
    $randomuser = $DB->get_record('user', array(), '*', IGNORE_MULTIPLE);
680
    foreach ($randomuser as $key => $discard) {
681
        if (in_array($key, $excludes) || in_array($key, $forced)) {
682
            continue;
683
        }
684
        $fields[$key] = $key;
685
    }
686
    $info = array(
687
        'forced'   => $forced,
688
        'optional' => $fields,
689
        'legacy'   => $legacy,
690
    );
691
    return $info;
692
}
693
 
694
 
695
/**
696
 * Returns information about MNet peers
697
 *
698
 * @param bool $withdeleted should the deleted peers be returned too
699
 * @return array
700
 */
701
function mnet_get_hosts($withdeleted = false) {
702
    global $CFG, $DB;
703
 
704
    $sql = "SELECT h.id, h.deleted, h.wwwroot, h.ip_address, h.name, h.public_key, h.public_key_expires,
705
                   h.transport, h.portno, h.last_connect_time, h.last_log_id, h.applicationid,
706
                   a.name as app_name, a.display_name as app_display_name, a.xmlrpc_server_url
707
              FROM {mnet_host} h
708
              JOIN {mnet_application} a ON h.applicationid = a.id
709
             WHERE h.id <> ?";
710
 
711
    if (!$withdeleted) {
712
        $sql .= "  AND h.deleted = 0";
713
    }
714
 
715
    $sql .= " ORDER BY h.deleted, h.name, h.id";
716
 
717
    return $DB->get_records_sql($sql, array($CFG->mnet_localhost_id));
718
}
719
 
720
 
721
/**
722
 * return an array information about services enabled for the given peer.
723
 * in two modes, fulldata or very basic data.
724
 *
725
 * @param mnet_peer $mnet_peer the peer to get information abut
726
 * @param boolean   $fulldata whether to just return which services are published/subscribed, or more information (defaults to full)
727
 *
728
 * @return array  If $fulldata is false, an array is returned like:
729
 *                publish => array(
730
 *                    serviceid => boolean,
731
 *                    serviceid => boolean,
732
 *                ),
733
 *                subscribe => array(
734
 *                    serviceid => boolean,
735
 *                    serviceid => boolean,
736
 *                )
737
 *                If $fulldata is true, an array is returned like:
738
 *                servicename => array(
739
 *                   apiversion => array(
740
 *                        name           => string
741
 *                        offer          => boolean
742
 *                        apiversion     => int
743
 *                        plugintype     => string
744
 *                        pluginname     => string
745
 *                        hostsubscribes => boolean
746
 *                        hostpublishes  => boolean
747
 *                   ),
748
 *               )
749
 */
750
function mnet_get_service_info(mnet_peer $mnet_peer, $fulldata=true) {
751
    global $CFG, $DB;
752
 
753
    $requestkey = (!empty($fulldata) ? 'fulldata' : 'mydata');
754
 
755
    static $cache = array();
756
    if (array_key_exists($mnet_peer->id, $cache)) {
757
        return $cache[$mnet_peer->id][$requestkey];
758
    }
759
 
760
    $id_list = $mnet_peer->id;
761
    if (!empty($CFG->mnet_all_hosts_id)) {
762
        $id_list .= ', '.$CFG->mnet_all_hosts_id;
763
    }
764
 
765
    $concat = $DB->sql_concat('COALESCE(h2s.id,0) ', ' \'-\' ', ' svc.id', '\'-\'', 'r.plugintype', '\'-\'', 'r.pluginname');
766
 
767
    $query = "
768
        SELECT DISTINCT
769
            $concat as id,
770
            svc.id as serviceid,
771
            svc.name,
772
            svc.offer,
773
            svc.apiversion,
774
            r.plugintype,
775
            r.pluginname,
776
            h2s.hostid,
777
            h2s.publish,
778
            h2s.subscribe
779
        FROM
780
            {mnet_service2rpc} s2r,
781
            {mnet_rpc} r,
782
            {mnet_service} svc
783
        LEFT JOIN
784
            {mnet_host2service} h2s
785
        ON
786
            h2s.hostid in ($id_list) AND
787
            h2s.serviceid = svc.id
788
        WHERE
789
            svc.offer = '1' AND
790
            s2r.serviceid = svc.id AND
791
            s2r.rpcid = r.id
792
        ORDER BY
793
            svc.name ASC";
794
 
795
    $resultset = $DB->get_records_sql($query);
796
 
797
    if (is_array($resultset)) {
798
        $resultset = array_values($resultset);
799
    } else {
800
        $resultset = array();
801
    }
802
 
803
    require_once $CFG->dirroot.'/mnet/xmlrpc/client.php';
804
 
805
    $remoteservices = array();
806
    if ($mnet_peer->id != $CFG->mnet_all_hosts_id) {
807
        // Create a new request object
808
        $mnet_request = new mnet_xmlrpc_client();
809
 
810
        // Tell it the path to the method that we want to execute
811
        $mnet_request->set_method('system/listServices');
812
        $mnet_request->send($mnet_peer);
813
        if (is_array($mnet_request->response)) {
814
            foreach($mnet_request->response as $service) {
815
                $remoteservices[$service['name']][$service['apiversion']] = $service;
816
            }
817
        }
818
    }
819
 
820
    $myservices = array();
821
    $mydata = array();
822
    foreach($resultset as $result) {
823
        $result->hostpublishes  = false;
824
        $result->hostsubscribes = false;
825
        if (isset($remoteservices[$result->name][$result->apiversion])) {
826
            if ($remoteservices[$result->name][$result->apiversion]['publish'] == 1) {
827
                $result->hostpublishes  = true;
828
            }
829
            if ($remoteservices[$result->name][$result->apiversion]['subscribe'] == 1) {
830
                $result->hostsubscribes  = true;
831
            }
832
        }
833
 
834
        if (empty($myservices[$result->name][$result->apiversion])) {
835
            $myservices[$result->name][$result->apiversion] = array('serviceid' => $result->serviceid,
836
                                                                    'name' => $result->name,
837
                                                                    'offer' => $result->offer,
838
                                                                    'apiversion' => $result->apiversion,
839
                                                                    'plugintype' => $result->plugintype,
840
                                                                    'pluginname' => $result->pluginname,
841
                                                                    'hostsubscribes' => $result->hostsubscribes,
842
                                                                    'hostpublishes' => $result->hostpublishes
843
                                                                    );
844
        }
845
 
846
        // allhosts_publish allows us to tell the admin that even though he
847
        // is disabling a service, it's still available to the host because
848
        // he's also publishing it to 'all hosts'
849
        if ($result->hostid == $CFG->mnet_all_hosts_id && $CFG->mnet_all_hosts_id != $mnet_peer->id) {
850
            $myservices[$result->name][$result->apiversion]['allhosts_publish'] = $result->publish;
851
            $myservices[$result->name][$result->apiversion]['allhosts_subscribe'] = $result->subscribe;
852
        } elseif (!empty($result->hostid)) {
853
            $myservices[$result->name][$result->apiversion]['I_publish'] = $result->publish;
854
            $myservices[$result->name][$result->apiversion]['I_subscribe'] = $result->subscribe;
855
        }
856
        $mydata['publish'][$result->serviceid] = $result->publish;
857
        $mydata['subscribe'][$result->serviceid] = $result->subscribe;
858
 
859
    }
860
 
861
    $cache[$mnet_peer->id]['fulldata'] = $myservices;
862
    $cache[$mnet_peer->id]['mydata'] = $mydata;
863
 
864
    return $cache[$mnet_peer->id][$requestkey];
865
}
866
 
867
/**
868
 * return an array of the profile fields to send
869
 * with user information to the given mnet host.
870
 *
871
 * @param mnet_peer $peer the peer to send the information to
872
 *
873
 * @return array (like 'username', 'firstname', etc)
874
 */
875
function mnet_fields_to_send(mnet_peer $peer) {
876
    return _mnet_field_helper($peer, 'export');
877
}
878
 
879
/**
880
 * return an array of the profile fields to import
881
 * from the given host, when creating/updating user accounts
882
 *
883
 * @param mnet_peer $peer the peer we're getting the information from
884
 *
885
 * @return array (like 'username', 'firstname', etc)
886
 */
887
function mnet_fields_to_import(mnet_peer $peer) {
888
    return _mnet_field_helper($peer, 'import');
889
}
890
 
891
/**
892
 * helper for {@see mnet_fields_to_import} and {@mnet_fields_to_send}
893
 *
894
 * @access private
895
 *
896
 * @param mnet_peer $peer the peer object
897
 * @param string    $key 'import' or 'export'
898
 *
899
 * @return array (like 'username', 'firstname', etc)
900
 */
901
function _mnet_field_helper(mnet_peer $peer, $key) {
902
    $tmp = mnet_profile_field_options();
903
    $defaults = explode(',', get_config('moodle', 'mnetprofile' . $key . 'fields'));
904
    if ('1' === get_config('mnet', 'host' . $peer->id . $key . 'default')) {
905
        return array_merge($tmp['forced'], $defaults);
906
    }
907
    $hostsettings = get_config('mnet', 'host' . $peer->id . $key . 'fields');
908
    if (false === $hostsettings) {
909
        return array_merge($tmp['forced'], $defaults);
910
    }
911
    return array_merge($tmp['forced'], explode(',', $hostsettings));
912
}
913
 
914
 
915
/**
916
 * given a user object (or array) and a list of allowed fields,
917
 * strip out all the fields that should not be included.
918
 * This can be used both for outgoing data and incoming data.
919
 *
920
 * @param mixed $user array or object representing a database record
921
 * @param array $fields an array of allowed fields (usually from mnet_fields_to_{send,import}
922
 *
923
 * @return mixed array or object, depending what type of $user object was passed (datatype is respected)
924
 */
925
function mnet_strip_user($user, $fields) {
926
    if (is_object($user)) {
927
        $user = (array)$user;
928
        $wasobject = true; // so we can cast back before we return
929
    }
930
 
931
    foreach ($user as $key => $value) {
932
        if (!in_array($key, $fields)) {
933
            unset($user[$key]);
934
        }
935
    }
936
    if (!empty($wasobject)) {
937
        $user = (object)$user;
938
    }
939
    return $user;
940
}