externallib.php 43.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

17

18
19
20
/**
 * Support for external API
 *
21
22
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
23
24
25
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

26
defined('MOODLE_INTERNAL') || die();
27

28
/**
29
 * Returns detailed function information
30
 *
31
32
33
 * @param string|object $function name of external function or record from external_function
 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
 *                        MUST_EXIST means throw exception if no record or multiple records found
34
35
 * @return stdClass description or false if not found or exception thrown
 * @since Moodle 2.0
36
37
 */
function external_function_info($function, $strictness=MUST_EXIST) {
38
    return external_api::external_function_info($function, $strictness);
39
40
}

41
/**
42
43
44
45
46
47
 * Exception indicating user is not allowed to use external function in the current context.
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.0
48
49
50
51
 */
class restricted_context_exception extends moodle_exception {
    /**
     * Constructor
52
53
     *
     * @since Moodle 2.0
54
55
56
57
58
59
60
61
     */
    function __construct() {
        parent::__construct('restrictedcontextexception', 'error');
    }
}

/**
 * Base class for external api methods.
62
63
64
65
66
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.0
67
68
 */
class external_api {
69
70

    /** @var stdClass context where the function calls will be restricted */
71
72
    private static $contextrestriction;

73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
    /**
     * Returns detailed function information
     *
     * @param string|object $function name of external function or record from external_function
     * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
     *                        MUST_EXIST means throw exception if no record or multiple records found
     * @return stdClass description or false if not found or exception thrown
     * @since Moodle 2.0
     */
    public static function external_function_info($function, $strictness=MUST_EXIST) {
        global $DB, $CFG;

        if (!is_object($function)) {
            if (!$function = $DB->get_record('external_functions', array('name' => $function), '*', $strictness)) {
                return false;
            }
        }

        // First try class autoloading.
        if (!class_exists($function->classname)) {
            // Fallback to explicit include of externallib.php.
            if (empty($function->classpath)) {
                $function->classpath = core_component::get_component_directory($function->component).'/externallib.php';
            } else {
                $function->classpath = $CFG->dirroot.'/'.$function->classpath;
            }
            if (!file_exists($function->classpath)) {
                throw new coding_exception('Cannot find file with external function implementation');
            }
            require_once($function->classpath);
            if (!class_exists($function->classname)) {
                throw new coding_exception('Cannot find external class');
            }
        }

        $function->ajax_method = $function->methodname.'_is_allowed_from_ajax';
        $function->parameters_method = $function->methodname.'_parameters';
        $function->returns_method    = $function->methodname.'_returns';
        $function->deprecated_method = $function->methodname.'_is_deprecated';

        // Make sure the implementaion class is ok.
        if (!method_exists($function->classname, $function->methodname)) {
            throw new coding_exception('Missing implementation method of '.$function->classname.'::'.$function->methodname);
        }
        if (!method_exists($function->classname, $function->parameters_method)) {
            throw new coding_exception('Missing parameters description');
        }
        if (!method_exists($function->classname, $function->returns_method)) {
            throw new coding_exception('Missing returned values description');
        }
        if (method_exists($function->classname, $function->deprecated_method)) {
            if (call_user_func(array($function->classname, $function->deprecated_method)) === true) {
                $function->deprecated = true;
            }
        }
        $function->allowed_from_ajax = false;

        // Fetch the parameters description.
        $function->parameters_desc = call_user_func(array($function->classname, $function->parameters_method));
        if (!($function->parameters_desc instanceof external_function_parameters)) {
            throw new coding_exception('Invalid parameters description');
        }

        // Fetch the return values description.
        $function->returns_desc = call_user_func(array($function->classname, $function->returns_method));
        // Null means void result or result is ignored.
        if (!is_null($function->returns_desc) and !($function->returns_desc instanceof external_description)) {
            throw new coding_exception('Invalid return description');
        }

        // Now get the function description.

        // TODO MDL-31115 use localised lang pack descriptions, it would be nice to have
        // easy to understand descriptions in admin UI,
        // on the other hand this is still a bit in a flux and we need to find some new naming
        // conventions for these descriptions in lang packs.
        $function->description = null;
        $servicesfile = core_component::get_component_directory($function->component).'/db/services.php';
        if (file_exists($servicesfile)) {
            $functions = null;
            include($servicesfile);
            if (isset($functions[$function->name]['description'])) {
                $function->description = $functions[$function->name]['description'];
            }
            if (isset($functions[$function->name]['testclientpath'])) {
                $function->testclientpath = $functions[$function->name]['testclientpath'];
            }
            if (isset($functions[$function->name]['type'])) {
                $function->type = $functions[$function->name]['type'];
            }
            if (isset($functions[$function->name]['ajax'])) {
                $function->allowed_from_ajax = $functions[$function->name]['ajax'];
            } else if (method_exists($function->classname, $function->ajax_method)) {
                if (call_user_func(array($function->classname, $function->ajax_method)) === true) {
                    debugging('External function ' . $function->ajax_method . '() function is deprecated.' .
                              'Set ajax=>true in db/service.php instead.', DEBUG_DEVELOPER);
                    $function->allowed_from_ajax = true;
                }
            }
            if (isset($functions[$function->name]['loginrequired'])) {
                $function->loginrequired = $functions[$function->name]['loginrequired'];
            } else {
                $function->loginrequired = true;
            }
        }

        return $function;
    }

    /**
     * Call an external function validating all params/returns correctly.
     *
     * Note that an external function may modify the state of the current page, so this wrapper
     * saves and restores tha PAGE and COURSE global variables before/after calling the external function.
     *
     * @param string $function A webservice function name.
     * @param array $args Params array (named params)
     * @param boolean $ajaxonly If true, an extra check will be peformed to see if ajax is required.
     * @return array containing keys for error (bool), exception and data.
     */
    public static function call_external_function($function, $args, $ajaxonly=false) {
        global $PAGE, $COURSE, $CFG, $SITE;

        require_once($CFG->libdir . "/pagelib.php");

        $externalfunctioninfo = self::external_function_info($function);

        $currentpage = $PAGE;
        $currentcourse = $COURSE;
        $response = array();

        try {
205
206
207
208
209
210
211
212
213
214
            // Taken straight from from setup.php.
            if (!empty($CFG->moodlepageclass)) {
                if (!empty($CFG->moodlepageclassfile)) {
                    require_once($CFG->moodlepageclassfile);
                }
                $classname = $CFG->moodlepageclass;
            } else {
                $classname = 'moodle_page';
            }
            $PAGE = new $classname();
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
            $COURSE = clone($SITE);

            if ($ajaxonly && !$externalfunctioninfo->allowed_from_ajax) {
                throw new moodle_exception('servicenotavailable', 'webservice');
            }

            // Do not allow access to write or delete webservices as a public user.
            if ($externalfunctioninfo->loginrequired) {
                if (defined('NO_MOODLE_COOKIES') && NO_MOODLE_COOKIES && !PHPUNIT_TEST) {
                    throw new moodle_exception('servicenotavailable', 'webservice');
                }
                if (!isloggedin()) {
                    throw new moodle_exception('servicenotavailable', 'webservice');
                } else {
                    require_sesskey();
                }
            }

            // Validate params, this also sorts the params properly, we need the correct order in the next part.
            $callable = array($externalfunctioninfo->classname, 'validate_parameters');
            $params = call_user_func($callable,
                                     $externalfunctioninfo->parameters_desc,
                                     $args);

            // Execute - gulp!
            $callable = array($externalfunctioninfo->classname, $externalfunctioninfo->methodname);
            $result = call_user_func_array($callable,
                                           array_values($params));

            // Validate the return parameters.
            if ($externalfunctioninfo->returns_desc !== null) {
                $callable = array($externalfunctioninfo->classname, 'clean_returnvalue');
                $result = call_user_func($callable, $externalfunctioninfo->returns_desc, $result);
            }

            $response['error'] = false;
            $response['data'] = $result;
        } catch (Exception $e) {
            $exception = get_exception_info($e);
            unset($exception->a);
            if (!debugging('', DEBUG_DEVELOPER)) {
                unset($exception->debuginfo);
                unset($exception->backtrace);
            }
            $response['error'] = true;
            $response['exception'] = $exception;
            // Do not process the remaining requests.
        }

        $PAGE = $currentpage;
        $COURSE = $currentcourse;

        return $response;
    }

270
    /**
Petr Skoda's avatar
Petr Skoda committed
271
     * Set context restriction for all following subsequent function calls.
272
273
274
     *
     * @param stdClass $context the context restriction
     * @since Moodle 2.0
275
     */
276
    public static function set_context_restriction($context) {
277
278
279
        self::$contextrestriction = $context;
    }

280
281
282
283
284
    /**
     * This method has to be called before every operation
     * that takes a longer time to finish!
     *
     * @param int $seconds max expected time the next operation needs
285
     * @since Moodle 2.0
286
287
288
     */
    public static function set_timeout($seconds=360) {
        $seconds = ($seconds < 300) ? 300 : $seconds;
289
        core_php_time_limit::raise($seconds);
290
291
    }

292
    /**
293
     * Validates submitted function parameters, if anything is incorrect
294
     * invalid_parameter_exception is thrown.
skodak's avatar
skodak committed
295
296
     * This is a simple recursive method which is intended to be called from
     * each implementation method of external API.
297
     *
298
299
300
     * @param external_description $description description of parameters
     * @param mixed $params the actual parameters
     * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
301
     * @since Moodle 2.0
302
     */
303
    public static function validate_parameters(external_description $description, $params) {
304
        if ($description instanceof external_value) {
305
            if (is_array($params) or is_object($params)) {
306
                throw new invalid_parameter_exception('Scalar type expected, array or object received.');
307
            }
308
309
310
311
312
313
314

            if ($description->type == PARAM_BOOL) {
                // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
                if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
                    return (bool)$params;
                }
            }
315
316
317
            $debuginfo = 'Invalid external api parameter: the value is "' . $params .
                    '", the server was expecting "' . $description->type . '" type';
            return validate_param($params, $description->type, $description->allownull, $debuginfo);
318

319
320
        } else if ($description instanceof external_single_structure) {
            if (!is_array($params)) {
321
322
                throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
                        . print_r($params, true) . '\'');
323
324
325
326
            }
            $result = array();
            foreach ($description->keys as $key=>$subdesc) {
                if (!array_key_exists($key, $params)) {
327
                    if ($subdesc->required == VALUE_REQUIRED) {
328
                        throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
329
                    }
330
331
332
333
                    if ($subdesc->required == VALUE_DEFAULT) {
                        try {
                            $result[$key] = self::validate_parameters($subdesc, $subdesc->default);
                        } catch (invalid_parameter_exception $e) {
334
335
336
                            //we are only interested by exceptions returned by validate_param() and validate_parameters()
                            //(in order to build the path to the faulty attribut)
                            throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
337
                        }
338
                    }
339
                } else {
340
341
342
                    try {
                        $result[$key] = self::validate_parameters($subdesc, $params[$key]);
                    } catch (invalid_parameter_exception $e) {
343
344
345
                        //we are only interested by exceptions returned by validate_param() and validate_parameters()
                        //(in order to build the path to the faulty attribut)
                        throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
346
                    }
347
348
349
350
                }
                unset($params[$key]);
            }
            if (!empty($params)) {
351
                throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
352
353
            }
            return $result;
354

355
356
        } else if ($description instanceof external_multiple_structure) {
            if (!is_array($params)) {
357
358
                throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
                        . print_r($params, true) . '\'');
359
360
361
362
363
364
365
366
            }
            $result = array();
            foreach ($params as $param) {
                $result[] = self::validate_parameters($description->content, $param);
            }
            return $result;

        } else {
367
            throw new invalid_parameter_exception('Invalid external api description');
368
        }
369
370
    }

371
372
    /**
     * Clean response
Petr Skoda's avatar
Petr Skoda committed
373
374
     * If a response attribute is unknown from the description, we just ignore the attribute.
     * If a response attribute is incorrect, invalid_response_exception is thrown.
375
376
     * Note: this function is similar to validate parameters, however it is distinct because
     * parameters validation must be distinct from cleaning return values.
377
     *
378
379
380
     * @param external_description $description description of the return values
     * @param mixed $response the actual response
     * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
381
382
     * @author 2010 Jerome Mouneyrac
     * @since Moodle 2.0
383
384
385
386
     */
    public static function clean_returnvalue(external_description $description, $response) {
        if ($description instanceof external_value) {
            if (is_array($response) or is_object($response)) {
387
                throw new invalid_response_exception('Scalar type expected, array or object received.');
388
389
390
391
392
393
394
395
            }

            if ($description->type == PARAM_BOOL) {
                // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
                if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
                    return (bool)$response;
                }
            }
396
397
398
399
400
401
402
403
            $debuginfo = 'Invalid external api response: the value is "' . $response .
                    '", the server was expecting "' . $description->type . '" type';
            try {
                return validate_param($response, $description->type, $description->allownull, $debuginfo);
            } catch (invalid_parameter_exception $e) {
                //proper exception name, to be recursively catched to build the path to the faulty attribut
                throw new invalid_response_exception($e->debuginfo);
            }
404
405

        } else if ($description instanceof external_single_structure) {
406
407
            if (!is_array($response) && !is_object($response)) {
                throw new invalid_response_exception('Only arrays/objects accepted. The bad value is: \'' .
408
                        print_r($response, true) . '\'');
409
            }
410
411
412
413
414
415

            // Cast objects into arrays.
            if (is_object($response)) {
                $response = (array) $response;
            }

416
417
418
419
            $result = array();
            foreach ($description->keys as $key=>$subdesc) {
                if (!array_key_exists($key, $response)) {
                    if ($subdesc->required == VALUE_REQUIRED) {
420
                        throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
421
422
                    }
                    if ($subdesc instanceof external_value) {
423
424
                        if ($subdesc->required == VALUE_DEFAULT) {
                            try {
425
                                    $result[$key] = self::clean_returnvalue($subdesc, $subdesc->default);
426
427
428
                            } catch (invalid_response_exception $e) {
                                //build the path to the faulty attribut
                                throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
429
430
                            }
                        }
431
                    }
432
433
434
                } else {
                    try {
                        $result[$key] = self::clean_returnvalue($subdesc, $response[$key]);
435
436
437
                    } catch (invalid_response_exception $e) {
                        //build the path to the faulty attribut
                        throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
438
439
440
441
442
443
444
445
446
                    }
                }
                unset($response[$key]);
            }

            return $result;

        } else if ($description instanceof external_multiple_structure) {
            if (!is_array($response)) {
447
448
                throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
                        print_r($response, true) . '\'');
449
450
451
452
453
454
455
456
            }
            $result = array();
            foreach ($response as $param) {
                $result[] = self::clean_returnvalue($description->content, $param);
            }
            return $result;

        } else {
457
            throw new invalid_response_exception('Invalid external api response description');
458
459
460
        }
    }

461
462
    /**
     * Makes sure user may execute functions in this context.
463
464
465
     *
     * @param stdClass $context
     * @since Moodle 2.0
466
     */
467
    public static function validate_context($context) {
468
        global $CFG, $PAGE;
469

470
471
472
        if (empty($context)) {
            throw new invalid_parameter_exception('Context does not exist');
        }
473
        if (empty(self::$contextrestriction)) {
474
            self::$contextrestriction = context_system::instance();
475
476
477
478
        }
        $rcontext = self::$contextrestriction;

        if ($rcontext->contextlevel == $context->contextlevel) {
479
            if ($rcontext->id != $context->id) {
480
481
482
483
484
                throw new restricted_context_exception();
            }
        } else if ($rcontext->contextlevel > $context->contextlevel) {
            throw new restricted_context_exception();
        } else {
485
            $parents = $context->get_parent_context_ids();
486
487
488
489
490
            if (!in_array($rcontext->id, $parents)) {
                throw new restricted_context_exception();
            }
        }

491
492
493
494
        $PAGE->reset_theme_and_output();
        list($unused, $course, $cm) = get_context_info_array($context->id);
        require_login($course, false, $cm, false, true);
        $PAGE->set_context($context);
495
    }
496
497

    /**
498
499
500
501
502
     * Get context from passed parameters.
     * The passed array must either contain a contextid or a combination of context level and instance id to fetch the context.
     * For example, the context level can be "course" and instanceid can be courseid.
     *
     * See context_helper::get_all_levels() for a list of valid context levels.
503
504
505
506
507
508
     *
     * @param array $param
     * @since Moodle 2.6
     * @throws invalid_parameter_exception
     * @return context
     */
509
    protected static function get_context_from_params($param) {
510
        $levels = context_helper::get_all_levels();
511
        if (!empty($param['contextid'])) {
512
            return context::instance_by_id($param['contextid'], IGNORE_MISSING);
513
        } else if (!empty($param['contextlevel']) && isset($param['instanceid'])) {
514
515
516
517
518
519
520
521
522
523
            $contextlevel = "context_".$param['contextlevel'];
            if (!array_search($contextlevel, $levels)) {
                throw new invalid_parameter_exception('Invalid context level = '.$param['contextlevel']);
            }
           return $contextlevel::instance($param['instanceid'], IGNORE_MISSING);
        } else {
            // No valid context info was found.
            throw new invalid_parameter_exception('Missing parameters, please provide either context level with instance id or contextid');
        }
    }
524
525
}

526
527
/**
 * Common ancestor of all parameter description classes
528
529
530
531
532
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.0
533
534
 */
abstract class external_description {
535
    /** @var string Description of element */
536
    public $desc;
537
538

    /** @var bool Element value required, null not allowed */
539
    public $required;
540
541

    /** @var mixed Default value */
542
    public $default;
543
544
545

    /**
     * Contructor
546
     *
547
548
     * @param string $desc
     * @param bool $required
549
     * @param mixed $default
550
     * @since Moodle 2.0
551
     */
552
    public function __construct($desc, $required, $default) {
553
554
        $this->desc = $desc;
        $this->required = $required;
555
        $this->default = $default;
556
557
558
559
    }
}

/**
560
561
562
563
564
565
 * Scalar value description class
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.0
566
 */
567
class external_value extends external_description {
568
569

    /** @var mixed Value type PARAM_XX */
570
    public $type;
571
572

    /** @var bool Allow null values */
573
574
575
576
    public $allownull;

    /**
     * Constructor
577
     *
578
579
580
581
582
     * @param mixed $type
     * @param string $desc
     * @param bool $required
     * @param mixed $default
     * @param bool $allownull
583
     * @since Moodle 2.0
584
     */
585
586
587
    public function __construct($type, $desc='', $required=VALUE_REQUIRED,
            $default=null, $allownull=NULL_ALLOWED) {
        parent::__construct($desc, $required, $default);
588
        $this->type      = $type;
589
590
591
592
593
594
        $this->allownull = $allownull;
    }
}

/**
 * Associative array description class
595
596
597
598
599
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.0
600
601
 */
class external_single_structure extends external_description {
602
603

     /** @var array Description of array keys key=>external_description */
604
605
606
607
    public $keys;

    /**
     * Constructor
608
     *
609
610
611
     * @param array $keys
     * @param string $desc
     * @param bool $required
612
     * @param array $default
613
     * @since Moodle 2.0
614
     */
615
616
617
    public function __construct(array $keys, $desc='',
            $required=VALUE_REQUIRED, $default=null) {
        parent::__construct($desc, $required, $default);
618
619
620
621
622
623
        $this->keys = $keys;
    }
}

/**
 * Bulk array description class.
624
625
626
627
628
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.0
629
630
 */
class external_multiple_structure extends external_description {
631
632

     /** @var external_description content */
633
634
635
636
    public $content;

    /**
     * Constructor
637
     *
638
639
640
     * @param external_description $content
     * @param string $desc
     * @param bool $required
641
     * @param array $default
642
     * @since Moodle 2.0
643
     */
644
645
646
    public function __construct(external_description $content, $desc='',
            $required=VALUE_REQUIRED, $default=null) {
        parent::__construct($desc, $required, $default);
647
648
649
        $this->content = $content;
    }
}
650
651
652
653

/**
 * Description of top level - PHP function parameters.
 *
654
655
656
657
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.0
658
659
 */
class external_function_parameters extends external_single_structure {
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683

    /**
     * Constructor - does extra checking to prevent top level optional parameters.
     *
     * @param array $keys
     * @param string $desc
     * @param bool $required
     * @param array $default
     */
    public function __construct(array $keys, $desc='', $required=VALUE_REQUIRED, $default=null) {
        global $CFG;

        if ($CFG->debugdeveloper) {
            foreach ($keys as $key => $value) {
                if ($value instanceof external_value) {
                    if ($value->required == VALUE_OPTIONAL) {
                        debugging('External function parameters: invalid OPTIONAL value specified.', DEBUG_DEVELOPER);
                        break;
                    }
                }
            }
        }
        parent::__construct($keys, $desc, $required, $default);
    }
684
}
685

686
687
688
689
690
691
692
693
694
695
696
697
698
/**
 * Generate a token
 *
 * @param string $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
 * @param stdClass|int $serviceorid service linked to the token
 * @param int $userid user linked to the token
 * @param stdClass|int $contextorid
 * @param int $validuntil date when the token expired
 * @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
 * @return string generated token
 * @author  2010 Jamie Pratt
 * @since Moodle 2.0
 */
699
700
701
702
703
704
705
706
707
708
709
function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
    global $DB, $USER;
    // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
    $numtries = 0;
    do {
        $numtries ++;
        $generatedtoken = md5(uniqid(rand(),1));
        if ($numtries > 5){
            throw new moodle_exception('tokengenerationfailed');
        }
    } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
710
    $newtoken = new stdClass();
711
712
713
714
715
716
717
    $newtoken->token = $generatedtoken;
    if (!is_object($serviceorid)){
        $service = $DB->get_record('external_services', array('id' => $serviceorid));
    } else {
        $service = $serviceorid;
    }
    if (!is_object($contextorid)){
718
        $context = context::instance_by_id($contextorid, MUST_EXIST);
719
720
721
722
723
724
725
726
727
728
    } else {
        $context = $contextorid;
    }
    if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
        $newtoken->externalserviceid = $service->id;
    } else {
        throw new moodle_exception('nocapabilitytousethisservice');
    }
    $newtoken->tokentype = $tokentype;
    $newtoken->userid = $userid;
729
730
731
    if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
        $newtoken->sid = session_id();
    }
732
733

    $newtoken->contextid = $context->id;
734
735
736
737
738
739
740
741
    $newtoken->creatorid = $USER->id;
    $newtoken->timecreated = time();
    $newtoken->validuntil = $validuntil;
    if (!empty($iprestriction)) {
        $newtoken->iprestriction = $iprestriction;
    }
    $DB->insert_record('external_tokens', $newtoken);
    return $newtoken->token;
742
}
743

744
/**
745
 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
746
747
748
 * with the Moodle server through web services. The token is linked to the current session for the current page request.
 * It is expected this will be called in the script generating the html page that is embedding the client app and that the
 * returned token will be somehow passed into the client app being embedded in the page.
749
 *
750
751
752
 * @param string $servicename name of the web service. Service name as defined in db/services.php
 * @param int $context context within which the web service can operate.
 * @return int returns token id.
753
 * @since Moodle 2.0
754
755
756
757
758
 */
function external_create_service_token($servicename, $context){
    global $USER, $DB;
    $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST);
    return external_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $USER->id, $context, 0);
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
}

/**
 * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
 *
 * @param string $component name of component (moodle, mod_assignment, etc.)
 */
function external_delete_descriptions($component) {
    global $DB;

    $params = array($component);

    $DB->delete_records_select('external_tokens',
            "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
    $DB->delete_records_select('external_services_users',
            "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
    $DB->delete_records_select('external_services_functions',
            "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
    $DB->delete_records('external_services', array('component'=>$component));
    $DB->delete_records('external_functions', array('component'=>$component));
Yang's avatar
Yang committed
779
780
781
}

/**
782
 * Standard Moodle web service warnings
Yang's avatar
Yang committed
783
 *
784
785
786
787
788
789
790
791
792
793
794
795
 * @package    core_webservice
 * @copyright  2012 Jerome Mouneyrac
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.3
 */
class external_warnings extends external_multiple_structure {

    /**
     * Constructor
     *
     * @since Moodle 2.3
     */
796
797
    public function __construct($itemdesc = 'item', $itemiddesc = 'item id',
        $warningcodedesc = 'the warning code can be used by the client app to implement specific behaviour') {
798
799
800
801

        parent::__construct(
            new external_single_structure(
                array(
802
803
804
                    'item' => new external_value(PARAM_TEXT, $itemdesc, VALUE_OPTIONAL),
                    'itemid' => new external_value(PARAM_INT, $itemiddesc, VALUE_OPTIONAL),
                    'warningcode' => new external_value(PARAM_ALPHANUM, $warningcodedesc),
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
                    'message' => new external_value(PARAM_TEXT,
                            'untranslated english message to explain the warning')
                ), 'warning'),
            'list of warnings', VALUE_OPTIONAL);
    }
}

/**
 * A pre-filled external_value class for text format.
 *
 * Default is FORMAT_HTML
 * This should be used all the time in external xxx_params()/xxx_returns functions
 * as it is the standard way to implement text format param/return values.
 *
 * @package    core_webservice
 * @copyright  2012 Jerome Mouneyrac
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.3
Yang's avatar
Yang committed
823
 */
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
class external_format_value extends external_value {

    /**
     * Constructor
     *
     * @param string $textfieldname Name of the text field
     * @param int $required if VALUE_REQUIRED then set standard default FORMAT_HTML
     * @since Moodle 2.3
     */
    public function __construct($textfieldname, $required = VALUE_REQUIRED) {

        $default = ($required == VALUE_DEFAULT) ? FORMAT_HTML : null;

        $desc = $textfieldname . ' format (' . FORMAT_HTML . ' = HTML, '
                . FORMAT_MOODLE . ' = MOODLE, '
                . FORMAT_PLAIN . ' = PLAIN or '
                . FORMAT_MARKDOWN . ' = MARKDOWN)';

842
        parent::__construct(PARAM_INT, $desc, $required, $default);
843
844
845
846
847
848
849
850
851
    }
}

/**
 * Validate text field format against known FORMAT_XXX
 *
 * @param array $format the format to validate
 * @return the validated format
 * @throws coding_exception
Tim Hunt's avatar
Tim Hunt committed
852
 * @since Moodle 2.3
853
854
855
856
857
858
859
860
861
862
 */
function external_validate_format($format) {
    $allowedformats = array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN);
    if (!in_array($format, $allowedformats)) {
        throw new moodle_exception('formatnotsupported', 'webservice', '' , null,
                'The format with value=' . $format . ' is not supported by this Moodle site');
    }
    return $format;
}

863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
/**
 * Format the string to be returned properly as requested by the either the web service server,
 * either by an internally call.
 * The caller can change the format (raw) with the external_settings singleton
 * All web service servers must set this singleton when parsing the $_GET and $_POST.
 *
 * @param string $str The string to be filtered. Should be plain text, expect
 * possibly for multilang tags.
 * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
 * @param int $contextid The id of the context for the string (affects filters).
 * @param array $options options array/object or courseid
 * @return string text
 * @since Moodle 3.0
 */
function external_format_string($str, $contextid, $striplinks = true, $options = array()) {

    // Get settings (singleton).
    $settings = external_settings::get_instance();
    if (empty($contextid)) {
        throw new coding_exception('contextid is required');
    }

    if (!$settings->get_raw()) {
        $context = context::instance_by_id($contextid);
        $options['context'] = $context;
888
        $options['filter'] = $settings->get_filter();
889
890
891
892
893
894
        $str = format_string($str, $striplinks, $options);
    }

    return $str;
}

895
896
897
898
899
900
/**
 * Format the text to be returned properly as requested by the either the web service server,
 * either by an internally call.
 * The caller can change the format (raw, filter, file, fileurl) with the external_settings singleton
 * All web service servers must set this singleton when parsing the $_GET and $_POST.
 *
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
 * <pre>
 * Options are the same that in {@link format_text()} with some changes in defaults to provide backwards compatibility:
 *      trusted     :   If true the string won't be cleaned. Default false.
 *      noclean     :   If true the string won't be cleaned only if trusted is also true. Default false.
 *      nocache     :   If true the string will not be cached and will be formatted every call. Default false.
 *      filter      :   If true the string will be run through applicable filters as well. Default (different from format_text)
 *                      got form settings.
 *      para        :   If true then the returned string will be wrapped in div tags. Default (different from format_text) false.
 *                      Default changed because div tags are not commonly needed.
 *      newlines    :   If true then lines newline breaks will be converted to HTML newline breaks. Default true.
 *      context     :   Not used! Using contextid parameter instead.
 *      overflowdiv :   If set to true the formatted text will be encased in a div with the class no-overflow before being
 *                      returned. Default false.
 *      allowid     :   If true then id attributes will not be removed, even when using htmlpurifier. Default (different from
 *                      format_text) true. Default changed id attributes are commonly needed.
 * </pre>
 *
918
 * @param string $text The content that may contain ULRs in need of rewriting.
919
 * @param int $textformat The text format.
920
921
922
923
 * @param int $contextid This parameter and the next two identify the file area to use.
 * @param string $component
 * @param string $filearea helps identify the file area.
 * @param int $itemid helps identify the file area.
924
 * @param object/array $options text formatting options
925
926
927
 * @return array text + textformat
 * @since Moodle 2.3
 */
928
function external_format_text($text, $textformat, $contextid, $component, $filearea, $itemid, $options = null) {
929
930
931
932
933
934
    global $CFG;

    // Get settings (singleton).
    $settings = external_settings::get_instance();

    if ($settings->get_fileurl()) {
935
        require_once($CFG->libdir . "/filelib.php");
936
937
938
939
        $text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $contextid, $component, $filearea, $itemid);
    }

    if (!$settings->get_raw()) {
940
941
942
943
944
        $options = (array)$options;

        // If context is passed in options, check that is the same to show a debug message.
        if (isset($options['context'])) {
            if ((is_object($options['context']) && $options['context']->id != $contextid)
945
                    || (!is_object($options['context']) && $options['context'] != $contextid)) {
946
947
948
949
950
951
952
953
954
955
956
                debugging('Different contexts found in external_format_text parameters. $options[\'context\'] not allowed.
                    Using $contextid parameter...', DEBUG_DEVELOPER);
            }
        }

        $options['filter'] = isset($options['filter']) ? $options['filter'] : $settings->get_filter();
        $options['para'] = isset($options['para']) ? $options['para'] : false;
        $options['context'] = context::instance_by_id($contextid);
        $options['allowid'] = isset($options['allowid']) ? $options['allowid'] : true;

        $text = format_text($text, $textformat, $options);
957
        $textformat = FORMAT_HTML; // Once converted to html (from markdown, plain... lets inform consumer this is already HTML).
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
    }

    return array($text, $textformat);
}

/**
 * Singleton to handle the external settings.
 *
 * We use singleton to encapsulate the "logic"
 *
 * @package    core_webservice
 * @copyright  2012 Jerome Mouneyrac
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.3
 */
class external_settings {

    /** @var object the singleton instance */
    public static $instance = null;

    /** @var boolean Should the external function return raw text or formatted */
    private $raw = false;

    /** @var boolean Should the external function filter the text */
    private $filter = false;

    /** @var boolean Should the external function rewrite plugin file url */
    private $fileurl = true;

    /** @var string In which file should the urls be rewritten */
    private $file = 'webservice/pluginfile.php';

    /**
     * Constructor - protected - can not be instanciated
     */
    protected function __construct() {
994
995
996
997
        if (!defined('AJAX_SCRIPT') && !defined('CLI_SCRIPT') && !defined('WS_SERVER')) {
            // For normal pages, the default should match the default for format_text.
            $this->filter = true;
        }
998
999
1000
    }

    /**
For faster browsing, not all history is shown. View entire blame