Proyectos de Subversion Moodle

Rev

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

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// 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.
13
//
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/>.
16
 
17
 
18
/**
19
 * Web services utility functions and classes
20
 *
21
 * @package    core_webservice
22
 * @copyright  2009 Jerome Mouneyrac <jerome@moodle.com>
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25
 
26
use core_external\external_api;
27
use core_external\external_multiple_structure;
28
use core_external\external_settings;
29
use core_external\external_single_structure;
30
use core_external\external_value;
31
 
32
/**
33
 * WEBSERVICE_AUTHMETHOD_USERNAME - username/password authentication (also called simple authentication)
34
 */
35
define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
36
 
37
/**
38
 * WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN - most common token authentication (external app, mobile app...)
39
 */
40
define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
41
 
42
/**
43
 * WEBSERVICE_AUTHMETHOD_SESSION_TOKEN - token for embedded application (requires Moodle session)
44
 */
45
define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);
46
 
47
/**
48
 * General web service library
49
 *
50
 * @package    core_webservice
51
 * @copyright  2010 Jerome Mouneyrac <jerome@moodle.com>
52
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
53
 */
54
class webservice {
55
    /**
56
     * Only update token last access once per this many seconds. (This constant controls update of
57
     * the external tokens last access field. There is a similar define LASTACCESS_UPDATE_SECS
58
     * which controls update of the web site last access fields.)
59
     *
60
     * @var int
61
     */
62
    const TOKEN_LASTACCESS_UPDATE_SECS = 60;
63
 
64
    /**
65
     * Authenticate user (used by download/upload file scripts)
66
     *
67
     * @param string $token
68
     * @return array - contains the authenticated user, token and service objects
69
     */
70
    public function authenticate_user($token) {
71
        global $DB, $CFG;
72
 
73
        // web service must be enabled to use this script
74
        if (!$CFG->enablewebservices) {
75
            throw new webservice_access_exception('Web services are not enabled in Advanced features.');
76
        }
77
 
78
        // Obtain token record
79
        if (!$token = $DB->get_record('external_tokens', array('token' => $token))) {
80
            //client may want to display login form => moodle_exception
81
            throw new moodle_exception('invalidtoken', 'webservice');
82
        }
83
 
84
        $loginfaileddefaultparams = array(
85
            'other' => array(
86
                'method' => WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN,
87
                'reason' => null,
88
                'tokenid' => $token->id
89
            )
90
        );
91
 
92
        // Validate token date
93
        if ($token->validuntil and $token->validuntil < time()) {
94
            $params = $loginfaileddefaultparams;
95
            $params['other']['reason'] = 'token_expired';
96
            $event = \core\event\webservice_login_failed::create($params);
97
            $event->add_record_snapshot('external_tokens', $token);
98
            $event->trigger();
99
            $DB->delete_records('external_tokens', array('token' => $token->token));
100
            throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
101
        }
102
 
103
        // Check ip
104
        if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
105
            $params = $loginfaileddefaultparams;
106
            $params['other']['reason'] = 'ip_restricted';
107
            $event = \core\event\webservice_login_failed::create($params);
108
            $event->add_record_snapshot('external_tokens', $token);
109
            $event->trigger();
110
            throw new webservice_access_exception('Invalid token - IP:' . getremoteaddr()
111
                    . ' is not supported');
112
        }
113
 
114
        //retrieve user link to the token
115
        $user = $DB->get_record('user', array('id' => $token->userid, 'deleted' => 0), '*', MUST_EXIST);
116
 
117
        // let enrol plugins deal with new enrolments if necessary
118
        enrol_check_plugins($user, false);
119
 
120
        // setup user session to check capability
121
        \core\session\manager::set_user($user);
122
        set_login_session_preferences();
123
 
124
        //assumes that if sid is set then there must be a valid associated session no matter the token type
125
        if ($token->sid) {
126
            if (!\core\session\manager::session_exists($token->sid)) {
127
                $DB->delete_records('external_tokens', array('sid' => $token->sid));
128
                throw new webservice_access_exception('Invalid session based token - session not found or expired');
129
            }
130
        }
131
 
132
        // Cannot authenticate unless maintenance access is granted.
133
        $hasmaintenanceaccess = has_capability('moodle/site:maintenanceaccess', context_system::instance(), $user);
134
        if (!empty($CFG->maintenance_enabled) and !$hasmaintenanceaccess) {
135
            //this is usually temporary, client want to implement code logic  => moodle_exception
136
            throw new moodle_exception('sitemaintenance', 'admin');
137
        }
138
 
139
        //retrieve web service record
140
        $service = $DB->get_record('external_services', array('id' => $token->externalserviceid, 'enabled' => 1));
141
        if (empty($service)) {
142
            // will throw exception if no token found
143
            throw new webservice_access_exception('Web service is not available (it doesn\'t exist or might be disabled)');
144
        }
145
 
146
        //check if there is any required system capability
147
        if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance(), $user)) {
148
            throw new webservice_access_exception('The capability ' . $service->requiredcapability . ' is required.');
149
        }
150
 
151
        //specific checks related to user restricted service
152
        if ($service->restrictedusers) {
153
            $authoriseduser = $DB->get_record('external_services_users', array('externalserviceid' => $service->id, 'userid' => $user->id));
154
 
155
            if (empty($authoriseduser)) {
156
                throw new webservice_access_exception(
157
                        'The user is not allowed for this service. First you need to allow this user on the '
158
                        . $service->name . '\'s allowed users administration page.');
159
            }
160
 
161
            if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
162
                throw new webservice_access_exception('Invalid service - service expired - check validuntil time for this allowed user');
163
            }
164
 
165
            if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
166
                throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
167
                    . ' is not supported - check this allowed user');
168
            }
169
        }
170
 
171
        //only confirmed user should be able to call web service
172
        if (empty($user->confirmed)) {
173
            $params = $loginfaileddefaultparams;
174
            $params['other']['reason'] = 'user_unconfirmed';
175
            $event = \core\event\webservice_login_failed::create($params);
176
            $event->add_record_snapshot('external_tokens', $token);
177
            $event->trigger();
178
            throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username);
179
        }
180
 
181
        //check the user is suspended
182
        if (!empty($user->suspended)) {
183
            $params = $loginfaileddefaultparams;
184
            $params['other']['reason'] = 'user_suspended';
185
            $event = \core\event\webservice_login_failed::create($params);
186
            $event->add_record_snapshot('external_tokens', $token);
187
            $event->trigger();
188
            throw new moodle_exception('wsaccessusersuspended', 'moodle', '', $user->username);
189
        }
190
 
191
        //check if the auth method is nologin (in this case refuse connection)
192
        if ($user->auth == 'nologin') {
193
            $params = $loginfaileddefaultparams;
194
            $params['other']['reason'] = 'nologin';
195
            $event = \core\event\webservice_login_failed::create($params);
196
            $event->add_record_snapshot('external_tokens', $token);
197
            $event->trigger();
198
            throw new moodle_exception('wsaccessusernologin', 'moodle', '', $user->username);
199
        }
200
 
201
        //Check if the user password is expired
202
        $auth = get_auth_plugin($user->auth);
203
        if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
204
            $days2expire = $auth->password_expire($user->username);
205
            if (intval($days2expire) < 0) {
206
                $params = $loginfaileddefaultparams;
207
                $params['other']['reason'] = 'password_expired';
208
                $event = \core\event\webservice_login_failed::create($params);
209
                $event->add_record_snapshot('external_tokens', $token);
210
                $event->trigger();
211
                throw new moodle_exception('passwordisexpired', 'webservice');
212
            }
213
        }
214
 
215
        // log token access
216
        self::update_token_lastaccess($token);
217
 
218
        return array('user' => $user, 'token' => $token, 'service' => $service);
219
    }
220
 
221
    /**
222
     * Updates the last access time for a token.
223
     *
224
     * @param \stdClass $token Token object (must include id, lastaccess fields)
225
     * @param int $time Time of access (0 = use current time)
226
     * @throws dml_exception If database error
227
     */
228
    public static function update_token_lastaccess($token, int $time = 0) {
229
        global $DB;
230
 
231
        if (!$time) {
232
            $time = time();
233
        }
234
 
235
        // Only update the field if it is a different time from previous request,
236
        // so as not to waste database effort.
237
        if ($time >= $token->lastaccess + self::TOKEN_LASTACCESS_UPDATE_SECS) {
238
            $DB->set_field('external_tokens', 'lastaccess', $time, array('id' => $token->id));
239
        }
240
    }
241
 
242
    /**
243
     * Allow user to call a service
244
     *
245
     * @param stdClass $user a user
246
     */
247
    public function add_ws_authorised_user($user) {
248
        global $DB;
249
        $user->timecreated = time();
250
        $DB->insert_record('external_services_users', $user);
251
    }
252
 
253
    /**
254
     * Disallow a user to call a service
255
     *
256
     * @param stdClass $user a user
257
     * @param int $serviceid
258
     */
259
    public function remove_ws_authorised_user($user, $serviceid) {
260
        global $DB;
261
        $DB->delete_records('external_services_users',
262
                array('externalserviceid' => $serviceid, 'userid' => $user->id));
263
    }
264
 
265
    /**
266
     * Update allowed user settings (ip restriction, valid until...)
267
     *
268
     * @param stdClass $user
269
     */
270
    public function update_ws_authorised_user($user) {
271
        global $DB;
272
        $DB->update_record('external_services_users', $user);
273
    }
274
 
275
    /**
276
     * Return list of allowed users with their options (ip/timecreated / validuntil...)
277
     * for a given service
278
     *
279
     * @param int $serviceid the service id to search against
280
     * @return array $users
281
     */
282
    public function get_ws_authorised_users($serviceid) {
283
        global $DB, $CFG;
284
 
285
        $params = array($CFG->siteguest, $serviceid);
286
 
287
        $userfields = \core_user\fields::for_identity(context_system::instance())->with_name()->excluding('id');
288
        $fieldsql = $userfields->get_sql('u');
289
 
290
        $sql = " SELECT u.id as id, esu.id as serviceuserid {$fieldsql->selects},
291
                        esu.iprestriction as iprestriction, esu.validuntil as validuntil,
292
                        esu.timecreated as timecreated
293
                   FROM {user} u
294
                   JOIN {external_services_users} esu ON esu.userid = u.id
295
                        {$fieldsql->joins}
296
                  WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
297
                        AND esu.externalserviceid = ?";
298
 
299
        $users = $DB->get_records_sql($sql, array_merge($fieldsql->params, $params));
300
 
301
        return $users;
302
    }
303
 
304
    /**
305
     * Return an authorised user with their options (ip/timecreated / validuntil...)
306
     *
307
     * @param int $serviceid the service id to search against
308
     * @param int $userid the user to search against
309
     * @return stdClass
310
     */
311
    public function get_ws_authorised_user($serviceid, $userid) {
312
        global $DB, $CFG;
313
        $params = array($CFG->siteguest, $serviceid, $userid);
314
        $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
315
                        u.lastname as lastname,
316
                        esu.iprestriction as iprestriction, esu.validuntil as validuntil,
317
                        esu.timecreated as timecreated
318
                   FROM {user} u, {external_services_users} esu
319
                  WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
320
                        AND esu.userid = u.id
321
                        AND esu.externalserviceid = ?
322
                        AND u.id = ?";
323
        $user = $DB->get_record_sql($sql, $params);
324
        return $user;
325
    }
326
 
327
    /**
328
     * Generate all tokens of a specific user
329
     *
330
     * @param int $userid user id
331
     */
332
    public function generate_user_ws_tokens($userid) {
333
        global $CFG, $DB;
334
 
335
        // generate a token for non admin if web service are enable and the user has the capability to create a token
336
        if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', context_system::instance(), $userid) && !empty($CFG->enablewebservices)) {
337
            // for every service than the user is authorised on, create a token (if it doesn't already exist)
338
 
339
            // get all services which are set to all user (no restricted to specific users)
340
            $norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0));
341
            $serviceidlist = array();
342
            foreach ($norestrictedservices as $service) {
343
                $serviceidlist[] = $service->id;
344
            }
345
 
346
            // get all services which are set to the current user (the current user is specified in the restricted user list)
347
            $servicesusers = $DB->get_records('external_services_users', array('userid' => $userid));
348
            foreach ($servicesusers as $serviceuser) {
349
                if (!in_array($serviceuser->externalserviceid,$serviceidlist)) {
350
                     $serviceidlist[] = $serviceuser->externalserviceid;
351
                }
352
            }
353
 
354
            // get all services which already have a token set for the current user
355
            $usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
356
            $tokenizedservice = array();
357
            foreach ($usertokens as $token) {
358
                    $tokenizedservice[]  = $token->externalserviceid;
359
            }
360
 
361
            // create a token for the service which have no token already
362
            foreach ($serviceidlist as $serviceid) {
363
                if (!in_array($serviceid, $tokenizedservice)) {
364
                    // create the token for this service
365
                    $newtoken = new stdClass();
366
                    $newtoken->token = md5(uniqid(rand(),1));
367
                    // check that the user has capability on this service
368
                    $newtoken->tokentype = EXTERNAL_TOKEN_PERMANENT;
369
                    $newtoken->userid = $userid;
370
                    $newtoken->externalserviceid = $serviceid;
371
                    // TODO MDL-31190 find a way to get the context - UPDATE FOLLOWING LINE
372
                    $newtoken->contextid = context_system::instance()->id;
373
                    $newtoken->creatorid = $userid;
374
                    $newtoken->timecreated = time();
375
                    $newtoken->name = \core_external\util::generate_token_name();
376
                    // Generate the private token, it must be transmitted only via https.
377
                    $newtoken->privatetoken = random_string(64);
378
 
379
                    $DB->insert_record('external_tokens', $newtoken);
380
                }
381
            }
382
 
383
 
384
        }
385
    }
386
 
387
    /**
388
     * Return all tokens of a specific user
389
     * + the service state (enabled/disabled)
390
     * + the authorised user mode (restricted/not restricted)
391
     *
392
     * @param int $userid user id
393
     * @return array
394
     */
395
    public function get_user_ws_tokens($userid) {
396
        global $DB;
397
        //here retrieve token list (including linked users firstname/lastname and linked services name)
398
        $sql = "SELECT
399
                    t.id, t.creatorid, t.name as tokenname, u.firstname, u.lastname,
400
                    s.id as wsid, s.name as servicename, s.enabled, s.restrictedusers, t.validuntil, t.lastaccess
401
                FROM
402
                    {external_tokens} t, {user} u, {external_services} s
403
                WHERE
404
                    t.userid=? AND t.tokentype = ".EXTERNAL_TOKEN_PERMANENT." AND s.id = t.externalserviceid AND t.userid = u.id";
405
        $tokens = $DB->get_records_sql($sql, array( $userid));
406
        return $tokens;
407
    }
408
 
409
    /**
410
     * Return a token that has been created by the user (i.e. to created by an admin)
411
     * If no tokens exist an exception is thrown
412
     *
413
     * The returned value is a stdClass:
414
     * ->id token id
415
     * ->token
416
     * ->tokenname
417
     * ->firstname user firstname
418
     * ->lastname
419
     * ->externalserviceid
420
     * ->name service name
421
     *
422
     * @param int $userid user id
423
     * @param int $tokenid token id
424
     * @return stdClass
425
     */
426
    public function get_created_by_user_ws_token($userid, $tokenid) {
427
        global $DB;
428
        $sql = "SELECT
429
                        t.id, t.token, t.name AS tokenname, u.firstname, u.lastname, t.externalserviceid, s.name
430
                    FROM
431
                        {external_tokens} t, {user} u, {external_services} s
432
                    WHERE
433
                        t.creatorid=? AND t.id=? AND t.tokentype = "
434
                . EXTERNAL_TOKEN_PERMANENT
435
                . " AND s.id = t.externalserviceid AND t.userid = u.id";
436
        //must be the token creator
437
        $token = $DB->get_record_sql($sql, array($userid, $tokenid), MUST_EXIST);
438
        return $token;
439
    }
440
 
441
    /**
442
     * Return a token of an arbitrary user by tokenid, including details of the associated user and the service name.
443
     * If no tokens exist an exception is thrown
444
     *
445
     * The returned value is a stdClass:
446
     * ->id token id
447
     * ->token
448
     * ->firstname user firstname
449
     * ->lastname
450
     * ->name service name
451
     *
452
     * @param int $tokenid token id
453
     * @return stdClass
454
     */
455
    public function get_token_by_id_with_details($tokenid) {
456
        global $DB;
1441 ariadna 457
 
1 efrain 458
        $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.creatorid
1441 ariadna 459
                  FROM {external_tokens} t
460
             LEFT JOIN {user} u ON u.id = t.userid
461
             LEFT JOIN {external_services} s ON s.id = t.externalserviceid
462
                 WHERE t.id = ? AND t.tokentype = ?";
463
 
464
        return $DB->get_record_sql($sql, [$tokenid, EXTERNAL_TOKEN_PERMANENT], MUST_EXIST);
1 efrain 465
    }
466
 
467
    /**
468
     * Return a database token record for a token id
469
     *
470
     * @param int $tokenid token id
471
     * @return object token
472
     */
473
    public function get_token_by_id($tokenid) {
474
        global $DB;
475
        return $DB->get_record('external_tokens', array('id' => $tokenid));
476
    }
477
 
478
    /**
479
     * Delete a token
480
     *
481
     * @param int $tokenid token id
482
     */
483
    public function delete_user_ws_token($tokenid) {
484
        global $DB;
485
        $DB->delete_records('external_tokens', array('id'=>$tokenid));
486
    }
487
 
488
    /**
489
     * Delete all the tokens belonging to a user.
490
     *
491
     * @param int $userid the user id whose tokens must be deleted
492
     */
493
    public static function delete_user_ws_tokens($userid) {
494
        global $DB;
495
        $DB->delete_records('external_tokens', array('userid' => $userid));
496
    }
497
 
498
    /**
499
     * Delete a service
500
     * Also delete function references and authorised user references.
501
     *
502
     * @param int $serviceid service id
503
     */
504
    public function delete_service($serviceid) {
505
        global $DB;
506
        $DB->delete_records('external_services_users', array('externalserviceid' => $serviceid));
507
        $DB->delete_records('external_services_functions', array('externalserviceid' => $serviceid));
508
        $DB->delete_records('external_tokens', array('externalserviceid' => $serviceid));
509
        $DB->delete_records('external_services', array('id' => $serviceid));
510
    }
511
 
512
    /**
513
     * Get a full database token record for a given token value
514
     *
515
     * @param string $token
516
     * @throws moodle_exception if there is multiple result
517
     */
518
    public function get_user_ws_token($token) {
519
        global $DB;
520
        return $DB->get_record('external_tokens', array('token'=>$token), '*', MUST_EXIST);
521
    }
522
 
523
    /**
524
     * Get the functions list of a service list (by id)
525
     *
526
     * @param array $serviceids service ids
527
     * @return array of functions
528
     */
529
    public function get_external_functions($serviceids) {
530
        global $DB;
531
        if (!empty($serviceids)) {
532
            list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
533
            $sql = "SELECT f.*
534
                      FROM {external_functions} f
535
                     WHERE f.name IN (SELECT sf.functionname
536
                                        FROM {external_services_functions} sf
537
                                       WHERE sf.externalserviceid $serviceids)
538
                     ORDER BY f.name ASC";
539
            $functions = $DB->get_records_sql($sql, $params);
540
        } else {
541
            $functions = array();
542
        }
543
        return $functions;
544
    }
545
 
546
    /**
547
     * Get the functions of a service list (by shortname). It can return only enabled functions if required.
548
     *
549
     * @param array $serviceshortnames service shortnames
550
     * @param bool $enabledonly if true then only return functions for services that have been enabled
551
     * @return array functions
552
     */
553
    public function get_external_functions_by_enabled_services($serviceshortnames, $enabledonly = true) {
554
        global $DB;
555
        if (!empty($serviceshortnames)) {
556
            $enabledonlysql = $enabledonly?' AND s.enabled = 1 ':'';
557
            list($serviceshortnames, $params) = $DB->get_in_or_equal($serviceshortnames);
558
            $sql = "SELECT f.*
559
                      FROM {external_functions} f
560
                     WHERE f.name IN (SELECT sf.functionname
561
                                        FROM {external_services_functions} sf, {external_services} s
562
                                       WHERE s.shortname $serviceshortnames
563
                                             AND sf.externalserviceid = s.id
564
                                             " . $enabledonlysql . ")";
565
            $functions = $DB->get_records_sql($sql, $params);
566
        } else {
567
            $functions = array();
568
        }
569
        return $functions;
570
    }
571
 
572
    /**
573
     * Get functions not included in a service
574
     *
575
     * @param int $serviceid service id
576
     * @return array functions
577
     */
578
    public function get_not_associated_external_functions($serviceid) {
579
        global $DB;
580
        $select = "name NOT IN (SELECT s.functionname
581
                                  FROM {external_services_functions} s
582
                                 WHERE s.externalserviceid = :sid
583
                               )";
584
 
585
        $functions = $DB->get_records_select('external_functions',
586
                        $select, array('sid' => $serviceid), 'name');
587
 
588
        return $functions;
589
    }
590
 
591
    /**
592
     * Get list of required capabilities of a service, sorted by functions
593
     * Example of returned value:
594
     *  Array
595
     *  (
596
     *    [core_group_create_groups] => Array
597
     *    (
598
     *       [0] => moodle/course:managegroups
599
     *    )
600
     *
601
     *    [core_enrol_get_enrolled_users] => Array
602
     *    (
603
     *       [0] => moodle/user:viewdetails
604
     *       [1] => moodle/user:viewhiddendetails
605
     *       [2] => moodle/course:useremail
606
     *       [3] => moodle/user:update
607
     *       [4] => moodle/site:accessallgroups
608
     *    )
609
     *  )
610
     * @param int $serviceid service id
611
     * @return array
612
     */
613
    public function get_service_required_capabilities($serviceid) {
614
        $functions = $this->get_external_functions(array($serviceid));
615
        $requiredusercaps = array();
616
        foreach ($functions as $function) {
617
            $functioncaps = explode(',', $function->capabilities);
618
            if (!empty($functioncaps) and !empty($functioncaps[0])) {
619
                foreach ($functioncaps as $functioncap) {
620
                    $requiredusercaps[$function->name][] = trim($functioncap);
621
                }
622
            }
623
        }
624
        return $requiredusercaps;
625
    }
626
 
627
    /**
628
     * Get user capabilities (with context)
629
     * Only useful for documentation purpose
630
     * WARNING: do not use this "broken" function. It was created in the goal to display some capabilities
631
     * required by users. In theory we should not need to display this kind of information
632
     * as the front end does not display it itself. In pratice,
633
     * admins would like the info, for more info you can follow: MDL-29962
634
     *
635
     * @deprecated since Moodle 3.11 in MDL-67748 without a replacement.
636
     * @todo MDL-70187 Please delete this method completely in Moodle 4.3, thank you.
637
     * @param int $userid user id
638
     * @return array
639
     */
640
    public function get_user_capabilities($userid) {
641
        global $DB;
642
 
643
        debugging('webservice::get_user_capabilities() has been deprecated.', DEBUG_DEVELOPER);
644
 
645
        //retrieve the user capabilities
646
        $sql = "SELECT DISTINCT rc.id, rc.capability FROM {role_capabilities} rc, {role_assignments} ra
647
            WHERE rc.roleid=ra.roleid AND ra.userid= ? AND rc.permission = ?";
648
        $dbusercaps = $DB->get_records_sql($sql, array($userid, CAP_ALLOW));
649
        $usercaps = array();
650
        foreach ($dbusercaps as $usercap) {
651
            $usercaps[$usercap->capability] = true;
652
        }
653
        return $usercaps;
654
    }
655
 
656
    /**
657
     * Get missing user capabilities for the given service's functions.
658
     *
659
     * Every external function can declare some required capabilities to allow for easier setup of the web services.
660
     * However, that is supposed to be used for informational admin report only. There is no automatic evaluation of
661
     * the declared capabilities and the context of the capability evaluation is ignored. Also, actual capability
662
     * evaluation is much more complex as it allows for overrides etc.
663
     *
664
     * Returned are capabilities that the given users do not seem to have assigned anywhere at the site and that should
665
     * be checked by the admin.
666
     *
667
     * Do not use this method for anything else, particularly not for any security related checks. See MDL-29962 for the
668
     * background of why we have this - there are arguments for dropping this feature completely.
669
     *
670
     * @param array $users List of users to check, consisting of objects, arrays or integer ids.
671
     * @param int $serviceid The id of the external service to check.
672
     * @return array List of missing capabilities: (int)userid => array of (string)capabilitynames
673
     */
674
    public function get_missing_capabilities_by_users(array $users, int $serviceid): array {
675
        global $DB;
676
 
677
        // The following are default capabilities for all authenticated users and we will assume them granted.
678
        $commoncaps = get_default_capabilities('user');
679
 
680
        // Get the list of additional capabilities required by the service.
681
        $servicecaps = [];
682
        foreach ($this->get_service_required_capabilities($serviceid) as $service => $caps) {
683
            foreach ($caps as $cap) {
684
                if (empty($commoncaps[$cap])) {
685
                    $servicecaps[$cap] = true;
686
                }
687
            }
688
        }
689
 
690
        // Bail out early if there's nothing to process.
691
        if (empty($users) || empty($servicecaps)) {
692
            return [];
693
        }
694
 
695
        // Prepare a list of user ids we want to check.
696
        $userids = [];
697
        foreach ($users as $user) {
698
            if (is_object($user) && isset($user->id)) {
699
                $userids[$user->id] = true;
700
            } else if (is_array($user) && isset($user['id'])) {
701
                $userids[$user['id']] = true;
702
            } else {
703
                throw new coding_exception('Unexpected format of users list in webservice::get_missing_capabilities_by_users().');
704
            }
705
        }
706
 
707
        // Prepare a matrix of missing capabilities x users - consider them all missing by default.
708
        foreach (array_keys($userids) as $userid) {
709
            foreach (array_keys($servicecaps) as $capname) {
710
                $matrix[$userid][$capname] = true;
711
            }
712
        }
713
 
714
        list($capsql, $capparams) = $DB->get_in_or_equal(array_keys($servicecaps), SQL_PARAMS_NAMED, 'paramcap');
715
        list($usersql, $userparams) = $DB->get_in_or_equal(array_keys($userids), SQL_PARAMS_NAMED, 'paramuser');
716
 
717
        $sql = "SELECT c.name AS capability, u.id AS userid
718
                  FROM {capabilities} c
719
                  JOIN {role_capabilities} rc ON c.name = rc.capability
720
                  JOIN {role_assignments} ra ON ra.roleid = rc.roleid
721
                  JOIN {user} u ON ra.userid = u.id
722
                 WHERE rc.permission = :capallow
723
                   AND c.name {$capsql}
724
                   AND u.id {$usersql}";
725
 
726
        $params = $capparams + $userparams + [
727
            'capallow' => CAP_ALLOW,
728
        ];
729
 
730
        $rs = $DB->get_recordset_sql($sql, $params);
731
 
732
        foreach ($rs as $record) {
733
            // If there was a potential role assignment found that might grant the user the given capability,
734
            // remove it from the matrix. Again, we ignore all the contexts, prohibits, prevents and other details
735
            // of the permissions evaluations. See the function docblock for details.
736
            unset($matrix[$record->userid][$record->capability]);
737
        }
738
 
739
        $rs->close();
740
 
741
        foreach ($matrix as $userid => $caps) {
742
            $matrix[$userid] = array_keys($caps);
743
            if (empty($matrix[$userid])) {
744
                unset($matrix[$userid]);
745
            }
746
        }
747
 
748
        return $matrix;
749
    }
750
 
751
    /**
752
     * Get an external service for a given service id
753
     *
754
     * @param int $serviceid service id
755
     * @param int $strictness IGNORE_MISSING, MUST_EXIST...
756
     * @return stdClass external service
757
     */
758
    public function get_external_service_by_id($serviceid, $strictness=IGNORE_MISSING) {
759
        global $DB;
760
        $service = $DB->get_record('external_services',
761
                        array('id' => $serviceid), '*', $strictness);
762
        return $service;
763
    }
764
 
765
    /**
766
     * Get an external service for a given shortname
767
     *
768
     * @param string $shortname service shortname
769
     * @param int $strictness IGNORE_MISSING, MUST_EXIST...
770
     * @return stdClass external service
771
     */
772
    public function get_external_service_by_shortname($shortname, $strictness=IGNORE_MISSING) {
773
        global $DB;
774
        $service = $DB->get_record('external_services',
775
                        array('shortname' => $shortname), '*', $strictness);
776
        return $service;
777
    }
778
 
779
    /**
780
     * Get an external function for a given function id
781
     *
782
     * @param int $functionid function id
783
     * @param int $strictness IGNORE_MISSING, MUST_EXIST...
784
     * @return stdClass external function
785
     */
786
    public function get_external_function_by_id($functionid, $strictness=IGNORE_MISSING) {
787
        global $DB;
788
        $function = $DB->get_record('external_functions',
789
                            array('id' => $functionid), '*', $strictness);
790
        return $function;
791
    }
792
 
793
    /**
794
     * Add a function to a service
795
     *
796
     * @param string $functionname function name
797
     * @param int $serviceid service id
798
     */
799
    public function add_external_function_to_service($functionname, $serviceid) {
800
        global $DB;
801
        $addedfunction = new stdClass();
802
        $addedfunction->externalserviceid = $serviceid;
803
        $addedfunction->functionname = $functionname;
804
        $DB->insert_record('external_services_functions', $addedfunction);
805
    }
806
 
807
    /**
808
     * Add a service
809
     * It generates the timecreated field automatically.
810
     *
811
     * @param stdClass $service
812
     * @return serviceid integer
813
     */
814
    public function add_external_service($service) {
815
        global $DB;
816
        $service->timecreated = time();
817
        $serviceid = $DB->insert_record('external_services', $service);
818
        return $serviceid;
819
    }
820
 
821
    /**
822
     * Update a service
823
     * It modifies the timemodified automatically.
824
     *
825
     * @param stdClass $service
826
     */
827
    public function update_external_service($service) {
828
        global $DB;
829
        $service->timemodified = time();
830
        $DB->update_record('external_services', $service);
831
    }
832
 
833
    /**
834
     * Test whether an external function is already linked to a service
835
     *
836
     * @param string $functionname function name
837
     * @param int $serviceid service id
838
     * @return bool true if a matching function exists for the service, else false.
839
     * @throws dml_exception if error
840
     */
841
    public function service_function_exists($functionname, $serviceid) {
842
        global $DB;
843
        return $DB->record_exists('external_services_functions',
844
                            array('externalserviceid' => $serviceid,
845
                                'functionname' => $functionname));
846
    }
847
 
848
    /**
849
     * Remove a function from a service
850
     *
851
     * @param string $functionname function name
852
     * @param int $serviceid service id
853
     */
854
    public function remove_external_function_from_service($functionname, $serviceid) {
855
        global $DB;
856
        $DB->delete_records('external_services_functions',
857
                    array('externalserviceid' => $serviceid, 'functionname' => $functionname));
858
 
859
    }
860
 
861
    /**
862
     * Return a list with all the valid user tokens for the given user, it only excludes expired tokens.
863
     *
864
     * @param  string $userid user id to retrieve tokens from
865
     * @return array array of token entries
866
     * @since Moodle 3.2
867
     */
868
    public static function get_active_tokens($userid) {
869
        global $DB;
870
 
871
        $sql = 'SELECT t.id, t.creatorid, t.externalserviceid, t.name AS tokenname, t.validuntil, s.name AS servicename
872
                  FROM {external_tokens} t
873
                  JOIN {external_services} s ON t.externalserviceid = s.id
874
                 WHERE t.userid = :userid AND (COALESCE(t.validuntil, 0) = 0 OR t.validuntil > :now)';
875
        $params = array('userid' => $userid, 'now' => time());
876
        return $DB->get_records_sql($sql, $params);
877
    }
878
}
879
 
880
/**
881
 * Exception indicating access control problem in web service call
882
 * This exception should return general errors about web service setup.
883
 * Errors related to the user like wrong username/password should not use it,
884
 * you should not use this exception if you want to let the client implement
885
 * some code logic against an access error.
886
 *
887
 * @package    core_webservice
888
 * @copyright  2009 Petr Skodak
889
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
890
 */
891
class webservice_access_exception extends moodle_exception {
892
 
893
    /**
894
     * Constructor
895
     *
896
     * @param string $debuginfo the debug info
897
     */
898
    function __construct($debuginfo) {
899
        parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
900
    }
901
}
902
 
903
/**
904
 * Check if a protocol is enabled
905
 *
906
 * @param string $protocol name of WS protocol ('rest', 'soap', ...)
907
 * @return bool true if the protocol is enabled
908
 */
909
function webservice_protocol_is_enabled($protocol) {
910
    global $CFG;
911
 
912
    if (empty($CFG->enablewebservices) || empty($CFG->webserviceprotocols)) {
913
        return false;
914
    }
915
 
916
    $active = explode(',', $CFG->webserviceprotocols);
917
 
918
    return(in_array($protocol, $active));
919
}
920
 
921
/**
922
 * Mandatory interface for all test client classes.
923
 *
924
 * @package    core_webservice
925
 * @copyright  2009 Petr Skodak
926
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
927
 */
928
interface webservice_test_client_interface {
929
 
930
    /**
931
     * Execute test client WS request
932
     *
933
     * @param string $serverurl server url (including the token param)
934
     * @param string $function web service function name
935
     * @param array $params parameters of the web service function
936
     * @return mixed
937
     */
938
    public function simpletest($serverurl, $function, $params);
939
}
940
 
941
/**
942
 * Mandatory interface for all web service protocol classes
943
 *
944
 * @package    core_webservice
945
 * @copyright  2009 Petr Skodak
946
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
947
 */
948
interface webservice_server_interface {
949
 
950
    /**
951
     * Process request from client.
952
     */
953
    public function run();
954
}
955
 
956
/**
957
 * Abstract web service base class.
958
 *
959
 * @package    core_webservice
960
 * @copyright  2009 Petr Skodak
961
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
962
 */
963
abstract class webservice_server implements webservice_server_interface {
964
 
965
    /** @var string Name of the web server plugin */
966
    protected $wsname = null;
967
 
968
    /** @var string Name of local user */
969
    protected $username = null;
970
 
971
    /** @var string Password of the local user */
972
    protected $password = null;
973
 
974
    /** @var int The local user */
975
    protected $userid = null;
976
 
977
    /** @var integer Authentication method one of WEBSERVICE_AUTHMETHOD_* */
978
    protected $authmethod;
979
 
980
    /** @var string Authentication token*/
981
    protected $token = null;
982
 
983
    /** @var stdClass Restricted context */
984
    protected $restricted_context;
985
 
986
    /** @var int Restrict call to one service id*/
987
    protected $restricted_serviceid = null;
988
 
989
    /**
990
     * Constructor
991
     *
992
     * @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
993
     */
994
    public function __construct($authmethod) {
995
        $this->authmethod = $authmethod;
996
    }
997
 
998
 
999
    /**
1000
     * Authenticate user using username+password or token.
1001
     * This function sets up $USER global.
1002
     * It is safe to use has_capability() after this.
1003
     * This method also verifies user is allowed to use this
1004
     * server.
1005
     */
1006
    protected function authenticate_user() {
1007
        global $CFG, $DB;
1008
 
1009
        if (!NO_MOODLE_COOKIES) {
1010
            throw new coding_exception('Cookies must be disabled in WS servers!');
1011
        }
1012
 
1013
        $loginfaileddefaultparams = array(
1014
            'other' => array(
1015
                'method' => $this->authmethod,
1016
                'reason' => null
1017
            )
1018
        );
1019
 
1020
        if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1021
 
1022
            //we check that authentication plugin is enabled
1023
            //it is only required by simple authentication
1024
            if (!is_enabled_auth('webservice')) {
1025
                throw new webservice_access_exception('The web service authentication plugin is disabled.');
1026
            }
1027
 
1028
            if (!$auth = get_auth_plugin('webservice')) {
1029
                throw new webservice_access_exception('The web service authentication plugin is missing.');
1030
            }
1031
 
1032
            $this->restricted_context = context_system::instance();
1033
 
1034
            if (!$this->username) {
1035
                throw new moodle_exception('missingusername', 'webservice');
1036
            }
1037
 
1038
            if (!$this->password) {
1039
                throw new moodle_exception('missingpassword', 'webservice');
1040
            }
1041
 
1042
            if (!$auth->user_login_webservice($this->username, $this->password)) {
1043
 
1044
                // Log failed login attempts.
1045
                $params = $loginfaileddefaultparams;
1046
                $params['other']['reason'] = 'password';
1047
                $params['other']['username'] = $this->username;
1048
                $event = \core\event\webservice_login_failed::create($params);
1049
                $event->trigger();
1050
 
1051
                throw new moodle_exception('wrongusernamepassword', 'webservice');
1052
            }
1053
 
1054
            $user = $DB->get_record('user', array('username'=>$this->username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
1055
 
1056
        } else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN){
1057
            $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
1058
        } else {
1059
            $user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED);
1060
        }
1061
 
1062
        // Cannot authenticate unless maintenance access is granted.
1063
        $hasmaintenanceaccess = has_capability('moodle/site:maintenanceaccess', context_system::instance(), $user);
1064
        if (!empty($CFG->maintenance_enabled) and !$hasmaintenanceaccess) {
1065
            throw new moodle_exception('sitemaintenance', 'admin');
1066
        }
1067
 
1068
        //only confirmed user should be able to call web service
1069
        if (!empty($user->deleted)) {
1070
            $params = $loginfaileddefaultparams;
1071
            $params['other']['reason'] = 'user_deleted';
1072
            $params['other']['username'] = $user->username;
1073
            $event = \core\event\webservice_login_failed::create($params);
1074
            $event->trigger();
1075
            throw new moodle_exception('wsaccessuserdeleted', 'webservice', '', $user->username);
1076
        }
1077
 
1078
        //only confirmed user should be able to call web service
1079
        if (empty($user->confirmed)) {
1080
            $params = $loginfaileddefaultparams;
1081
            $params['other']['reason'] = 'user_unconfirmed';
1082
            $params['other']['username'] = $user->username;
1083
            $event = \core\event\webservice_login_failed::create($params);
1084
            $event->trigger();
1085
            throw new moodle_exception('wsaccessuserunconfirmed', 'webservice', '', $user->username);
1086
        }
1087
 
1088
        //check the user is suspended
1089
        if (!empty($user->suspended)) {
1090
            $params = $loginfaileddefaultparams;
1091
            $params['other']['reason'] = 'user_unconfirmed';
1092
            $params['other']['username'] = $user->username;
1093
            $event = \core\event\webservice_login_failed::create($params);
1094
            $event->trigger();
1095
            throw new moodle_exception('wsaccessusersuspended', 'webservice', '', $user->username);
1096
        }
1097
 
1098
        //retrieve the authentication plugin if no previously done
1099
        if (empty($auth)) {
1100
          $auth  = get_auth_plugin($user->auth);
1101
        }
1102
 
1103
        // check if credentials have expired
1104
        if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
1105
            $days2expire = $auth->password_expire($user->username);
1106
            if (intval($days2expire) < 0 ) {
1107
                $params = $loginfaileddefaultparams;
1108
                $params['other']['reason'] = 'password_expired';
1109
                $params['other']['username'] = $user->username;
1110
                $event = \core\event\webservice_login_failed::create($params);
1111
                $event->trigger();
1112
                throw new moodle_exception('wsaccessuserexpired', 'webservice', '', $user->username);
1113
            }
1114
        }
1115
 
1116
        //check if the auth method is nologin (in this case refuse connection)
1117
        if ($user->auth=='nologin') {
1118
            $params = $loginfaileddefaultparams;
1119
            $params['other']['reason'] = 'login';
1120
            $params['other']['username'] = $user->username;
1121
            $event = \core\event\webservice_login_failed::create($params);
1122
            $event->trigger();
1123
            throw new moodle_exception('wsaccessusernologin', 'webservice', '', $user->username);
1124
        }
1125
 
1126
        // now fake user login, the session is completely empty too
1127
        enrol_check_plugins($user, false);
1128
        \core\session\manager::set_user($user);
1129
        set_login_session_preferences();
1130
        $this->userid = $user->id;
1131
 
1132
        if ($this->authmethod != WEBSERVICE_AUTHMETHOD_SESSION_TOKEN && !has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
1133
            throw new webservice_access_exception("You are not allowed to use the {$this->wsname} protocol " .
1134
                "(missing capability: webservice/{$this->wsname}:use)");
1135
        }
1136
 
1137
        external_api::set_context_restriction($this->restricted_context);
1138
    }
1139
 
1140
    /**
1141
     * User authentication by token
1142
     *
1143
     * @param string $tokentype token type (EXTERNAL_TOKEN_EMBEDDED or EXTERNAL_TOKEN_PERMANENT)
1144
     * @return stdClass the authenticated user
1145
     * @throws webservice_access_exception
1146
     */
1147
    protected function authenticate_by_token($tokentype){
1148
        global $DB;
1149
 
1150
        $loginfaileddefaultparams = array(
1151
            'other' => array(
1152
                'method' => $this->authmethod,
1153
                'reason' => null
1154
            )
1155
        );
1156
 
1157
        if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype))) {
1158
            // Log failed login attempts.
1159
            $params = $loginfaileddefaultparams;
1160
            $params['other']['reason'] = 'invalid_token';
1161
            $event = \core\event\webservice_login_failed::create($params);
1162
            $event->trigger();
1163
            throw new moodle_exception('invalidtoken', 'webservice');
1164
        }
1165
 
1166
        if ($token->validuntil and $token->validuntil < time()) {
1167
            $DB->delete_records('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype));
1168
            throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
1169
        }
1170
 
1171
        if ($token->sid){//assumes that if sid is set then there must be a valid associated session no matter the token type
1172
            if (!\core\session\manager::session_exists($token->sid)){
1173
                $DB->delete_records('external_tokens', array('sid'=>$token->sid));
1174
                throw new webservice_access_exception('Invalid session based token - session not found or expired');
1175
            }
1176
        }
1177
 
1178
        if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
1179
            $params = $loginfaileddefaultparams;
1180
            $params['other']['reason'] = 'ip_restricted';
1181
            $params['other']['tokenid'] = $token->id;
1182
            $event = \core\event\webservice_login_failed::create($params);
1183
            $event->add_record_snapshot('external_tokens', $token);
1184
            $event->trigger();
1185
            throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
1186
                    . ' is not supported - check this allowed user');
1187
        }
1188
 
1189
        $this->restricted_context = context::instance_by_id($token->contextid);
1190
        $this->restricted_serviceid = $token->externalserviceid;
1191
 
1192
        $user = $DB->get_record('user', array('id'=>$token->userid), '*', MUST_EXIST);
1193
 
1194
        // log token access
1195
        webservice::update_token_lastaccess($token);
1196
 
1197
        return $user;
1198
 
1199
    }
1200
 
1201
    /**
1202
     * Intercept some moodlewssettingXXX $_GET and $_POST parameter
1203
     * that are related to the web service call and are not the function parameters
1204
     */
1205
    protected function set_web_service_call_settings() {
1206
        global $CFG;
1207
 
1208
        // Default web service settings.
1209
        // Must be the same XXX key name as the external_settings::set_XXX function.
1210
        // Must be the same XXX ws parameter name as 'moodlewssettingXXX'.
1211
        $externalsettings = array(
1212
            'raw' => array('default' => false, 'type' => PARAM_BOOL),
1213
            'fileurl' => array('default' => true, 'type' => PARAM_BOOL),
1214
            'filter' => array('default' => false, 'type' => PARAM_BOOL),
1215
            'lang' => array('default' => '', 'type' => PARAM_LANG),
1216
            'timezone' => array('default' => '', 'type' => PARAM_TIMEZONE),
1217
        );
1218
 
1219
        // Load the external settings with the web service settings.
1220
        $settings = external_settings::get_instance();
1221
        foreach ($externalsettings as $name => $settingdata) {
1222
 
1223
            $wsparamname = 'moodlewssetting' . $name;
1224
 
1225
            // Retrieve and remove the setting parameter from the request.
1226
            $value = optional_param($wsparamname, $settingdata['default'], $settingdata['type']);
1227
            unset($_GET[$wsparamname]);
1228
            unset($_POST[$wsparamname]);
1229
 
1230
            $functioname = 'set_' . $name;
1231
            $settings->$functioname($value);
1232
        }
1233
 
1234
    }
1235
}
1236
 
1237
/**
1238
 * Web Service server base class.
1239
 *
1240
 * This class handles both simple and token authentication.
1241
 *
1242
 * @package    core_webservice
1243
 * @copyright  2009 Petr Skodak
1244
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1245
 */
1246
abstract class webservice_base_server extends webservice_server {
1247
 
1248
    /** @var array The function parameters - the real values submitted in the request */
1249
    protected $parameters = null;
1250
 
1251
    /** @var string The name of the function that is executed */
1252
    protected $functionname = null;
1253
 
1254
    /** @var stdClass Full function description */
1255
    protected $function = null;
1256
 
1257
    /** @var mixed Function return value */
1258
    protected $returns = null;
1259
 
1260
    /** @var array List of methods and their information provided by the web service. */
1261
    protected $servicemethods;
1262
 
1263
    /** @var  array List of struct classes generated for the web service methods. */
1264
    protected $servicestructs;
1265
 
1266
    /** @var string service class name. */
1267
    protected $serviceclass;
1268
 
1269
    /**
1270
     * This method parses the request input, it needs to get:
1271
     *  1/ user authentication - username+password or token
1272
     *  2/ function name
1273
     *  3/ function parameters
1274
     */
1275
    abstract protected function parse_request();
1276
 
1277
    /**
1278
     * Send the result of function call to the WS client.
1279
     */
1280
    abstract protected function send_response();
1281
 
1282
    /**
1283
     * Send the error information to the WS client.
1284
     *
1285
     * @param exception $ex
1286
     */
1287
    abstract protected function send_error($ex=null);
1288
 
1289
    /**
1290
     * Process request from client.
1291
     *
1292
     * @uses die
1293
     */
1294
    public function run() {
1295
        global $CFG, $USER, $SESSION;
1296
 
1297
        // we will probably need a lot of memory in some functions
1298
        raise_memory_limit(MEMORY_EXTRA);
1299
 
1300
        // set some longer timeout, this script is not sending any output,
1301
        // this means we need to manually extend the timeout operations
1302
        // that need longer time to finish
1303
        external_api::set_timeout();
1304
 
1305
        // set up exception handler first, we want to sent them back in correct format that
1306
        // the other system understands
1307
        // we do not need to call the original default handler because this ws handler does everything
1308
        set_exception_handler(array($this, 'exception_handler'));
1309
 
1310
        // init all properties from the request data
1311
        $this->parse_request();
1312
 
1313
        // authenticate user, this has to be done after the request parsing
1314
        // this also sets up $USER and $SESSION
1315
        $this->authenticate_user();
1316
 
1317
        // find all needed function info and make sure user may actually execute the function
1318
        $this->load_function_info();
1319
 
1320
        // Log the web service request.
1321
        $params = array(
1322
            'other' => array(
1323
                'function' => $this->functionname
1324
            )
1325
        );
1326
        $event = \core\event\webservice_function_called::create($params);
1327
        $event->trigger();
1328
 
1329
        // Do additional setup stuff.
1330
        $settings = external_settings::get_instance();
1331
        $sessionlang = $settings->get_lang();
1332
        if (!empty($sessionlang)) {
1333
            $SESSION->lang = $sessionlang;
1334
        }
1335
 
1336
        setup_lang_from_browser();
1337
 
1338
        if (empty($CFG->lang)) {
1339
            if (empty($SESSION->lang)) {
1340
                $CFG->lang = 'en';
1341
            } else {
1342
                $CFG->lang = $SESSION->lang;
1343
            }
1344
        }
1345
 
1346
        // Change timezone only in sites where it isn't forced.
1347
        $newtimezone = $settings->get_timezone();
1348
        if (!empty($newtimezone) && (!isset($CFG->forcetimezone) || $CFG->forcetimezone == 99)) {
1349
            $USER->timezone = $newtimezone;
1350
        }
1351
 
1352
        // finally, execute the function - any errors are catched by the default exception handler
1353
        $this->execute();
1354
 
1355
        // send the results back in correct format
1356
        $this->send_response();
1357
 
1358
        // session cleanup
1359
        $this->session_cleanup();
1360
 
1361
        die;
1362
    }
1363
 
1364
    /**
1365
     * Specialised exception handler, we can not use the standard one because
1366
     * it can not just print html to output.
1367
     *
1368
     * @param exception $ex
1369
     * $uses exit
1370
     */
1371
    public function exception_handler($ex) {
1372
        // detect active db transactions, rollback and log as error
1373
        abort_all_db_transactions();
1374
 
1375
        // some hacks might need a cleanup hook
1376
        $this->session_cleanup($ex);
1377
 
1378
        // now let the plugin send the exception to client
1379
        $this->send_error($ex);
1380
 
1381
        // not much else we can do now, add some logging later
1382
        exit(1);
1383
    }
1384
 
1385
    /**
1386
     * Future hook needed for emulated sessions.
1387
     *
1388
     * @param exception $exception null means normal termination, $exception received when WS call failed
1389
     */
1390
    protected function session_cleanup($exception=null) {
1391
        if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1392
            // nothing needs to be done, there is no persistent session
1393
        } else {
1394
            // close emulated session if used
1395
        }
1396
    }
1397
 
1398
    /**
1399
     * Fetches the function description from database,
1400
     * verifies user is allowed to use this function and
1401
     * loads all paremeters and return descriptions.
1402
     */
1403
    protected function load_function_info() {
1404
        global $DB, $USER, $CFG;
1405
 
1406
        if (empty($this->functionname)) {
1407
            throw new invalid_parameter_exception('Missing function name');
1408
        }
1409
 
1410
        // function must exist
1411
        $function = external_api::external_function_info($this->functionname);
1412
 
1413
        if ($this->restricted_serviceid) {
1414
            $params = array('sid1'=>$this->restricted_serviceid, 'sid2'=>$this->restricted_serviceid);
1415
            $wscond1 = 'AND s.id = :sid1';
1416
            $wscond2 = 'AND s.id = :sid2';
1417
        } else {
1418
            $params = array();
1419
            $wscond1 = '';
1420
            $wscond2 = '';
1421
        }
1422
 
1423
        // now let's verify access control
1424
 
1425
        // now make sure the function is listed in at least one service user is allowed to use
1426
        // allow access only if:
1427
        //  1/ entry in the external_services_users table if required
1428
        //  2/ validuntil not reached
1429
        //  3/ has capability if specified in service desc
1430
        //  4/ iprestriction
1431
 
1432
        $sql = "SELECT s.*, NULL AS iprestriction
1433
                  FROM {external_services} s
1434
                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0 AND sf.functionname = :name1)
1435
                 WHERE s.enabled = 1 $wscond1
1436
 
1437
                 UNION
1438
 
1439
                SELECT s.*, su.iprestriction
1440
                  FROM {external_services} s
1441
                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1 AND sf.functionname = :name2)
1442
                  JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1443
                 WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2";
1444
        $params = array_merge($params, array('userid'=>$USER->id, 'name1'=>$function->name, 'name2'=>$function->name, 'now'=>time()));
1445
 
1446
        $rs = $DB->get_recordset_sql($sql, $params);
1447
        // now make sure user may access at least one service
1448
        $remoteaddr = getremoteaddr();
1449
        $allowed = false;
1450
        foreach ($rs as $service) {
1451
            if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
1452
                continue; // cap required, sorry
1453
            }
1454
            if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
1455
                continue; // wrong request source ip, sorry
1456
            }
1457
            $allowed = true;
1458
            break; // one service is enough, no need to continue
1459
        }
1460
        $rs->close();
1461
        if (!$allowed) {
1462
            throw new webservice_access_exception(
1463
                    'Access to the function '.$this->functionname.'() is not allowed.
1464
                     There could be multiple reasons for this:
1465
                     1. The service linked to the user token does not contain the function.
1466
                     2. The service is user-restricted and the user is not listed.
1467
                     3. The service is IP-restricted and the user IP is not listed.
1468
                     4. The service is time-restricted and the time has expired.
1469
                     5. The token is time-restricted and the time has expired.
1470
                     6. The service requires a specific capability which the user does not have.
1471
                     7. The function is called with username/password (no user token is sent)
1472
                     and none of the services has the function to allow the user.
1473
                     These settings can be found in Administration > Site administration
1474
                     > Server > Web services > External services and Manage tokens.');
1475
        }
1476
 
1477
        // we have all we need now
1478
        $this->function = $function;
1479
    }
1480
 
1481
    /**
1482
     * Execute previously loaded function using parameters parsed from the request data.
1483
     */
1484
    protected function execute() {
1485
        // validate params, this also sorts the params properly, we need the correct order in the next part
1486
        $params = call_user_func(array($this->function->classname, 'validate_parameters'), $this->function->parameters_desc, $this->parameters);
1487
        $params = array_values($params);
1488
 
1489
        // Allow any Moodle plugin a chance to override this call. This is a convenient spot to
1490
        // make arbitrary behaviour customisations, for example to affect the mobile app behaviour.
1491
        // The overriding plugin could call the 'real' function first and then modify the results,
1492
        // or it could do a completely separate thing.
1493
        $callbacks = get_plugins_with_function('override_webservice_execution');
1494
        foreach ($callbacks as $plugintype => $plugins) {
1495
            foreach ($plugins as $plugin => $callback) {
1496
                $result = $callback($this->function, $params);
1497
                if ($result !== false) {
1498
                    // If the callback returns anything other than false, we assume it replaces the
1499
                    // real function.
1500
                    $this->returns = $result;
1501
                    return;
1502
                }
1503
            }
1504
        }
1505
 
1506
        // execute - yay!
1507
        $this->returns = call_user_func_array(array($this->function->classname, $this->function->methodname), $params);
1508
    }
1509
 
1510
    /**
1511
     * Load the virtual class needed for the web service.
1512
     *
1513
     * Initialises the virtual class that contains the web service functions that the user is allowed to use.
1514
     * The web service function will be available if the user:
1515
     * - is validly registered in the external_services_users table.
1516
     * - has the required capability.
1517
     * - meets the IP restriction requirement.
1518
     * This virtual class can be used by web service protocols such as SOAP, especially when generating WSDL.
1519
     */
1520
    protected function init_service_class() {
1521
        global $USER, $DB;
1522
 
1523
        // Initialise service methods and struct classes.
1524
        $this->servicemethods = array();
1525
        $this->servicestructs = array();
1526
 
1527
        $params = array();
1528
        $wscond1 = '';
1529
        $wscond2 = '';
1530
        if ($this->restricted_serviceid) {
1531
            $params = array('sid1' => $this->restricted_serviceid, 'sid2' => $this->restricted_serviceid);
1532
            $wscond1 = 'AND s.id = :sid1';
1533
            $wscond2 = 'AND s.id = :sid2';
1534
        }
1535
 
1536
        $sql = "SELECT s.*, NULL AS iprestriction
1537
                  FROM {external_services} s
1538
                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 0)
1539
                 WHERE s.enabled = 1 $wscond1
1540
 
1541
                 UNION
1542
 
1543
                SELECT s.*, su.iprestriction
1544
                  FROM {external_services} s
1545
                  JOIN {external_services_functions} sf ON (sf.externalserviceid = s.id AND s.restrictedusers = 1)
1546
                  JOIN {external_services_users} su ON (su.externalserviceid = s.id AND su.userid = :userid)
1547
                 WHERE s.enabled = 1 AND (su.validuntil IS NULL OR su.validuntil < :now) $wscond2";
1548
        $params = array_merge($params, array('userid' => $USER->id, 'now' => time()));
1549
 
1550
        $serviceids = array();
1551
        $remoteaddr = getremoteaddr();
1552
 
1553
        // Query list of external services for the user.
1554
        $rs = $DB->get_recordset_sql($sql, $params);
1555
 
1556
        // Check which service ID to include.
1557
        foreach ($rs as $service) {
1558
            if (isset($serviceids[$service->id])) {
1559
                continue; // Service already added.
1560
            }
1561
            if ($service->requiredcapability and !has_capability($service->requiredcapability, $this->restricted_context)) {
1562
                continue; // Cap required, sorry.
1563
            }
1564
            if ($service->iprestriction and !address_in_subnet($remoteaddr, $service->iprestriction)) {
1565
                continue; // Wrong request source ip, sorry.
1566
            }
1567
            $serviceids[$service->id] = $service->id;
1568
        }
1569
        $rs->close();
1570
 
1571
        // Generate the virtual class name.
1572
        $classname = $this->get_unique_classname('webservices_virtual_class');
1573
        $this->serviceclass = $classname;
1574
 
1575
        // Get the list of all available external functions.
1576
        $wsmanager = new webservice();
1577
        $functions = $wsmanager->get_external_functions($serviceids);
1578
 
1579
        // Generate code for the virtual methods for this web service.
1580
        $methods = '';
1581
        foreach ($functions as $function) {
1582
            $methods .= $this->get_virtual_method_code($function);
1583
        }
1584
 
1585
        $code = <<<EOD
1586
/**
1587
 * Virtual class web services for user id $USER->id in context {$this->restricted_context->id}.
1588
 */
1589
class $classname {
1590
$methods
1591
}
1592
EOD;
1593
        // Load the virtual class definition into memory.
1594
        eval($code);
1595
    }
1596
 
1597
    /**
1598
     * Generates a struct class.
1599
     *
1600
     * @param external_single_structure $structdesc The basis of the struct class to be generated.
1601
     * @return string The class name of the generated struct class.
1602
     */
1603
    protected function generate_simple_struct_class(external_single_structure $structdesc) {
1604
        global $USER;
1605
 
1606
        $propeties = array();
1607
        $fields = array();
1608
        foreach ($structdesc->keys as $name => $fieldsdesc) {
1609
            $type = $this->get_phpdoc_type($fieldsdesc);
1610
            $propertytype = array('type' => $type);
1611
            if (empty($fieldsdesc->allownull) || $fieldsdesc->allownull == NULL_ALLOWED) {
1612
                $propertytype['nillable'] = true;
1613
            }
1614
            $propeties[$name] = $propertytype;
1615
            $fields[] = '    /** @var ' . $type . ' $' . $name . '*/';
1616
            $fields[] = '    public $' . $name .';';
1617
        }
1618
        $fieldsstr = implode("\n", $fields);
1619
 
1620
        // We do this after the call to get_phpdoc_type() to avoid duplicate class creation.
1621
        $classname = $this->get_unique_classname('webservices_struct_class');
1622
        $code = <<<EOD
1623
/**
1624
 * Virtual struct class for web services for user id $USER->id in context {$this->restricted_context->id}.
1625
 */
1626
class $classname {
1627
$fieldsstr
1628
}
1629
EOD;
1630
        // Load into memory.
1631
        eval($code);
1632
 
1633
        // Prepare struct info.
1634
        $structinfo = new stdClass();
1635
        $structinfo->classname = $classname;
1636
        $structinfo->properties = $propeties;
1637
        // Add the struct info the the list of service struct classes.
1638
        $this->servicestructs[] = $structinfo;
1639
 
1640
        return $classname;
1641
    }
1642
 
1643
    /**
1644
     * Returns a virtual method code for a web service function.
1645
     *
1646
     * @param stdClass $function a record from external_function
1647
     * @return string The PHP code of the virtual method.
1648
     * @throws coding_exception
1649
     * @throws moodle_exception
1650
     */
1651
    protected function get_virtual_method_code($function) {
1652
        $function = external_api::external_function_info($function);
1653
 
1654
        // Parameters and their defaults for the method signature.
1655
        $paramanddefaults = array();
1656
        // Parameters for external lib call.
1657
        $params = array();
1658
        $paramdesc = array();
1659
        // The method's input parameters and their respective types.
1660
        $inputparams = array();
1661
        // The method's output parameters and their respective types.
1662
        $outputparams = array();
1663
 
1664
        foreach ($function->parameters_desc->keys as $name => $keydesc) {
1665
            $param = '$' . $name;
1666
            $paramanddefault = $param;
1667
            if ($keydesc->required == VALUE_OPTIONAL) {
1668
                // It does not make sense to declare a parameter VALUE_OPTIONAL. VALUE_OPTIONAL is used only for array/object key.
1669
                throw new moodle_exception('erroroptionalparamarray', 'webservice', '', $name);
1670
            } else if ($keydesc->required == VALUE_DEFAULT) {
1671
                // Need to generate the default, if there is any.
1672
                if ($keydesc instanceof external_value) {
1673
                    if ($keydesc->default === null) {
1674
                        $paramanddefault .= ' = null';
1675
                    } else {
1676
                        switch ($keydesc->type) {
1677
                            case PARAM_BOOL:
1678
                                $default = (int)$keydesc->default;
1679
                                break;
1680
                            case PARAM_INT:
1681
                                $default = $keydesc->default;
1682
                                break;
1683
                            case PARAM_FLOAT;
1684
                                $default = $keydesc->default;
1685
                                break;
1686
                            default:
1687
                                $default = "'$keydesc->default'";
1688
                        }
1689
                        $paramanddefault .= " = $default";
1690
                    }
1691
                } else {
1692
                    // Accept empty array as default.
1693
                    if (isset($keydesc->default) && is_array($keydesc->default) && empty($keydesc->default)) {
1694
                        $paramanddefault .= ' = array()';
1695
                    } else {
1696
                        // For the moment we do not support default for other structure types.
1697
                        throw new moodle_exception('errornotemptydefaultparamarray', 'webservice', '', $name);
1698
                    }
1699
                }
1700
            }
1701
 
1702
            $params[] = $param;
1703
            $paramanddefaults[] = $paramanddefault;
1704
            $type = $this->get_phpdoc_type($keydesc);
1705
            $inputparams[$name]['type'] = $type;
1706
 
1707
            $paramdesc[] = '* @param ' . $type . ' $' . $name . ' ' . $keydesc->desc;
1708
        }
1709
        $paramanddefaults = implode(', ', $paramanddefaults);
1710
        $paramdescstr = implode("\n ", $paramdesc);
1711
 
1712
        $serviceclassmethodbody = $this->service_class_method_body($function, $params);
1713
 
1714
        if (empty($function->returns_desc)) {
1715
            $return = '* @return void';
1716
        } else {
1717
            $type = $this->get_phpdoc_type($function->returns_desc);
1718
            $outputparams['return']['type'] = $type;
1719
            $return = '* @return ' . $type . ' ' . $function->returns_desc->desc;
1720
        }
1721
 
1722
        // Now create the virtual method that calls the ext implementation.
1723
        $code = <<<EOD
1724
/**
1725
 * $function->description.
1726
 *
1727
 $paramdescstr
1728
 $return
1729
 */
1730
public function $function->name($paramanddefaults) {
1731
$serviceclassmethodbody
1732
}
1733
EOD;
1734
 
1735
        // Prepare the method information.
1736
        $methodinfo = new stdClass();
1737
        $methodinfo->name = $function->name;
1738
        $methodinfo->inputparams = $inputparams;
1739
        $methodinfo->outputparams = $outputparams;
1740
        $methodinfo->description = $function->description;
1741
        // Add the method information into the list of service methods.
1742
        $this->servicemethods[] = $methodinfo;
1743
 
1744
        return $code;
1745
    }
1746
 
1747
    /**
1748
     * Get the phpdoc type for an external_description object.
1749
     * external_value => int, double or string
1750
     * external_single_structure => object|struct, on-fly generated stdClass name.
1751
     * external_multiple_structure => array
1752
     *
1753
     * @param mixed $keydesc The type description.
1754
     * @return string The PHP doc type of the external_description object.
1755
     */
1756
    protected function get_phpdoc_type($keydesc) {
1757
        $type = null;
1758
        if ($keydesc instanceof external_value) {
1759
            switch ($keydesc->type) {
1760
                case PARAM_BOOL: // 0 or 1 only for now.
1761
                case PARAM_INT:
1762
                    $type = 'int';
1763
                    break;
1764
                case PARAM_FLOAT;
1765
                    $type = 'double';
1766
                    break;
1767
                default:
1768
                    $type = 'string';
1769
            }
1770
        } else if ($keydesc instanceof external_single_structure) {
1771
            $type = $this->generate_simple_struct_class($keydesc);
1772
        } else if ($keydesc instanceof external_multiple_structure) {
1773
            $type = 'array';
1774
        }
1775
 
1776
        return $type;
1777
    }
1778
 
1779
    /**
1780
     * Get a unique integer-suffixed classname for dynamic code creation.
1781
     *
1782
     * @param string $prefix The class name prefix to use.
1783
     * @return string The unused class name
1784
     */
1785
    protected function get_unique_classname(string $prefix): string {
1786
        $suffix = 0;
1787
        do {
1788
            $classname = sprintf(
1789
                "%s_%06d",
1790
                $prefix,
1791
                $suffix,
1792
            );
1793
            $suffix++;
1794
        } while (class_exists($classname));
1795
 
1796
        return $classname;
1797
    }
1798
 
1799
    /**
1800
     * Generates the method body of the virtual external function.
1801
     *
1802
     * @param stdClass $function a record from external_function.
1803
     * @param array $params web service function parameters.
1804
     * @return string body of the method for $function ie. everything within the {} of the method declaration.
1805
     */
1806
    protected function service_class_method_body($function, $params) {
1807
        // Cast the param from object to array (validate_parameters except array only).
1808
        $castingcode = '';
1809
        $paramsstr = '';
1810
        if (!empty($params)) {
1811
            foreach ($params as $paramtocast) {
1812
                // Clean the parameter from any white space.
1813
                $paramtocast = trim($paramtocast);
1814
                $castingcode .= "    $paramtocast = json_decode(json_encode($paramtocast), true);\n";
1815
            }
1816
            $paramsstr = implode(', ', $params);
1817
        }
1818
 
1819
        $descriptionmethod = $function->methodname . '_returns()';
1820
        $callforreturnvaluedesc = $function->classname . '::' . $descriptionmethod;
1821
 
1822
        $methodbody = <<<EOD
1823
$castingcode
1824
    if ($callforreturnvaluedesc == null) {
1825
        $function->classname::$function->methodname($paramsstr);
1826
        return null;
1827
    }
1828
    return \\core_external\\external_api::clean_returnvalue($callforreturnvaluedesc, $function->classname::$function->methodname($paramsstr));
1829
EOD;
1830
        return $methodbody;
1831
    }
1832
}
1833
 
1834
/**
1835
 * Early WS exception handler.
1836
 * It handles exceptions during setup and returns the Exception text in the WS format.
1837
 * If a raise function is found nothing is returned. Throws Exception otherwise.
1838
 *
1839
 * @param  Exception $ex Raised exception.
1840
 * @throws Exception
1841
 */
1842
function early_ws_exception_handler(Exception $ex): void {
1843
    if (function_exists('raise_early_ws_exception')) {
1844
        raise_early_ws_exception($ex);
1845
        die;
1846
    }
1847
 
1848
    throw $ex;
1849
}