Merge branch 'MDL-62560-master'
[moodle.git] / lib / ajax / service.php
blob3298c0e7a7588a7f7f199dc147505dc39ecb94e6
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file is used to call any registered externallib function in Moodle.
20 * It will process more than one request and return more than one response if required.
21 * It is recommended to add webservice functions and re-use this script instead of
22 * writing any new custom ajax scripts.
24 * @since Moodle 2.9
25 * @package core
26 * @copyright 2015 Damyon Wiese
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 define('AJAX_SCRIPT', true);
32 require_once(__DIR__ . '/../../config.php');
33 require_once($CFG->libdir . '/externallib.php');
35 define('PREFERRED_RENDERER_TARGET', RENDERER_TARGET_GENERAL);
37 $rawjson = file_get_contents('php://input');
39 $requests = json_decode($rawjson, true);
40 if ($requests === null) {
41 $lasterror = json_last_error_msg();
42 throw new coding_exception('Invalid json in request: ' . $lasterror);
44 $responses = array();
46 // Defines the external settings required for Ajax processing.
47 $settings = external_settings::get_instance();
48 $settings->set_file('pluginfile.php');
49 $settings->set_fileurl(true);
50 $settings->set_filter(true);
51 $settings->set_raw(false);
53 foreach ($requests as $request) {
54 $response = array();
55 $methodname = clean_param($request['methodname'], PARAM_ALPHANUMEXT);
56 $index = clean_param($request['index'], PARAM_INT);
57 $args = $request['args'];
59 $response = external_api::call_external_function($methodname, $args, true);
60 $responses[$index] = $response;
61 if ($response['error']) {
62 // Do not process the remaining requests.
63 break;
67 echo json_encode($responses);