private function list_enabled_auth_plugins() { $plugins = get_enabled_auth_plugins(); echo "\nList of enabled auth plugins:\n\n"; for ($i = 0; $i < count($plugins); $i++) { echo $i + 1 . ". " . $plugins[$i] . "\n"; } }
function __logout() { $authsequence = get_enabled_auth_plugins(); // auths, in sequence foreach ($authsequence as $authname) { $authplugin = get_auth_plugin($authname); $authplugin->logoutpage_hook(); } require_logout(); }
public function execute() { global $CFG; $action = $this->arguments[0]; $pluginname = $this->arguments[1]; // Does the authentication module exist? if (!exists_auth_plugin($pluginname)) { print_error('pluginnotinstalled', 'auth', '', $pluginname); } // Get enabled plugins. $authsenabled = get_enabled_auth_plugins(true); if (empty($CFG->auth)) { $authsenabled = array(); } else { $authsenabled = explode(',', $CFG->auth); } switch ($action) { case 'disable': $key = array_search($pluginname, $authsenabled); if ($key !== false) { unset($authsenabled[$key]); set_config('auth', implode(',', $authsenabled)); } break; case 'down': $key = array_search($pluginname, $authsenabled); if ($key !== false && $key < count($authsenabled) - 1) { $fsave = $authsenabled[$key]; $authsenabled[$key] = $authsenabled[$key + 1]; $authsenabled[$key + 1] = $fsave; set_config('auth', implode(',', $authsenabled)); } case 'enable': if (!in_array($pluginname, $authsenabled)) { $authsenabled[] = $pluginname; $authsenabled = array_unique($authsenabled); set_config('auth', implode(',', $authsenabled)); } break; case 'up': $key = array_search($pluginname, $authsenabled); if ($key !== false && $key >= 1) { $fsave = $authsenabled[$key]; $authsenabled[$key] = $authsenabled[$key - 1]; $authsenabled[$key - 1] = $fsave; set_config('auth', implode(',', $authsenabled)); } break; } echo "Auth modules enabled: " . implode(',', $authsenabled) . "\n"; }
public function __construct() { global $CFG, $SESSION, $OUTPUT; // Get all alternative login methods and add to potentialipds array. $authsequence = get_enabled_auth_plugins(true); $potentialidps = []; foreach ($authsequence as $authname) { if (isset($SESSION->snapwantsurl)) { $urltogo = $SESSION->snapwantsurl; } else { $urltogo = $CFG->wwwroot . '/'; } unset($SESSION->snapwantsurl); $authplugin = get_auth_plugin($authname); $potentialidps = array_merge($potentialidps, $authplugin->loginpage_idp_list($urltogo)); } if (!empty($potentialidps)) { foreach ($potentialidps as $idp) { $this->potentialidps[] = (object) ['url' => $idp['url']->out(), 'name' => $idp['name'], 'icon' => $OUTPUT->pix_url($idp['icon']->pix)]; } } }
*/ require_once '../../config.php'; require_once 'lib.php'; require_once $CFG->libdir . '/adminlib.php'; $confirm = optional_param('confirm', 0, PARAM_BOOL); require_login(); admin_externalpage_setup('userbulk'); require_capability('moodle/user:update', get_context_instance(CONTEXT_SYSTEM)); $return = $CFG->wwwroot . '/' . $CFG->admin . '/user/user_bulk.php'; if (empty($SESSION->bulk_users)) { redirect($return); } echo $OUTPUT->header(); if ($confirm and confirm_sesskey()) { // only force password change if user may actually change the password $authsavailable = get_enabled_auth_plugins(); $changeable = array(); foreach ($authsavailable as $authplugin) { if (!($auth = get_auth_plugin($authplugin))) { continue; } if ($auth->is_internal() and $auth->can_change_password()) { $changeable[$authplugin] = true; } } $parts = array_chunk($SESSION->bulk_users, 300); foreach ($parts as $users) { list($in, $params) = $DB->get_in_or_equal($users); if ($rs = $DB->get_recordset_select('user', "id {$in}", $params)) { foreach ($rs as $user) { if (!empty($changeable[$user->auth])) {
/** * Periodic timed-out session cleanup. */ public static function gc() { global $CFG, $DB; // This may take a long time... \core_php_time_limit::raise(); $maxlifetime = $CFG->sessiontimeout; try { // Kill all sessions of deleted and suspended users without any hesitation. $rs = $DB->get_recordset_select('sessions', "userid IN (SELECT id FROM {user} WHERE deleted <> 0 OR suspended <> 0)", array(), 'id DESC', 'id, sid'); foreach ($rs as $session) { self::kill_session($session->sid); } $rs->close(); // Kill sessions of users with disabled plugins. $auth_sequence = get_enabled_auth_plugins(true); $auth_sequence = array_flip($auth_sequence); unset($auth_sequence['nologin']); // No login means user cannot login. $auth_sequence = array_flip($auth_sequence); list($notplugins, $params) = $DB->get_in_or_equal($auth_sequence, SQL_PARAMS_QM, '', false); $rs = $DB->get_recordset_select('sessions', "userid IN (SELECT id FROM {user} WHERE auth {$notplugins})", $params, 'id DESC', 'id, sid'); foreach ($rs as $session) { self::kill_session($session->sid); } $rs->close(); // Now get a list of time-out candidates - real users only. $sql = "SELECT u.*, s.sid, s.timecreated AS s_timecreated, s.timemodified AS s_timemodified\n FROM {user} u\n JOIN {sessions} s ON s.userid = u.id\n WHERE s.timemodified < :purgebefore AND u.id <> :guestid"; $params = array('purgebefore' => time() - $maxlifetime, 'guestid' => $CFG->siteguest); $authplugins = array(); foreach ($auth_sequence as $authname) { $authplugins[$authname] = get_auth_plugin($authname); } $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $user) { foreach ($authplugins as $authplugin) { /** @var \auth_plugin_base $authplugin*/ if ($authplugin->ignore_timeout_hook($user, $user->sid, $user->s_timecreated, $user->s_timemodified)) { continue; } } self::kill_session($user->sid); } $rs->close(); // Delete expired sessions for guest user account, give them larger timeout, there is no security risk here. $params = array('purgebefore' => time() - $maxlifetime * 5, 'guestid' => $CFG->siteguest); $rs = $DB->get_recordset_select('sessions', 'userid = :guestid AND timemodified < :purgebefore', $params, 'id DESC', 'id, sid'); foreach ($rs as $session) { self::kill_session($session->sid); } $rs->close(); // Delete expired sessions for userid = 0 (not logged in), better kill them asap to release memory. $params = array('purgebefore' => time() - $maxlifetime); $rs = $DB->get_recordset_select('sessions', 'userid = 0 AND timemodified < :purgebefore', $params, 'id DESC', 'id, sid'); foreach ($rs as $session) { self::kill_session($session->sid); } $rs->close(); // Cleanup letfovers from the first browser access because it may set multiple cookies and then use only one. $params = array('purgebefore' => time() - 60 * 3); $rs = $DB->get_recordset_select('sessions', 'userid = 0 AND timemodified = timecreated AND timemodified < :purgebefore', $params, 'id ASC', 'id, sid'); foreach ($rs as $session) { self::kill_session($session->sid); } $rs->close(); } catch (\Exception $ex) { debugging('Error gc-ing sessions: ' . $ex->getMessage(), DEBUG_NORMAL, $ex->getTrace()); } }
/** * Cron functions. * * @package core * @subpackage admin * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ function cron_run() { global $DB, $CFG, $OUTPUT; if (CLI_MAINTENANCE) { echo "CLI maintenance mode active, cron execution suspended.\n"; exit(1); } if (moodle_needs_upgrading()) { echo "Moodle upgrade pending, cron execution suspended.\n"; exit(1); } require_once $CFG->libdir . '/adminlib.php'; require_once $CFG->libdir . '/gradelib.php'; if (!empty($CFG->showcronsql)) { $DB->set_debug(true); } if (!empty($CFG->showcrondebugging)) { $CFG->debug = DEBUG_DEVELOPER; $CFG->debugdisplay = true; } set_time_limit(0); $starttime = microtime(); /// increase memory limit raise_memory_limit(MEMORY_EXTRA); /// emulate normal session cron_setup_user(); /// Start output log $timenow = time(); mtrace("Server Time: " . date('r', $timenow) . "\n\n"); /// Session gc mtrace("Cleaning up stale sessions"); session_gc(); /// Run all cron jobs for each module mtrace("Starting activity modules"); get_mailer('buffer'); if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) { foreach ($mods as $mod) { $libfile = "{$CFG->dirroot}/mod/{$mod->name}/lib.php"; if (file_exists($libfile)) { include_once $libfile; $cron_function = $mod->name . "_cron"; if (function_exists($cron_function)) { mtrace("Processing module function {$cron_function} ...", ''); $pre_dbqueries = null; $pre_dbqueries = $DB->perf_get_queries(); $pre_time = microtime(1); if ($cron_function()) { $DB->set_field("modules", "lastcron", $timenow, array("id" => $mod->id)); } if (isset($pre_dbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries"); mtrace("... used " . (microtime(1) - $pre_time) . " seconds"); } /// Reset possible changes by modules to time_limit. MDL-11597 @set_time_limit(0); mtrace("done."); } } } } get_mailer('close'); mtrace("Finished activity modules"); mtrace("Starting blocks"); if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) { // we will need the base class. require_once $CFG->dirroot . '/blocks/moodleblock.class.php'; foreach ($blocks as $block) { $blockfile = $CFG->dirroot . '/blocks/' . $block->name . '/block_' . $block->name . '.php'; if (file_exists($blockfile)) { require_once $blockfile; $classname = 'block_' . $block->name; $blockobj = new $classname(); if (method_exists($blockobj, 'cron')) { mtrace("Processing cron function for " . $block->name . '....', ''); if ($blockobj->cron()) { $DB->set_field('block', 'lastcron', $timenow, array('id' => $block->id)); } /// Reset possible changes by blocks to time_limit. MDL-11597 @set_time_limit(0); mtrace('done.'); } } } } mtrace('Finished blocks'); //now do plagiarism checks require_once $CFG->libdir . '/plagiarismlib.php'; plagiarism_cron(); mtrace("Starting quiz reports"); if ($reports = $DB->get_records_select('quiz_report', "cron > 0 AND ((? - lastcron) > cron)", array($timenow))) { foreach ($reports as $report) { $cronfile = "{$CFG->dirroot}/mod/quiz/report/{$report->name}/cron.php"; if (file_exists($cronfile)) { include_once $cronfile; $cron_function = 'quiz_report_' . $report->name . "_cron"; if (function_exists($cron_function)) { mtrace("Processing quiz report cron function {$cron_function} ...", ''); $pre_dbqueries = null; $pre_dbqueries = $DB->perf_get_queries(); $pre_time = microtime(1); if ($cron_function()) { $DB->set_field('quiz_report', "lastcron", $timenow, array("id" => $report->id)); } if (isset($pre_dbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries"); mtrace("... used " . (microtime(1) - $pre_time) . " seconds"); } mtrace("done."); } } } } mtrace("Finished quiz reports"); mtrace('Starting admin reports'); // Admin reports do not have a database table that lists them. Instead a // report includes cron.php with function report_reportname_cron() if it wishes // to be cronned. It is up to cron.php to handle e.g. if it only needs to // actually do anything occasionally. $reports = get_plugin_list('report'); foreach ($reports as $report => $reportdir) { $cronfile = $reportdir . '/cron.php'; if (file_exists($cronfile)) { require_once $cronfile; $cronfunction = 'report_' . $report . '_cron'; mtrace('Processing cron function for ' . $report . '...', ''); $pre_dbqueries = null; $pre_dbqueries = $DB->perf_get_queries(); $pre_time = microtime(true); $cronfunction(); if (isset($pre_dbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries"); mtrace("... used " . round(microtime(true) - $pre_time, 2) . " seconds"); } mtrace('done.'); } } mtrace('Finished admin reports'); mtrace('Starting main gradebook job ...'); grade_cron(); mtrace('done.'); mtrace('Starting processing the event queue...'); events_cron(); mtrace('done.'); if ($CFG->enablecompletion) { // Completion cron mtrace('Starting the completion cron...'); require_once $CFG->libdir . '/completion/cron.php'; completion_cron(); mtrace('done'); } if ($CFG->enableportfolios) { // Portfolio cron mtrace('Starting the portfolio cron...'); require_once $CFG->libdir . '/portfoliolib.php'; portfolio_cron(); mtrace('done'); } /// Run all core cron jobs, but not every time since they aren't too important. /// These don't have a timer to reduce load, so we'll use a random number /// to randomly choose the percentage of times we should run these jobs. srand((double) microtime() * 10000000); $random100 = rand(0, 100); if ($random100 < 20) { // Approximately 20% of the time. mtrace("Running clean-up tasks..."); /// Delete users who haven't confirmed within required period if (!empty($CFG->deleteunconfirmed)) { $cuttime = $timenow - $CFG->deleteunconfirmed * 3600; $rs = $DB->get_recordset_sql("SELECT id, firstname, lastname\n FROM {user}\n WHERE confirmed = 0 AND firstaccess > 0\n AND firstaccess < ?", array($cuttime)); foreach ($rs as $user) { if ($DB->delete_records('user', array('id' => $user->id))) { mtrace("Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})"); } } $rs->close(); } flush(); /// Delete users who haven't completed profile within required period if (!empty($CFG->deleteincompleteusers)) { $cuttime = $timenow - $CFG->deleteincompleteusers * 3600; $rs = $DB->get_recordset_sql("SELECT id, username\n FROM {user}\n WHERE confirmed = 1 AND lastaccess > 0\n AND lastaccess < ? AND deleted = 0\n AND (lastname = '' OR firstname = '' OR email = '')", array($cuttime)); foreach ($rs as $user) { if (delete_user($user)) { mtrace("Deleted not fully setup user {$user->username} ({$user->id})"); } } $rs->close(); } flush(); /// Delete old logs to save space (this might need a timer to slow it down...) if (!empty($CFG->loglifetime)) { // value in days $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24; if ($DB->delete_records_select("log", "time < ?", array($loglifetime))) { mtrace("Deleted old log records"); } } flush(); // Delete old backup_controllers and logs if (!empty($CFG->loglifetime)) { // value in days $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24; // Delete child records from backup_logs $DB->execute("DELETE FROM {backup_logs}\n WHERE EXISTS (\n SELECT 'x'\n FROM {backup_controllers} bc\n WHERE bc.backupid = {backup_logs}.backupid\n AND bc.timecreated < ?)", array($loglifetime)); // Delete records from backup_controllers $DB->execute("DELETE FROM {backup_controllers}\n WHERE timecreated < ?", array($loglifetime)); mtrace("Deleted old backup records"); } flush(); /// Delete old cached texts if (!empty($CFG->cachetext)) { // Defined in config.php $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites if ($DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime))) { mtrace("Deleted old cache_text records"); } } flush(); if (!empty($CFG->notifyloginfailures)) { notify_login_failures(); mtrace('Notified login failured'); } flush(); // // generate new password emails for users // mtrace('checking for create_password'); if ($DB->count_records('user_preferences', array('name' => 'create_password', 'value' => '1'))) { mtrace('creating passwords for new users'); $newusers = $DB->get_records_sql("SELECT u.id as id, u.email, u.firstname,\n u.lastname, u.username,\n p.id as prefid\n FROM {user} u\n JOIN {user_preferences} p ON u.id=p.userid\n WHERE p.name='create_password' AND p.value='1' AND u.email !='' "); foreach ($newusers as $newuserid => $newuser) { // email user if (setnew_password_and_mail($newuser)) { // remove user pref $DB->delete_records('user_preferences', array('id' => $newuser->prefid)); } else { trigger_error("Could not create and mail new user password!"); } } } if (!empty($CFG->usetags)) { require_once $CFG->dirroot . '/tag/lib.php'; tag_cron(); mtrace('Executed tag cron'); } // Accesslib stuff cleanup_contexts(); mtrace('Cleaned up contexts'); gc_cache_flags(); mtrace('Cleaned cache flags'); // If you suspect that the context paths are somehow corrupt // replace the line below with: build_context_path(true); build_context_path(); mtrace('Built context paths'); if (!empty($CFG->messagingdeletereadnotificationsdelay)) { $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay; $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime' => $notificationdeletetime)); mtrace('Cleaned up read notifications'); } mtrace("Finished clean-up tasks..."); } // End of occasional clean-up tasks // Run automated backups if required. require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php'; require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php'; backup_cron_automated_helper::run_automated_backup(); /// Run the auth cron, if any /// before enrolments because it might add users that will be needed in enrol plugins $auths = get_enabled_auth_plugins(); mtrace("Running auth crons if required..."); foreach ($auths as $auth) { $authplugin = get_auth_plugin($auth); if (method_exists($authplugin, 'cron')) { mtrace("Running cron for auth/{$auth}..."); $authplugin->cron(); if (!empty($authplugin->log)) { mtrace($authplugin->log); } } unset($authplugin); } mtrace("Running enrol crons if required..."); $enrols = enrol_get_plugins(true); foreach ($enrols as $ename => $enrol) { // do this for all plugins, disabled plugins might want to cleanup stuff such as roles if (!$enrol->is_cron_required()) { continue; } mtrace("Running cron for enrol_{$ename}..."); $enrol->cron(); $enrol->set_config('lastcron', time()); } if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) { require_once $CFG->dirroot . '/lib/statslib.php'; // check we're not before our runtime $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour * 60 * 60 + $CFG->statsruntimestartminute * 60; if (time() > $timetocheck) { // process configured number of days as max (defaulting to 31) $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays); if (stats_cron_daily($maxdays)) { if (stats_cron_weekly()) { if (stats_cron_monthly()) { stats_clean_old(); } } } @set_time_limit(0); } else { mtrace('Next stats run after:' . userdate($timetocheck)); } } // run gradebook import/export/report cron if ($gradeimports = get_plugin_list('gradeimport')) { foreach ($gradeimports as $gradeimport => $plugindir) { if (file_exists($plugindir . '/lib.php')) { require_once $plugindir . '/lib.php'; $cron_function = 'grade_import_' . $gradeimport . '_cron'; if (function_exists($cron_function)) { mtrace("Processing gradebook import function {$cron_function} ...", ''); $cron_function(); } } } } if ($gradeexports = get_plugin_list('gradeexport')) { foreach ($gradeexports as $gradeexport => $plugindir) { if (file_exists($plugindir . '/lib.php')) { require_once $plugindir . '/lib.php'; $cron_function = 'grade_export_' . $gradeexport . '_cron'; if (function_exists($cron_function)) { mtrace("Processing gradebook export function {$cron_function} ...", ''); $cron_function(); } } } } if ($gradereports = get_plugin_list('gradereport')) { foreach ($gradereports as $gradereport => $plugindir) { if (file_exists($plugindir . '/lib.php')) { require_once $plugindir . '/lib.php'; $cron_function = 'grade_report_' . $gradereport . '_cron'; if (function_exists($cron_function)) { mtrace("Processing gradebook report function {$cron_function} ...", ''); $cron_function(); } } } } // Run external blog cron if needed if ($CFG->useexternalblogs) { require_once $CFG->dirroot . '/blog/lib.php'; mtrace("Fetching external blog entries...", ''); $sql = "timefetched < ? OR timefetched = 0"; $externalblogs = $DB->get_records_select('blog_external', $sql, array(mktime() - $CFG->externalblogcrontime)); foreach ($externalblogs as $eb) { blog_sync_external_entries($eb); } } // Run blog associations cleanup if ($CFG->useblogassociations) { require_once $CFG->dirroot . '/blog/lib.php'; // delete entries whose contextids no longer exists mtrace("Deleting blog associations linked to non-existent contexts...", ''); $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})'); } //Run registration updated cron mtrace(get_string('siteupdatesstart', 'hub')); require_once $CFG->dirroot . '/admin/registration/lib.php'; $registrationmanager = new registration_manager(); $registrationmanager->cron(); mtrace(get_string('siteupdatesend', 'hub')); // cleanup file trash $fs = get_file_storage(); $fs->cron(); //cleanup old session linked tokens //deletes the session linked tokens that are over a day old. mtrace("Deleting session linked tokens more than one day old...", ''); $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype', array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED)); mtrace('done.'); // run any customized cronjobs, if any if ($locals = get_plugin_list('local')) { mtrace('Processing customized cron scripts ...', ''); foreach ($locals as $local => $localdir) { if (file_exists("{$localdir}/cron.php")) { include "{$localdir}/cron.php"; } } mtrace('done.'); } mtrace("Cron script completed correctly"); $difftime = microtime_diff($starttime, microtime()); mtrace("Execution took " . $difftime . " seconds"); }
<td><?php print_string("auth_saml_supportcourses_description", "auth_saml"); ?> </td> </tr> <tr valign="top"> <td class="right"><?php print_string('auth_saml_syncusersfrom', 'auth_saml'); ?> :</td> <td> <select name="syncusersfrom"> <option name="none" value="">Disabled</option> <?php foreach (get_enabled_auth_plugins() as $name) { $plugin = get_auth_plugin($name); if (method_exists($plugin, 'sync_users')) { print '<option name="' . $name . '" value ="' . $name . '" ' . ($config->syncusersfrom == $name ? 'selected="selected"' : '') . '>' . $name . '</option>'; } } ?> </select> </td> <td><?php print_string("auth_saml_syncusersfrom_description", "auth_saml"); ?> </td> </tr> <tr valign="top" class="required" id="samlcourses_tr" <?php
/** * Specifies whether the CM system should link to a Jasper * reporting server * * @return boolean true if applicable, otherwise false */ function cm_jasper_link_enabled() { $show_jasper_link = false; //check the necessary auth plugins $auths_enabled = get_enabled_auth_plugins(); $mnet_auth_enabled = in_array('mnet', $auths_enabled); $elis_auth_enabled = in_array('elis', $auths_enabled); if ($mnet_auth_enabled && $elis_auth_enabled) { //check the necessary config data $jasper_shortname = get_config('auth/elis', 'jasper_shortname'); $jasper_wwwroot = get_config('auth/elis', 'jasper_wwwroot'); if ($jasper_shortname !== false && $jasper_wwwroot !== false) { //don't respond to bogus data $jasper_shortname = trim($jasper_shortname); $jasper_wwwroot = trim($jasper_wwwroot); if (strlen($jasper_shortname) > 0 && strlen($jasper_wwwroot) > 0) { $show_jasper_link = true; } } } return $show_jasper_link; }
/** * Authenticates a user against the chosen authentication mechanism * * Given a username and password, this function looks them * up using the currently selected authentication mechanism, * and if the authentication is successful, it returns a * valid $user object from the 'user' table. * * Uses auth_ functions from the currently active auth module * * After authenticate_user_login() returns success, you will need to * log that the user has logged in, and call complete_user_login() to set * the session up. * * Note: this function works only with non-mnet accounts! * * @param string $username User's username * @param string $password User's password * @return user|flase A {@link $USER} object or false if error */ function authenticate_user_login($username, $password) { global $CFG, $DB; $authsenabled = get_enabled_auth_plugins(); if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) { $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set if (!empty($user->suspended)) { add_to_log(SITEID, 'login', 'error', 'index.php', $username); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Suspended Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); return false; } if ($auth == 'nologin' or !is_enabled_auth($auth)) { add_to_log(SITEID, 'login', 'error', 'index.php', $username); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Disabled Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); return false; } $auths = array($auth); } else { // check if there's a deleted record (cheaply) if ($DB->get_field('user', 'id', array('username' => $username, 'deleted' => 1))) { error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Deleted Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); return false; } // User does not exist $auths = $authsenabled; $user = new stdClass(); $user->id = 0; } foreach ($auths as $auth) { $authplugin = get_auth_plugin($auth); // on auth fail fall through to the next plugin if (!$authplugin->user_login($username, $password)) { continue; } // successful authentication if ($user->id) { // User already exists in database if (empty($user->auth)) { // For some reason auth isn't set yet $DB->set_field('user', 'auth', $auth, array('username' => $username)); $user->auth = $auth; } if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation $DB->set_field('user', 'firstaccess', $user->timemodified, array('id' => $user->id)); $user->firstaccess = $user->timemodified; } update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day) if ($authplugin->is_synchronised_with_external()) { // update user record from external DB $user = update_user_record($username); } } else { // if user not found, create him $user = create_user_record($username, $password, $auth); } $authplugin->sync_roles($user); foreach ($authsenabled as $hau) { $hauth = get_auth_plugin($hau); $hauth->user_authenticated_hook($user, $username, $password); } if (empty($user->id)) { return false; } if (!empty($user->suspended)) { // just in case some auth plugin suspended account add_to_log(SITEID, 'login', 'error', 'index.php', $username); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Suspended Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); return false; } return $user; } // failed if all the plugins have failed add_to_log(SITEID, 'login', 'error', 'index.php', $username); if (debugging('', DEBUG_ALL)) { error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Failed Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); } return false; }
// along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * @package enrol_attributes * @author Nicolas Dunand <*****@*****.**> * @copyright 2012-2015 Université de Lausanne (@link http://www.unil.ch} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die; if ($ADMIN->fulltree) { // 1. Default role $options = get_default_enrol_roles(context_system::instance()); $student = get_archetype_roles('student'); $student_role = array_shift($student); // $settings->add(new admin_setting_heading('enrol_myunil_defaults', get_string('enrolinstancedefaults', 'admin'), // '')); $settings->add(new admin_setting_configselect('enrol_attributes/default_roleid', get_string('defaultrole', 'enrol_attributes'), get_string('defaultrole_desc', 'enrol_attributes'), $student_role->id, $options)); // 2. Fields to use in the selector $customfieldrecords = $DB->get_records('user_info_field'); if ($customfieldrecords) { $customfields = []; foreach ($customfieldrecords as $customfieldrecord) { $customfields[$customfieldrecord->shortname] = $customfieldrecord->name; } asort($customfields); $settings->add(new admin_setting_configmultiselect('enrol_attributes/profilefields', get_string('profilefields', 'enrol_attributes'), get_string('profilefields_desc', 'enrol_attributes'), [], $customfields)); } // 3. Fields to update via Shibboleth login if (in_array('shibboleth', get_enabled_auth_plugins())) { $settings->add(new admin_setting_configtextarea('enrol_attributes/mappings', get_string('mappings', 'enrol_attributes'), get_string('mappings_desc', 'enrol_attributes'), '', PARAM_TEXT, 60, 10)); } }
/** * Return XHTML to display control * * @param mixed $data Unused * @param string $query * @return string highlight */ public function output_html($data, $query='') { global $CFG, $OUTPUT, $DB; // display strings $txt = get_strings(array('authenticationplugins', 'users', 'administration', 'settings', 'edit', 'name', 'enable', 'disable', 'up', 'down', 'none', 'users')); $txt->updown = "$txt->up/$txt->down"; $txt->uninstall = get_string('uninstallplugin', 'core_admin'); $txt->testsettings = get_string('testsettings', 'core_auth'); $authsavailable = core_component::get_plugin_list('auth'); get_enabled_auth_plugins(true); // fix the list of enabled auths if (empty($CFG->auth)) { $authsenabled = array(); } else { $authsenabled = explode(',', $CFG->auth); } // construct the display array, with enabled auth plugins at the top, in order $displayauths = array(); $registrationauths = array(); $registrationauths[''] = $txt->disable; $authplugins = array(); foreach ($authsenabled as $auth) { $authplugin = get_auth_plugin($auth); $authplugins[$auth] = $authplugin; /// Get the auth title (from core or own auth lang files) $authtitle = $authplugin->get_title(); /// Apply titles $displayauths[$auth] = $authtitle; if ($authplugin->can_signup()) { $registrationauths[$auth] = $authtitle; } } foreach ($authsavailable as $auth => $dir) { if (array_key_exists($auth, $displayauths)) { continue; //already in the list } $authplugin = get_auth_plugin($auth); $authplugins[$auth] = $authplugin; /// Get the auth title (from core or own auth lang files) $authtitle = $authplugin->get_title(); /// Apply titles $displayauths[$auth] = $authtitle; if ($authplugin->can_signup()) { $registrationauths[$auth] = $authtitle; } } $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main'); $return .= $OUTPUT->box_start('generalbox authsui'); $table = new html_table(); $table->head = array($txt->name, $txt->users, $txt->enable, $txt->updown, $txt->settings, $txt->testsettings, $txt->uninstall); $table->colclasses = array('leftalign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign', 'centeralign'); $table->data = array(); $table->attributes['class'] = 'admintable generaltable'; $table->id = 'manageauthtable'; //add always enabled plugins first $displayname = $displayauths['manual']; $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>"; //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>"; $usercount = $DB->count_records('user', array('auth'=>'manual', 'deleted'=>0)); $table->data[] = array($displayname, $usercount, '', '', $settings, '', ''); $displayname = $displayauths['nologin']; $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>"; $usercount = $DB->count_records('user', array('auth'=>'nologin', 'deleted'=>0)); $table->data[] = array($displayname, $usercount, '', '', $settings, '', ''); // iterate through auth plugins and add to the display table $updowncount = 1; $authcount = count($authsenabled); $url = "auth.php?sesskey=" . sesskey(); foreach ($displayauths as $auth => $name) { if ($auth == 'manual' or $auth == 'nologin') { continue; } $class = ''; // hide/show link if (in_array($auth, $authsenabled)) { $hideshow = "<a href=\"$url&action=disable&auth=$auth\">"; $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/hide') . "\" class=\"iconsmall\" alt=\"disable\" /></a>"; // $hideshow = "<a href=\"$url&action=disable&auth=$auth\"><input type=\"checkbox\" checked /></a>"; $enabled = true; $displayname = $name; } else { $hideshow = "<a href=\"$url&action=enable&auth=$auth\">"; $hideshow .= "<img src=\"" . $OUTPUT->pix_url('t/show') . "\" class=\"iconsmall\" alt=\"enable\" /></a>"; // $hideshow = "<a href=\"$url&action=enable&auth=$auth\"><input type=\"checkbox\" /></a>"; $enabled = false; $displayname = $name; $class = 'dimmed_text'; } $usercount = $DB->count_records('user', array('auth'=>$auth, 'deleted'=>0)); // up/down link (only if auth is enabled) $updown = ''; if ($enabled) { if ($updowncount > 1) { $updown .= "<a href=\"$url&action=up&auth=$auth\">"; $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" class=\"iconsmall\" /></a> "; } else { $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" /> "; } if ($updowncount < $authcount) { $updown .= "<a href=\"$url&action=down&auth=$auth\">"; $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" class=\"iconsmall\" /></a>"; } else { $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"iconsmall\" alt=\"\" />"; } ++ $updowncount; } // settings link if (file_exists($CFG->dirroot.'/auth/'.$auth.'/settings.php')) { $settings = "<a href=\"settings.php?section=authsetting$auth\">{$txt->settings}</a>"; } else { $settings = "<a href=\"auth_config.php?auth=$auth\">{$txt->settings}</a>"; } // Uninstall link. $uninstall = ''; if ($uninstallurl = core_plugin_manager::instance()->get_uninstall_url('auth_'.$auth, 'manage')) { $uninstall = html_writer::link($uninstallurl, $txt->uninstall); } $test = ''; if (!empty($authplugins[$auth]) and method_exists($authplugins[$auth], 'test_settings')) { $testurl = new moodle_url('/auth/test_settings.php', array('auth'=>$auth, 'sesskey'=>sesskey())); $test = html_writer::link($testurl, $txt->testsettings); } // Add a row to the table. $row = new html_table_row(array($displayname, $usercount, $hideshow, $updown, $settings, $test, $uninstall)); if ($class) { $row->attributes['class'] = $class; } $table->data[] = $row; } $return .= html_writer::table($table); $return .= get_string('configauthenticationplugins', 'admin').'<br />'.get_string('tablenosave', 'filters'); $return .= $OUTPUT->box_end(); return highlight($query, $return); }
function RWSPCReqs() { global $RWSESL3; global $RWSCRURL; $r_rwc = RWSGSOpt("rwscas", PARAM_ALPHANUM); if ($r_rwc === false || strlen($r_rwc) == 0) { return; } if ($r_rwc != "1" && $r_rwc != "2" && $r_rwc != "3") { return; } $r_ver = RWSGSOpt("version", PARAM_ALPHANUMEXT); if ($r_ver === false || strlen($r_ver) == 0) { return; } $r_rwu = RWSGSOpt("rwsuser", PARAM_RAW); if ($r_rwu === false || strlen($r_rwu) == 0) { unset($r_rwu); } $r_rwp = RWSGSOpt("rwspass", PARAM_RAW); if ($r_rwp === false || strlen($r_rwp) == 0) { unset($r_rwp); } $r_tkt = RWSGSOpt("ticket", PARAM_RAW); if ($r_tkt === false || strlen($r_tkt) == 0) { unset($r_tkt); } $r_pid = RWSGSOpt("pgtId", PARAM_RAW); if ($r_pid === false || strlen($r_pid) == 0) { unset($r_pid); } $r_piou = RWSGSOpt("pgtIou", PARAM_RAW); if ($r_piou === false || strlen($r_piou) == 0) { unset($r_piou); } $r_aus = get_enabled_auth_plugins(); foreach ($r_aus as $r_aun) { $r_aup = get_auth_plugin($r_aun); if (strcasecmp($r_aup->authtype, RWSCAS) == 0) { $r_csp = $r_aup; break; } } if (!isset($r_csp)) { return; } if (empty($r_csp->config->hostname)) { return; } list($r_v1, $r_v2, $r_v3) = explode(".", phpCAS::getVersion()); $r_csp->connectCAS(); if ($r_rwc == "1") { if (isset($r_tkt)) { RWSRHXml(); echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"; echo "<rwscas>\r\n"; echo "\t<st>"; echo utf8_encode(htmlspecialchars(trim($r_tkt))); echo "\t</st>\r\n"; echo "</rwscas>\r\n"; exit; } else { if ($_SERVER['REQUEST_METHOD'] == "GET") { $r_ok = phpCAS::checkAuthentication(); if (!isset($r_rwu)) { $r_rwu = phpCAS::getUser(); } if (!isset($r_rwp)) { $r_rwp = "passwdCas"; } RWSLIMUser($r_rwu, $r_rwp, $r_ok); } else { if ($_SERVER['REQUEST_METHOD'] == "POST") { $r_psd = urldecode(file_get_contents("php://input")); if (stripos($r_psd, "<samlp:LogoutRequest ") !== false) { RWSAOLog(); } } } } } else { if ($r_rwc == "2") { if (isset($r_pid) && isset($r_piou)) { if ($r_csp->config->proxycas) { phpCAS::checkAuthentication(); } } else { if ($_SERVER['REQUEST_METHOD'] == "POST") { $r_psd = urldecode(file_get_contents("php://input")); if (stripos($r_psd, "<samlp:LogoutRequest ") !== false) { RWSAOLog(); } } } } else { if ($r_rwc == "3") { if (isset($r_tkt)) { if (strlen($RWSCRURL) > 0) { $r_svu = $RWSCRURL; } else { $r_svu = RWSGSUrl(false, false); } $r_svu .= "?rwscas=1"; if (isset($r_ver)) { $r_svu .= "&version="; $r_svu .= urlencode($r_ver); } if (isset($r_rwu)) { $r_svu .= "&rwsuser="******"&rwspass="******"?rwscas=2"; if (isset($r_ver)) { $r_cbu .= "&version="; $r_cbu .= urlencode($r_ver); } if (isset($r_rwu)) { $r_cbu .= "&rwsuser="******"&rwspass="******"2008"); }
public static function process_login(\core\event\user_loggedin $event) { global $CFG, $DB; // we just received the event from the authentication system; check if well-formed: if (!$event->userid) { // didn't get an user ID, return as there is nothing we can do return true; } if (in_array('shibboleth', get_enabled_auth_plugins()) && $_SERVER['SCRIPT_FILENAME'] == $CFG->dirroot . '/auth/shibboleth/index.php') { // we did get this event from the Shibboleth authentication plugin, // so let's try to make the relevant mappings, ensuring that necessary profile fields exist and Shibboleth attributes are provided: $customfieldrecords = $DB->get_records('user_info_field'); $customfields = array(); foreach ($customfieldrecords as $customfieldrecord) { $customfields[] = $customfieldrecord->shortname; } $mapping = array(); $mappings_str = explode("\n", str_replace("\r", '', get_config('enrol_attributes', 'mappings'))); foreach ($mappings_str as $mapping_str) { if (preg_match('/^\\s*([^: ]+)\\s*:\\s*([^: ]+)\\s*$/', $mapping_str, $matches) && in_array($matches[2], $customfields) && array_key_exists($matches[1], $_SERVER)) { $mapping[$matches[1]] = $matches[2]; } } if (count($mapping)) { // now update user profile data from Shibboleth params received as part of the event: $user = $DB->get_record('user', ['id' => $event->userid], '*', MUST_EXIST); foreach ($mapping as $shibattr => $fieldname) { if (isset($_SERVER[$shibattr])) { $propertyname = 'profile_field_' . $fieldname; $user->{$propertyname} = $_SERVER[$shibattr]; } } require_once $CFG->dirroot . '/user/profile/lib.php'; profile_save_data($user); } } // last, process the actual enrolments, whether we're using Shibboleth authentication or not: self::process_enrolments($event); }
function get_content() { global $USER, $CFG, $SESSION, $OUTPUT; require_once $CFG->libdir . '/authlib.php'; $wwwroot = ''; $signup = ''; if ($this->content !== NULL) { return $this->content; } if (empty($CFG->loginhttps)) { $wwwroot = $CFG->wwwroot; } else { // This actually is not so secure ;-), 'cause we're // in unencrypted connection... $wwwroot = str_replace("http://", "https://", $CFG->wwwroot); } if (signup_is_enabled()) { $signup = $wwwroot . '/login/signup.php'; } // TODO: now that we have multiauth it is hard to find out if there is a way to change password $forgot = $wwwroot . '/login/forgot_password.php'; if (!empty($CFG->loginpasswordautocomplete)) { $autocomplete = 'autocomplete="off"'; } else { $autocomplete = ''; } $username = get_moodle_cookie(); $this->content = new stdClass(); $this->content->footer = ''; $this->content->text = ''; if (!isloggedin() or isguestuser()) { // Show the block if (empty($CFG->authloginviaemail)) { $strusername = get_string('username'); } else { $strusername = get_string('usernameemail'); } $this->content->text .= "\n" . '<form class="loginform" id="login" method="post" action="' . get_login_url() . '" ' . $autocomplete . '>'; $this->content->text .= '<div class="form-group"><label for="login_username">' . $strusername . '</label>'; $this->content->text .= '<input type="text" name="username" id="login_username" class="form-control" value="' . s($username) . '" /></div>'; $this->content->text .= '<div class="form-group"><label for="login_password">' . get_string('password') . '</label>'; $this->content->text .= '<input type="password" name="password" id="login_password" class="form-control" value="" ' . $autocomplete . ' /></div>'; if (isset($CFG->rememberusername) and $CFG->rememberusername == 2) { $checked = $username ? 'checked="checked"' : ''; $this->content->text .= '<div class="form-check">'; $this->content->text .= '<label class="form-check-label">'; $this->content->text .= '<input type="checkbox" name="rememberusername" id="rememberusername" class="form-check-input" value="1" ' . $checked . '/> '; $this->content->text .= get_string('rememberusername', 'admin') . '</label>'; $this->content->text .= '</div>'; } $this->content->text .= '<div class="form-group">'; $this->content->text .= '<input type="submit" class="btn btn-primary btn-block" value="' . get_string('login') . '" />'; $this->content->text .= '</div>'; $this->content->text .= "</form>\n"; if (!empty($signup)) { $this->content->text .= '<div><a href="' . $signup . '">' . get_string('startsignup') . '</a></div>'; } if (!empty($forgot)) { $this->content->text .= '<div><a href="' . $forgot . '">' . get_string('forgotaccount') . '</a></div>'; } $authsequence = get_enabled_auth_plugins(true); // Get all auths, in sequence. $potentialidps = array(); foreach ($authsequence as $authname) { $authplugin = get_auth_plugin($authname); $potentialidps = array_merge($potentialidps, $authplugin->loginpage_idp_list($this->page->url->out(false))); } if (!empty($potentialidps)) { $this->content->text .= '<div class="potentialidps">'; $this->content->text .= '<h6>' . get_string('potentialidps', 'auth') . '</h6>'; $this->content->text .= '<div class="potentialidplist">'; foreach ($potentialidps as $idp) { $this->content->text .= '<div class="potentialidp"><a href="' . $idp['url']->out() . '" title="' . s($idp['name']) . '">'; $this->content->text .= $OUTPUT->render($idp['icon'], $idp['name']) . s($idp['name']) . '</a></div>'; } $this->content->text .= '</div>'; $this->content->text .= '</div>'; } } return $this->content; }
/** * Returns list of auth plugins that are enabled and known to work. */ function uu_allowed_auths() { global $CFG; // only following plugins are guaranteed to work properly // TODO: add support for more plguins in 2.0 $whitelist = array('manual', 'nologin', 'none', 'email'); $plugins = get_enabled_auth_plugins(); $choices = array(); foreach ($plugins as $plugin) { $choices[$plugin] = auth_get_plugin_title($plugin); } return $choices; }
/** * Authenticates a user against the chosen authentication mechanism * * Given a username and password, this function looks them * up using the currently selected authentication mechanism, * and if the authentication is successful, it returns a * valid $user object from the 'user' table. * * Uses auth_ functions from the currently active auth module * * After authenticate_user_login() returns success, you will need to * log that the user has logged in, and call complete_user_login() to set * the session up. * * Note: this function works only with non-mnet accounts! * * @param string $username User's username * @param string $password User's password * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists) * @return stdClass|false A {@link $USER} object or false if error */ function authenticate_user_login($username, $password, $ignorelockout = false, &$failurereason = null) { global $CFG, $DB; require_once "{$CFG->libdir}/authlib.php"; $authsenabled = get_enabled_auth_plugins(); if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) { // Use manual if auth not set. $auth = empty($user->auth) ? 'manual' : $user->auth; if (!empty($user->suspended)) { add_to_log(SITEID, 'login', 'error', 'index.php', $username); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Suspended Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); $failurereason = AUTH_LOGIN_SUSPENDED; return false; } if ($auth == 'nologin' or !is_enabled_auth($auth)) { add_to_log(SITEID, 'login', 'error', 'index.php', $username); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Disabled Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); // Legacy way to suspend user. $failurereason = AUTH_LOGIN_SUSPENDED; return false; } $auths = array($auth); } else { // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user(). if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) { error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Deleted Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); $failurereason = AUTH_LOGIN_NOUSER; return false; } // Do not try to authenticate non-existent accounts when user creation is not disabled. if (!empty($CFG->authpreventaccountcreation)) { add_to_log(SITEID, 'login', 'error', 'index.php', $username); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Unknown user, can not create new accounts: {$username} " . $_SERVER['HTTP_USER_AGENT']); $failurereason = AUTH_LOGIN_NOUSER; return false; } // User does not exist. $auths = $authsenabled; $user = new stdClass(); $user->id = 0; } if ($ignorelockout) { // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA // or this function is called from a SSO script. } else { if ($user->id) { // Verify login lockout after other ways that may prevent user login. if (login_is_lockedout($user)) { add_to_log(SITEID, 'login', 'error', 'index.php', $username); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Login lockout: {$username} " . $_SERVER['HTTP_USER_AGENT']); $failurereason = AUTH_LOGIN_LOCKOUT; return false; } } else { // We can not lockout non-existing accounts. } } foreach ($auths as $auth) { $authplugin = get_auth_plugin($auth); // On auth fail fall through to the next plugin. if (!$authplugin->user_login($username, $password)) { continue; } // Successful authentication. if ($user->id) { // User already exists in database. if (empty($user->auth)) { // For some reason auth isn't set yet. $DB->set_field('user', 'auth', $auth, array('username' => $username)); $user->auth = $auth; } // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to // the current hash algorithm while we have access to the user's password. update_internal_user_password($user, $password); if ($authplugin->is_synchronised_with_external()) { // Update user record from external DB. $user = update_user_record($username); } } else { // Create account, we verified above that user creation is allowed. $user = create_user_record($username, $password, $auth); } $authplugin->sync_roles($user); foreach ($authsenabled as $hau) { $hauth = get_auth_plugin($hau); $hauth->user_authenticated_hook($user, $username, $password); } if (empty($user->id)) { $failurereason = AUTH_LOGIN_NOUSER; return false; } if (!empty($user->suspended)) { // Just in case some auth plugin suspended account. add_to_log(SITEID, 'login', 'error', 'index.php', $username); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Suspended Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); $failurereason = AUTH_LOGIN_SUSPENDED; return false; } login_attempt_valid($user); $failurereason = AUTH_LOGIN_OK; return $user; } // Failed if all the plugins have failed. add_to_log(SITEID, 'login', 'error', 'index.php', $username); if (debugging('', DEBUG_ALL)) { error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Failed Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); } if ($user->id) { login_attempt_failed($user); $failurereason = AUTH_LOGIN_FAILED; } else { $failurereason = AUTH_LOGIN_NOUSER; } return false; }
public function handler_read($sid) { global $CFG; if ($this->record and $this->record->sid != $sid) { error_log('Weird error reading database session - mismatched sid'); return ''; } try { if ($record = $this->database->get_record('sessions', array('sid' => $sid))) { $this->database->get_session_lock($record->id); } else { $record = new stdClass(); $record->state = 0; $record->sid = $sid; $record->sessdata = null; $record->userid = 0; $record->timecreated = $record->timemodified = time(); $record->firstip = $record->lastip = getremoteaddr(); $record->id = $this->database->insert_record_raw('sessions', $record); $this->database->get_session_lock($record->id); } } catch (dml_exception $ex) { error_log('Can not read or insert database sessions'); return ''; } // verify timeout if ($record->timemodified + $CFG->sessiontimeout < time()) { $ignoretimeout = false; if (!empty($record->userid)) { // skips not logged in if ($user = $this->database->get_record('user', array('id' => $record->userid))) { if (!isguestuser($user)) { $authsequence = get_enabled_auth_plugins(); // auths, in sequence foreach ($authsequence as $authname) { $authplugin = get_auth_plugin($authname); if ($authplugin->ignore_timeout_hook($user, $record->sid, $record->timecreated, $record->timemodified)) { $ignoretimeout = true; break; } } } } } if ($ignoretimeout) { //refresh session $record->timemodified = time(); try { $this->database->update_record('sessions', $record); } catch (dml_exception $ex) { error_log('Can not refresh database session'); return ''; } } else { //time out session $record->state = 0; $record->sessdata = null; $record->userid = 0; $record->timecreated = $record->timemodified = time(); $record->firstip = $record->lastip = getremoteaddr(); try { $this->database->update_record('sessions', $record); } catch (dml_exception $ex) { error_log('Can not time out database session'); return ''; } } } $data = is_null($record->sessdata) ? '' : base64_decode($record->sessdata); unset($record->sessdata); // conserve memory $this->record = $record; return $data; }
/** * Given a username and password, this function looks them * up using the currently selected authentication mechanism, * and if the authentication is successful, it returns a * valid $user object from the 'user' table. * * Uses auth_ functions from the currently active auth module * * After authenticate_user_login() returns success, you will need to * log that the user has logged in, and call complete_user_login() to set * the session up. * * @uses $CFG * @param string $username User's username (with system magic quotes) * @param string $password User's password (with system magic quotes) * @return user|flase A {@link $USER} object or false if error */ function authenticate_user_login($username, $password) { global $CFG; $authsenabled = get_enabled_auth_plugins(); if ($user = get_complete_user_data('username', $username)) { $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set if ($auth == 'nologin' or !is_enabled_auth($auth)) { add_to_log(0, 'login', 'error', 'index.php', $username); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Disabled Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); return false; } $auths = array($auth); } else { // check if there's a deleted record (cheaply) if (get_field('user', 'id', 'username', $username, 'deleted', 1, '')) { error_log('[client ' . $_SERVER['REMOTE_ADDR'] . "] {$CFG->wwwroot} Deleted Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); return false; } $auths = $authsenabled; $user = new object(); $user->id = 0; // User does not exist } foreach ($auths as $auth) { $authplugin = get_auth_plugin($auth); // on auth fail fall through to the next plugin if (!$authplugin->user_login($username, $password)) { continue; } // successful authentication if ($user->id) { // User already exists in database if (empty($user->auth)) { // For some reason auth isn't set yet set_field('user', 'auth', $auth, 'username', $username); $user->auth = $auth; } if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation set_field('user', 'firstaccess', $user->timemodified, 'id', $user->id); $user->firstaccess = $user->timemodified; } update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day) if (!$authplugin->is_internal()) { // update user record from external DB $user = update_user_record($username, get_auth_plugin($user->auth)); } } else { // if user not found, create him $user = create_user_record($username, $password, $auth); } $authplugin->sync_roles($user); foreach ($authsenabled as $hau) { $hauth = get_auth_plugin($hau); $hauth->user_authenticated_hook($user, $username, $password); } /// Log in to a second system if necessary /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead if (!empty($CFG->sso)) { include_once $CFG->dirroot . '/sso/' . $CFG->sso . '/lib.php'; if (function_exists('sso_user_login')) { if (!sso_user_login($username, $password)) { // Perform the signon process notify('Second sign-on failed'); } } } if ($user->id === 0) { return false; } return $user; } // failed if all the plugins have failed add_to_log(0, 'login', 'error', 'index.php', $username); if (debugging('', DEBUG_ALL)) { error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Failed Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); } return false; }
/** * Do the job. * Throw exceptions on errors (the job will be retried). */ public function execute() { global $CFG, $DB; $timenow = time(); // Run the auth cron, if any before enrolments // because it might add users that will be needed in enrol plugins. $auths = get_enabled_auth_plugins(); mtrace("Running auth crons if required..."); foreach ($auths as $auth) { $authplugin = get_auth_plugin($auth); if (method_exists($authplugin, 'cron')) { mtrace("Running cron for auth/{$auth}..."); $authplugin->cron(); if (!empty($authplugin->log)) { mtrace($authplugin->log); } } unset($authplugin); } // It is very important to run enrol early // because other plugins depend on correct enrolment info. mtrace("Running enrol crons if required..."); $enrols = enrol_get_plugins(true); foreach ($enrols as $ename => $enrol) { // Do this for all plugins, disabled plugins might want to cleanup stuff such as roles. if (!$enrol->is_cron_required()) { continue; } mtrace("Running cron for enrol_{$ename}..."); $enrol->cron(); $enrol->set_config('lastcron', time()); } // Run all cron jobs for each module. mtrace("Starting activity modules"); if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) { foreach ($mods as $mod) { $libfile = "{$CFG->dirroot}/mod/{$mod->name}/lib.php"; if (file_exists($libfile)) { include_once $libfile; $cronfunction = $mod->name . "_cron"; if (function_exists($cronfunction)) { mtrace("Processing module function {$cronfunction} ...\n", ''); $predbqueries = null; $predbqueries = $DB->perf_get_queries(); $pretime = microtime(1); if ($cronfunction()) { $DB->set_field("modules", "lastcron", $timenow, array("id" => $mod->id)); } if (isset($predbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $predbqueries) . " dbqueries"); mtrace("... used " . (microtime(1) - $pretime) . " seconds"); } // Reset possible changes by modules to time_limit. MDL-11597. \core_php_time_limit::raise(); mtrace("done."); } } } } mtrace("Finished activity modules"); mtrace("Starting blocks"); if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) { // We will need the base class. require_once $CFG->dirroot . '/blocks/moodleblock.class.php'; foreach ($blocks as $block) { $blockfile = $CFG->dirroot . '/blocks/' . $block->name . '/block_' . $block->name . '.php'; if (file_exists($blockfile)) { require_once $blockfile; $classname = '\\block_' . $block->name; $blockobj = new $classname(); if (method_exists($blockobj, 'cron')) { mtrace("Processing cron function for " . $block->name . '....', ''); if ($blockobj->cron()) { $DB->set_field('block', 'lastcron', $timenow, array('id' => $block->id)); } // Reset possible changes by blocks to time_limit. MDL-11597. \core_php_time_limit::raise(); mtrace('done.'); } } } } mtrace('Finished blocks'); mtrace('Starting admin reports'); cron_execute_plugin_type('report'); mtrace('Finished admin reports'); mtrace('Starting course reports'); cron_execute_plugin_type('coursereport'); mtrace('Finished course reports'); // Run gradebook import/export/report cron. mtrace('Starting gradebook plugins'); cron_execute_plugin_type('gradeimport'); cron_execute_plugin_type('gradeexport'); cron_execute_plugin_type('gradereport'); mtrace('Finished gradebook plugins'); // All other plugins. cron_execute_plugin_type('message', 'message plugins'); cron_execute_plugin_type('filter', 'filters'); cron_execute_plugin_type('editor', 'editors'); cron_execute_plugin_type('format', 'course formats'); cron_execute_plugin_type('profilefield', 'profile fields'); cron_execute_plugin_type('webservice', 'webservices'); cron_execute_plugin_type('repository', 'repository plugins'); cron_execute_plugin_type('qbehaviour', 'question behaviours'); cron_execute_plugin_type('qformat', 'question import/export formats'); cron_execute_plugin_type('qtype', 'question types'); cron_execute_plugin_type('plagiarism', 'plagiarism plugins'); cron_execute_plugin_type('theme', 'themes'); cron_execute_plugin_type('tool', 'admin tools'); cron_execute_plugin_type('local', 'local plugins'); }
if (!($plugins = explode(',', $CFG->enrol_plugins_enabled))) { $plugins = array($CFG->enrol); } require_once $CFG->dirroot . '/enrol/enrol.class.php'; foreach ($plugins as $p) { $enrol = enrolment_factory::factory($p); if (method_exists($enrol, 'cron')) { $enrol->cron(); } if (!empty($enrol->log)) { mtrace($enrol->log); } unset($enrol); } /// Run the auth cron, if any $auths = get_enabled_auth_plugins(); mtrace("Running auth crons if required..."); foreach ($auths as $auth) { $authplugin = get_auth_plugin($auth); if (method_exists($authplugin, 'cron')) { mtrace("Running cron for auth/{$auth}..."); $authplugin->cron(); if (!empty($authplugin->log)) { mtrace($authplugin->log); } } unset($authplugin); } if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) { // check we're not before our runtime $timetocheck = strtotime("today {$CFG->statsruntimestarthour}:{$CFG->statsruntimestartminute}");
/** * Execute cron tasks */ function cron_run() { global $DB, $CFG, $OUTPUT; if (CLI_MAINTENANCE) { echo "CLI maintenance mode active, cron execution suspended.\n"; exit(1); } if (moodle_needs_upgrading()) { echo "Moodle upgrade pending, cron execution suspended.\n"; exit(1); } require_once $CFG->libdir . '/adminlib.php'; require_once $CFG->libdir . '/gradelib.php'; if (!empty($CFG->showcronsql)) { $DB->set_debug(true); } if (!empty($CFG->showcrondebugging)) { set_debugging(DEBUG_DEVELOPER, true); } set_time_limit(0); $starttime = microtime(); // Increase memory limit raise_memory_limit(MEMORY_EXTRA); // Emulate normal session - we use admin accoutn by default cron_setup_user(); // Start output log $timenow = time(); mtrace("Server Time: " . date('r', $timenow) . "\n\n"); // Run cleanup core cron jobs, but not every time since they aren't too important. // These don't have a timer to reduce load, so we'll use a random number // to randomly choose the percentage of times we should run these jobs. $random100 = rand(0, 100); if ($random100 < 20) { // Approximately 20% of the time. mtrace("Running clean-up tasks..."); cron_trace_time_and_memory(); // Delete users who haven't confirmed within required period if (!empty($CFG->deleteunconfirmed)) { $cuttime = $timenow - $CFG->deleteunconfirmed * 3600; $rs = $DB->get_recordset_sql("SELECT *\n FROM {user}\n WHERE confirmed = 0 AND firstaccess > 0\n AND firstaccess < ?", array($cuttime)); foreach ($rs as $user) { delete_user($user); // we MUST delete user properly first $DB->delete_records('user', array('id' => $user->id)); // this is a bloody hack, but it might work mtrace(" Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})"); } $rs->close(); } // Delete users who haven't completed profile within required period if (!empty($CFG->deleteincompleteusers)) { $cuttime = $timenow - $CFG->deleteincompleteusers * 3600; $rs = $DB->get_recordset_sql("SELECT *\n FROM {user}\n WHERE confirmed = 1 AND lastaccess > 0\n AND lastaccess < ? AND deleted = 0\n AND (lastname = '' OR firstname = '' OR email = '')", array($cuttime)); foreach ($rs as $user) { if (isguestuser($user) or is_siteadmin($user)) { continue; } delete_user($user); mtrace(" Deleted not fully setup user {$user->username} ({$user->id})"); } $rs->close(); } // Delete old logs to save space (this might need a timer to slow it down...) if (!empty($CFG->loglifetime)) { // value in days $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24; $DB->delete_records_select("log", "time < ?", array($loglifetime)); mtrace(" Deleted old log records"); } // Delete old backup_controllers and logs. $loglifetime = get_config('backup', 'loglifetime'); if (!empty($loglifetime)) { // Value in days. $loglifetime = $timenow - $loglifetime * 3600 * 24; // Delete child records from backup_logs. $DB->execute("DELETE FROM {backup_logs}\n WHERE EXISTS (\n SELECT 'x'\n FROM {backup_controllers} bc\n WHERE bc.backupid = {backup_logs}.backupid\n AND bc.timecreated < ?)", array($loglifetime)); // Delete records from backup_controllers. $DB->execute("DELETE FROM {backup_controllers}\n WHERE timecreated < ?", array($loglifetime)); mtrace(" Deleted old backup records"); } // Delete old cached texts if (!empty($CFG->cachetext)) { // Defined in config.php $cachelifetime = time() - $CFG->cachetext - 60; // Add an extra minute to allow for really heavy sites $DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime)); mtrace(" Deleted old cache_text records"); } if (!empty($CFG->usetags)) { require_once $CFG->dirroot . '/tag/lib.php'; tag_cron(); mtrace(' Executed tag cron'); } // Context maintenance stuff context_helper::cleanup_instances(); mtrace(' Cleaned up context instances'); context_helper::build_all_paths(false); // If you suspect that the context paths are somehow corrupt // replace the line below with: context_helper::build_all_paths(true); mtrace(' Built context paths'); // Remove expired cache flags gc_cache_flags(); mtrace(' Cleaned cache flags'); // Cleanup messaging if (!empty($CFG->messagingdeletereadnotificationsdelay)) { $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay; $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime' => $notificationdeletetime)); mtrace(' Cleaned up read notifications'); } mtrace(' Deleting temporary files...'); cron_delete_from_temp(); // Cleanup user password reset records // Delete any reset request records which are expired by more than a day. // (We keep recently expired requests around so we can give a different error msg to users who // are trying to user a recently expired reset attempt). $pwresettime = isset($CFG->pwresettime) ? $CFG->pwresettime : 1800; $earliestvalid = time() - $pwresettime - DAYSECS; $DB->delete_records_select('user_password_resets', "timerequested < ?", array($earliestvalid)); mtrace(' Cleaned up old password reset records'); mtrace("...finished clean-up tasks"); } // End of occasional clean-up tasks // Send login failures notification - brute force protection in moodle is weak, // we should at least send notices early in each cron execution if (notify_login_failures()) { mtrace(' Notified login failures'); } // Make sure all context instances are properly created - they may be required in auth, enrol, etc. context_helper::create_instances(); mtrace(' Created missing context instances'); // Session gc. mtrace("Running session gc tasks..."); \core\session\manager::gc(); mtrace("...finished stale session cleanup"); // Run the auth cron, if any before enrolments // because it might add users that will be needed in enrol plugins $auths = get_enabled_auth_plugins(); mtrace("Running auth crons if required..."); cron_trace_time_and_memory(); foreach ($auths as $auth) { $authplugin = get_auth_plugin($auth); if (method_exists($authplugin, 'cron')) { mtrace("Running cron for auth/{$auth}..."); $authplugin->cron(); if (!empty($authplugin->log)) { mtrace($authplugin->log); } } unset($authplugin); } // Generate new password emails for users - ppl expect these generated asap if ($DB->count_records('user_preferences', array('name' => 'create_password', 'value' => '1'))) { mtrace('Creating passwords for new users...'); $usernamefields = get_all_user_name_fields(true, 'u'); $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email,\n {$usernamefields}, u.username, u.lang,\n p.id as prefid\n FROM {user} u\n JOIN {user_preferences} p ON u.id=p.userid\n WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin' AND u.deleted = 0"); // note: we can not send emails to suspended accounts foreach ($newusers as $newuser) { // Use a low cost factor when generating bcrypt hash otherwise // hashing would be slow when emailing lots of users. Hashes // will be automatically updated to a higher cost factor the first // time the user logs in. if (setnew_password_and_mail($newuser, true)) { unset_user_preference('create_password', $newuser); set_user_preference('auth_forcepasswordchange', 1, $newuser); } else { trigger_error("Could not create and mail new user password!"); } } $newusers->close(); } // It is very important to run enrol early // because other plugins depend on correct enrolment info. mtrace("Running enrol crons if required..."); $enrols = enrol_get_plugins(true); foreach ($enrols as $ename => $enrol) { // do this for all plugins, disabled plugins might want to cleanup stuff such as roles if (!$enrol->is_cron_required()) { continue; } mtrace("Running cron for enrol_{$ename}..."); cron_trace_time_and_memory(); $enrol->cron(); $enrol->set_config('lastcron', time()); } // Run all cron jobs for each module mtrace("Starting activity modules"); get_mailer('buffer'); if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) { foreach ($mods as $mod) { $libfile = "{$CFG->dirroot}/mod/{$mod->name}/lib.php"; if (file_exists($libfile)) { include_once $libfile; $cron_function = $mod->name . "_cron"; if (function_exists($cron_function)) { mtrace("Processing module function {$cron_function} ...", ''); cron_trace_time_and_memory(); $pre_dbqueries = null; $pre_dbqueries = $DB->perf_get_queries(); $pre_time = microtime(1); if ($cron_function()) { $DB->set_field("modules", "lastcron", $timenow, array("id" => $mod->id)); } if (isset($pre_dbqueries)) { mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries"); mtrace("... used " . (microtime(1) - $pre_time) . " seconds"); } // Reset possible changes by modules to time_limit. MDL-11597 @set_time_limit(0); mtrace("done."); } } } } get_mailer('close'); mtrace("Finished activity modules"); mtrace("Starting blocks"); if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) { // We will need the base class. require_once $CFG->dirroot . '/blocks/moodleblock.class.php'; foreach ($blocks as $block) { $blockfile = $CFG->dirroot . '/blocks/' . $block->name . '/block_' . $block->name . '.php'; if (file_exists($blockfile)) { require_once $blockfile; $classname = 'block_' . $block->name; $blockobj = new $classname(); if (method_exists($blockobj, 'cron')) { mtrace("Processing cron function for " . $block->name . '....', ''); cron_trace_time_and_memory(); if ($blockobj->cron()) { $DB->set_field('block', 'lastcron', $timenow, array('id' => $block->id)); } // Reset possible changes by blocks to time_limit. MDL-11597 @set_time_limit(0); mtrace('done.'); } } } } mtrace('Finished blocks'); mtrace('Starting admin reports'); cron_execute_plugin_type('report'); mtrace('Finished admin reports'); mtrace('Starting main gradebook job...'); cron_trace_time_and_memory(); grade_cron(); mtrace('done.'); mtrace('Starting processing the event queue...'); cron_trace_time_and_memory(); events_cron(); mtrace('done.'); if ($CFG->enablecompletion) { // Completion cron mtrace('Starting the completion cron...'); cron_trace_time_and_memory(); require_once $CFG->dirroot . '/completion/cron.php'; completion_cron(); mtrace('done'); } if ($CFG->enableportfolios) { // Portfolio cron mtrace('Starting the portfolio cron...'); cron_trace_time_and_memory(); require_once $CFG->libdir . '/portfoliolib.php'; portfolio_cron(); mtrace('done'); } //now do plagiarism checks require_once $CFG->libdir . '/plagiarismlib.php'; plagiarism_cron(); mtrace('Starting course reports'); cron_execute_plugin_type('coursereport'); mtrace('Finished course reports'); // run gradebook import/export/report cron mtrace('Starting gradebook plugins'); cron_execute_plugin_type('gradeimport'); cron_execute_plugin_type('gradeexport'); cron_execute_plugin_type('gradereport'); mtrace('Finished gradebook plugins'); // run calendar cron require_once "{$CFG->dirroot}/calendar/lib.php"; calendar_cron(); // Run external blog cron if needed if (!empty($CFG->enableblogs) && $CFG->useexternalblogs) { require_once $CFG->dirroot . '/blog/lib.php'; mtrace("Fetching external blog entries...", ''); cron_trace_time_and_memory(); $sql = "timefetched < ? OR timefetched = 0"; $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime)); foreach ($externalblogs as $eb) { blog_sync_external_entries($eb); } mtrace('done.'); } // Run blog associations cleanup if (!empty($CFG->enableblogs) && $CFG->useblogassociations) { require_once $CFG->dirroot . '/blog/lib.php'; // delete entries whose contextids no longer exists mtrace("Deleting blog associations linked to non-existent contexts...", ''); cron_trace_time_and_memory(); $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})'); mtrace('done.'); } // Run question bank clean-up. mtrace("Starting the question bank cron...", ''); cron_trace_time_and_memory(); require_once $CFG->libdir . '/questionlib.php'; question_bank::cron(); mtrace('done.'); //Run registration updated cron mtrace(get_string('siteupdatesstart', 'hub')); cron_trace_time_and_memory(); require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php'; $registrationmanager = new registration_manager(); $registrationmanager->cron(); mtrace(get_string('siteupdatesend', 'hub')); // If enabled, fetch information about available updates and eventually notify site admins if (empty($CFG->disableupdatenotifications)) { $updateschecker = \core\update\checker::instance(); $updateschecker->cron(); } //cleanup old session linked tokens //deletes the session linked tokens that are over a day old. mtrace("Deleting session linked tokens more than one day old...", ''); cron_trace_time_and_memory(); $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype', array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED)); mtrace('done.'); // all other plugins cron_execute_plugin_type('message', 'message plugins'); cron_execute_plugin_type('filter', 'filters'); cron_execute_plugin_type('editor', 'editors'); cron_execute_plugin_type('format', 'course formats'); cron_execute_plugin_type('profilefield', 'profile fields'); cron_execute_plugin_type('webservice', 'webservices'); cron_execute_plugin_type('repository', 'repository plugins'); cron_execute_plugin_type('qbehaviour', 'question behaviours'); cron_execute_plugin_type('qformat', 'question import/export formats'); cron_execute_plugin_type('qtype', 'question types'); cron_execute_plugin_type('plagiarism', 'plagiarism plugins'); cron_execute_plugin_type('theme', 'themes'); cron_execute_plugin_type('tool', 'admin tools'); // and finally run any local cronjobs, if any if ($locals = core_component::get_plugin_list('local')) { mtrace('Processing customized cron scripts ...', ''); // new cron functions in lib.php first cron_execute_plugin_type('local'); // legacy cron files are executed directly foreach ($locals as $local => $localdir) { if (file_exists("{$localdir}/cron.php")) { include "{$localdir}/cron.php"; } } mtrace('done.'); } mtrace('Running cache cron routines'); cache_helper::cron(); mtrace('done.'); // Run automated backups if required - these may take a long time to execute require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php'; require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php'; backup_cron_automated_helper::run_automated_backup(); // Run stats as at the end because they are known to take very long time on large sites if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) { require_once $CFG->dirroot . '/lib/statslib.php'; // check we're not before our runtime $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour * 60 * 60 + $CFG->statsruntimestartminute * 60; if (time() > $timetocheck) { // process configured number of days as max (defaulting to 31) $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays); if (stats_cron_daily($maxdays)) { if (stats_cron_weekly()) { if (stats_cron_monthly()) { stats_clean_old(); } } } @set_time_limit(0); } else { mtrace('Next stats run after:' . userdate($timetocheck)); } } // Run badges review cron. mtrace("Starting badges cron..."); require_once $CFG->dirroot . '/badges/cron.php'; badge_cron(); mtrace('done.'); // cleanup file trash - not very important $fs = get_file_storage(); $fs->cron(); mtrace("Cron script completed correctly"); gc_collect_cycles(); mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.'); $difftime = microtime_diff($starttime, microtime()); mtrace("Execution took " . $difftime . " seconds"); }
protected function enable_plugin() { $auths = get_enabled_auth_plugins(true); if (!in_array('ldap', $auths)) { $auths[] = 'ldap'; } set_config('auth', implode(',', $auths)); }
// TODO: try to find out what is the exact reason why sessions do not work $errormsg = get_string("cookiesnotenabled"); $errorcode = 1; } } /// Check for timed out sessions if (!empty($SESSION->has_timed_out)) { $session_has_timed_out = true; unset($SESSION->has_timed_out); } else { $session_has_timed_out = false; } /// auth plugins may override these - SSO anyone? $frm = false; $user = false; $authsequence = get_enabled_auth_plugins(true); // auths, in sequence foreach ($authsequence as $authname) { $authplugin = get_auth_plugin($authname); $authplugin->loginpage_hook(); } /// Define variables used in page $site = get_site(); // Ignore any active pages in the navigation/settings. // We do this because there won't be an active page there, and by ignoring the active pages the // navigation and settings won't be initialised unless something else needs them. $PAGE->navbar->ignore_active(); $loginsite = get_string("loginsite"); $PAGE->navbar->add($loginsite); if ($user !== false or $frm !== false or $errormsg !== '') { // some auth plugin already supplied full user, fake form data or prevented user login with error message
/** * Return XHTML to display control * * @param mixed $data Unused * @param string $query * @return string highlight */ public function output_html($data, $query = '') { global $CFG, $OUTPUT; // display strings $txt = get_strings(array('authenticationplugins', 'users', 'administration', 'settings', 'edit', 'name', 'enable', 'disable', 'up', 'down', 'none')); $txt->updown = "{$txt->up}/{$txt->down}"; $authsavailable = get_plugin_list('auth'); get_enabled_auth_plugins(true); // fix the list of enabled auths if (empty($CFG->auth)) { $authsenabled = array(); } else { $authsenabled = explode(',', $CFG->auth); } // construct the display array, with enabled auth plugins at the top, in order $displayauths = array(); $registrationauths = array(); $registrationauths[''] = $txt->disable; foreach ($authsenabled as $auth) { $authplugin = get_auth_plugin($auth); /// Get the auth title (from core or own auth lang files) $authtitle = $authplugin->get_title(); /// Apply titles $displayauths[$auth] = $authtitle; if ($authplugin->can_signup()) { $registrationauths[$auth] = $authtitle; } } foreach ($authsavailable as $auth => $dir) { if (array_key_exists($auth, $displayauths)) { continue; //already in the list } $authplugin = get_auth_plugin($auth); /// Get the auth title (from core or own auth lang files) $authtitle = $authplugin->get_title(); /// Apply titles $displayauths[$auth] = $authtitle; if ($authplugin->can_signup()) { $registrationauths[$auth] = $authtitle; } } $return = $OUTPUT->heading(get_string('actauthhdr', 'auth'), 3, 'main'); $return .= $OUTPUT->box_start('generalbox authsui'); $table = new html_table(); $table->head = array($txt->name, $txt->enable, $txt->updown, $txt->settings); $table->align = array('left', 'center', 'center', 'center'); $table->data = array(); $table->attributes['class'] = 'manageauthtable generaltable'; //add always enabled plugins first $displayname = "<span>" . $displayauths['manual'] . "</span>"; $settings = "<a href=\"auth_config.php?auth=manual\">{$txt->settings}</a>"; //$settings = "<a href=\"settings.php?section=authsettingmanual\">{$txt->settings}</a>"; $table->data[] = array($displayname, '', '', $settings); $displayname = "<span>" . $displayauths['nologin'] . "</span>"; $settings = "<a href=\"auth_config.php?auth=nologin\">{$txt->settings}</a>"; $table->data[] = array($displayname, '', '', $settings); // iterate through auth plugins and add to the display table $updowncount = 1; $authcount = count($authsenabled); $url = "auth.php?sesskey=" . sesskey(); foreach ($displayauths as $auth => $name) { if ($auth == 'manual' or $auth == 'nologin') { continue; } // hide/show link if (in_array($auth, $authsenabled)) { $hideshow = "<a href=\"{$url}&action=disable&auth={$auth}\">"; $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/hide') . "\" class=\"icon\" alt=\"disable\" /></a>"; // $hideshow = "<a href=\"$url&action=disable&auth=$auth\"><input type=\"checkbox\" checked /></a>"; $enabled = true; $displayname = "<span>{$name}</span>"; } else { $hideshow = "<a href=\"{$url}&action=enable&auth={$auth}\">"; $hideshow .= "<img src=\"" . $OUTPUT->pix_url('i/show') . "\" class=\"icon\" alt=\"enable\" /></a>"; // $hideshow = "<a href=\"$url&action=enable&auth=$auth\"><input type=\"checkbox\" /></a>"; $enabled = false; $displayname = "<span class=\"dimmed_text\">{$name}</span>"; } // up/down link (only if auth is enabled) $updown = ''; if ($enabled) { if ($updowncount > 1) { $updown .= "<a href=\"{$url}&action=up&auth={$auth}\">"; $updown .= "<img src=\"" . $OUTPUT->pix_url('t/up') . "\" alt=\"up\" /></a> "; } else { $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" /> "; } if ($updowncount < $authcount) { $updown .= "<a href=\"{$url}&action=down&auth={$auth}\">"; $updown .= "<img src=\"" . $OUTPUT->pix_url('t/down') . "\" alt=\"down\" /></a>"; } else { $updown .= "<img src=\"" . $OUTPUT->pix_url('spacer') . "\" class=\"icon\" alt=\"\" />"; } ++$updowncount; } // settings link if (file_exists($CFG->dirroot . '/auth/' . $auth . '/settings.php')) { $settings = "<a href=\"settings.php?section=authsetting{$auth}\">{$txt->settings}</a>"; } else { $settings = "<a href=\"auth_config.php?auth={$auth}\">{$txt->settings}</a>"; } // add a row to the table $table->data[] = array($displayname, $hideshow, $updown, $settings); } $return .= html_writer::table($table); $return .= get_string('configauthenticationplugins', 'admin') . '<br />' . get_string('tablenosave', 'filters'); $return .= $OUTPUT->box_end(); return highlight($query, $return); }
* Allows admin to edit all auth plugin settings. * * JH: copied and Hax0rd from admin/enrol.php and admin/filters.php * */ require_once '../config.php'; require_once $CFG->libdir . '/adminlib.php'; require_once $CFG->libdir . '/tablelib.php'; require_login(); require_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM)); $returnurl = "{$CFG->wwwroot}/{$CFG->admin}/settings.php?section=manageauths"; $action = optional_param('action', '', PARAM_ACTION); $auth = optional_param('auth', '', PARAM_SAFEDIR); // get currently installed and enabled auth plugins $authsavailable = get_list_of_plugins('auth'); get_enabled_auth_plugins(true); // fix the list of enabled auths if (empty($CFG->auth)) { $authsenabled = array(); } else { $authsenabled = explode(',', $CFG->auth); } if (!empty($auth) and !exists_auth_plugin($auth)) { print_error('pluginnotinstalled', 'auth', $url, $auth); } //////////////////////////////////////////////////////////////////////////////// // process actions if (!confirm_sesskey()) { redirect($returnurl); } switch ($action) {
/** * Authenticates a user against the chosen authentication mechanism * * Given a username and password, this function looks them * up using the currently selected authentication mechanism, * and if the authentication is successful, it returns a * valid $user object from the 'user' table. * * Uses auth_ functions from the currently active auth module * * After authenticate_user_login() returns success, you will need to * log that the user has logged in, and call complete_user_login() to set * the session up. * * Note: this function works only with non-mnet accounts! * * @param string $username User's username (or also email if $CFG->authloginviaemail enabled) * @param string $password User's password * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists) * @return stdClass|false A {@link $USER} object or false if error */ function authenticate_user_login($username, $password, $ignorelockout = false, &$failurereason = null) { global $CFG, $DB; require_once "{$CFG->libdir}/authlib.php"; if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) { // we have found the user } else { if (!empty($CFG->authloginviaemail)) { if ($email = clean_param($username, PARAM_EMAIL)) { $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0"; $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email); $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2); if (count($users) === 1) { // Use email for login only if unique. $user = reset($users); $user = get_complete_user_data('id', $user->id); $username = $user->username; } unset($users); } } } $authsenabled = get_enabled_auth_plugins(); if ($user) { // Use manual if auth not set. $auth = empty($user->auth) ? 'manual' : $user->auth; if (in_array($user->auth, $authsenabled)) { $authplugin = get_auth_plugin($user->auth); $authplugin->pre_user_login_hook($user); } if (!empty($user->suspended)) { $failurereason = AUTH_LOGIN_SUSPENDED; // Trigger login failed event. $event = \core\event\user_login_failed::create(array('userid' => $user->id, 'other' => array('username' => $username, 'reason' => $failurereason))); $event->trigger(); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Suspended Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); return false; } if ($auth == 'nologin' or !is_enabled_auth($auth)) { // Legacy way to suspend user. $failurereason = AUTH_LOGIN_SUSPENDED; // Trigger login failed event. $event = \core\event\user_login_failed::create(array('userid' => $user->id, 'other' => array('username' => $username, 'reason' => $failurereason))); $event->trigger(); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Disabled Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); return false; } $auths = array($auth); } else { // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user(). if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) { $failurereason = AUTH_LOGIN_NOUSER; // Trigger login failed event. $event = \core\event\user_login_failed::create(array('other' => array('username' => $username, 'reason' => $failurereason))); $event->trigger(); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Deleted Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); return false; } // User does not exist. $auths = $authsenabled; $user = new stdClass(); $user->id = 0; } if ($ignorelockout) { // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA // or this function is called from a SSO script. } else { if ($user->id) { // Verify login lockout after other ways that may prevent user login. if (login_is_lockedout($user)) { $failurereason = AUTH_LOGIN_LOCKOUT; // Trigger login failed event. $event = \core\event\user_login_failed::create(array('userid' => $user->id, 'other' => array('username' => $username, 'reason' => $failurereason))); $event->trigger(); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Login lockout: {$username} " . $_SERVER['HTTP_USER_AGENT']); return false; } } else { // We can not lockout non-existing accounts. } } foreach ($auths as $auth) { $authplugin = get_auth_plugin($auth); // On auth fail fall through to the next plugin. if (!$authplugin->user_login($username, $password)) { continue; } // Successful authentication. if ($user->id) { // User already exists in database. if (empty($user->auth)) { // For some reason auth isn't set yet. $DB->set_field('user', 'auth', $auth, array('id' => $user->id)); $user->auth = $auth; } // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to // the current hash algorithm while we have access to the user's password. update_internal_user_password($user, $password); if ($authplugin->is_synchronised_with_external()) { // Update user record from external DB. $user = update_user_record_by_id($user->id); } } else { // The user is authenticated but user creation may be disabled. if (!empty($CFG->authpreventaccountcreation)) { $failurereason = AUTH_LOGIN_UNAUTHORISED; // Trigger login failed event. $event = \core\event\user_login_failed::create(array('other' => array('username' => $username, 'reason' => $failurereason))); $event->trigger(); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Unknown user, can not create new accounts: {$username} " . $_SERVER['HTTP_USER_AGENT']); return false; } else { $user = create_user_record($username, $password, $auth); } } $authplugin->sync_roles($user); foreach ($authsenabled as $hau) { $hauth = get_auth_plugin($hau); $hauth->user_authenticated_hook($user, $username, $password); } if (empty($user->id)) { $failurereason = AUTH_LOGIN_NOUSER; // Trigger login failed event. $event = \core\event\user_login_failed::create(array('other' => array('username' => $username, 'reason' => $failurereason))); $event->trigger(); return false; } if (!empty($user->suspended)) { // Just in case some auth plugin suspended account. $failurereason = AUTH_LOGIN_SUSPENDED; // Trigger login failed event. $event = \core\event\user_login_failed::create(array('userid' => $user->id, 'other' => array('username' => $username, 'reason' => $failurereason))); $event->trigger(); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Suspended Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); return false; } login_attempt_valid($user); $failurereason = AUTH_LOGIN_OK; return $user; } // Failed if all the plugins have failed. if (debugging('', DEBUG_ALL)) { error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Failed Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); } if ($user->id) { login_attempt_failed($user); $failurereason = AUTH_LOGIN_FAILED; // Trigger login failed event. $event = \core\event\user_login_failed::create(array('userid' => $user->id, 'other' => array('username' => $username, 'reason' => $failurereason))); $event->trigger(); } else { $failurereason = AUTH_LOGIN_NOUSER; // Trigger login failed event. $event = \core\event\user_login_failed::create(array('other' => array('username' => $username, 'reason' => $failurereason))); $event->trigger(); } return false; }
function local_ombieltoken_authenticate_user($username) { global $CFG, $DB; $authsenabled = get_enabled_auth_plugins(); $authplugin = get_auth_plugin('cosign'); if ($username) { $user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id); } else { $user = get_complete_user_data('username', auth_plugin_cosign::get_cosign_username(), $CFG->mnet_localhost_id); } if ($user) { if ($user->auth !== 'cosign') { // Invalid auth - we only allow cosign users in this token generator add_to_log(SITEID, 'login', 'error', 'index.php', $username); return false; } if (!empty($user->suspended)) { add_to_log(SITEID, 'login', 'error', 'index.php', $username); error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Suspended Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); return false; } } else { // check if there's a deleted record (cheaply) if ($DB->get_field('user', 'id', array('username' => $username, 'deleted' => 1))) { error_log('[client ' . getremoteaddr() . "] {$CFG->wwwroot} Deleted Login: {$username} " . $_SERVER['HTTP_USER_AGENT']); } return false; } $user = update_user_record($username); return $user; }
/** * Returns list of auth plugins that are enabled and known to work. * * If ppl want to use some other auth type they have to include it * in the CSV file next on each line. * * @return array type=>name */ function uu_supported_auths() { // only following plugins are guaranteed to work properly $whitelist = array('manual', 'nologin', 'none', 'email'); $plugins = get_enabled_auth_plugins(); $choices = array(); foreach ($plugins as $plugin) { if (!in_array($plugin, $whitelist)) { continue; } $choices[$plugin] = get_string('pluginname', "auth_{$plugin}"); } return $choices; }
/** * Read session handler * * {@see http://php.net/manual/en/function.session-set-save-handler.php} * * @param string $sid * @return string */ public function handler_read($sid) { global $CFG; if ($this->record and $this->record->sid != $sid) { error_log('Weird error reading database session - mismatched sid'); $this->failed = true; return ''; } try { // Do not fetch full record yet, wait until it is locked. if (!($record = $this->database->get_record('sessions', array('sid' => $sid), 'id, userid'))) { $record = new stdClass(); $record->state = 0; $record->sid = $sid; $record->sessdata = null; $record->userid = 0; $record->timecreated = $record->timemodified = time(); $record->firstip = $record->lastip = getremoteaddr(); $record->id = $this->database->insert_record_raw('sessions', $record); } } catch (Exception $ex) { // do not rethrow exceptions here, we need this to work somehow before 1.9.x upgrade and during install error_log('Can not read or insert database sessions'); $this->failed = true; return ''; } try { if (!empty($CFG->sessionlockloggedinonly) and (isguestuser($record->userid) or empty($record->userid))) { // No session locking for guests and not-logged-in users, // these users mostly read stuff, there should not be any major // session race conditions. Hopefully they do not access other // pages while being logged-in. } else { $this->database->get_session_lock($record->id, SESSION_ACQUIRE_LOCK_TIMEOUT); } } catch (Exception $ex) { // This is a fatal error, better inform users. // It should not happen very often - all pages that need long time to execute // should close session soon after access control checks error_log('Can not obtain session lock'); $this->failed = true; throw $ex; } // Finally read the full session data because we know we have the lock now. if (!($record = $this->database->get_record('sessions', array('id' => $record->id)))) { error_log('Cannot read session record'); $this->failed = true; return ''; } // verify timeout if ($record->timemodified + $CFG->sessiontimeout < time()) { $ignoretimeout = false; if (!empty($record->userid)) { // skips not logged in if ($user = $this->database->get_record('user', array('id' => $record->userid))) { // Refresh session if logged as a guest if (isguestuser($user)) { $ignoretimeout = true; } else { $authsequence = get_enabled_auth_plugins(); // auths, in sequence foreach ($authsequence as $authname) { $authplugin = get_auth_plugin($authname); if ($authplugin->ignore_timeout_hook($user, $record->sid, $record->timecreated, $record->timemodified)) { $ignoretimeout = true; break; } } } } } if ($ignoretimeout) { //refresh session $record->timemodified = time(); try { $this->database->update_record('sessions', $record); } catch (Exception $ex) { // very unlikely error error_log('Can not refresh database session'); $this->failed = true; throw $ex; } } else { //time out session $record->state = 0; $record->sessdata = null; $record->userid = 0; $record->timecreated = $record->timemodified = time(); $record->firstip = $record->lastip = getremoteaddr(); try { $this->database->update_record('sessions', $record); } catch (Exception $ex) { // very unlikely error error_log('Can not time out database session'); $this->failed = true; throw $ex; } } } if (is_null($record->sessdata)) { $data = ''; $this->lasthash = sha1(''); } else { $data = base64_decode($record->sessdata); $this->lasthash = sha1($record->sessdata); } unset($record->sessdata); // conserve memory $this->record = $record; return $data; }