externallib.php 60.6 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
30
31
32
33
34
 * 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
35
36
37
38
 */
class restricted_context_exception extends moodle_exception {
    /**
     * Constructor
39
40
     *
     * @since Moodle 2.0
41
42
43
44
45
46
47
48
     */
    function __construct() {
        parent::__construct('restrictedcontextexception', 'error');
    }
}

/**
 * Base class for external api methods.
49
50
51
52
53
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.0
54
55
 */
class external_api {
56
57

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

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
    /**
     * 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)) {
87
88
                throw new coding_exception('Cannot find file ' . $function->classpath .
                        ' with external function implementation');
89
90
91
            }
            require_once($function->classpath);
            if (!class_exists($function->classname)) {
92
                throw new coding_exception('Cannot find external class ' . $function->classname);
93
94
95
96
97
98
99
100
101
102
            }
        }

        $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)) {
103
104
            throw new coding_exception('Missing implementation method ' .
                    $function->classname . '::' . $function->methodname);
105
106
        }
        if (!method_exists($function->classname, $function->parameters_method)) {
107
108
            throw new coding_exception('Missing parameters description method ' .
                    $function->classname . '::' . $function->parameters_method);
109
110
        }
        if (!method_exists($function->classname, $function->returns_method)) {
111
112
            throw new coding_exception('Missing returned values description method ' .
                    $function->classname . '::' . $function->returns_method);
113
114
115
116
117
118
119
120
121
122
123
        }
        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)) {
124
125
            throw new coding_exception($function->classname . '::' . $function->parameters_method .
                    ' did not return a valid external_function_parameters object.');
126
127
128
129
130
131
        }

        // 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)) {
132
133
            throw new coding_exception($function->classname . '::' . $function->returns_method .
                    ' did not return a valid external_description object');
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
        }

        // 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;
            }
170
171
            if (isset($functions[$function->name]['readonlysession'])) {
                $function->readonlysession = $functions[$function->name]['readonlysession'];
172
            } else {
173
                $function->readonlysession = false;
174
            }
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
        }

        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");

196
        $externalfunctioninfo = static::external_function_info($function);
197

198
        // Eventually this should shift into the various handlers and not be handled via config.
199
200
        $readonlysession = $externalfunctioninfo->readonlysession ?? false;
        if (!$readonlysession || empty($CFG->enable_read_only_sessions)) {
201
202
203
            \core\session\manager::restart_with_write_lock();
        }

204
205
206
207
208
        $currentpage = $PAGE;
        $currentcourse = $COURSE;
        $response = array();

        try {
209
210
211
212
213
214
215
216
217
218
            // 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();
219
220
221
222
223
224
            $COURSE = clone($SITE);

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

225
            // Do not allow access to write or delete webservices as a public user.
226
            if ($externalfunctioninfo->loginrequired && !WS_SERVER) {
227
                if (defined('NO_MOODLE_COOKIES') && NO_MOODLE_COOKIES && !PHPUNIT_TEST) {
228
                    throw new moodle_exception('servicerequireslogin', 'webservice');
229
230
                }
                if (!isloggedin()) {
231
                    throw new moodle_exception('servicerequireslogin', 'webservice');
232
233
234
235
236
237
238
239
240
                } 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);
241
            $params = array_values($params);
242

243
244
245
246
247
248
249
250
251
252
            // Allow any Moodle plugin a chance to override this call. This is a convenient spot to
            // make arbitrary behaviour customisations. The overriding plugin could call the 'real'
            // function first and then modify the results, or it could do a completely separate
            // thing.
            $callbacks = get_plugins_with_function('override_webservice_execution');
            $result = false;
            foreach ($callbacks as $plugintype => $plugins) {
                foreach ($plugins as $plugin => $callback) {
                    $result = $callback($externalfunctioninfo, $params);
                    if ($result !== false) {
253
                        break 2;
254
255
256
257
258
259
260
261
262
                    }
                }
            }

            // If the function was not overridden, call the real one.
            if ($result === false) {
                $callable = array($externalfunctioninfo->classname, $externalfunctioninfo->methodname);
                $result = call_user_func_array($callable, $params);
            }
263
264
265
266
267
268
269
270
271

            // 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;
272
        } catch (Throwable $e) {
273
274
            $exception = get_exception_info($e);
            unset($exception->a);
275
            $exception->backtrace = format_backtrace($exception->backtrace, true);
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
            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;
    }

291
    /**
Petr Skoda's avatar
Petr Skoda committed
292
     * Set context restriction for all following subsequent function calls.
293
294
295
     *
     * @param stdClass $context the context restriction
     * @since Moodle 2.0
296
     */
297
    public static function set_context_restriction($context) {
298
299
300
        self::$contextrestriction = $context;
    }

301
302
303
304
305
    /**
     * 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
306
     * @since Moodle 2.0
307
308
309
     */
    public static function set_timeout($seconds=360) {
        $seconds = ($seconds < 300) ? 300 : $seconds;
310
        core_php_time_limit::raise($seconds);
311
312
    }

313
    /**
314
     * Validates submitted function parameters, if anything is incorrect
315
     * invalid_parameter_exception is thrown.
skodak's avatar
skodak committed
316
317
     * This is a simple recursive method which is intended to be called from
     * each implementation method of external API.
318
     *
319
320
321
     * @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
322
     * @since Moodle 2.0
323
     */
324
    public static function validate_parameters(external_description $description, $params) {
325
        if ($description instanceof external_value) {
326
            if (is_array($params) or is_object($params)) {
327
                throw new invalid_parameter_exception('Scalar type expected, array or object received.');
328
            }
329
330
331
332
333
334
335

            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;
                }
            }
336
337
338
            $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);
339

340
341
        } else if ($description instanceof external_single_structure) {
            if (!is_array($params)) {
342
343
                throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
                        . print_r($params, true) . '\'');
344
345
346
347
            }
            $result = array();
            foreach ($description->keys as $key=>$subdesc) {
                if (!array_key_exists($key, $params)) {
348
                    if ($subdesc->required == VALUE_REQUIRED) {
349
                        throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
350
                    }
351
352
                    if ($subdesc->required == VALUE_DEFAULT) {
                        try {
353
                            $result[$key] = static::validate_parameters($subdesc, $subdesc->default);
354
                        } catch (invalid_parameter_exception $e) {
355
356
357
                            //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);
358
                        }
359
                    }
360
                } else {
361
                    try {
362
                        $result[$key] = static::validate_parameters($subdesc, $params[$key]);
363
                    } catch (invalid_parameter_exception $e) {
364
365
366
                        //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);
367
                    }
368
369
370
371
                }
                unset($params[$key]);
            }
            if (!empty($params)) {
372
                throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
373
374
            }
            return $result;
375

376
377
        } else if ($description instanceof external_multiple_structure) {
            if (!is_array($params)) {
378
379
                throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
                        . print_r($params, true) . '\'');
380
381
382
            }
            $result = array();
            foreach ($params as $param) {
383
                $result[] = static::validate_parameters($description->content, $param);
384
385
386
387
            }
            return $result;

        } else {
388
            throw new invalid_parameter_exception('Invalid external api description');
389
        }
390
391
    }

392
393
    /**
     * Clean response
Petr Skoda's avatar
Petr Skoda committed
394
395
     * 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.
396
397
     * Note: this function is similar to validate parameters, however it is distinct because
     * parameters validation must be distinct from cleaning return values.
398
     *
399
400
401
     * @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
402
403
     * @author 2010 Jerome Mouneyrac
     * @since Moodle 2.0
404
405
406
407
     */
    public static function clean_returnvalue(external_description $description, $response) {
        if ($description instanceof external_value) {
            if (is_array($response) or is_object($response)) {
408
                throw new invalid_response_exception('Scalar type expected, array or object received.');
409
410
411
412
413
414
415
416
            }

            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;
                }
            }
417
            $responsetype = gettype($response);
418
            $debuginfo = 'Invalid external api response: the value is "' . $response .
419
                    '" of PHP type "' . $responsetype . '", the server was expecting "' . $description->type . '" type';
420
421
422
423
424
425
            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);
            }
426
427

        } else if ($description instanceof external_single_structure) {
428
429
            if (!is_array($response) && !is_object($response)) {
                throw new invalid_response_exception('Only arrays/objects accepted. The bad value is: \'' .
430
                        print_r($response, true) . '\'');
431
            }
432
433
434
435
436
437

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

438
439
440
441
            $result = array();
            foreach ($description->keys as $key=>$subdesc) {
                if (!array_key_exists($key, $response)) {
                    if ($subdesc->required == VALUE_REQUIRED) {
442
                        throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
443
444
                    }
                    if ($subdesc instanceof external_value) {
445
446
                        if ($subdesc->required == VALUE_DEFAULT) {
                            try {
447
                                    $result[$key] = static::clean_returnvalue($subdesc, $subdesc->default);
448
449
450
                            } catch (invalid_response_exception $e) {
                                //build the path to the faulty attribut
                                throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
451
452
                            }
                        }
453
                    }
454
455
                } else {
                    try {
456
                        $result[$key] = static::clean_returnvalue($subdesc, $response[$key]);
457
458
459
                    } catch (invalid_response_exception $e) {
                        //build the path to the faulty attribut
                        throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
460
461
462
463
464
465
466
467
468
                    }
                }
                unset($response[$key]);
            }

            return $result;

        } else if ($description instanceof external_multiple_structure) {
            if (!is_array($response)) {
469
470
                throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
                        print_r($response, true) . '\'');
471
472
473
            }
            $result = array();
            foreach ($response as $param) {
474
                $result[] = static::clean_returnvalue($description->content, $param);
475
476
477
478
            }
            return $result;

        } else {
479
            throw new invalid_response_exception('Invalid external api response description');
480
481
482
        }
    }

483
484
    /**
     * Makes sure user may execute functions in this context.
485
486
487
     *
     * @param stdClass $context
     * @since Moodle 2.0
488
     */
489
    public static function validate_context($context) {
490
        global $CFG, $PAGE;
491

492
493
494
        if (empty($context)) {
            throw new invalid_parameter_exception('Context does not exist');
        }
495
        if (empty(self::$contextrestriction)) {
496
            self::$contextrestriction = context_system::instance();
497
498
499
500
        }
        $rcontext = self::$contextrestriction;

        if ($rcontext->contextlevel == $context->contextlevel) {
501
            if ($rcontext->id != $context->id) {
502
503
504
505
506
                throw new restricted_context_exception();
            }
        } else if ($rcontext->contextlevel > $context->contextlevel) {
            throw new restricted_context_exception();
        } else {
507
            $parents = $context->get_parent_context_ids();
508
509
510
511
512
            if (!in_array($rcontext->id, $parents)) {
                throw new restricted_context_exception();
            }
        }

513
514
515
516
        $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);
517
    }
518
519

    /**
520
521
522
523
524
     * 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.
525
526
527
528
529
530
     *
     * @param array $param
     * @since Moodle 2.6
     * @throws invalid_parameter_exception
     * @return context
     */
531
    protected static function get_context_from_params($param) {
532
        $levels = context_helper::get_all_levels();
533
        if (!empty($param['contextid'])) {
534
            return context::instance_by_id($param['contextid'], IGNORE_MISSING);
535
        } else if (!empty($param['contextlevel']) && isset($param['instanceid'])) {
536
537
538
539
540
541
542
543
544
545
            $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');
        }
    }
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576

    /**
     * Returns a prepared structure to use a context parameters.
     * @return external_single_structure
     */
    protected static function get_context_parameters() {
        $id = new external_value(
            PARAM_INT,
            'Context ID. Either use this value, or level and instanceid.',
            VALUE_DEFAULT,
            0
        );
        $level = new external_value(
            PARAM_ALPHA,
            'Context level. To be used with instanceid.',
            VALUE_DEFAULT,
            ''
        );
        $instanceid = new external_value(
            PARAM_INT,
            'Context instance ID. To be used with level',
            VALUE_DEFAULT,
            0
        );
        return new external_single_structure(array(
            'contextid' => $id,
            'contextlevel' => $level,
            'instanceid' => $instanceid,
        ));
    }

577
578
}

579
580
/**
 * Common ancestor of all parameter description classes
581
582
583
584
585
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.0
586
587
 */
abstract class external_description {
588
    /** @var string Description of element */
589
    public $desc;
590
591

    /** @var bool Element value required, null not allowed */
592
    public $required;
593
594

    /** @var mixed Default value */
595
    public $default;
596
597
598

    /**
     * Contructor
599
     *
600
601
     * @param string $desc
     * @param bool $required
602
     * @param mixed $default
603
     * @since Moodle 2.0
604
     */
605
    public function __construct($desc, $required, $default) {
606
607
        $this->desc = $desc;
        $this->required = $required;
608
        $this->default = $default;
609
610
611
612
    }
}

/**
613
614
615
616
617
618
 * 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
619
 */
620
class external_value extends external_description {
621
622

    /** @var mixed Value type PARAM_XX */
623
    public $type;
624
625

    /** @var bool Allow null values */
626
627
628
629
    public $allownull;

    /**
     * Constructor
630
     *
631
632
633
634
635
     * @param mixed $type
     * @param string $desc
     * @param bool $required
     * @param mixed $default
     * @param bool $allownull
636
     * @since Moodle 2.0
637
     */
638
639
640
    public function __construct($type, $desc='', $required=VALUE_REQUIRED,
            $default=null, $allownull=NULL_ALLOWED) {
        parent::__construct($desc, $required, $default);
641
        $this->type      = $type;
642
643
644
645
646
647
        $this->allownull = $allownull;
    }
}

/**
 * Associative array description class
648
649
650
651
652
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.0
653
654
 */
class external_single_structure extends external_description {
655
656

     /** @var array Description of array keys key=>external_description */
657
658
659
660
    public $keys;

    /**
     * Constructor
661
     *
662
663
664
     * @param array $keys
     * @param string $desc
     * @param bool $required
665
     * @param array $default
666
     * @since Moodle 2.0
667
     */
668
669
670
    public function __construct(array $keys, $desc='',
            $required=VALUE_REQUIRED, $default=null) {
        parent::__construct($desc, $required, $default);
671
672
673
674
675
676
        $this->keys = $keys;
    }
}

/**
 * Bulk array description class.
677
678
679
680
681
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.0
682
683
 */
class external_multiple_structure extends external_description {
684
685

     /** @var external_description content */
686
687
688
689
    public $content;

    /**
     * Constructor
690
     *
691
692
693
     * @param external_description $content
     * @param string $desc
     * @param bool $required
694
     * @param array $default
695
     * @since Moodle 2.0
696
     */
697
698
699
    public function __construct(external_description $content, $desc='',
            $required=VALUE_REQUIRED, $default=null) {
        parent::__construct($desc, $required, $default);
700
701
702
        $this->content = $content;
    }
}
703
704
705
706

/**
 * Description of top level - PHP function parameters.
 *
707
708
709
710
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 * @since Moodle 2.0
711
712
 */
class external_function_parameters extends external_single_structure {
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736

    /**
     * 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);
    }
737
}
738

739
740
741
742
743
744
745
746
747
748
749
750
751
/**
 * 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
 */
752
753
754
755
756
757
758
759
760
761
762
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)));
763
    $newtoken = new stdClass();
764
765
766
767
768
769
770
    $newtoken->token = $generatedtoken;
    if (!is_object($serviceorid)){
        $service = $DB->get_record('external_services', array('id' => $serviceorid));
    } else {
        $service = $serviceorid;
    }
    if (!is_object($contextorid)){
771
        $context = context::instance_by_id($contextorid, MUST_EXIST);
772
773
774
775
776
777
778
779
780
781
    } 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;
782
783
784
    if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
        $newtoken->sid = session_id();
    }
785
786

    $newtoken->contextid = $context->id;
787
788
789
790
791
792
    $newtoken->creatorid = $USER->id;
    $newtoken->timecreated = time();
    $newtoken->validuntil = $validuntil;
    if (!empty($iprestriction)) {
        $newtoken->iprestriction = $iprestriction;
    }
793
794
    // Generate the private token, it must be transmitted only via https.
    $newtoken->privatetoken = random_string(64);
795
796
    $DB->insert_record('external_tokens', $newtoken);
    return $newtoken->token;
797
}
798

799
/**
800
 * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
801
802
803
 * 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.
804
 *
805
806
807
 * @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.
808
 * @since Moodle 2.0
809
810
811
812
813
 */
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);
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
}

/**
 * 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
834
835
836
}

/**
837
 * Standard Moodle web service warnings
Yang's avatar
Yang committed
838
 *
839
840
841
842
843
844
845
846
847
848
849
850
 * @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
     */
851
852
    public function __construct($itemdesc = 'item', $itemiddesc = 'item id',
        $warningcodedesc = 'the warning code can be used by the client app to implement specific behaviour') {
853
854
855
856

        parent::__construct(
            new external_single_structure(
                array(
857
858
859
                    '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),
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
                    '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
878
 */
879
880
881
882
883
884
885
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
886
     * @param int $default Default value.
887
888
     * @since Moodle 2.3
     */
889
    public function __construct($textfieldname, $required = VALUE_REQUIRED, $default = null) {
890

891
892
893
        if ($default == null && $required == VALUE_DEFAULT) {
            $default = FORMAT_HTML;
        }
894
895
896
897
898
899

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

900
        parent::__construct(PARAM_INT, $desc, $required, $default);
901
902
903
904
905
906
907
908
909
    }
}

/**
 * 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
910
 * @since Moodle 2.3
911
912
913
914
915
916
917
918
919
920
 */
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;
}

921
922
923
924
925
926
/**
 * 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.
 *
927
928
929
930
931
 * <pre>
 * Options are the same that in {@link format_string()} with some changes:
 *      filter      : Can be set to false to force filters off, else observes {@link external_settings}.
 * </pre>
 *
932
933
934
 * @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
935
 * @param context|int $contextorid The id of the context for the string or the context (affects filters).
936
937
938
939
 * @param array $options options array/object or courseid
 * @return string text
 * @since Moodle 3.0
 */
940
function external_format_string($str, $contextorid, $striplinks = true, $options = array()) {
941
942
943

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

    if (!$settings->get_raw()) {
949
950
951
952
953
        if (is_object($contextorid) && is_a($contextorid, 'context')) {
            $context = $contextorid;
        } else {
            $context = context::instance_by_id($contextorid);
        }
954
        $options['context'] = $context;
955
        $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
956
957
958
959
960
961
        $str = format_string($str, $striplinks, $options);
    }

    return $str;
}

962
963
964
965
966
967
/**
 * 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.
 *
968
969
970
971
972
 * <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.
973
 *      filter      :   Can be set to false to force filters off, else observes {@link external_settings}.
974
975
976
977
978
979
980
981
 *      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.
982
 *      blanktarget :   If true all <a> tags will have target="_blank" added unless target is explicitly specified.
983
984
 * </pre>
 *
985
 * @param string $text The content that may contain ULRs in need of rewriting.
986
 * @param int $textformat The text format.
987
 * @param context|int $contextorid This parameter and the next two identify the file area to use.
988
989
990
 * @param string $component
 * @param string $filearea helps identify the file area.
 * @param int $itemid helps identify the file area.
991
 * @param object/array $options text formatting options
992
993
 * @return array text + textformat
 * @since Moodle 2.3
994
 * @since Moodle 3.2 component, filearea and itemid are optional parameters
995
 */
996
function external_format_text($text, $textformat, $contextorid, $component = null, $filearea = null, $itemid = null,
997
                                $options = null) {
998
999
1000
    global $CFG;

    // Get settings (singleton).
For faster browsing, not all history is shown. View entire blame