qtype database definitions: MDL-16978 Lots of foreign key definitions in install...
[moodle.git] / mnet / xmlrpc / server.php
CommitLineData
71558f85 1<?php
2/**
3 * An XML-RPC server
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
11// Make certain that config.php doesn't display any errors, and that it doesn't
12// override our do-not-display-errors setting:
13ini_set('display_errors',0);
14require_once(dirname(dirname(dirname(__FILE__))) . '/config.php');
15ini_set('display_errors',0);
16
17// Include MNET stuff:
18require_once $CFG->dirroot.'/mnet/lib.php';
19require_once $CFG->dirroot.'/mnet/remote_client.php';
20
600be062 21if ($CFG->mnet_dispatcher_mode === 'off') {
22 print_error('mnetdisabled', 'mnet');
23}
24
71558f85 25// Content type for output is not html:
1008dad6 26header('Content-type: text/xml; charset=utf-8');
71558f85 27
25202581 28// PHP 5.2.2: $HTTP_RAW_POST_DATA not populated bug:
29// http://bugs.php.net/bug.php?id=41293
30if (empty($HTTP_RAW_POST_DATA)) {
31 $HTTP_RAW_POST_DATA = file_get_contents('php://input');
32}
33
71558f85 34if (!empty($CFG->mnet_rpcdebug)) {
35 trigger_error("HTTP_RAW_POST_DATA");
36 trigger_error($HTTP_RAW_POST_DATA);
37}
38
8d60e942 39if (!isset($_SERVER)) {
40 exit(mnet_server_fault(712, "phperror"));
41}
42
43
71558f85 44// New global variable which ONLY gets set in this server page, so you know that
45// if you've been called by a remote Moodle, this should be set:
46$MNET_REMOTE_CLIENT = new mnet_remote_client();
47
8d60e942 48$plaintextmessage = mnet_server_strip_encryption($HTTP_RAW_POST_DATA);
49$xmlrpcrequest = mnet_server_strip_signature($plaintextmessage);
50
334e66c1 51if($MNET_REMOTE_CLIENT->pushkey == true) {
8d60e942 52 // The peer used one of our older public keys, we will return a
53 // signed/encrypted error message containing our new public key
54 // Sign message with our old key, and encrypt to the peer's private key.
334e66c1 55 exit(mnet_server_fault_xml(7025, $MNET->public_key, $MNET_REMOTE_CLIENT->useprivatekey));
8d60e942 56}
57// Have a peek at what the request would be if we were to process it
58$params = xmlrpc_decode_request($xmlrpcrequest, $method);
59
60// One of three conditions need to be met before we continue processing this request:
61// 1. Request is properly encrypted and signed
62// 2. Request is for a keyswap (we don't mind enencrypted or unsigned requests for a public key)
63// 3. Request is properly signed and we're happy with it being unencrypted
64if ((($MNET_REMOTE_CLIENT->request_was_encrypted == true) && ($MNET_REMOTE_CLIENT->signatureok == true))
65 || (($method == 'system.keyswap') || ($method == 'system/keyswap'))
66 || (($MNET_REMOTE_CLIENT->signatureok == true) && ($MNET_REMOTE_CLIENT->plaintext_is_ok() == true))) {
67 $response = mnet_server_dispatch($xmlrpcrequest);
68} else {
69 if (($MNET_REMOTE_CLIENT->request_was_encrypted == false) && ($MNET_REMOTE_CLIENT->plaintext_is_ok() == false)) {
70 exit(mnet_server_fault(7021, 'forbidden-transport'));
71 }
72
73 if ($MNET_REMOTE_CLIENT->request_was_signed == false) {
74 // Request was not signed
75 exit(mnet_server_fault(711, 'verifysignature-error'));
76 }
77
78 if ($MNET_REMOTE_CLIENT->signatureok == false) {
79 // We were unable to verify the signature
80 exit(mnet_server_fault(710, 'verifysignature-invalid'));
81 }
82}
83
71558f85 84
85if (!empty($CFG->mnet_rpcdebug)) {
86 trigger_error("XMLRPC Payload");
5f6b28fa 87 trigger_error(print_r($xmlrpcrequest,1));
71558f85 88}
89
71558f85 90/**
71558f85 91 * -----XML-Envelope---------------------------------
92 * | |
93 * | Encrypted-Symmetric-key---------------- |
94 * | |_____________________________________| |
95 * | |
96 * | Encrypted data------------------------- |
97 * | | | |
98 * | | -XML-Envelope------------------ | |
99 * | | | | | |
100 * | | | --Signature------------- | | |
101 * | | | |______________________| | | |
102 * | | | | | |
103 * | | | --Signed-Payload-------- | | |
104 * | | | | | | | |
105 * | | | | XML-RPC Request | | | |
106 * | | | |______________________| | | |
107 * | | | | | |
108 * | | |_____________________________| | |
109 * | |_____________________________________| |
110 * | |
111 * |________________________________________________|
112 *
71558f85 113 */
5f6b28fa 114
8d60e942 115/* Strip encryption envelope (if present) and decrypt data
5f6b28fa 116 *
117 * @param string $HTTP_RAW_POST_DATA The XML that the client sent
8d60e942 118 * @return string XML with any encryption envolope removed
5f6b28fa 119 */
8d60e942 120function mnet_server_strip_encryption($HTTP_RAW_POST_DATA) {
71558f85 121 global $MNET, $MNET_REMOTE_CLIENT;
2a75520f 122 $crypt_parser = new mnet_encxml_parser();
123 $crypt_parser->parse($HTTP_RAW_POST_DATA);
71558f85 124
8d60e942 125 if (!$crypt_parser->payload_encrypted) {
126 return $HTTP_RAW_POST_DATA;
127 }
128
2a75520f 129 // Make sure we know who we're talking to
130 $host_record_exists = $MNET_REMOTE_CLIENT->set_wwwroot($crypt_parser->remote_wwwroot);
9dd0e611 131
2a75520f 132 if (false == $host_record_exists) {
133 exit(mnet_server_fault(7020, 'wrong-wwwroot', $crypt_parser->remote_wwwroot));
134 }
9dd0e611 135
5f6b28fa 136 // This key is symmetric, and is itself encrypted. Can be decrypted using our private key
137 $key = array_pop($crypt_parser->cipher);
138 // This data is symmetrically encrypted, can be decrypted using the above key
139 $data = array_pop($crypt_parser->cipher);
140
141 $crypt_parser->free_resource();
142 $payload = ''; // Initialize payload var
143
144 // &$payload
145 $isOpen = openssl_open(base64_decode($data), $payload, base64_decode($key), $MNET->get_private_key());
8d60e942 146 if ($isOpen) {
147 $MNET_REMOTE_CLIENT->was_encrypted();
148 return $payload;
149 }
5f6b28fa 150
8d60e942 151 // Decryption failed... let's try our archived keys
152 $openssl_history = get_config('mnet', 'openssl_history');
153 if(empty($openssl_history)) {
154 $openssl_history = array();
155 set_config('openssl_history', serialize($openssl_history), 'mnet');
156 } else {
157 $openssl_history = unserialize($openssl_history);
158 }
159 foreach($openssl_history as $keyset) {
160 $keyresource = openssl_pkey_get_private($keyset['keypair_PEM']);
161 $isOpen = openssl_open(base64_decode($data), $payload, base64_decode($key), $keyresource);
162 if ($isOpen) {
163 // It's an older code, sir, but it checks out
164
165 $MNET_REMOTE_CLIENT->was_encrypted();
166 $MNET_REMOTE_CLIENT->encrypted_to($keyresource);
167 $MNET_REMOTE_CLIENT->set_pushkey();
168 return $payload;
71558f85 169 }
5f6b28fa 170 }
71558f85 171
8d60e942 172 //If after all that we still couldn't decrypt the message, error out.
173 exit(mnet_server_fault(7023, 'encryption-invalid'));
5f6b28fa 174}
71558f85 175
8d60e942 176/* Strip signature envelope (if present), try to verify any signature using our record of remote peer's public key.
5f6b28fa 177 *
178 * @param string $plaintextmessage XML envelope containing XMLRPC request and signature
179 * @return string XMLRPC request
180 */
8d60e942 181function mnet_server_strip_signature($plaintextmessage) {
5f6b28fa 182 global $MNET, $MNET_REMOTE_CLIENT;
183 $sig_parser = new mnet_encxml_parser();
184 $sig_parser->parse($plaintextmessage);
71558f85 185
8d60e942 186 if ($sig_parser->signature == '') {
187 return $plaintextmessage;
2a75520f 188 }
189
8d60e942 190 // Record that the request was signed in some way
191 $MNET_REMOTE_CLIENT->was_signed();
192
193 // Load any information we have about this mnet peer
194 $MNET_REMOTE_CLIENT->set_wwwroot($crypt_parser->remote_wwwroot);
195
2a75520f 196 $payload = base64_decode($sig_parser->data_object);
5f6b28fa 197 $signature = base64_decode($sig_parser->signature);
8d60e942 198 $certificate = $MNET_REMOTE_CLIENT->public_key;
199
c8a6dfee 200 // If we don't have any certificate for the host, don't try to check the signature
8d60e942 201 // Just return the parsed request
202 if ($certificate == false) {
203 return $payload;
204 }
2a75520f 205
206 // Does the signature match the data and the public cert?
5f6b28fa 207 $signature_verified = openssl_verify($payload, $signature, $certificate);
454a6e7c 208 if ($signature_verified == 0) {
209 // $signature was not generated for $payload using $certificate
210 // Get the key the remote peer is currently publishing:
2a75520f 211 $currkey = mnet_get_public_key($MNET_REMOTE_CLIENT->wwwroot, $MNET_REMOTE_CLIENT->application);
454a6e7c 212 // If the key the remote peer is currently publishing is different to $certificate
2a75520f 213 if($currkey != $certificate) {
8d60e942 214 // Try and get the server's new key through trusted means
215 $MNET_REMOTE_CLIENT->refresh_key();
988b0b22 216 // If we did manage to re-key, try to verify the signature again using the new public key.
217 $certificate = $MNET_REMOTE_CLIENT->public_key;
250f84d6 218 $signature_verified = openssl_verify($payload, $signature, $certificate);
71558f85 219 }
454a6e7c 220 }
221
222 if ($signature_verified == 1) {
8d60e942 223 $MNET_REMOTE_CLIENT->signature_verified();
454a6e7c 224 $MNET_REMOTE_CLIENT->touch();
71558f85 225 }
2a75520f 226
227 $sig_parser->free_resource();
228
229 return $payload;
71558f85 230}
231
232/**
151a9872 233 * Return the proper XML-RPC content to report an error in the local language.
71558f85 234 *
235 * @param int $code The ID code of the error message
151a9872 236 * @param string $text The array-key of the error message in the lang file
ea676d6e 237 * or the full string (will be detected by the function
151a9872 238 * @param string $param The $a param for the error message in the lang file
71558f85 239 * @return string $text The text of the error message
240 */
241function mnet_server_fault($code, $text, $param = null) {
151a9872 242 global $MNET_REMOTE_CLIENT;
71558f85 243 if (!is_numeric($code)) {
244 $code = 0;
245 }
246 $code = intval($code);
247
ea676d6e 248 $string = get_string($text, 'mnet', $param);
249 if (strpos($string, '[[') === 0) {
250 $string = $text;
251 }
252
253 return mnet_server_fault_xml($code, $string);
151a9872 254}
71558f85 255
151a9872 256/**
257 * Return the proper XML-RPC content to report an error.
258 *
09f0abb2 259 * @param int $code The ID code of the error message
260 * @param string $text The error message
261 * @param resource $privatekey The private key that should be used to sign the response
262 * @return string $text The XML text of the error message
151a9872 263 */
09f0abb2 264function mnet_server_fault_xml($code, $text, $privatekey = null) {
573f8b02 265 global $MNET_REMOTE_CLIENT, $CFG;
71558f85 266 // Replace illegal XML chars - is this already in a lib somewhere?
267 $text = str_replace(array('<','>','&','"',"'"), array('&lt;','&gt;','&amp;','&quot;','&apos;'), $text);
268
269 $return = mnet_server_prepare_response('<?xml version="1.0"?>
270<methodResponse>
271 <fault>
272 <value>
273 <struct>
274 <member>
275 <name>faultCode</name>
276 <value><int>'.$code.'</int></value>
277 </member>
278 <member>
279 <name>faultString</name>
280 <value><string>'.$text.'</string></value>
25202581 281 </member>
282 </struct>
283 </value>
284 </fault>
09f0abb2 285</methodResponse>', $privatekey);
573f8b02 286
287 if (!empty($CFG->mnet_rpcdebug)) {
3d706b49 288 trigger_error("XMLRPC Error Response $code: $text");
573f8b02 289 trigger_error(print_r($return,1));
290 }
291
71558f85 292 return $return;
293}
294
295/**
296 * Dummy function for the XML-RPC dispatcher - use to call a method on an object
297 * or to call a function
298 *
299 * Translate XML-RPC's strange function call syntax into a more straightforward
300 * PHP-friendly alternative. This dummy function will be called by the
301 * dispatcher, and can be used to call a method on an object, or just a function
302 *
303 * The methodName argument (eg. mnet/testlib/mnet_concatenate_strings)
304 * is ignored.
305 *
306 * @param string $methodname We discard this - see 'functionname'
307 * @param array $argsarray Each element is an argument to the real
308 * function
309 * @param string $functionname The name of the PHP function you want to call
310 * @return mixed The return value will be that of the real
311 * function, whateber it may be.
312 */
313function mnet_server_dummy_method($methodname, $argsarray, $functionname) {
314 global $MNET_REMOTE_CLIENT;
315
b91b274b 316 if (is_object($MNET_REMOTE_CLIENT->object_to_call)) {
71558f85 317 return @call_user_method_array($functionname, $MNET_REMOTE_CLIENT->object_to_call, $argsarray);
b91b274b 318 } else if (!empty($MNET_REMOTE_CLIENT->static_location)) {
319 return @call_user_func_array(array($MNET_REMOTE_CLIENT->static_location, $functionname), $argsarray);
320 } else {
321 return @call_user_func_array($functionname, $argsarray);
71558f85 322 }
323}
324
325/**
326 * Package a response in any required envelope, and return it to the client
327 *
09f0abb2 328 * @param string $response The XMLRPC response string
329 * @param resource $privatekey The private key to sign the response with
330 * @return string The encoded response string
71558f85 331 */
09f0abb2 332function mnet_server_prepare_response($response, $privatekey = null) {
71558f85 333 global $MNET_REMOTE_CLIENT;
334
335 if ($MNET_REMOTE_CLIENT->request_was_signed) {
09f0abb2 336 $response = mnet_sign_message($response, $privatekey);
71558f85 337 }
338
339 if ($MNET_REMOTE_CLIENT->request_was_encrypted) {
340 $response = mnet_encrypt_message($response, $MNET_REMOTE_CLIENT->public_key);
341 }
342
343 return $response;
344}
345
346/**
347 * If security checks are passed, dispatch the request to the function/method
348 *
349 * The config variable 'mnet_dispatcher_mode' can be:
350 * strict: Only execute functions that are in specific files
351 * off: The default - don't execute anything
352 *
353 * @param string $payload The XML-RPC request
354 * @return No return val - just echo the response
355 */
356function mnet_server_dispatch($payload) {
357 global $CFG, $MNET_REMOTE_CLIENT;
358 // xmlrpc_decode_request returns an array of parameters, and the $method
359 // variable (which is passed by reference) is instantiated with the value from
360 // the methodName tag in the xml payload
361 // xmlrpc_decode_request($xml, &$method)
362 $params = xmlrpc_decode_request($payload, $method);
363
b26a847b 364 // $method is something like: "mod/forum/lib.php/forum_add_instance"
71558f85 365 // $params is an array of parameters. A parameter might itself be an array.
366
367 // Whitelist characters that are permitted in a method name
368 // The method name must not begin with a / - avoid absolute paths
369 // A dot character . is only allowed in the filename, i.e. something.php
370 if (0 == preg_match("@^[A-Za-z0-9]+/[A-Za-z0-9/_-]+(\.php/)?[A-Za-z0-9_-]+$@",$method)) {
371 exit(mnet_server_fault(713, 'nosuchfunction'));
372 }
373
4fc66605 374 if(preg_match("/^system\./", $method)) {
b26a847b 375 $callstack = explode('.', $method);
376 } else {
377 $callstack = explode('/', $method);
378 // callstack will look like array('mod', 'forum', 'lib.php', 'forum_add_instance');
379 }
71558f85 380
381 /**
382 * What has the site administrator chosen as his dispatcher setting?
383 * strict: Only execute functions that are in specific files
384 * off: The default - don't execute anything
385 */
386 ////////////////////////////////////// OFF
387 if (!isset($CFG->mnet_dispatcher_mode) ) {
388 set_config('mnet_dispatcher_mode', 'off');
389 exit(mnet_server_fault(704, 'nosuchservice'));
390 } elseif ('off' == $CFG->mnet_dispatcher_mode) {
391 exit(mnet_server_fault(704, 'nosuchservice'));
392
393 ////////////////////////////////////// SYSTEM METHODS
394 } elseif ($callstack[0] == 'system') {
395 $functionname = $callstack[1];
396 $xmlrpcserver = xmlrpc_server_create();
397
398 // I'm adding the canonical xmlrpc references here, however we've
399 // already forbidden that the period (.) should be allowed in the call
400 // stack, so if someone tries to access our XMLRPC in the normal way,
401 // they'll already have received a RPC server fault message.
402
403 // Maybe we should allow an easement so that regular XMLRPC clients can
404 // call our system methods, and find out what we have to offer?
405
406 xmlrpc_server_register_method($xmlrpcserver, 'system.listMethods', 'mnet_system');
407 xmlrpc_server_register_method($xmlrpcserver, 'system/listMethods', 'mnet_system');
408
409 xmlrpc_server_register_method($xmlrpcserver, 'system.methodSignature', 'mnet_system');
410 xmlrpc_server_register_method($xmlrpcserver, 'system/methodSignature', 'mnet_system');
411
412 xmlrpc_server_register_method($xmlrpcserver, 'system.methodHelp', 'mnet_system');
413 xmlrpc_server_register_method($xmlrpcserver, 'system/methodHelp', 'mnet_system');
414
415 xmlrpc_server_register_method($xmlrpcserver, 'system.listServices', 'mnet_system');
416 xmlrpc_server_register_method($xmlrpcserver, 'system/listServices', 'mnet_system');
417
d3dfe9ae 418 xmlrpc_server_register_method($xmlrpcserver, 'system.listFiles', 'mnet_system');
419 xmlrpc_server_register_method($xmlrpcserver, 'system/listFiles', 'mnet_system');
420
421 xmlrpc_server_register_method($xmlrpcserver, 'system.retrieveFile', 'mnet_system');
422 xmlrpc_server_register_method($xmlrpcserver, 'system/retrieveFile', 'mnet_system');
423
71558f85 424 xmlrpc_server_register_method($xmlrpcserver, 'system.keyswap', 'mnet_keyswap');
425 xmlrpc_server_register_method($xmlrpcserver, 'system/keyswap', 'mnet_keyswap');
426
427 if ($method == 'system.listMethods' ||
428 $method == 'system/listMethods' ||
429 $method == 'system.methodSignature' ||
430 $method == 'system/methodSignature' ||
431 $method == 'system.methodHelp' ||
432 $method == 'system/methodHelp' ||
d3dfe9ae 433 $method == 'system.listServices' ||
434 $method == 'system/listServices' ||
435 $method == 'system.listFiles' ||
436 $method == 'system/listFiles' ||
437 $method == 'system.retrieveFile' ||
438 $method == 'system/retrieveFile' ||
439 $method == 'system.keyswap' ||
71558f85 440 $method == 'system/keyswap') {
441
1008dad6 442 $response = xmlrpc_server_call_method($xmlrpcserver, $payload, $MNET_REMOTE_CLIENT, array("encoding" => "utf-8"));
71558f85 443 $response = mnet_server_prepare_response($response);
444 } else {
445 exit(mnet_server_fault(7018, 'nosuchfunction'));
446 }
447
448 xmlrpc_server_destroy($xmlrpcserver);
449 echo $response;
450 ////////////////////////////////////// STRICT AUTH
451 } elseif ($callstack[0] == 'auth') {
452
453 // Break out the callstack into its elements
454 list($base, $plugin, $filename, $methodname) = $callstack;
455
456 // We refuse to include anything that is not auth.php
457 if ($filename == 'auth.php' && is_enabled_auth($plugin)) {
458 $authclass = 'auth_plugin_'.$plugin;
459 $includefile = '/auth/'.$plugin.'/auth.php';
460 $response = mnet_server_invoke_method($includefile, $methodname, $method, $payload, $authclass);
461 $response = mnet_server_prepare_response($response);
462 echo $response;
463 } else {
464 // Generate error response - unable to locate function
465 exit(mnet_server_fault(702, 'nosuchfunction'));
466 }
467
468 ////////////////////////////////////// STRICT ENROL
469 } elseif ($callstack[0] == 'enrol') {
470
471 // Break out the callstack into its elements
472 list($base, $plugin, $filename, $methodname) = $callstack;
473
474 if ($filename == 'enrol.php' && is_enabled_enrol($plugin)) {
475 $enrolclass = 'enrolment_plugin_'.$plugin;
476 $includefile = '/enrol/'.$plugin.'/enrol.php';
477 $response = mnet_server_invoke_method($includefile, $methodname, $method, $payload, $enrolclass);
478 $response = mnet_server_prepare_response($response);
479 echo $response;
480 } else {
481 // Generate error response - unable to locate function
482 exit(mnet_server_fault(703, 'nosuchfunction'));
483 }
484
b91b274b 485 } else if ($callstack[0] == 'portfolio') {
486 // Break out the callstack into its elements
487 list($base, $plugin, $filename, $methodname) = $callstack;
488
489 if ($filename == 'lib.php') {
490 $pluginclass = 'portfolio_plugin_' . $plugin;
491 $includefile = '/portfolio/type/'.$plugin.'/lib.php';
492 $response = mnet_server_invoke_method($includefile, $methodname, $method, $payload, $pluginclass);
493 $response = mnet_server_prepare_response($response);
494 echo $response;
495 } else {
496 // Generate error response - unable to locate function
497 exit(mnet_server_fault(7012, 'nosuchfunction'));
498 }
499
71558f85 500 ////////////////////////////////////// STRICT MOD/*
68bcd355 501 } elseif ($callstack[0] == 'mod' || 'dangerous' == $CFG->mnet_dispatcher_mode) {
71558f85 502 list($base, $module, $filename, $functionname) = $callstack;
503
504 ////////////////////////////////////// STRICT MOD/*
505 if ($base == 'mod' && $filename == 'rpclib.php') {
506 $includefile = '/mod/'.$module.'/rpclib.php';
507 $response = mnet_server_invoke_method($includefile, $functionname, $method, $payload);
508 $response = mnet_server_prepare_response($response);
509 echo $response;
510
68bcd355 511 ////////////////////////////////////// DANGEROUS
512 } elseif ('dangerous' == $CFG->mnet_dispatcher_mode && $MNET_REMOTE_CLIENT->plaintext_is_ok()) {
71558f85 513
514 $functionname = array_pop($callstack);
71558f85 515
516 if ($MNET_REMOTE_CLIENT->plaintext_is_ok()) {
517
1bef950e 518 $filename = clean_param(implode('/',$callstack), PARAM_PATH);
519 if (0 == preg_match("/php$/", $filename)) {
520 // Filename doesn't end in 'php'; possible attack?
521 // Generate error response - unable to locate function
522 exit(mnet_server_fault(7012, 'nosuchfunction'));
523 }
524
71558f85 525 // The call stack holds the path to any include file
1bef950e 526 $includefile = $CFG->dirroot.'/'.$filename;
71558f85 527
b26a847b 528 $response = mnet_server_invoke_method($includefile, $functionname, $method, $payload);
71558f85 529 echo $response;
530 }
531
532 } else {
533 // Generate error response - unable to locate function
534 exit(mnet_server_fault(7012, 'nosuchfunction'));
535 }
536
537 } else {
538 // Generate error response - unable to locate function
539 exit(mnet_server_fault(7012, 'nosuchfunction'));
540 }
541}
542
543/**
544 * Execute the system functions - mostly for introspection
545 *
546 * @param string $method XMLRPC method name, e.g. system.listMethods
547 * @param array $params Array of parameters from the XMLRPC request
548 * @param string $hostinfo Hostinfo object from the mnet_host table
549 * @return mixed Response data - any kind of PHP variable
550 */
551function mnet_system($method, $params, $hostinfo) {
cc38ff5d 552 global $CFG, $DB;
71558f85 553
554 if (empty($hostinfo)) return array();
555
556 $id_list = $hostinfo->id;
557 if (!empty($CFG->mnet_all_hosts_id)) {
558 $id_list .= ', '.$CFG->mnet_all_hosts_id;
559 }
560
561 if ('system.listMethods' == $method || 'system/listMethods' == $method) {
562 if (count($params) == 0) {
563 $query = '
564 SELECT DISTINCT
565 rpc.function_name,
566 rpc.xmlrpc_path,
567 rpc.enabled,
568 rpc.help,
569 rpc.profile
570 FROM
cc38ff5d 571 {mnet_host2service} h2s,
572 {mnet_service2rpc} s2r,
573 {mnet_rpc} rpc
71558f85 574 WHERE
575 s2r.rpcid = rpc.id AND
576 h2s.serviceid = s2r.serviceid AND
f633d85d 577 h2s.hostid in ('.$id_list .') AND
578 h2s.publish =\'1\'
71558f85 579 ORDER BY
580 rpc.xmlrpc_path ASC';
cc38ff5d 581 $params = array();
71558f85 582
583 } else {
584 $query = '
585 SELECT DISTINCT
586 rpc.function_name,
587 rpc.xmlrpc_path,
588 rpc.enabled,
589 rpc.help,
590 rpc.profile
591 FROM
cc38ff5d 592 {mnet_host2service} h2s,
593 {mnet_service2rpc} s2r,
594 {mnet_service} svc,
595 {mnet_rpc} rpc
71558f85 596 WHERE
597 s2r.rpcid = rpc.id AND
598 h2s.serviceid = s2r.serviceid AND
599 h2s.hostid in ('.$id_list .') AND
f633d85d 600 h2s.publish =\'1\' AND
71558f85 601 svc.id = h2s.serviceid AND
cc38ff5d 602 svc.name = ?
71558f85 603 ORDER BY
604 rpc.xmlrpc_path ASC';
cc38ff5d 605 $params = array($params[0]);
71558f85 606
607 }
cc38ff5d 608 $resultset = array_values($DB->get_records_sql($query, $params));
71558f85 609 $methods = array();
610 foreach($resultset as $result) {
611 $methods[] = $result->xmlrpc_path;
612 }
613 return $methods;
614 } elseif ('system.methodSignature' == $method || 'system/methodSignature' == $method) {
615 $query = '
616 SELECT DISTINCT
617 rpc.function_name,
618 rpc.xmlrpc_path,
619 rpc.enabled,
620 rpc.help,
621 rpc.profile
622 FROM
cc38ff5d 623 {mnet_host2service} h2s,
624 {mnet_service2rpc} s2r,
625 {mnet_rpc rpc}
71558f85 626 WHERE
cc38ff5d 627 rpc.xmlrpc_path = ? AND
71558f85 628 s2r.rpcid = rpc.id AND
629 h2s.serviceid = s2r.serviceid AND
f633d85d 630 h2s.publish =\'1\' AND
71558f85 631 h2s.hostid in ('.$id_list .')';
cc38ff5d 632 $params = array($params[0]);
71558f85 633
cc38ff5d 634 $result = $DB->get_records_sql($query, $params);
71558f85 635 $methodsigs = array();
636
637 if (is_array($result)) {
638 foreach($result as $method) {
639 $methodsigs[] = unserialize($method->profile);
640 }
641 }
642
643 return $methodsigs;
644 } elseif ('system.methodHelp' == $method || 'system/methodHelp' == $method) {
645 $query = '
646 SELECT DISTINCT
647 rpc.function_name,
648 rpc.xmlrpc_path,
649 rpc.enabled,
650 rpc.help,
651 rpc.profile
652 FROM
cc38ff5d 653 {mnet_host2service} h2s,
654 {mnet_service2rpc} s2r,
655 {mnet_rpc} rpc
71558f85 656 WHERE
cc38ff5d 657 rpc.xmlrpc_path = ? AND
71558f85 658 s2r.rpcid = rpc.id AND
f633d85d 659 h2s.publish =\'1\' AND
71558f85 660 h2s.serviceid = s2r.serviceid AND
661 h2s.hostid in ('.$id_list .')';
cc38ff5d 662 $params = array($params[0]);
71558f85 663
cc38ff5d 664 $result = $DB->get_record_sql($query, $params);
71558f85 665
666 if (is_object($result)) {
667 return $result->help;
668 }
669 } elseif ('system.listServices' == $method || 'system/listServices' == $method) {
670 $query = '
671 SELECT DISTINCT
672 s.id,
673 s.name,
674 s.apiversion,
675 h2s.publish,
676 h2s.subscribe
677 FROM
cc38ff5d 678 {mnet_host2service} h2s,
679 {mnet_service} s
71558f85 680 WHERE
681 h2s.serviceid = s.id AND
f633d85d 682 (h2s.publish =\'1\' OR h2s.subscribe =\'1\') AND
71558f85 683 h2s.hostid in ('.$id_list .')
684 ORDER BY
685 s.name ASC';
cc38ff5d 686 $params = array();
71558f85 687
cc38ff5d 688 $result = $DB->get_records_sql($query, $params);
71558f85 689 $services = array();
690
691 if (is_array($result)) {
692 foreach($result as $service) {
693 $services[] = array('name' => $service->name,
694 'apiversion' => $service->apiversion,
695 'publish' => $service->publish,
696 'subscribe' => $service->subscribe);
697 }
698 }
699
700 return $services;
d3dfe9ae 701 } elseif ('system/retrieveFile' == $method) {
702 global $DB, $USER;
703
704 $USER = $DB->get_record('user',array('username' => $params[0], 'mnethostid' => $hostinfo->id));
705 $pathnamehash = $params[1];
706 $fs = get_file_storage();
707
708 $sf = $fs->get_file_by_hash($pathnamehash);
709
710 $contents = base64_encode($sf->get_content());
711
712 return array($contents, $sf->get_filename());
713 } elseif ('system/listFiles' == $method) {
714
715 global $DB, $USER;
716
717 $USER = $DB->get_record('user',array('username' => $params[0], 'mnethostid' => $hostinfo->id));
718
719 $ret = array();
720 $search = '';
721 // no login required
722 $ret['nologin'] = true;
723 // todo: link to file manager
724 $ret['manage'] = $CFG->wwwroot .'/files/index.php'; // temporary
725
726 $browser = get_file_browser();
727 $itemid = null;
728 $filename = null;
729 $filearea = null;
730 $path = '/';
731 $ret['dynload'] = false;
732
733 if ($fileinfo = $browser->get_file_info(get_system_context(), $filearea, $itemid, $path, $filename)) {
734
735 $ret['path'] = array();
736 $params = $fileinfo->get_params();
737 $filearea = $params['filearea'];
738 //todo: fix this call, and similar ones here and in build_tree - encoding path works only for real folders
739 $ret['path'][] = _encode_path($filearea, $path, $fileinfo->get_visible_name());
740 if ($fileinfo->is_directory()) {
741 $level = $fileinfo->get_parent();
742 while ($level) {
743 $params = $level->get_params();
744 $ret['path'][] = _encode_path($params['filearea'], $params['filepath'], $level->get_visible_name());
745 $level = $level->get_parent();
746 }
747 }
748 $filecount = build_tree($fileinfo, $search, $ret['dynload'], $ret['list']);
749 $ret['path'] = array_reverse($ret['path']);
750 } else {
751 // throw some "context/filearea/item/path/file not found" exception?
752 }
753
754 if (empty($ret['list'])) {
755 throw new repository_exception('emptyfilelist', 'repository_local');
756 } else {
757 return $ret;
758 }
71558f85 759 }
760 exit(mnet_server_fault(7019, 'nosuchfunction'));
761}
762
d3dfe9ae 763 /**
764 *
765 * @param <type> $filearea
766 * @param <type> $path
767 * @param <type> $visiblename
768 * @return <type>
769 */
770 function _encode_path($filearea, $path, $visiblename) {
771 return array('path'=>serialize(array($filearea, $path)), 'name'=>$visiblename);
772 }
773
774 /**
775 * Builds a tree of files, to be used by get_listing(). This function is
776 * then called recursively.
777 *
778 * @param $fileinfo an object returned by file_browser::get_file_info()
779 * @param $search searched string
780 * @param $dynamicmode bool no recursive call is done when in dynamic mode
781 * @param $list - the array containing the files under the passed $fileinfo
782 * @returns int the number of files found
783 *
784 * todo: take $search into account, and respect a threshold for dynamic loading
785 */
786 function build_tree($fileinfo, $search, $dynamicmode, &$list) {
787 global $CFG;
788
789 $filecount = 0;
790 $children = $fileinfo->get_children();
791
792 foreach ($children as $child) {
793 $filename = $child->get_visible_name();
794 $filesize = $child->get_filesize();
795 $filesize = $filesize ? display_size($filesize) : '';
796 $filedate = $child->get_timemodified();
797 $filedate = $filedate ? userdate($filedate) : '';
798 $filetype = $child->get_mimetype();
799
800 if ($child->is_directory()) {
801 $path = array();
802 $level = $child->get_parent();
803 while ($level) {
804 $params = $level->get_params();
805 $path[] = _encode_path($params['filearea'], $params['filepath'], $level->get_visible_name());
806 $level = $level->get_parent();
807 }
808
809 $tmp = array(
810 'title' => $child->get_visible_name(),
811 'size' => 0,
812 'date' => $filedate,
813 'path' => array_reverse($path),
814 'thumbnail' => $CFG->pixpath .'/f/folder.gif'
815 );
816
817
818 $_search = $search;
819 if ($search && stristr($tmp['title'], $search) !== false) {
820 $_search = false;
821 }
822 $tmp['children'] = array();
823 $_filecount = build_tree($child, $_search, $dynamicmode, $tmp['children']);
824 if ($search && $_filecount) {
825 $tmp['expanded'] = 1;
826 }
827
828
829
830 if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
831 $list[] = $tmp;
832 $filecount += $_filecount;
833 }
834
835 } else { // not a directory
836 // skip the file, if we're in search mode and it's not a match
837 if ($search && (stristr($filename, $search) === false)) {
838 continue;
839 }
840
841 //retrieve the stored file id
842 $fs = get_file_storage();
843 $params = $child->get_params();
844
845 $pathnamehash = $fs->get_pathname_hash($params['contextid'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']);
846
847
848 $list[] = array(
849 'title' => $filename,
850 'size' => $filesize,
851 'date' => $filedate,
852 'source' => $pathnamehash,
853 'thumbnail' => $CFG->pixpath .'/f/'. mimeinfo_from_type("icon", $filetype)
854 );
855
856 $filecount++;
857 }
858 }
859
860 return $filecount;
861 }
862
71558f85 863/**
864 * Initialize the object (if necessary), execute the method or function, and
865 * return the response
866 *
867 * @param string $includefile The file that contains the object definition
868 * @param string $methodname The name of the method to execute
869 * @param string $method The full path to the method
870 * @param string $payload The XML-RPC request payload
871 * @param string $class The name of the class to instantiate (or false)
872 * @return string The XML-RPC response
873 */
874function mnet_server_invoke_method($includefile, $methodname, $method, $payload, $class=false) {
875
876 $permission = mnet_permit_rpc_call($includefile, $methodname, $class);
877
878 if (RPC_NOSUCHFILE == $permission) {
879 // Generate error response - unable to locate function
880 exit(mnet_server_fault(705, 'nosuchfile', $includefile));
881 }
882
883 if (RPC_NOSUCHFUNCTION == $permission) {
884 // Generate error response - unable to locate function
885 exit(mnet_server_fault(706, 'nosuchfunction'));
886 }
887
888 if (RPC_FORBIDDENFUNCTION == $permission) {
889 // Generate error response - unable to locate function
890 exit(mnet_server_fault(707, 'forbidden-function'));
891 }
892
893 if (RPC_NOSUCHCLASS == $permission) {
894 // Generate error response - unable to locate function
895 exit(mnet_server_fault(7013, 'nosuchfunction'));
896 }
897
898 if (RPC_NOSUCHMETHOD == $permission) {
899 // Generate error response - unable to locate function
900 exit(mnet_server_fault(7014, 'nosuchmethod'));
901 }
902
903 if (RPC_NOSUCHFUNCTION == $permission) {
904 // Generate error response - unable to locate function
905 exit(mnet_server_fault(7014, 'nosuchmethod'));
906 }
907
908 if (RPC_FORBIDDENMETHOD == $permission) {
909 // Generate error response - unable to locate function
910 exit(mnet_server_fault(7015, 'nosuchfunction'));
911 }
912
913 if (0 < $permission) {
914 // Generate error response - unable to locate function
915 exit(mnet_server_fault(7019, 'unknownerror'));
916 }
917
918 if (RPC_OK == $permission) {
919 $xmlrpcserver = xmlrpc_server_create();
920 $bool = xmlrpc_server_register_method($xmlrpcserver, $method, 'mnet_server_dummy_method');
1008dad6 921 $response = xmlrpc_server_call_method($xmlrpcserver, $payload, $methodname, array("encoding" => "utf-8"));
71558f85 922 $bool = xmlrpc_server_destroy($xmlrpcserver);
923 return $response;
924 }
925}
926
85d2d959 927/**
928 * Accepts a public key from a new remote host and returns the public key for
929 * this host. If 'register all hosts' is turned on, it will bootstrap a record
930 * for the remote host in the mnet_host table (if it's not already there)
931 *
932 * @param string $function XML-RPC requires this but we don't... discard!
933 * @param array $params Array of parameters
934 * $params[0] is the remote wwwroot
935 * $params[1] is the remote public key
936 * @return string The XML-RPC response
937 */
71558f85 938function mnet_keyswap($function, $params) {
735c7beb 939 global $CFG, $MNET;
71558f85 940 $return = array();
941
942 if (!empty($CFG->mnet_register_allhosts)) {
943 $mnet_peer = new mnet_peer();
25202581 944 @list($wwwroot, $pubkey, $application) = each($params);
945 $keyok = $mnet_peer->bootstrap($wwwroot, $pubkey, $application);
71558f85 946 if ($keyok) {
947 $mnet_peer->commit();
948 }
949 }
735c7beb 950 return $MNET->public_key;
71558f85 951}
85d2d959 952
71558f85 953?>