MDL-46975 core_auth: Make email validation case-insensitive
[moodle.git] / lib / authlib.php
CommitLineData
72dbdcea 1<?php
2
117bd748
PS
3// This file is part of Moodle - http://moodle.org/
4//
72dbdcea 5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
117bd748 14//
72dbdcea 15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
6bc1e5d5 18/**
72dbdcea 19 * Multiple plugin authentication Support library
6bc1e5d5 20 *
21 * 2006-08-28 File created, AUTH return values defined.
117bd748 22 *
78bfb562
PS
23 * @package core
24 * @subpackage auth
25 * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6bc1e5d5 27 */
28
78bfb562
PS
29defined('MOODLE_INTERNAL') || die();
30
6bc1e5d5 31/**
32 * Returned when the login was successful.
33 */
34define('AUTH_OK', 0);
35
36/**
37 * Returned when the login was unsuccessful.
38 */
39define('AUTH_FAIL', 1);
40
41/**
42 * Returned when the login was denied (a reason for AUTH_FAIL).
43 */
44define('AUTH_DENIED', 2);
45
46/**
47 * Returned when some error occurred (a reason for AUTH_FAIL).
48 */
49define('AUTH_ERROR', 4);
50
51/**
52 * Authentication - error codes for user confirm
53 */
54define('AUTH_CONFIRM_FAIL', 0);
55define('AUTH_CONFIRM_OK', 1);
56define('AUTH_CONFIRM_ALREADY', 2);
57define('AUTH_CONFIRM_ERROR', 3);
58
6f87ef52 59# MDL-14055
60define('AUTH_REMOVEUSER_KEEP', 0);
61define('AUTH_REMOVEUSER_SUSPEND', 1);
62define('AUTH_REMOVEUSER_FULLDELETE', 2);
6bc1e5d5 63
b28247fe
PS
64/** Login attempt successful. */
65define('AUTH_LOGIN_OK', 0);
66
67/** Can not login because user does not exist. */
68define('AUTH_LOGIN_NOUSER', 1);
69
70/** Can not login because user is suspended. */
71define('AUTH_LOGIN_SUSPENDED', 2);
72
73/** Can not login, most probably password did not match. */
74define('AUTH_LOGIN_FAILED', 3);
75
76/** Can not login because user is locked out. */
77define('AUTH_LOGIN_LOCKOUT', 4);
78
65d7932c
CF
79/** Can not login becauser user is not authorised. */
80define('AUTH_LOGIN_UNAUTHORISED', 5);
b28247fe 81
6bc1e5d5 82/**
83 * Abstract authentication plugin.
72dbdcea 84 *
85 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
86 * @package moodlecore
6bc1e5d5 87 */
88class auth_plugin_base {
89
90 /**
91 * The configuration details for the plugin.
72dbdcea 92 * @var object
6bc1e5d5 93 */
94 var $config;
95
96 /**
97 * Authentication plugin type - the same as db field.
72dbdcea 98 * @var string
6bc1e5d5 99 */
100 var $authtype;
4105caff 101 /*
102 * The fields we can lock and update from/to external authentication backends
72dbdcea 103 * @var array
4105caff 104 */
d9fbe314 105 var $userfields = \core_user::AUTHSYNCFIELDS;
6bc1e5d5 106
57d135a1
RT
107 /**
108 * Moodle custom fields to sync with.
109 * @var array()
110 */
d836e3ed 111 var $customfields = null;
57d135a1 112
4afad1fa
MN
113 /**
114 * The tag we want to prepend to any error log messages.
115 *
116 * @var string
117 */
118 protected $errorlogtag = '';
119
6bc1e5d5 120 /**
f5fd4347 121 * This is the primary method that is used by the authenticate_user_login()
117bd748 122 * function in moodlelib.php.
72dbdcea 123 *
124 * This method should return a boolean indicating
f5fd4347 125 * whether or not the username and password authenticate successfully.
126 *
6bc1e5d5 127 * Returns true if the username and password work and false if they are
128 * wrong or don't exist.
129 *
130 * @param string $username The username (with system magic quotes)
131 * @param string $password The password (with system magic quotes)
132 *
133 * @return bool Authentication success or failure.
134 */
135 function user_login($username, $password) {
2f137aa1 136 print_error('mustbeoveride', 'debug', '', 'user_login()' );
6bc1e5d5 137 }
138
139 /**
f5fd4347 140 * Returns true if this authentication plugin can change the users'
6bc1e5d5 141 * password.
142 *
143 * @return bool
144 */
145 function can_change_password() {
146 //override if needed
147 return false;
148 }
149
150 /**
f5fd4347 151 * Returns the URL for changing the users' passwords, or empty if the default
117bd748 152 * URL can be used.
72dbdcea 153 *
154 * This method is used if can_change_password() returns true.
80274abf 155 * This method is called only when user is logged in, it may use global $USER.
963cdce4
AA
156 * If you are using a plugin config variable in this method, please make sure it is set before using it,
157 * as this method can be called even if the plugin is disabled, in which case the config values won't be set.
6bc1e5d5 158 *
99f9f85f 159 * @return moodle_url url of the profile page or null if standard used
6bc1e5d5 160 */
161 function change_password_url() {
162 //override if needed
99f9f85f
PS
163 return null;
164 }
165
166 /**
167 * Returns true if this authentication plugin can edit the users'
168 * profile.
169 *
170 * @return bool
171 */
172 function can_edit_profile() {
173 //override if needed
174 return true;
175 }
176
177 /**
178 * Returns the URL for editing the users' profile, or empty if the default
179 * URL can be used.
180 *
181 * This method is used if can_edit_profile() returns true.
182 * This method is called only when user is logged in, it may use global $USER.
183 *
184 * @return moodle_url url of the profile page or null if standard used
185 */
186 function edit_profile_url() {
187 //override if needed
188 return null;
6bc1e5d5 189 }
190
191 /**
7415aed1
PS
192 * Returns true if this authentication plugin is "internal".
193 *
194 * Internal plugins use password hashes from Moodle user table for authentication.
6bc1e5d5 195 *
196 * @return bool
197 */
198 function is_internal() {
199 //override if needed
200 return true;
201 }
202
b6f28375
CF
203 /**
204 * Returns false if this plugin is enabled but not configured.
205 *
206 * @return bool
207 */
208 public function is_configured() {
209 return false;
210 }
211
edb5da83
PS
212 /**
213 * Indicates if password hashes should be stored in local moodle database.
214 * @return bool true means md5 password hash stored in user table, false means flag 'not_cached' stored there instead
215 */
216 function prevent_local_passwords() {
7415aed1
PS
217 return !$this->is_internal();
218 }
219
220 /**
221 * Indicates if moodle should automatically update internal user
222 * records with data from external sources using the information
223 * from get_userinfo() method.
224 *
225 * @return bool true means automatically copy data from ext to user table
226 */
227 function is_synchronised_with_external() {
228 return !$this->is_internal();
edb5da83
PS
229 }
230
6bc1e5d5 231 /**
117bd748 232 * Updates the user's password.
72dbdcea 233 *
234 * In previous versions of Moodle, the function
f5fd4347 235 * auth_user_update_password accepted a username as the first parameter. The
236 * revised function expects a user object.
6bc1e5d5 237 *
ae040d4b 238 * @param object $user User table object
239 * @param string $newpassword Plaintext password
6bc1e5d5 240 *
241 * @return bool True on success
242 */
243 function user_update_password($user, $newpassword) {
244 //override if needed
245 return true;
246 }
247
248 /**
249 * Called when the user record is updated.
250 * Modifies user in external database. It takes olduser (before changes) and newuser (after changes)
640df5d0 251 * compares information saved modified information to external db.
6bc1e5d5 252 *
253 * @param mixed $olduser Userobject before modifications (without system magic quotes)
254 * @param mixed $newuser Userobject new modified userobject (without system magic quotes)
255 * @return boolean true if updated or update ignored; false if error
256 *
257 */
258 function user_update($olduser, $newuser) {
259 //override if needed
260 return true;
261 }
262
90afcf32 263 /**
264 * User delete requested - internal user record is mared as deleted already, username not present anymore.
72dbdcea 265 *
90afcf32 266 * Do any action in external database.
72dbdcea 267 *
90afcf32 268 * @param object $user Userobject before delete (without system magic quotes)
72dbdcea 269 * @return void
90afcf32 270 */
271 function user_delete($olduser) {
272 //override if needed
273 return;
274 }
275
6bc1e5d5 276 /**
277 * Returns true if plugin allows resetting of internal password.
278 *
279 * @return bool
280 */
281 function can_reset_password() {
282 //override if needed
283 return false;
284 }
285
286 /**
287 * Returns true if plugin allows resetting of internal password.
288 *
289 * @return bool
290 */
291 function can_signup() {
292 //override if needed
293 return false;
294 }
295
296 /**
297 * Sign up a new user ready for confirmation.
298 * Password is passed in plaintext.
299 *
5d910388 300 * @param object $user new user object
6bc1e5d5 301 * @param boolean $notify print notice with link and terminate
302 */
303 function user_signup($user, $notify=true) {
304 //override when can signup
2f137aa1 305 print_error('mustbeoveride', 'debug', '', 'user_signup()' );
6bc1e5d5 306 }
b217edd2 307
57d38adc 308 /**
b217edd2 309 * Return a form to capture user details for account creation.
57d38adc
MA
310 * This is used in /login/signup.php.
311 * @return moodle_form A form which edits a record from the user table.
312 */
313 function signup_form() {
314 global $CFG;
b217edd2 315
57d38adc
MA
316 require_once($CFG->dirroot.'/login/signup_form.php');
317 return new login_signup_form(null, null, 'post', '', array('autocomplete'=>'on'));
318 }
6bc1e5d5 319
320 /**
321 * Returns true if plugin allows confirming of new users.
322 *
323 * @return bool
324 */
325 function can_confirm() {
326 //override if needed
327 return false;
328 }
329
330 /**
331 * Confirm the new user as registered.
332 *
b9a66360 333 * @param string $username
334 * @param string $confirmsecret
6bc1e5d5 335 */
336 function user_confirm($username, $confirmsecret) {
337 //override when can confirm
2f137aa1 338 print_error('mustbeoveride', 'debug', '', 'user_confirm()' );
6bc1e5d5 339 }
340
341 /**
342 * Checks if user exists in external db
343 *
344 * @param string $username (with system magic quotes)
03cedd62 345 * @return bool
6bc1e5d5 346 */
d61ffb0f 347 function user_exists($username) {
6bc1e5d5 348 //override if needed
349 return false;
350 }
351
6bc1e5d5 352 /**
353 * return number of days to user password expires
354 *
355 * If userpassword does not expire it should return 0. If password is already expired
356 * it should return negative value.
357 *
358 * @param mixed $username username (with system magic quotes)
359 * @return integer
360 */
361 function password_expire($username) {
362 return 0;
363 }
364 /**
365 * Sync roles for this user - usually creator
366 *
367 * @param $user object user object (without system magic quotes)
368 */
369 function sync_roles($user) {
370 //override if needed
371 }
372
373 /**
374 * Read user information from external database and returns it as array().
375 * Function should return all information available. If you are saving
640df5d0 376 * this information to moodle user-table you should honour synchronisation flags
6bc1e5d5 377 *
be544ec3 378 * @param string $username username
6bc1e5d5 379 *
380 * @return mixed array with no magic quotes or false on error
381 */
382 function get_userinfo($username) {
383 //override if needed
384 return array();
385 }
386
f5fd4347 387 /**
388 * Prints a form for configuring this authentication plugin.
389 *
390 * This function is called from admin/auth.php, and outputs a full page with
391 * a form for configuring this plugin.
72dbdcea 392 *
393 * @param object $config
394 * @param object $err
395 * @param array $user_fields
037273d8 396 * @deprecated since Moodle 3.3
f5fd4347 397 */
398 function config_form($config, $err, $user_fields) {
037273d8 399 debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
f5fd4347 400 //override if needed
401 }
402
6bc1e5d5 403 /**
404 * A chance to validate form data, and last chance to
405 * do stuff before it is inserted in config_plugin
f4f2b8fb 406 * @param object object with submitted configuration settings (without system magic quotes)
407 * @param array $err array of error messages
037273d8 408 * @deprecated since Moodle 3.3
6bc1e5d5 409 */
e2bb3c92 410 function validate_form($form, &$err) {
037273d8 411 debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
6bc1e5d5 412 //override if needed
413 }
414
415 /**
f5fd4347 416 * Processes and stores configuration data for this authentication plugin.
f4f2b8fb 417 *
418 * @param object object with submitted configuration settings (without system magic quotes)
037273d8 419 * @deprecated since Moodle 3.3
6bc1e5d5 420 */
f5fd4347 421 function process_config($config) {
037273d8 422 debugging('Use of config.html files have been deprecated, please update your code to use the admin settings API.');
f5fd4347 423 //override if needed
424 return true;
425 }
426
427 /**
640df5d0 428 * Hook for overriding behaviour of login page.
f5fd4347 429 * This method is called from login/index.php page for all enabled auth plugins.
72dbdcea 430 *
431 * @global object
432 * @global object
f5fd4347 433 */
434 function loginpage_hook() {
435 global $frm; // can be used to override submitted login form
436 global $user; // can be used to replace authenticate_user_login()
437
6bc1e5d5 438 //override if needed
439 }
440
bf08e3f9
BH
441 /**
442 * Hook for overriding behaviour before going to the login page.
443 *
444 * This method is called from require_login from potentially any page for
445 * all enabled auth plugins and gives each plugin a chance to redirect
446 * directly to an external login page, or to instantly login a user where
447 * possible.
448 *
449 * If an auth plugin implements this hook, it must not rely on ONLY this
450 * hook in order to work, as there are many ways a user can browse directly
451 * to the standard login page. As a general rule in this case you should
452 * also implement the loginpage_hook as well.
453 *
454 */
455 function pre_loginpage_hook() {
456 // override if needed, eg by redirecting to an external login page
457 // or logging in a user:
458 // complete_user_login($user);
459 }
460
cffd0fa1
J
461 /**
462 * Pre user_login hook.
463 * This method is called from authenticate_user_login() right after the user
464 * object is generated. This gives the auth plugins an option to make adjustments
465 * before the verification process starts.
466 *
467 * @param object $user user object, later used for $USER
468 */
469 public function pre_user_login_hook(&$user) {
470 // Override if needed.
471 }
472
6bc1e5d5 473 /**
474 * Post authentication hook.
f5fd4347 475 * This method is called from authenticate_user_login() for all enabled auth plugins.
476 *
477 * @param object $user user object, later used for $USER
478 * @param string $username (with system magic quotes)
479 * @param string $password plain text password (with system magic quotes)
6bc1e5d5 480 */
f5fd4347 481 function user_authenticated_hook(&$user, $username, $password) {
482 //override if needed
6bc1e5d5 483 }
484
485 /**
f5fd4347 486 * Pre logout hook.
487 * This method is called from require_logout() for all enabled auth plugins,
72dbdcea 488 *
489 * @global object
6bc1e5d5 490 */
491 function prelogout_hook() {
f5fd4347 492 global $USER; // use $USER->auth to find the plugin used for login
493
494 //override if needed
495 }
496
497 /**
640df5d0 498 * Hook for overriding behaviour of logout page.
f5fd4347 499 * This method is called from login/logout.php page for all enabled auth plugins.
72dbdcea 500 *
501 * @global object
502 * @global string
f5fd4347 503 */
504 function logoutpage_hook() {
505 global $USER; // use $USER->auth to find the plugin used for login
506 global $redirect; // can be used to override redirect after logout
507
6bc1e5d5 508 //override if needed
509 }
2a5f4a88 510
e8656bef 511 /**
512 * Hook called before timing out of database session.
640df5d0 513 * This is useful for SSO and MNET.
72dbdcea 514 *
e8656bef 515 * @param object $user
516 * @param string $sid session id
517 * @param int $timecreated start of session
518 * @param int $timemodified user last seen
519 * @return bool true means do not timeout session yet
520 */
521 function ignore_timeout_hook($user, $sid, $timecreated, $timemodified) {
88fdd846 522 return false;
523 }
524
2a5f4a88 525 /**
526 * Return the properly translated human-friendly title of this auth plugin
72dbdcea 527 *
528 * @todo Document this function
2a5f4a88 529 */
530 function get_title() {
370f10b7 531 return get_string('pluginname', "auth_{$this->authtype}");
2a5f4a88 532 }
533
534 /**
72dbdcea 535 * Get the auth description (from core or own auth lang files)
536 *
537 * @return string The description
2a5f4a88 538 */
539 function get_description() {
37f005b1 540 $authdescription = get_string("auth_{$this->authtype}description", "auth_{$this->authtype}");
2a5f4a88 541 return $authdescription;
542 }
117bd748 543
9b5f87d2 544 /**
0f7f3002 545 * Returns whether or not the captcha element is enabled.
72dbdcea 546 *
9b5f87d2 547 * @abstract Implement in child classes
548 * @return bool
549 */
550 function is_captcha_enabled() {
551 return false;
552 }
553
9b29f686
MN
554 /**
555 * Returns whether or not this authentication plugin can be manually set
556 * for users, for example, when bulk uploading users.
557 *
558 * This should be overriden by authentication plugins where setting the
559 * authentication method manually is allowed.
560 *
561 * @return bool
5bcfd504 562 * @since Moodle 2.6
9b29f686
MN
563 */
564 function can_be_manually_set() {
565 // Override if needed.
566 return false;
567 }
568
b257d7c4
PL
569 /**
570 * Returns a list of potential IdPs that this authentication plugin supports.
b257d7c4 571 *
1cb5c7b3 572 * This is used to provide links on the login page and the login block.
b257d7c4 573 *
1cb5c7b3
DM
574 * The parameter $wantsurl is typically used by the plugin to implement a
575 * return-url feature.
576 *
577 * The returned value is expected to be a list of associative arrays with
578 * string keys:
579 *
580 * - url => (moodle_url|string) URL of the page to send the user to for authentication
581 * - name => (string) Human readable name of the IdP
582 * - iconurl => (moodle_url|string) URL of the icon representing the IdP (since Moodle 3.3)
583 *
584 * For legacy reasons, pre-3.3 plugins can provide the icon via the key:
585 *
586 * - icon => (pix_icon) Icon representing the IdP
587 *
588 * @param string $wantsurl The relative url fragment the user wants to get to.
589 * @return array List of associative arrays with keys url, name, iconurl|icon
b257d7c4
PL
590 */
591 function loginpage_idp_list($wantsurl) {
592 return array();
593 }
9b5f87d2 594
57d135a1
RT
595 /**
596 * Return custom user profile fields.
597 *
598 * @return array list of custom fields.
599 */
600 public function get_custom_user_profile_fields() {
601 global $DB;
d836e3ed
RT
602 // If already retrieved then return.
603 if (!is_null($this->customfields)) {
604 return $this->customfields;
57d135a1
RT
605 }
606
d836e3ed 607 $this->customfields = array();
57d135a1
RT
608 if ($proffields = $DB->get_records('user_info_field')) {
609 foreach ($proffields as $proffield) {
d836e3ed 610 $this->customfields[] = 'profile_field_'.$proffield->shortname;
57d135a1
RT
611 }
612 }
613 unset($proffields);
57d135a1 614
d836e3ed 615 return $this->customfields;
57d135a1 616 }
f9f9d187
SL
617
618 /**
619 * Post logout hook.
620 *
621 * This method is used after moodle logout by auth classes to execute server logout.
622 *
623 * @param stdClass $user clone of USER object before the user session was terminated
624 */
625 public function postlogout_hook($user) {
626 }
627ea5b1 627
2c977ceb
AG
628 /**
629 * Update a local user record from an external source.
630 * This is a lighter version of the one in moodlelib -- won't do
631 * expensive ops such as enrolment.
632 *
633 * @param string $username username
634 * @param array $updatekeys fields to update, false updates all fields.
635 * @param bool $triggerevent set false if user_updated event should not be triggered.
636 * This will not affect user_password_updated event triggering.
4e133e77 637 * @param bool $suspenduser Should the user be suspended?
2c977ceb
AG
638 * @return stdClass|bool updated user record or false if there is no new info to update.
639 */
4e133e77 640 protected function update_user_record($username, $updatekeys = false, $triggerevent = false, $suspenduser = false) {
2c977ceb
AG
641 global $CFG, $DB;
642
643 require_once($CFG->dirroot.'/user/profile/lib.php');
644
645 // Just in case check text case.
646 $username = trim(core_text::strtolower($username));
647
648 // Get the current user record.
649 $user = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id));
650 if (empty($user)) { // Trouble.
4afad1fa
MN
651 error_log($this->errorlogtag . get_string('auth_usernotexist', 'auth', $username));
652 print_error('auth_usernotexist', 'auth', '', $username);
2c977ceb
AG
653 die;
654 }
655
2c977ceb
AG
656 // Protect the userid from being overwritten.
657 $userid = $user->id;
658
659 $needsupdate = false;
660
661 if ($newinfo = $this->get_userinfo($username)) {
662 $newinfo = truncate_userinfo($newinfo);
663
664 if (empty($updatekeys)) { // All keys? this does not support removing values.
665 $updatekeys = array_keys($newinfo);
666 }
667
668 if (!empty($updatekeys)) {
669 $newuser = new stdClass();
670 $newuser->id = $userid;
4e133e77
MN
671 // The cast to int is a workaround for MDL-53959.
672 $newuser->suspended = (int) $suspenduser;
e8a1a586
MN
673 // Load all custom fields.
674 $profilefields = (array) profile_user_record($user->id, false);
675 $newprofilefields = [];
2c977ceb
AG
676
677 foreach ($updatekeys as $key) {
678 if (isset($newinfo[$key])) {
679 $value = $newinfo[$key];
680 } else {
681 $value = '';
682 }
683
684 if (!empty($this->config->{'field_updatelocal_' . $key})) {
685 if (preg_match('/^profile_field_(.*)$/', $key, $match)) {
686 // Custom field.
687 $field = $match[1];
e8a1a586
MN
688 $currentvalue = isset($profilefields[$field]) ? $profilefields[$field] : null;
689 $newprofilefields[$field] = $value;
2c977ceb
AG
690 } else {
691 // Standard field.
692 $currentvalue = isset($user->$key) ? $user->$key : null;
693 $newuser->$key = $value;
694 }
695
696 // Only update if it's changed.
697 if ($currentvalue !== $value) {
698 $needsupdate = true;
699 }
700 }
701 }
702 }
703
704 if ($needsupdate) {
705 user_update_user($newuser, false, $triggerevent);
e8a1a586 706 profile_save_custom_fields($newuser->id, $newprofilefields);
2c977ceb
AG
707 return $DB->get_record('user', array('id' => $userid, 'deleted' => 0));
708 }
709 }
710
711 return false;
712 }
713
627ea5b1
JP
714 /**
715 * Return the list of enabled identity providers.
716 *
1cb5c7b3
DM
717 * Each identity provider data contains the keys url, name and iconurl (or
718 * icon). See the documentation of {@link auth_plugin_base::loginpage_idp_list()}
719 * for detailed description of the returned structure.
627ea5b1
JP
720 *
721 * @param array $authsequence site's auth sequence (list of auth plugins ordered)
1cb5c7b3 722 * @return array List of arrays describing the identity providers
627ea5b1
JP
723 */
724 public static function get_identity_providers($authsequence) {
725 global $SESSION;
726
727 $identityproviders = [];
728 foreach ($authsequence as $authname) {
729 $authplugin = get_auth_plugin($authname);
730 $wantsurl = (isset($SESSION->wantsurl)) ? $SESSION->wantsurl : '';
731 $identityproviders = array_merge($identityproviders, $authplugin->loginpage_idp_list($wantsurl));
732 }
733 return $identityproviders;
734 }
735
736 /**
737 * Prepare a list of identity providers for output.
738 *
1cb5c7b3 739 * @param array $identityproviders as returned by {@link self::get_identity_providers()}
627ea5b1
JP
740 * @param renderer_base $output
741 * @return array the identity providers ready for output
742 */
743 public static function prepare_identity_providers_for_output($identityproviders, renderer_base $output) {
744 $data = [];
745 foreach ($identityproviders as $idp) {
746 if (!empty($idp['icon'])) {
220656e8 747 // Pre-3.3 auth plugins provide icon as a pix_icon instance. New auth plugins (since 3.3) provide iconurl.
c17d949c 748 $idp['iconurl'] = $output->image_url($idp['icon']->pix, $idp['icon']->component);
220656e8
JL
749 }
750 if ($idp['iconurl'] instanceof moodle_url) {
627ea5b1
JP
751 $idp['iconurl'] = $idp['iconurl']->out(false);
752 }
753 unset($idp['icon']);
754 if ($idp['url'] instanceof moodle_url) {
755 $idp['url'] = $idp['url']->out(false);
756 }
757 $data[] = $idp;
758 }
759 return $data;
760 }
6bc1e5d5 761}
b28247fe
PS
762
763/**
764 * Verify if user is locked out.
765 *
766 * @param stdClass $user
767 * @return bool true if user locked out
768 */
769function login_is_lockedout($user) {
770 global $CFG;
771
772 if ($user->mnethostid != $CFG->mnet_localhost_id) {
773 return false;
774 }
775 if (isguestuser($user)) {
776 return false;
777 }
778
779 if (empty($CFG->lockoutthreshold)) {
780 // Lockout not enabled.
781 return false;
782 }
783
784 if (get_user_preferences('login_lockout_ignored', 0, $user)) {
785 // This preference may be used for accounts that must not be locked out.
786 return false;
787 }
788
789 $locked = get_user_preferences('login_lockout', 0, $user);
790 if (!$locked) {
791 return false;
792 }
793
794 if (empty($CFG->lockoutduration)) {
795 // Locked out forever.
796 return true;
797 }
798
799 if (time() - $locked < $CFG->lockoutduration) {
800 return true;
801 }
802
803 login_unlock_account($user);
804
805 return false;
806}
807
808/**
809 * To be called after valid user login.
810 * @param stdClass $user
811 */
812function login_attempt_valid($user) {
813 global $CFG;
814
d79d5ac2 815 // Note: user_loggedin event is triggered in complete_user_login().
3b086e30 816
b28247fe
PS
817 if ($user->mnethostid != $CFG->mnet_localhost_id) {
818 return;
819 }
820 if (isguestuser($user)) {
821 return;
822 }
823
824 // Always unlock here, there might be some race conditions or leftovers when switching threshold.
825 login_unlock_account($user);
826}
827
828/**
829 * To be called after failed user login.
830 * @param stdClass $user
831 */
832function login_attempt_failed($user) {
833 global $CFG;
834
835 if ($user->mnethostid != $CFG->mnet_localhost_id) {
836 return;
837 }
838 if (isguestuser($user)) {
839 return;
840 }
841
52dc1de7
AA
842 $count = get_user_preferences('login_failed_count', 0, $user);
843 $last = get_user_preferences('login_failed_last', 0, $user);
844 $sincescuccess = get_user_preferences('login_failed_count_since_success', $count, $user);
845 $sincescuccess = $sincescuccess + 1;
846 set_user_preference('login_failed_count_since_success', $sincescuccess, $user);
847
b28247fe
PS
848 if (empty($CFG->lockoutthreshold)) {
849 // No threshold means no lockout.
850 // Always unlock here, there might be some race conditions or leftovers when switching threshold.
851 login_unlock_account($user);
852 return;
853 }
854
b28247fe
PS
855 if (!empty($CFG->lockoutwindow) and time() - $last > $CFG->lockoutwindow) {
856 $count = 0;
857 }
858
859 $count = $count+1;
860
861 set_user_preference('login_failed_count', $count, $user);
862 set_user_preference('login_failed_last', time(), $user);
863
864 if ($count >= $CFG->lockoutthreshold) {
865 login_lock_account($user);
866 }
867}
868
869/**
870 * Lockout user and send notification email.
871 *
872 * @param stdClass $user
873 */
874function login_lock_account($user) {
c484af5a 875 global $CFG;
b28247fe
PS
876
877 if ($user->mnethostid != $CFG->mnet_localhost_id) {
878 return;
879 }
880 if (isguestuser($user)) {
881 return;
882 }
883
884 if (get_user_preferences('login_lockout_ignored', 0, $user)) {
885 // This user can not be locked out.
886 return;
887 }
888
889 $alreadylockedout = get_user_preferences('login_lockout', 0, $user);
890
891 set_user_preference('login_lockout', time(), $user);
892
893 if ($alreadylockedout == 0) {
894 $secret = random_string(15);
895 set_user_preference('login_lockout_secret', $secret, $user);
896
c484af5a 897 $oldforcelang = force_current_language($user->lang);
b28247fe
PS
898
899 $site = get_site();
2b503e40 900 $supportuser = core_user::get_support_user();
b28247fe
PS
901
902 $data = new stdClass();
903 $data->firstname = $user->firstname;
904 $data->lastname = $user->lastname;
905 $data->username = $user->username;
906 $data->sitename = format_string($site->fullname);
907 $data->link = $CFG->wwwroot.'/login/unlock_account.php?u='.$user->id.'&s='.$secret;
908 $data->admin = generate_email_signoff();
909
910 $message = get_string('lockoutemailbody', 'admin', $data);
911 $subject = get_string('lockoutemailsubject', 'admin', format_string($site->fullname));
912
913 if ($message) {
914 // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
915 email_to_user($user, $supportuser, $subject, $message);
916 }
917
c484af5a 918 force_current_language($oldforcelang);
b28247fe
PS
919 }
920}
921
922/**
923 * Unlock user account and reset timers.
924 *
925 * @param stdClass $user
926 */
927function login_unlock_account($user) {
928 unset_user_preference('login_lockout', $user);
929 unset_user_preference('login_failed_count', $user);
930 unset_user_preference('login_failed_last', $user);
931
932 // Note: do not clear the lockout secret because user might click on the link repeatedly.
933}
574b9d86
JL
934
935/**
936 * Returns whether or not the captcha element is enabled, and the admin settings fulfil its requirements.
937 * @return bool
938 */
939function signup_captcha_enabled() {
940 global $CFG;
941 $authplugin = get_auth_plugin($CFG->registerauth);
942 return !empty($CFG->recaptchapublickey) && !empty($CFG->recaptchaprivatekey) && $authplugin->is_captcha_enabled();
943}
944
945/**
946 * Validates the standard sign-up data (except recaptcha that is validated by the form element).
947 *
948 * @param array $data the sign-up data
949 * @param array $files files among the data
950 * @return array list of errors, being the key the data element name and the value the error itself
951 * @since Moodle 3.2
952 */
953function signup_validate_data($data, $files) {
954 global $CFG, $DB;
955
956 $errors = array();
957 $authplugin = get_auth_plugin($CFG->registerauth);
958
959 if ($DB->record_exists('user', array('username' => $data['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
960 $errors['username'] = get_string('usernameexists');
961 } else {
962 // Check allowed characters.
963 if ($data['username'] !== core_text::strtolower($data['username'])) {
964 $errors['username'] = get_string('usernamelowercase');
965 } else {
966 if ($data['username'] !== core_user::clean_field($data['username'], 'username')) {
967 $errors['username'] = get_string('invalidusername');
968 }
969
970 }
971 }
972
973 // Check if user exists in external db.
974 // TODO: maybe we should check all enabled plugins instead.
975 if ($authplugin->user_exists($data['username'])) {
976 $errors['username'] = get_string('usernameexists');
977 }
978
979 if (! validate_email($data['email'])) {
980 $errors['email'] = get_string('invalidemail');
981
cd69d45d
JP
982 } else if (empty($CFG->allowaccountssameemail)) {
983 // Make a case-insensitive query for the given email address.
984 $select = $DB->sql_equal('email', ':email', false) . ' AND mnethostid = :mnethostid';
985 $params = array(
986 'email' => $data['email'],
987 'mnethostid' => $CFG->mnet_localhost_id,
988 );
989 // If there are other user(s) that already have the same email, show an error.
990 if ($DB->record_exists_select('user', $select, $params)) {
991 $forgotpasswordurl = new moodle_url('/login/forgot_password.php');
992 $forgotpasswordlink = html_writer::link($forgotpasswordurl, get_string('emailexistshintlink'));
993 $errors['email'] = get_string('emailexists') . ' ' . get_string('emailexistssignuphint', 'moodle', $forgotpasswordlink);
994 }
574b9d86
JL
995 }
996 if (empty($data['email2'])) {
997 $errors['email2'] = get_string('missingemail');
998
cd69d45d 999 } else if (core_text::strtolower($data['email2']) != core_text::strtolower($data['email'])) {
574b9d86
JL
1000 $errors['email2'] = get_string('invalidemail');
1001 }
1002 if (!isset($errors['email'])) {
1003 if ($err = email_is_not_allowed($data['email'])) {
1004 $errors['email'] = $err;
1005 }
1006 }
1007
1008 $errmsg = '';
1009 if (!check_password_policy($data['password'], $errmsg)) {
1010 $errors['password'] = $errmsg;
1011 }
1012
1013 // Validate customisable profile fields. (profile_validation expects an object as the parameter with userid set).
1014 $dataobject = (object)$data;
1015 $dataobject->id = 0;
1016 $errors += profile_validation($dataobject, $files);
1017
1018 return $errors;
1019}
1020
1021/**
1022 * Add the missing fields to a user that is going to be created
1023 *
1024 * @param stdClass $user the new user object
1025 * @return stdClass the user filled
1026 * @since Moodle 3.2
1027 */
1028function signup_setup_new_user($user) {
1029 global $CFG;
1030
1031 $user->confirmed = 0;
1032 $user->lang = current_language();
1033 $user->firstaccess = 0;
1034 $user->timecreated = time();
1035 $user->mnethostid = $CFG->mnet_localhost_id;
1036 $user->secret = random_string(15);
1037 $user->auth = $CFG->registerauth;
1038 // Initialize alternate name fields to empty strings.
1039 $namefields = array_diff(get_all_user_name_fields(), useredit_get_required_name_fields());
1040 foreach ($namefields as $namefield) {
1041 $user->$namefield = '';
1042 }
1043 return $user;
1044}
83e4dc17
JL
1045
1046/**
1047 * Check if user confirmation is enabled on this site and return the auth plugin handling registration if enabled.
1048 *
1049 * @return stdClass the current auth plugin handling user registration or false if registration not enabled
1050 * @since Moodle 3.2
1051 */
1052function signup_get_user_confirmation_authplugin() {
1053 global $CFG;
1054
1055 if (empty($CFG->registerauth)) {
1056 return false;
1057 }
1058 $authplugin = get_auth_plugin($CFG->registerauth);
1059
1060 if (!$authplugin->can_confirm()) {
1061 return false;
1062 }
1063 return $authplugin;
1064}
813320fb
JL
1065
1066/**
1067 * Check if sign-up is enabled in the site. If is enabled, the function will return the authplugin instance.
1068 *
1069 * @return mixed false if sign-up is not enabled, the authplugin instance otherwise.
1070 * @since Moodle 3.2
1071 */
1072function signup_is_enabled() {
1073 global $CFG;
1074
1075 if (!empty($CFG->registerauth)) {
1076 $authplugin = get_auth_plugin($CFG->registerauth);
1077 if ($authplugin->can_signup()) {
1078 return $authplugin;
1079 }
1080 }
1081 return false;
1082}
037273d8
SB
1083
1084/**
1085 * Helper function used to print locking for auth plugins on admin pages.
1086 * @param stdclass $settings Moodle admin settings instance
1087 * @param string $auth authentication plugin shortname
1088 * @param array $userfields user profile fields
1089 * @param string $helptext help text to be displayed at top of form
1090 * @param boolean $mapremotefields Map fields or lock only.
1091 * @param boolean $updateremotefields Allow remote updates
1092 * @param array $customfields list of custom profile fields
1093 * @since Moodle 3.3
1094 */
1095function display_auth_lock_options($settings, $auth, $userfields, $helptext, $mapremotefields, $updateremotefields, $customfields = array()) {
1096 global $DB;
1097
1098 // Introductory explanation and help text.
1099 if ($mapremotefields) {
1100 $settings->add(new admin_setting_heading($auth.'/data_mapping', new lang_string('auth_data_mapping', 'auth'), $helptext));
1101 } else {
1102 $settings->add(new admin_setting_heading($auth.'/auth_fieldlocks', new lang_string('auth_fieldlocks', 'auth'), $helptext));
1103 }
1104
1105 // Generate the list of options.
1106 $lockoptions = array ('unlocked' => get_string('unlocked', 'auth'),
1107 'unlockedifempty' => get_string('unlockedifempty', 'auth'),
1108 'locked' => get_string('locked', 'auth'));
1109 $updatelocaloptions = array('oncreate' => get_string('update_oncreate', 'auth'),
1110 'onlogin' => get_string('update_onlogin', 'auth'));
1111 $updateextoptions = array('0' => get_string('update_never', 'auth'),
1112 '1' => get_string('update_onupdate', 'auth'));
1113
1114 // Generate the list of profile fields to allow updates / lock.
1115 if (!empty($customfields)) {
1116 $userfields = array_merge($userfields, $customfields);
1117 $customfieldname = $DB->get_records('user_info_field', null, '', 'shortname, name');
1118 }
1119
1120 foreach ($userfields as $field) {
037273d8
SB
1121 // Define the fieldname we display to the user.
1122 // this includes special handling for some profile fields.
1123 $fieldname = $field;
65a77c73 1124 $fieldnametoolong = false;
037273d8
SB
1125 if ($fieldname === 'lang') {
1126 $fieldname = get_string('language');
1127 } else if (!empty($customfields) && in_array($field, $customfields)) {
1128 // If custom field then pick name from database.
1129 $fieldshortname = str_replace('profile_field_', '', $fieldname);
1130 $fieldname = $customfieldname[$fieldshortname]->name;
65a77c73
MG
1131 if (core_text::strlen($fieldshortname) > 67) {
1132 // If custom profile field name is longer than 67 characters we will not be able to store the setting
1133 // such as 'field_updateremote_profile_field_NOTSOSHORTSHORTNAME' in the database because the character
1134 // limit for the setting name is 100.
1135 $fieldnametoolong = true;
1136 }
037273d8
SB
1137 } else if ($fieldname == 'url') {
1138 $fieldname = get_string('webpage');
1139 } else {
1140 $fieldname = get_string($fieldname);
1141 }
1142
1143 // Generate the list of fields / mappings.
65a77c73
MG
1144 if ($fieldnametoolong) {
1145 // Display a message that the field can not be mapped because it's too long.
1146 $url = new moodle_url('/user/profile/index.php');
1147 $a = (object)['fieldname' => s($fieldname), 'shortname' => s($field), 'charlimit' => 67, 'link' => $url->out()];
1148 $settings->add(new admin_setting_heading($auth.'/field_not_mapped_'.sha1($field), '',
1149 get_string('cannotmapfield', 'auth', $a)));
1150 } else if ($mapremotefields) {
037273d8
SB
1151 // We are mapping to a remote field here.
1152 // Mapping.
1153 $settings->add(new admin_setting_configtext("auth_{$auth}/field_map_{$field}",
b5883736 1154 get_string('auth_fieldmapping', 'auth', $fieldname), '', '', PARAM_RAW, 30));
037273d8
SB
1155
1156 // Update local.
1157 $settings->add(new admin_setting_configselect("auth_{$auth}/field_updatelocal_{$field}",
3ee50231 1158 get_string('auth_updatelocalfield', 'auth', $fieldname), '', 'oncreate', $updatelocaloptions));
037273d8
SB
1159
1160 // Update remote.
1161 if ($updateremotefields) {
1162 $settings->add(new admin_setting_configselect("auth_{$auth}/field_updateremote_{$field}",
3ee50231 1163 get_string('auth_updateremotefield', 'auth', $fieldname), '', 0, $updateextoptions));
037273d8
SB
1164 }
1165
1166 // Lock fields.
1167 $settings->add(new admin_setting_configselect("auth_{$auth}/field_lock_{$field}",
3ee50231 1168 get_string('auth_fieldlockfield', 'auth', $fieldname), '', 'unlocked', $lockoptions));
037273d8
SB
1169
1170 } else {
1171 // Lock fields Only.
1172 $settings->add(new admin_setting_configselect("auth_{$auth}/field_lock_{$field}",
3ee50231 1173 get_string('auth_fieldlockfield', 'auth', $fieldname), '', 'unlocked', $lockoptions));
037273d8
SB
1174 }
1175 }
627ea5b1 1176}