lib.php 69.6 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
     *
     * @param int $userid user id
627
628
629
630
631
     * @return array
     */
    public function get_user_capabilities($userid) {
        global $DB;
        //retrieve the user capabilities
632
633
634
        $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));
635
636
637
638
639
640
641
642
        $usercaps = array();
        foreach ($dbusercaps as $usercap) {
            $usercaps[$usercap->capability] = true;
        }
        return $usercaps;
    }

    /**
643
     * Get missing user capabilities for a given service
644
645
646
647
     * 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
648
649
650
651
     *
     * @param array $users users
     * @param int $serviceid service id
     * @return array of missing capabilities, keys being the user ids
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
     */
    public function get_missing_capabilities_by_users($users, $serviceid) {
        global $DB;
        $usersmissingcaps = array();

        //retrieve capabilities required by the service
        $servicecaps = $this->get_service_required_capabilities($serviceid);

        //retrieve users missing capabilities
        foreach ($users as $user) {
            //cast user array into object to be a bit more flexible
            if (is_array($user)) {
                $user = (object) $user;
            }
            $usercaps = $this->get_user_capabilities($user->id);

            //detect the missing capabilities
            foreach ($servicecaps as $functioname => $functioncaps) {
                foreach ($functioncaps as $functioncap) {
671
                    if (!array_key_exists($functioncap, $usercaps)) {
672
673
674
675
676
677
678
679
680
681
682
683
                        if (!isset($usersmissingcaps[$user->id])
                                or array_search($functioncap, $usersmissingcaps[$user->id]) === false) {
                            $usersmissingcaps[$user->id][] = $functioncap;
                        }
                    }
                }
            }
        }

        return $usersmissingcaps;
    }

684
    /**
685
686
687
688
689
     * 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
690
691
692
693
694
695
696
697
     */
    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;
    }

698
    /**
699
700
701
702
703
     * Get an external service for a given shortname
     *
     * @param string $shortname service shortname
     * @param int $strictness IGNORE_MISSING, MUST_EXIST...
     * @return stdClass external service
704
705
706
707
708
709
710
711
     */
    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;
    }

712
    /**
713
714
715
716
717
     * 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
718
719
720
721
722
723
724
725
726
727
     */
    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
728
729
730
     *
     * @param string $functionname function name
     * @param int $serviceid service id
731
732
733
     */
    public function add_external_function_to_service($functionname, $serviceid) {
        global $DB;
734
        $addedfunction = new stdClass();
735
736
737
738
739
        $addedfunction->externalserviceid = $serviceid;
        $addedfunction->functionname = $functionname;
        $DB->insert_record('external_services_functions', $addedfunction);
    }

740
741
    /**
     * Add a service
742
743
744
     * It generates the timecreated field automatically.
     *
     * @param stdClass $service
745
746
747
748
     * @return serviceid integer
     */
    public function add_external_service($service) {
        global $DB;
Petr Skoda's avatar
Petr Skoda committed
749
        $service->timecreated = time();
750
751
752
753
        $serviceid = $DB->insert_record('external_services', $service);
        return $serviceid;
    }

754
    /**
755
     * Update a service
756
757
758
     * It modifies the timemodified automatically.
     *
     * @param stdClass $service
759
760
761
     */
    public function update_external_service($service) {
        global $DB;
Petr Skoda's avatar
Petr Skoda committed
762
        $service->timemodified = time();
763
764
765
        $DB->update_record('external_services', $service);
    }

766
    /**
767
768
769
770
     * Test whether an external function is already linked to a service
     *
     * @param string $functionname function name
     * @param int $serviceid service id
771
772
773
774
775
776
777
778
779
780
     * @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));
    }

781
782
783
784
785
786
    /**
     * Remove a function from a service
     *
     * @param string $functionname function name
     * @param int $serviceid service id
     */
787
788
789
790
791
792
793
    public function remove_external_function_from_service($functionname, $serviceid) {
        global $DB;
        $DB->delete_records('external_services_functions',
                    array('externalserviceid' => $serviceid, 'functionname' => $functionname));

    }

794
795
796
797
798
799
800
801
802
    /**
     * 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;
803

804
805
806
807
808
809
        $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);
    }
810
}
811

812
813
/**
 * Exception indicating access control problem in web service call
814
815
816
817
 * 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.
818
819
820
821
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
822
823
 */
class webservice_access_exception extends moodle_exception {
824

825
826
    /**
     * Constructor
827
828
     *
     * @param string $debuginfo the debug info
829
830
     */
    function __construct($debuginfo) {
831
        parent::__construct('accessexception', 'webservice', '', null, $debuginfo);
832
833
834
    }
}

835
/**
836
837
 * Check if a protocol is enabled
 *
838
 * @param string $protocol name of WS protocol ('rest', 'soap', 'xmlrpc'...)
839
 * @return bool true if the protocol is enabled
840
 */
841
842
function webservice_protocol_is_enabled($protocol) {
    global $CFG;
843

844
845
    if (empty($CFG->enablewebservices)) {
        return false;
846
847
    }

848
    $active = explode(',', $CFG->webserviceprotocols);
849

850
851
    return(in_array($protocol, $active));
}
852

853
/**
Petr Skoda's avatar
Petr Skoda committed
854
 * Mandatory interface for all test client classes.
855
856
857
858
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
859
860
 */
interface webservice_test_client_interface {
861

862
863
    /**
     * Execute test client WS request
864
865
866
867
     *
     * @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
868
869
870
871
872
     * @return mixed
     */
    public function simpletest($serverurl, $function, $params);
}

873
/**
Petr Skoda's avatar
Petr Skoda committed
874
 * Mandatory interface for all web service protocol classes
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
interface webservice_server_interface {
881

882
883
884
885
886
    /**
     * Process request from client.
     */
    public function run();
}
887

888
889
/**
 * Abstract web service base class.
890
891
892
893
 *
 * @package    core_webservice
 * @copyright  2009 Petr Skodak
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
894
895
 */
abstract class webservice_server implements webservice_server_interface {
896

897
    /** @var string Name of the web server plugin */
898
899
    protected $wsname = null;

900
    /** @var string Name of local user */
901
902
    protected $username = null;

903
    /** @var string Password of the local user */
904
    protected $password = null;
905

906
    /** @var int The local user */
907
908
    protected $userid = null;

909
    /** @var integer Authentication method one of WEBSERVICE_AUTHMETHOD_* */
910
    protected $authmethod;
911

912
    /** @var string Authentication token*/
913
    protected $token = null;
914

915
    /** @var stdClass Restricted context */
916
917
    protected $restricted_context;

918
    /** @var int Restrict call to one service id*/
919
920
    protected $restricted_serviceid = null;

921
    /**
922
923
     * Constructor
     *
924
     * @param integer $authmethod authentication method one of WEBSERVICE_AUTHMETHOD_*
925
926
927
     */
    public function __construct($authmethod) {
        $this->authmethod = $authmethod;
928
929
930
    }


931
932
933
934
935
936
937
938
939
940
941
942
943
944
    /**
     * 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!');
        }

945
946
947
        $loginfaileddefaultparams = array(
            'other' => array(
                'method' => $this->authmethod,
948
                'reason' => null
949
950
951
            )
        );

952
        if ($this->authmethod == WEBSERVICE_AUTHMETHOD_USERNAME) {
953

954
955
956
            //we check that authentication plugin is enabled
            //it is only required by simple authentication
            if (!is_enabled_auth('webservice')) {
957
                throw new webservice_access_exception('The web service authentication plugin is disabled.');
958
            }
959

960
            if (!$auth = get_auth_plugin('webservice')) {
961
                throw new webservice_access_exception('The web service authentication plugin is missing.');
962
            }
963

964
            $this->restricted_context = context_system::instance();
965
966

            if (!$this->username) {
967
                throw new moodle_exception('missingusername', 'webservice');
968
969
970
            }

            if (!$this->password) {
971
                throw new moodle_exception('missingpassword', 'webservice');
972
973
974
            }

            if (!$auth->user_login_webservice($this->username, $this->password)) {
975
976
977
978
979
980
981
982
983
984

                // 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();

985
                throw new moodle_exception('wrongusernamepassword', 'webservice');
986
987
            }

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

990
991
        } else if ($this->authmethod == WEBSERVICE_AUTHMETHOD_PERMANENT_TOKEN){
            $user = $this->authenticate_by_token(EXTERNAL_TOKEN_PERMANENT);
992
        } else {
993
            $user = $this->authenticate_by_token(EXTERNAL_TOKEN_EMBEDDED);
994
        }
995

996
997
998
        // Cannot authenticate unless maintenance access is granted.
        $hasmaintenanceaccess = has_capability('moodle/site:maintenanceaccess', context_system::instance(), $user);
        if (!empty($CFG->maintenance_enabled) and !$hasmaintenanceaccess) {
999
            throw new moodle_exception('sitemaintenance', 'admin');
1000
        }
For faster browsing, not all history is shown. View entire blame