lib.php 72.2 KB
Newer Older
1
<?php
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 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
 * Web services utility functions and classes
20
 *
21
22
23
 * @package    core_webservice
 * @copyright  2009 Jerome Mouneyrac <jerome@moodle.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
25
 */

26
require_once($CFG->libdir.'/externallib.php');
27

28
29
30
/**
 * WEBSERVICE_AUTHMETHOD_USERNAME - username/password authentication (also called simple authentication)
 */
31
define('WEBSERVICE_AUTHMETHOD_USERNAME', 0);
32
33
34
35

/**
 * WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN - most common token authentication (external app, mobile app...)
 */
36
define('WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN', 1);
37
38
39
40

/**
 * WEBSERVICE_AUTHMETHOD_SESSION_TOKEN - token for embedded application (requires Moodle session)
 */
41
42
define('WEBSERVICE_AUTHMETHOD_SESSION_TOKEN', 2);

43
44
/**
 * General web service library
45
46
47
48
 *
 * @package    core_webservice
 * @copyright  2010 Jerome Mouneyrac <jerome@moodle.com>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49
50
 */
class webservice {
51
52
53
54
55
56
57
58
    /**
     * Only update token last access once per this many seconds. (This constant controls update of
     * the external tokens last access field. There is a similar define LASTACCESS_UPDATE_SECS
     * which controls update of the web site last access fields.)
     *
     * @var int
     */
    const TOKEN_LASTACCESS_UPDATE_SECS = 60;
59

60
61
    /**
     * Authenticate user (used by download/upload file scripts)
62
     *
63
64
65
66
67
68
69
70
     * @param string $token
     * @return array - contains the authenticated user, token and service objects
     */
    public function authenticate_user($token) {
        global $DB, $CFG;

        // web service must be enabled to use this script
        if (!$CFG->enablewebservices) {
71
            throw new webservice_access_exception('Web services are not enabled in Advanced features.');
72
73
74
75
        }

        // Obtain token record
        if (!$token = $DB->get_record('external_tokens', array('token' => $token))) {
76
77
            //client may want to display login form => moodle_exception
            throw new moodle_exception('invalidtoken', 'webservice');
78
79
        }

80
81
82
83
84
85
86
87
        $loginfaileddefaultparams = array(
            'other' => array(
                'method' => WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN,
                'reason' => null,
                'tokenid' => $token->id
            )
        );

88
89
        // Validate token date
        if ($token->validuntil and $token->validuntil < time()) {
90
91
92
93
94
95
96
            $params = $loginfaileddefaultparams;
            $params['other']['reason'] = 'token_expired';
            $event = \core\event\webservice_login_failed::create($params);
            $event->add_record_snapshot('external_tokens', $token);
            $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '',
                get_string('invalidtimedtoken', 'webservice'), 0));
            $event->trigger();
97
            $DB->delete_records('external_tokens', array('token' => $token->token));
98
            throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
99
100
101
102
        }

        // Check ip
        if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
103
104
105
106
107
108
109
            $params = $loginfaileddefaultparams;
            $params['other']['reason'] = 'ip_restricted';
            $event = \core\event\webservice_login_failed::create($params);
            $event->add_record_snapshot('external_tokens', $token);
            $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '',
                get_string('failedtolog', 'webservice') . ": " . getremoteaddr(), 0));
            $event->trigger();
110
111
            throw new webservice_access_exception('Invalid token - IP:' . getremoteaddr()
                    . ' is not supported');
112
113
114
115
116
117
118
119
120
        }

        //retrieve user link to the token
        $user = $DB->get_record('user', array('id' => $token->userid, 'deleted' => 0), '*', MUST_EXIST);

        // let enrol plugins deal with new enrolments if necessary
        enrol_check_plugins($user);

        // setup user session to check capability
121
        \core\session\manager::set_user($user);
122
        set_login_session_preferences();
123
124
125

        //assumes that if sid is set then there must be a valid associated session no matter the token type
        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
133
134
        // Cannot authenticate unless maintenance access is granted.
        $hasmaintenanceaccess = has_capability('moodle/site:maintenanceaccess', context_system::instance(), $user);
        if (!empty($CFG->maintenance_enabled) and !$hasmaintenanceaccess) {
135
136
            //this is usually temporary, client want to implement code logic  => moodle_exception
            throw new moodle_exception('sitemaintenance', 'admin');
137
138
139
140
141
142
        }

        //retrieve web service record
        $service = $DB->get_record('external_services', array('id' => $token->externalserviceid, 'enabled' => 1));
        if (empty($service)) {
            // 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
152
153
154
155
        }

        //specific checks related to user restricted service
        if ($service->restrictedusers) {
            $authoriseduser = $DB->get_record('external_services_users', array('externalserviceid' => $service->id, 'userid' => $user->id));

            if (empty($authoriseduser)) {
156
157
158
                throw new webservice_access_exception(
                        'The user is not allowed for this service. First you need to allow this user on the '
                        . $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
167
                throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
                    . ' is not supported - check this allowed user');
168
169
170
171
172
            }
        }

        //only confirmed user should be able to call web service
        if (empty($user->confirmed)) {
173
174
175
176
177
178
            $params = $loginfaileddefaultparams;
            $params['other']['reason'] = 'user_unconfirmed';
            $event = \core\event\webservice_login_failed::create($params);
            $event->add_record_snapshot('external_tokens', $token);
            $event->set_legacy_logdata(array(SITEID, 'webservice', 'user unconfirmed', '', $user->username));
            $event->trigger();
179
            throw new moodle_exception('usernotconfirmed', 'moodle', '', $user->username);
180
181
182
183
        }

        //check the user is suspended
        if (!empty($user->suspended)) {
184
185
186
187
188
189
            $params = $loginfaileddefaultparams;
            $params['other']['reason'] = 'user_suspended';
            $event = \core\event\webservice_login_failed::create($params);
            $event->add_record_snapshot('external_tokens', $token);
            $event->set_legacy_logdata(array(SITEID, 'webservice', 'user suspended', '', $user->username));
            $event->trigger();
190
            throw new webservice_access_exception('Refused web service access for suspended username: ' . $user->username);
191
192
193
194
        }

        //check if the auth method is nologin (in this case refuse connection)
        if ($user->auth == 'nologin') {
195
196
197
198
199
200
            $params = $loginfaileddefaultparams;
            $params['other']['reason'] = 'nologin';
            $event = \core\event\webservice_login_failed::create($params);
            $event->add_record_snapshot('external_tokens', $token);
            $event->set_legacy_logdata(array(SITEID, 'webservice', 'nologin auth attempt with web service', '', $user->username));
            $event->trigger();
201
            throw new webservice_access_exception('Refused web service access for nologin authentication username: ' . $user->username);
202
203
204
205
206
207
208
        }

        //Check if the user password is expired
        $auth = get_auth_plugin($user->auth);
        if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
            $days2expire = $auth->password_expire($user->username);
            if (intval($days2expire) < 0) {
209
210
211
212
213
214
                $params = $loginfaileddefaultparams;
                $params['other']['reason'] = 'password_expired';
                $event = \core\event\webservice_login_failed::create($params);
                $event->add_record_snapshot('external_tokens', $token);
                $event->set_legacy_logdata(array(SITEID, 'webservice', 'expired password', '', $user->username));
                $event->trigger();
215
                throw new moodle_exception('passwordisexpired', 'webservice');
216
217
218
219
            }
        }

        // log token access
220
        self::update_token_lastaccess($token);
221
222
223
224

        return array('user' => $user, 'token' => $token, 'service' => $service);
    }

225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
    /**
     * Updates the last access time for a token.
     *
     * @param \stdClass $token Token object (must include id, lastaccess fields)
     * @param int $time Time of access (0 = use current time)
     * @throws dml_exception If database error
     */
    public static function update_token_lastaccess($token, int $time = 0) {
        global $DB;

        if (!$time) {
            $time = time();
        }

        // Only update the field if it is a different time from previous request,
        // so as not to waste database effort.
        if ($time >= $token->lastaccess + self::TOKEN_LASTACCESS_UPDATE_SECS) {
            $DB->set_field('external_tokens', 'lastaccess', $time, array('id' => $token->id));
        }
    }

246
    /**
247
248
249
     * Allow user to call a service
     *
     * @param stdClass $user a user
250
251
252
     */
    public function add_ws_authorised_user($user) {
        global $DB;
Petr Skoda's avatar
Petr Skoda committed
253
        $user->timecreated = time();
254
255
256
257
        $DB->insert_record('external_services_users', $user);
    }

    /**
258
259
260
     * Disallow a user to call a service
     *
     * @param stdClass $user a user
261
262
263
264
265
266
267
268
269
     * @param int $serviceid
     */
    public function remove_ws_authorised_user($user, $serviceid) {
        global $DB;
        $DB->delete_records('external_services_users',
                array('externalserviceid' => $serviceid, 'userid' => $user->id));
    }

    /**
270
271
272
     * Update allowed user settings (ip restriction, valid until...)
     *
     * @param stdClass $user
273
274
275
276
277
278
279
280
281
     */
    public function update_ws_authorised_user($user) {
        global $DB;
        $DB->update_record('external_services_users', $user);
    }

    /**
     * Return list of allowed users with their options (ip/timecreated / validuntil...)
     * for a given service
282
283
     *
     * @param int $serviceid the service id to search against
284
285
286
     * @return array $users
     */
    public function get_ws_authorised_users($serviceid) {
287
288
        global $DB, $CFG;
        $params = array($CFG->siteguest, $serviceid);
289
        $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
290
291
292
293
294
                        u.lastname as lastname,
                        esu.iprestriction as iprestriction, esu.validuntil as validuntil,
                        esu.timecreated as timecreated
                   FROM {user} u, {external_services_users} esu
                  WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
295
296
297
298
299
300
301
302
                        AND esu.userid = u.id
                        AND esu.externalserviceid = ?";

        $users = $DB->get_records_sql($sql, $params);
        return $users;
    }

    /**
303
304
305
306
307
     * Return an authorised user with their options (ip/timecreated / validuntil...)
     *
     * @param int $serviceid the service id to search against
     * @param int $userid the user to search against
     * @return stdClass
308
309
     */
    public function get_ws_authorised_user($serviceid, $userid) {
310
311
        global $DB, $CFG;
        $params = array($CFG->siteguest, $serviceid, $userid);
312
        $sql = " SELECT u.id as id, esu.id as serviceuserid, u.email as email, u.firstname as firstname,
313
314
315
316
317
                        u.lastname as lastname,
                        esu.iprestriction as iprestriction, esu.validuntil as validuntil,
                        esu.timecreated as timecreated
                   FROM {user} u, {external_services_users} esu
                  WHERE u.id <> ? AND u.deleted = 0 AND u.confirmed = 1
318
319
320
321
322
323
324
                        AND esu.userid = u.id
                        AND esu.externalserviceid = ?
                        AND u.id = ?";
        $user = $DB->get_record_sql($sql, $params);
        return $user;
    }

325
    /**
326
327
328
     * Generate all tokens of a specific user
     *
     * @param int $userid user id
329
330
331
     */
    public function generate_user_ws_tokens($userid) {
        global $CFG, $DB;
332

333
        // generate a token for non admin if web service are enable and the user has the capability to create a token
334
        if (!is_siteadmin() && has_capability('moodle/webservice:createtoken', context_system::instance(), $userid) && !empty($CFG->enablewebservices)) {
335
            // for every service than the user is authorised on, create a token (if it doesn't already exist)
336

337
            // get all services which are set to all user (no restricted to specific users)
338
339
340
341
342
343
            $norestrictedservices = $DB->get_records('external_services', array('restrictedusers' => 0));
            $serviceidlist = array();
            foreach ($norestrictedservices as $service) {
                $serviceidlist[] = $service->id;
            }

344
            // get all services which are set to the current user (the current user is specified in the restricted user list)
345
346
347
348
349
350
351
            $servicesusers = $DB->get_records('external_services_users', array('userid' => $userid));
            foreach ($servicesusers as $serviceuser) {
                if (!in_array($serviceuser->externalserviceid,$serviceidlist)) {
                     $serviceidlist[] = $serviceuser->externalserviceid;
                }
            }

352
            // get all services which already have a token set for the current user
353
354
355
356
357
358
            $usertokens = $DB->get_records('external_tokens', array('userid' => $userid, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
            $tokenizedservice = array();
            foreach ($usertokens as $token) {
                    $tokenizedservice[]  = $token->externalserviceid;
            }

359
            // create a token for the service which have no token already
360
361
            foreach ($serviceidlist as $serviceid) {
                if (!in_array($serviceid, $tokenizedservice)) {
362
                    // create the token for this service
363
                    $newtoken = new stdClass();
364
                    $newtoken->token = md5(uniqid(rand(),1));
365
                    // check that the user has capability on this service
366
367
368
                    $newtoken->tokentype = EXTERNAL_TOKEN_PERMANENT;
                    $newtoken->userid = $userid;
                    $newtoken->externalserviceid = $serviceid;
369
                    // TODO MDL-31190 find a way to get the context - UPDATE FOLLOWING LINE
370
                    $newtoken->contextid = context_system::instance()->id;
371
372
                    $newtoken->creatorid = $userid;
                    $newtoken->timecreated = time();
373
374
                    // Generate the private token, it must be transmitted only via https.
                    $newtoken->privatetoken = random_string(64);
375
376
377
378
379
380
381
382
383
384

                    $DB->insert_record('external_tokens', $newtoken);
                }
            }


        }
    }

    /**
385
386
387
388
389
390
     * Return all tokens of a specific user
     * + the service state (enabled/disabled)
     * + the authorised user mode (restricted/not restricted)
     *
     * @param int $userid user id
     * @return array
391
392
393
394
395
     */
    public function get_user_ws_tokens($userid) {
        global $DB;
        //here retrieve token list (including linked users firstname/lastname and linked services name)
        $sql = "SELECT
396
                    t.id, t.creatorid, t.token, u.firstname, u.lastname, s.id as wsid, s.name, s.enabled, s.restrictedusers, t.validuntil
397
398
399
400
401
402
403
404
405
                FROM
                    {external_tokens} t, {user} u, {external_services} s
                WHERE
                    t.userid=? AND t.tokentype = ".EXTERNAL_TOKEN_PERMANENT." AND s.id = t.externalserviceid AND t.userid = u.id";
        $tokens = $DB->get_records_sql($sql, array( $userid));
        return $tokens;
    }

    /**
406
407
408
409
     * Return a token that has been created by the user (i.e. to created by an admin)
     * If no tokens exist an exception is thrown
     *
     * The returned value is a stdClass:
410
411
412
413
414
     * ->id token id
     * ->token
     * ->firstname user firstname
     * ->lastname
     * ->name service name
415
416
417
418
     *
     * @param int $userid user id
     * @param int $tokenid token id
     * @return stdClass
419
420
421
422
423
424
425
426
     */
    public function get_created_by_user_ws_token($userid, $tokenid) {
        global $DB;
        $sql = "SELECT
                        t.id, t.token, u.firstname, u.lastname, s.name
                    FROM
                        {external_tokens} t, {user} u, {external_services} s
                    WHERE
427
428
429
430
431
                        t.creatorid=? AND t.id=? AND t.tokentype = "
                . EXTERNAL_TOKEN_PERMANENT
                . " AND s.id = t.externalserviceid AND t.userid = u.id";
        //must be the token creator
        $token = $DB->get_record_sql($sql, array($userid, $tokenid), MUST_EXIST);
432
433
434
        return $token;
    }

435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
    /**
     * Return a token of an arbitrary user by tokenid, including details of the associated user and the service name.
     * If no tokens exist an exception is thrown
     *
     * The returned value is a stdClass:
     * ->id token id
     * ->token
     * ->firstname user firstname
     * ->lastname
     * ->name service name
     *
     * @param int $tokenid token id
     * @return stdClass
     */
    public function get_token_by_id_with_details($tokenid) {
        global $DB;
451
452
453
454
        $sql = "SELECT t.id, t.token, u.id AS userid, u.firstname, u.lastname, s.name, t.creatorid
                FROM {external_tokens} t, {user} u, {external_services} s
                WHERE t.id=? AND t.tokentype = ? AND s.id = t.externalserviceid AND t.userid = u.id";
        $token = $DB->get_record_sql($sql, array($tokenid, EXTERNAL_TOKEN_PERMANENT), MUST_EXIST);
455
456
457
        return $token;
    }

458
    /**
459
460
461
     * Return a database token record for a token id
     *
     * @param int $tokenid token id
462
463
464
465
466
467
468
     * @return object token
     */
    public function get_token_by_id($tokenid) {
        global $DB;
        return $DB->get_record('external_tokens', array('id' => $tokenid));
    }

469
    /**
470
471
472
     * Delete a token
     *
     * @param int $tokenid token id
473
474
475
476
477
     */
    public function delete_user_ws_token($tokenid) {
        global $DB;
        $DB->delete_records('external_tokens', array('id'=>$tokenid));
    }
478

479
480
481
482
483
484
485
486
487
488
    /**
     * Delete all the tokens belonging to a user.
     *
     * @param int $userid the user id whose tokens must be deleted
     */
    public static function delete_user_ws_tokens($userid) {
        global $DB;
        $DB->delete_records('external_tokens', array('userid' => $userid));
    }

489
    /**
490
491
492
493
     * Delete a service
     * Also delete function references and authorised user references.
     *
     * @param int $serviceid service id
494
495
496
497
498
499
     */
    public function delete_service($serviceid) {
        global $DB;
        $DB->delete_records('external_services_users', array('externalserviceid' => $serviceid));
        $DB->delete_records('external_services_functions', array('externalserviceid' => $serviceid));
        $DB->delete_records('external_tokens', array('externalserviceid' => $serviceid));
Petr Skoda's avatar
Petr Skoda committed
500
        $DB->delete_records('external_services', array('id' => $serviceid));
501
502
    }

503
    /**
504
505
     * Get a full database token record for a given token value
     *
506
507
508
509
510
511
512
     * @param string $token
     * @throws moodle_exception if there is multiple result
     */
    public function get_user_ws_token($token) {
        global $DB;
        return $DB->get_record('external_tokens', array('token'=>$token), '*', MUST_EXIST);
    }
513

514
    /**
515
516
517
518
     * Get the functions list of a service list (by id)
     *
     * @param array $serviceids service ids
     * @return array of functions
519
520
521
522
523
524
525
526
527
     */
    public function get_external_functions($serviceids) {
        global $DB;
        if (!empty($serviceids)) {
            list($serviceids, $params) = $DB->get_in_or_equal($serviceids);
            $sql = "SELECT f.*
                      FROM {external_functions} f
                     WHERE f.name IN (SELECT sf.functionname
                                        FROM {external_services_functions} sf
528
529
                                       WHERE sf.externalserviceid $serviceids)
                     ORDER BY f.name ASC";
530
531
532
533
534
535
536
            $functions = $DB->get_records_sql($sql, $params);
        } else {
            $functions = array();
        }
        return $functions;
    }

537
    /**
538
539
540
541
     * Get the functions of a service list (by shortname). It can return only enabled functions if required.
     *
     * @param array $serviceshortnames service shortnames
     * @param bool $enabledonly if true then only return functions for services that have been enabled
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
     * @return array functions
     */
    public function get_external_functions_by_enabled_services($serviceshortnames, $enabledonly = true) {
        global $DB;
        if (!empty($serviceshortnames)) {
            $enabledonlysql = $enabledonly?' AND s.enabled = 1 ':'';
            list($serviceshortnames, $params) = $DB->get_in_or_equal($serviceshortnames);
            $sql = "SELECT f.*
                      FROM {external_functions} f
                     WHERE f.name IN (SELECT sf.functionname
                                        FROM {external_services_functions} sf, {external_services} s
                                       WHERE s.shortname $serviceshortnames
                                             AND sf.externalserviceid = s.id
                                             " . $enabledonlysql . ")";
            $functions = $DB->get_records_sql($sql, $params);
        } else {
            $functions = array();
        }
        return $functions;
561
562
    }

563
    /**
564
565
566
     * Get functions not included in a service
     *
     * @param int $serviceid service id
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
     * @return array functions
     */
    public function get_not_associated_external_functions($serviceid) {
        global $DB;
        $select = "name NOT IN (SELECT s.functionname
                                  FROM {external_services_functions} s
                                 WHERE s.externalserviceid = :sid
                               )";

        $functions = $DB->get_records_select('external_functions',
                        $select, array('sid' => $serviceid), 'name');

        return $functions;
    }

582
583
    /**
     * Get list of required capabilities of a service, sorted by functions
584
     * Example of returned value:
585
586
     *  Array
     *  (
587
     *    [core_group_create_groups] => Array
588
589
590
591
     *    (
     *       [0] => moodle/course:managegroups
     *    )
     *
592
     *    [core_enrol_get_enrolled_users] => Array
593
     *    (
594
595
596
597
598
     *       [0] => moodle/user:viewdetails
     *       [1] => moodle/user:viewhiddendetails
     *       [2] => moodle/course:useremail
     *       [3] => moodle/user:update
     *       [4] => moodle/site:accessallgroups
599
600
     *    )
     *  )
601
602
     * @param int $serviceid service id
     * @return array
603
604
605
606
607
     */
    public function get_service_required_capabilities($serviceid) {
        $functions = $this->get_external_functions(array($serviceid));
        $requiredusercaps = array();
        foreach ($functions as $function) {
608
            $functioncaps = explode(',', $function->capabilities);
609
610
611
612
613
614
615
616
617
618
619
            if (!empty($functioncaps) and !empty($functioncaps[0])) {
                foreach ($functioncaps as $functioncap) {
                    $requiredusercaps[$function->name][] = trim($functioncap);
                }
            }
        }
        return $requiredusercaps;
    }

    /**
     * Get user capabilities (with context)
620
     * Only useful for documentation purpose
621
622
623
624
     * WARNING: do not use this "broken" function. It was created in the goal to display some capabilities
     * required by users. In theory we should not need to display this kind of information
     * as the front end does not display it itself. In pratice,
     * admins would like the info, for more info you can follow: MDL-29962
625
     *
626
627
     * @deprecated since Moodle 3.11 in MDL-67748 without a replacement.
     * @todo MDL-70187 Please delete this method completely in Moodle 4.3, thank you.
628
     * @param int $userid user id
629
630
631
632
     * @return array
     */
    public function get_user_capabilities($userid) {
        global $DB;
633
634
635

        debugging('webservice::get_user_capabilities() has been deprecated.', DEBUG_DEVELOPER);

636
        //retrieve the user capabilities
637
638
639
        $sql = "SELECT DISTINCT rc.id, rc.capability FROM {role_capabilities} rc, {role_assignments} ra
            WHERE rc.roleid=ra.roleid AND ra.userid= ? AND rc.permission = ?";
        $dbusercaps = $DB->get_records_sql($sql, array($userid, CAP_ALLOW));
640
641
642
643
644
645
646
647
        $usercaps = array();
        foreach ($dbusercaps as $usercap) {
            $usercaps[$usercap->capability] = true;
        }
        return $usercaps;
    }

    /**
648
     * Get missing user capabilities for the given service's functions.
649
     *
650
651
652
653
654
655
656
657
658
659
660
661
662
663
     * Every external function can declare some required capabilities to allow for easier setup of the web services.
     * However, that is supposed to be used for informational admin report only. There is no automatic evaluation of
     * the declared capabilities and the context of the capability evaluation is ignored. Also, actual capability
     * evaluation is much more complex as it allows for overrides etc.
     *
     * Returned are capabilities that the given users do not seem to have assigned anywhere at the site and that should
     * be checked by the admin.
     *
     * Do not use this method for anything else, particularly not for any security related checks. See MDL-29962 for the
     * background of why we have this - there are arguments for dropping this feature completely.
     *
     * @param array $users List of users to check, consisting of objects, arrays or integer ids.
     * @param int $serviceid The id of the external service to check.
     * @return array List of missing capabilities: (int)userid => array of (string)capabilitynames
664
     */
665
    public function get_missing_capabilities_by_users(array $users, int $serviceid): array {
666
667
        global $DB;

668
669
        // The following are default capabilities for all authenticated users and we will assume them granted.
        $commoncaps = get_default_capabilities('user');
670

671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
        // Get the list of additional capabilities required by the service.
        $servicecaps = [];
        foreach ($this->get_service_required_capabilities($serviceid) as $service => $caps) {
            foreach ($caps as $cap) {
                if (empty($commoncaps[$cap])) {
                    $servicecaps[$cap] = true;
                }
            }
        }

        if (empty($servicecaps)) {
            return [];
        }

        // Prepare a list of user ids we want to check.
        $userids = [];
687
        foreach ($users as $user) {
688
689
690
691
692
693
            if (is_object($user) && isset($user->id)) {
                $userids[$user->id] = true;
            } else if (is_array($user) && isset($user['id'])) {
                $userids[$user['id']] = true;
            } else {
                throw new coding_exception('Unexpected format of users list in webservice::get_missing_capabilities_by_users().');
694
            }
695
        }
696

697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
        // Prepare a matrix of missing capabilities x users - consider them all missing by default.
        foreach (array_keys($userids) as $userid) {
            foreach (array_keys($servicecaps) as $capname) {
                $matrix[$userid][$capname] = true;
            }
        }

        list($capsql, $capparams) = $DB->get_in_or_equal(array_keys($servicecaps), SQL_PARAMS_NAMED, 'paramcap');
        list($usersql, $userparams) = $DB->get_in_or_equal(array_keys($userids), SQL_PARAMS_NAMED, 'paramuser');

        $sql = "SELECT c.name AS capability, u.id AS userid
                  FROM {capabilities} c
                  JOIN {role_capabilities} rc ON c.name = rc.capability
                  JOIN {role_assignments} ra ON ra.roleid = rc.roleid
                  JOIN {user} u ON ra.userid = u.id
                 WHERE rc.permission = :capallow
                   AND c.name {$capsql}
                   AND u.id {$usersql}";

        $params = $capparams + $userparams + [
            'capallow' => CAP_ALLOW,
        ];

        $rs = $DB->get_recordset_sql($sql, $params);

        foreach ($rs as $record) {
            // If there was a potential role assignment found that might grant the user the given capability,
            // remove it from the matrix. Again, we ignore all the contexts, prohibits, prevents and other details
            // of the permissions evaluations. See the function docblock for details.
            unset($matrix[$record->userid][$record->capability]);
        }

        $rs->close();

        foreach ($matrix as $userid => $caps) {
            $matrix[$userid] = array_keys($caps);
            if (empty($matrix[$userid])) {
                unset($matrix[$userid]);
735
736
737
            }
        }

738
        return $matrix;
739
740
    }

741
    /**
742
743
744
745
746
     * Get an external service for a given service id
     *
     * @param int $serviceid service id
     * @param int $strictness IGNORE_MISSING, MUST_EXIST...
     * @return stdClass external service
747
748
749
750
751
752
753
754
     */
    public function get_external_service_by_id($serviceid, $strictness=IGNORE_MISSING) {
        global $DB;
        $service = $DB->get_record('external_services',
                        array('id' => $serviceid), '*', $strictness);
        return $service;
    }

755
    /**
756
757
758
759
760
     * Get an external service for a given shortname
     *
     * @param string $shortname service shortname
     * @param int $strictness IGNORE_MISSING, MUST_EXIST...
     * @return stdClass external service
761
762
763
764
765
766
767
768
     */
    public function get_external_service_by_shortname($shortname, $strictness=IGNORE_MISSING) {
        global $DB;
        $service = $DB->get_record('external_services',
                        array('shortname' => $shortname), '*', $strictness);
        return $service;
    }

769
    /**
770
771
772
773
774
     * Get an external function for a given function id
     *
     * @param int $functionid function id
     * @param int $strictness IGNORE_MISSING, MUST_EXIST...
     * @return stdClass external function
775
776
777
778
779
780
781
782
783
784
     */
    public function get_external_function_by_id($functionid, $strictness=IGNORE_MISSING) {
        global $DB;
        $function = $DB->get_record('external_functions',
                            array('id' => $functionid), '*', $strictness);
        return $function;
    }

    /**
     * Add a function to a service
785
786
787
     *
     * @param string $functionname function name
     * @param int $serviceid service id
788
789
790
     */
    public function add_external_function_to_service($functionname, $serviceid) {
        global $DB;
791
        $addedfunction = new stdClass();
792
793
794
795
796
        $addedfunction->externalserviceid = $serviceid;
        $addedfunction->functionname = $functionname;
        $DB->insert_record('external_services_functions', $addedfunction);
    }

797
798
    /**
     * Add a service
799
800
801
     * It generates the timecreated field automatically.
     *
     * @param stdClass $service
802
803
804
805
     * @return serviceid integer
     */
    public function add_external_service($service) {
        global $DB;
Petr Skoda's avatar
Petr Skoda committed
806
        $service->timecreated = time();
807
808
809
810
        $serviceid = $DB->insert_record('external_services', $service);
        return $serviceid;
    }

811
    /**
812
     * Update a service
813
814
815
     * It modifies the timemodified automatically.
     *
     * @param stdClass $service
816
817
818
     */
    public function update_external_service($service) {
        global $DB;
Petr Skoda's avatar
Petr Skoda committed
819
        $service->timemodified = time();
820
821
822
        $DB->update_record('external_services', $service);
    }

823
    /**
824
825
826
827
     * Test whether an external function is already linked to a service
     *
     * @param string $functionname function name
     * @param int $serviceid service id
828
829
830
831
832
833
834
835
836
837
     * @return bool true if a matching function exists for the service, else false.
     * @throws dml_exception if error
     */
    public function service_function_exists($functionname, $serviceid) {
        global $DB;
        return $DB->record_exists('external_services_functions',
                            array('externalserviceid' => $serviceid,
                                'functionname' => $functionname));
    }

838
839
840
841
842
843
    /**
     * Remove a function from a service
     *
     * @param string $functionname function name
     * @param int $serviceid service id
     */
844
845
846
847
848
849
850
    public function remove_external_function_from_service($functionname, $serviceid) {
        global $DB;
        $DB->delete_records('external_services_functions',
                    array('externalserviceid' => $serviceid, 'functionname' => $functionname));

    }

851
852
853
854
855
856
857
858
859
    /**
     * Return a list with all the valid user tokens for the given user, it only excludes expired tokens.
     *
     * @param  string $userid user id to retrieve tokens from
     * @return array array of token entries
     * @since Moodle 3.2
     */
    public static function get_active_tokens($userid) {
        global $DB;
860

861
862
863
864
865
866
        $sql = 'SELECT t.*, s.name as servicename FROM {external_tokens} t JOIN
                {external_services} s ON t.externalserviceid = s.id WHERE
                t.userid = :userid AND (t.validuntil IS NULL OR t.validuntil > :now)';
        $params = array('userid' => $userid, 'now' => time());
        return $DB->get_records_sql($sql, $params);
    }
867
}
868

869
870
/**
 * Exception indicating access control problem in web service call
871
872
873
874
 * This exception should return general errors about web service setup.
 * Errors related to the user like wrong username/password should not use it,
 * you should not use this exception if you want to let the client implement
 * some code logic against an access error.
875
876
877
878
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
879
880
 */
class webservice_access_exception extends moodle_exception {
881

882
883
    /**
     * Constructor
884
885
     *
     * @param string $debuginfo the debug info
886
887
     */
    function __construct($debuginfo) {
888
        parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
889
890
891
    }
}

892
/**
893
894
 * Check if a protocol is enabled
 *
895
 * @param string $protocol name of WS protocol ('rest', 'soap', 'xmlrpc'...)
896
 * @return bool true if the protocol is enabled
897
 */
898
899
function webservice_protocol_is_enabled($protocol) {
    global $CFG;
900

901
902
    if (empty($CFG->enablewebservices)) {
        return false;
903
904
    }

905
    $active = explode(',', $CFG->webserviceprotocols);
906

907
908
    return(in_array($protocol, $active));
}
909

910
/**
Petr Skoda's avatar
Petr Skoda committed
911
 * Mandatory interface for all test client classes.
912
913
914
915
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
916
917
 */
interface webservice_test_client_interface {
918

919
920
    /**
     * Execute test client WS request
921
922
923
924
     *
     * @param string $serverurl server url (including the token param)
     * @param string $function web service function name
     * @param array $params parameters of the web service function
925
926
927
928
929
     * @return mixed
     */
    public function simpletest($serverurl, $function, $params);
}

930
/**
Petr Skoda's avatar
Petr Skoda committed
931
 * Mandatory interface for all web service protocol classes
932
933
934
935
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
936
 */
937
interface webservice_server_interface {
938

939
940
941
942
943
    /**
     * Process request from client.
     */
    public function run();
}
944

945
946
/**
 * Abstract web service base class.
947
948
949
950
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
951
952
 */
abstract class webservice_server implements webservice_server_interface {
953

954
    /** @var string Name of the web server plugin */
955
956
    protected $wsname = null;

957
    /** @var string Name of local user */
958
959
    protected $username = null;

960
    /** @var string Password of the local user */
961
    protected $password = null;
962

963
    /** @var int The local user */
964
965
    protected $userid = null;

966
    /** @var integer Authentication method one of WEBSERVICE_AUTHMETHOD_* */
967
    protected $authmethod;
968

969
    /** @var string Authentication token*/
970
    protected $token = null;
971

972
    /** @var stdClass Restricted context */
973
974
    protected $restricted_context;

975
    /** @var int Restrict call to one service id*/
976
977
    protected $restricted_serviceid = null;

978
    /**
979
980
     * Constructor
     *
981
     * @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
982
983
984
     */
    public function __construct($authmethod) {
        $this->authmethod = $authmethod;
985
986
987
    }


988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
    /**
     * Authenticate user using username+password or token.
     * This function sets up $USER global.
     * It is safe to use has_capability() after this.
     * This method also verifies user is allowed to use this
     * server.
     */
    protected function authenticate_user() {
        global $CFG, $DB;

        if (!NO_MOODLE_COOKIES) {
            throw new coding_exception('Cookies must be disabled in WS servers!');
        }

1002
1003
1004
        $loginfaileddefaultparams = array(
            'other' => array(
                'method' => $this->authmethod,
1005
                'reason' => null
1006
1007
1008
            )
        );

1009
        if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
1010

1011
1012
1013
            //we check that authentication plugin is enabled
            //it is only required by simple authentication
            if (!is_enabled_auth('webservice')) {
1014
                throw new webservice_access_exception('The web service authentication plugin is disabled.');
1015
            }
1016

1017
            if (!$auth = get_auth_plugin('webservice')) {
1018
                throw new webservice_access_exception('The web service authentication plugin is missing.');
1019
            }
1020

1021
            $this->restricted_context = context_system::instance();
1022
1023

            if (!$this->username) {
1024
                throw new moodle_exception('missingusername', 'webservice');
1025
1026
1027
            }

            if (!$this->password) {
1028
                throw new moodle_exception('missingpassword', 'webservice');
1029
1030
1031
            }

            if (!$auth->user_login_webservice($this->username, $this->password)) {
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041

                // Log failed login attempts.
                $params = $loginfaileddefaultparams;
                $params['other']['reason'] = 'password';
                $params['other']['username'] = $this->username;
                $event = \core\event\webservice_login_failed::create($params);
                $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('simpleauthlog', 'webservice'), '' ,
                    get_string('failedtolog', 'webservice').": ".$this->username."/".$this->password." - ".getremoteaddr() , 0));
                $event->trigger();

1042
                throw new moodle_exception('wrongusernamepassword', 'webservice');
1043
1044
            }

1045
            $user = $DB->get_record('user', array('username'=>$this->username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
1046

1047
1048
        } else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN){
            $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
1049
        } else {
1050
            $user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED);
1051
        }
1052

1053
1054
1055
        // Cannot authenticate unless maintenance access is granted.
        $hasmaintenanceaccess = has_capability('moodle/site:maintenanceaccess', context_system::instance(), $user);
        if (!empty($CFG->maintenance_enabled) and !$hasmaintenanceaccess) {
1056
            throw new moodle_exception('sitemaintenance', 'admin');
1057
1058
1059
1060
        }

        //only confirmed user should be able to call web service
        if (!empty($user->deleted)) {
1061
1062
1063
1064
1065
1066
1067
            $params = $loginfaileddefaultparams;
            $params['other']['reason'] = 'user_deleted';
            $params['other']['username'] = $user->username;
            $event = \core\event\webservice_login_failed::create($params);
            $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserdeleted', 'webservice',
                $user->username) . " - ".getremoteaddr(), 0, $user->id));
            $event->trigger();
1068
            throw new webservice_access_exception('Refused web service access for deleted username: ' . $user->username);
1069
1070
1071
1072
        }

        //only confirmed user should be able to call web service
        if (empty($user->confirmed)) {
1073
1074
1075
1076
1077
1078
1079
            $params = $loginfaileddefaultparams;
            $params['other']['reason'] = 'user_unconfirmed';
            $params['other']['username'] = $user->username;
            $event = \core\event\webservice_login_failed::create($params);
            $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserunconfirmed', 'webservice',
                $user->username) . " - ".getremoteaddr(), 0, $user->id));
            $event->trigger();
1080
            throw new moodle_exception('wsaccessuserunconfirmed', 'webservice', '', $user->username);
1081
1082
1083
1084
        }

        //check the user is suspended
        if (!empty($user->suspended)) {
1085
1086
1087
1088
1089
1090
1091
            $params = $loginfaileddefaultparams;
            $params['other']['reason'] = 'user_unconfirmed';
            $params['other']['username'] = $user->username;
            $event = \core\event\webservice_login_failed::create($params);
            $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessusersuspended', 'webservice',
                $user->username) . " - ".getremoteaddr(), 0, $user->id));
            $event->trigger();
1092
            throw new webservice_access_exception('Refused web service access for suspended username: ' . $user->username);
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
        }

        //retrieve the authentication plugin if no previously done
        if (empty($auth)) {
          $auth  = get_auth_plugin($user->auth);
        }

        // check if credentials have expired
        if (!empty($auth->config->expiration) and $auth->config->expiration == 1) {
            $days2expire = $auth->password_expire($user->username);
            if (intval($days2expire) < 0 ) {
1104
1105
1106
1107
1108
1109
1110
                $params = $loginfaileddefaultparams;
                $params['other']['reason'] = 'password_expired';
                $params['other']['username'] = $user->username;
                $event = \core\event\webservice_login_failed::create($params);
                $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessuserexpired', 'webservice',
                    $user->username) . " - ".getremoteaddr(), 0, $user->id));
                $event->trigger();
1111
                throw new webservice_access_exception('Refused web service access for password expired username: ' . $user->username);
1112
1113
1114
1115
1116
            }
        }

        //check if the auth method is nologin (in this case refuse connection)
        if ($user->auth=='nologin') {
1117
1118
1119
1120
1121
1122
1123
            $params = $loginfaileddefaultparams;
            $params['other']['reason'] = 'login';
            $params['other']['username'] = $user->username;
            $event = \core\event\webservice_login_failed::create($params);
            $event->set_legacy_logdata(array(SITEID, '', '', '', get_string('wsaccessusernologin', 'webservice',
                $user->username) . " - ".getremoteaddr(), 0, $user->id));
            $event->trigger();
1124
            throw new webservice_access_exception('Refused web service access for nologin authentication username: ' . $user->username);
1125
1126
        }

1127
        // now fake user login, the session is completely empty too
Petr Skoda's avatar
Petr Skoda committed
1128
        enrol_check_plugins($user);
1129
        \core\session\manager::set_user($user);
1130
        set_login_session_preferences();
1131
        $this->userid = $user->id;
1132

1133
        if ($this->authmethod != WEBSERVICE_AUTHMETHOD_SESSION_TOKEN && !has_capability("webservice/$this->wsname:use", $this->restricted_context)) {
1134
            throw new webservice_access_exception('You are not allowed to use the {$a} protocol (missing capability: webservice/' . $this->wsname . ':use)');
1135
1136
1137
1138
        }

        external_api::set_context_restriction($this->restricted_context);
    }
1139

1140
1141
1142
1143
1144
1145
1146
    /**
     * User authentication by token
     *
     * @param string $tokentype token type (EXTERNAL_TOKEN_EMBEDDED or EXTERNAL_TOKEN_PERMANENT)
     * @return stdClass the authenticated user
     * @throws webservice_access_exception
     */
1147
1148
    protected function authenticate_by_token($tokentype){
        global $DB;
1149
1150
1151
1152

        $loginfaileddefaultparams = array(
            'other' => array(
                'method' => $this->authmethod,
1153
                'reason' => null
1154
1155
1156
            )
        );

1157
        if (!$token = $DB->get_record('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype))) {
1158
1159
1160
1161
1162
1163
1164
            // Log failed login attempts.
            $params = $loginfaileddefaultparams;
            $params['other']['reason'] = 'invalid_token';
            $event = \core\event\webservice_login_failed::create($params);
            $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' ,
                get_string('failedtolog', 'webservice').": ".$this->token. " - ".getremoteaddr() , 0));
            $event->trigger();
1165
            throw new moodle_exception('invalidtoken', 'webservice');
1166
        }
1167

1168
1169
        if ($token->validuntil and $token->validuntil < time()) {
            $DB->delete_records('external_tokens', array('token'=>$this->token, 'tokentype'=>$tokentype));
1170
            throw new webservice_access_exception('Invalid token - token expired - check validuntil time for the token');
1171
        }
1172

1173
        if ($token->sid){//assumes that if sid is set then there must be a valid associated session no matter the token type
1174
            if (!\core\session\manager::session_exists($token->sid)){
1175
                $DB->delete_records('external_tokens', array('sid'=>$token->sid));
1176
                throw new webservice_access_exception('Invalid session based token - session not found or expired');
1177
1178
1179
1180
            }
        }

        if ($token->iprestriction and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
1181
1182
1183
1184
1185
1186
1187
1188
            $params = $loginfaileddefaultparams;
            $params['other']['reason'] = 'ip_restricted';
            $params['other']['tokenid'] = $token->id;
            $event = \core\event\webservice_login_failed::create($params);
            $event->add_record_snapshot('external_tokens', $token);
            $event->set_legacy_logdata(array(SITEID, 'webservice', get_string('tokenauthlog', 'webservice'), '' ,
                get_string('failedtolog', 'webservice').": ".getremoteaddr() , 0));
            $event->trigger();
1189
1190
            throw new webservice_access_exception('Invalid service - IP:' . getremoteaddr()
                    . ' is not supported - check this allowed user');
1191
1192
        }

1193
        $this->restricted_context = context::instance_by_id($token->contextid);