public function get_content()
 {
     global $COURSE, $USER;
     if ($this->content !== null) {
         return $this->content;
     }
     $this->content = new stdClass();
     $this->content->text = var_export($this->context, true);
     $coursecontext = context_course::instance($COURSE->id);
     if (has_capability('block/demostudent:addinstance', $coursecontext)) {
         // If DemoStudent has not yet been enrolled, allow user to create/enrol one.
         $demostudentusername = generate_demostudent_name($USER->username);
         $demostudentuser = get_complete_user_data('username', $demostudentusername);
         if (!$demostudentuser || !is_enrolled($coursecontext, $demostudentuser)) {
             $this->render_view('firstuse');
         } else {
             $this->render_view('instructor');
         }
     } else {
         if (has_capability('block/demostudent:seedemostudentblock', $coursecontext)) {
             $this->render_view('demostudent');
         } else {
             // If the user does not need to see the block, do not display it at all.
             $this->content->text = '';
             $this->content->footer = '';
         }
     }
     return $this->content;
 }
Exemple #2
0
 /**
  * Updates the user's password.
  *
  * called when the user password is updated.
  *
  * @param  object  $user        User table object
  * @param  string  $newpassword Plaintext password
  * @return boolean result
  *
  */
 function user_update_password($user, $newpassword)
 {
     $user = get_complete_user_data('id', $user->id);
     // This will also update the stored hash to the latest algorithm
     // if the existing hash is using an out-of-date algorithm (or the
     // legacy md5 algorithm).
     return update_internal_user_password($user, $newpassword);
 }
 /**
  * Return user info for this event.
  */
 private function get_info_for_enrolment_change($panopto, $relateduserid, $contextid)
 {
     global $DB;
     // DB userkey is "[instancename]\\[username]". Get username and use it to create key.
     $user = get_complete_user_data('id', $relateduserid);
     $username = $user->username;
     $userkey = $panopto->panopto_decorate_username($username);
     // Get contextID to determine user's role.
     $role = $this->get_role_from_context($contextid, $relateduserid);
     return array("role" => $role, "userkey" => $userkey);
 }
 function validation($data, $files)
 {
     $errors = parent::validation($data, $files);
     // Ensure we don't miss errors from any higher-level validation
     // Do our own validation and add errors to array
     foreach ($data as $key => $value) {
         if ($key == 'username') {
             $user = get_complete_user_data('username', $value);
             if ($user === false) {
                 $errors[$key] = get_string('user_not_found', 'local_obu_forms');
             }
         }
     }
     return $errors;
 }
 public static function verify_code($code)
 {
     global $DB;
     //Parameter validation
     //REQUIRED
     $params = self::validate_parameters(self::verify_code_parameters(), array('code' => $code));
     $code = trim($params['code']);
     if (empty($code)) {
         throw new invalid_parameter_exception('Empty code');
     }
     if (!($issuecert = $DB->get_record('simplecertificate_issues', array('code' => $code)))) {
         throw new invalid_parameter_exception('Invalid code');
     }
     if (!($user = get_complete_user_data('id', $issuecert->userid))) {
         throw new moodle_exception('cannotfinduser', 'error', null, '');
     }
     return fullname($user);
 }
 function validation($data)
 {
     global $CFG;
     $errors = array();
     if (!empty($data['username']) and !empty($data['email']) or empty($data['username']) and empty($data['email'])) {
         $errors['username'] = get_string('usernameoremail');
         $errors['email'] = get_string('usernameoremail');
     } else {
         if (!empty($data['email'])) {
             if (!validate_email($data['email'])) {
                 $errors['email'] = get_string('invalidemail');
             } else {
                 if (count_records('user', 'email', $data['email']) > 1) {
                     $errors['email'] = get_string('forgottenduplicate');
                 } else {
                     if ($user = get_complete_user_data('email', $data['email'])) {
                         if (empty($user->confirmed)) {
                             $errors['email'] = get_string('confirmednot');
                         }
                     }
                     if (!$user and empty($CFG->protectusernames)) {
                         $errors['email'] = get_string('emailnotfound');
                     }
                 }
             }
         } else {
             if ($user = get_complete_user_data('username', $data['username'])) {
                 if (empty($user->confirmed)) {
                     $errors['email'] = get_string('confirmednot');
                 }
             }
             if (!$user and empty($CFG->protectusernames)) {
                 $errors['username'] = get_string('usernamenotfound');
             }
         }
     }
     if (0 == count($errors)) {
         return true;
     } else {
         return $errors;
     }
 }
 public function signature($course, $user_id, $show_assessor)
 {
     $user = get_complete_user_data('id', $user_id);
     $output = html_writer::start_tag('div', array('class' => 'marksheet-sign'));
     if ($user) {
         $output .= html_writer::start_tag('div', array('class' => 'student-info'));
         $output .= html_writer::tag('h4', 'Participant’s Full Name: ' . $user->firstname . ' ' . $user->lastname);
         $output .= html_writer::tag('h4', 'Participant’s ID: ' . $user->alternatename);
         $output .= html_writer::end_tag('div');
     }
     if ($show_assessor) {
         $output .= html_writer::start_tag('div', array('class' => 'assessor-info'));
         $output .= html_writer::tag('h4', 'Assessors Name: ______________________________ ');
         $output .= html_writer::tag('h4', 'Assessor’s Signature: ______________________________ ');
         $output .= html_writer::tag('h4', 'Date: _____/_____/__________ ');
         $output .= html_writer::end_tag('div');
     }
     $output .= html_writer::end_tag('div');
     return $output;
 }
    function validation($data, $files) {
        global $CFG, $DB;

        $errors = parent::validation($data, $files);

        if ((!empty($data['username']) and !empty($data['email'])) or (empty($data['username']) and empty($data['email']))) {
            $errors['username'] = get_string('usernameoremail');
            $errors['email']    = get_string('usernameoremail');

        } else if (!empty($data['email'])) {
            if (!validate_email($data['email'])) {
                $errors['email'] = get_string('invalidemail');

            } else if ($DB->count_records('user', array('email'=>$data['email'])) > 1) {
                $errors['email'] = get_string('forgottenduplicate');

            } else {
                if ($user = get_complete_user_data('email', $data['email'])) {
                    if (empty($user->confirmed)) {
                        $errors['email'] = get_string('confirmednot');
                    }
                }
                if (!$user and empty($CFG->protectusernames)) {
                    $errors['email'] = get_string('emailnotfound');
                }
            }

        } else {
            if ($user = get_complete_user_data('username', $data['username'])) {
                if (empty($user->confirmed)) {
                    $errors['email'] = get_string('confirmednot');
                }
            }
            if (!$user and empty($CFG->protectusernames)) {
                $errors['username'] = get_string('usernamenotfound');
            }
        }

        return $errors;
    }
function xmldb_block_repository_upgrade($oldversion = 0)
{
    $result = true;
    if ($oldversion < 2010090901) {
        $errors = false;
        $auths = block_repository_nopasswd_auths();
        $authlist = "'" . implode("', '", $auths) . "'";
        $users = get_records_select('user', "auth IN ({$authlist})", '', 'id, auth');
        if (!empty($users)) {
            foreach ($users as $user) {
                $user = get_complete_user_data('id', $user->id);
                $migrate_ok = block_repository_user_created($user);
                if (!$migrate_ok) {
                    $errors = true;
                    error_log("xmldb_block_repository_upgrade({$oldversion}) - failed migrating user ({$user->id}) to Alfresco.");
                }
            }
        }
        if (!$errors) {
            set_config('initialized', 1, repository_plugin_alfresco::$plugin_name);
        }
    }
    return $result;
}
require_once './locallib.php';
require_once './mdl_redirect_form.php';
require_login();
$context = context_system::instance();
require_capability('local/obu_application:manage', $context);
// We only handle an existing application (id given)
if (isset($_REQUEST['id'])) {
    $application_id = $_REQUEST['id'];
} else {
    echo get_string('invalid_data', 'local_obu_application');
    die;
}
// We may have been given the email of the new approver
if (isset($_REQUEST['approver_email'])) {
    $approver_email = $_REQUEST['approver_email'];
    $approver = get_complete_user_data('email', $approver_email);
    if ($approver) {
        $approver_name = $approver->firstname . ' ' . $approver->lastname;
    } else {
        $approver_name = 'Not Registered';
    }
} else {
    $approver_email = '';
    $approver_name = '';
}
$home = new moodle_url('/');
$dir = $home . 'local/obu_application/';
$program = $dir . 'mdl_redirect.php?id=' . $application_id;
$heading = get_string('redirect_application', 'local_obu_application');
$PAGE->set_context($context);
$PAGE->set_pagelayout('standard');
Exemple #11
0
/**
 * Login as another user - no security checks here.
 * @param int $userid
 * @param stdClass $context
 * @return void
 */
function session_loginas($userid, $context)
{
    if (session_is_loggedinas()) {
        return;
    }
    // switch to fresh new $SESSION
    $_SESSION['REALSESSION'] = $_SESSION['SESSION'];
    $_SESSION['SESSION'] = new stdClass();
    /// Create the new $USER object with all details and reload needed capabilities
    $_SESSION['REALUSER'] = $_SESSION['USER'];
    $user = get_complete_user_data('id', $userid);
    $user->realuser = $_SESSION['REALUSER']->id;
    $user->loginascontext = $context;
    // let enrol plugins deal with new enrolments if necessary
    enrol_check_plugins($user);
    // set up global $USER
    session_set_user($user);
}
Exemple #12
0
    print_error("Info received. Finishing authentication process through regular method hook because no SAML response detected.");
    display_object($_POST);
    $USER = authenticate_user_login($saml_user[$saml_account_matcher], time());
}
// check that the signin worked
if ($USER == false) {
    print_error("You could not be identified or created. <br />Login result: FAILURE<br />I have...<br />" . htmlspecialchars(print_r($USER, true)));
    session_write_close();
    $USER = new object();
    $USER->id = 0;
    require_once '../../config.php';
    print_error('pluginauthfailed', 'auth_onelogin_saml', '', !empty($saml_user['username']) ? $saml_user['username'] : $saml_user['email']);
}
// complete the user login sequence
$USER->loggedin = true;
$USER->site = $CFG->wwwroot;
$USER = get_complete_user_data('id', $USER->id);
complete_user_login($USER);
// flag this as a SAML based login
$SESSION->isSAMLSessionControlled = true;
if (isset($wantsurl)) {
    // and (strpos($wantsurl, $CFG->wwwroot) === 0)
    $urltogo = clean_param($wantsurl, PARAM_URL);
} else {
    $urltogo = $CFG->wwwroot . '/';
}
if (!$urltogo || $urltogo == "") {
    $urltogo = $CFG->wwwroot . '/';
}
unset($SESSION->wantsurl);
redirect($urltogo, 0);
Exemple #13
0
 }
 $confirmed = $authplugin->user_confirm($username, $usersecret);
 if ($confirmed == AUTH_CONFIRM_ALREADY) {
     $user = get_complete_user_data('username', $username);
     print_header(get_string("alreadyconfirmed"), get_string("alreadyconfirmed"), array(), "");
     echo $OUTPUT->box_start('generalbox centerpara boxwidthnormal boxaligncenter');
     echo "<h3>" . get_string("thanks") . ", " . fullname($user) . "</h3>\n";
     echo "<p>" . get_string("alreadyconfirmed") . "</p>\n";
     echo $OUTPUT->button(html_form::make_button("{$CFG->wwwroot}/course/", null, get_string('courses')));
     echo $OUTPUT->box_end();
     echo $OUTPUT->footer();
     exit;
 } else {
     if ($confirmed == AUTH_CONFIRM_OK) {
         // The user has confirmed successfully, let's log them in
         if (!($user = get_complete_user_data('username', $username))) {
             print_error('cannotfinduser', '', '', $username);
         }
         complete_user_login($user);
         if (!empty($SESSION->wantsurl)) {
             // Send them where they were going
             $goto = $SESSION->wantsurl;
             unset($SESSION->wantsurl);
             redirect($goto);
         }
         print_header(get_string("confirmed"), get_string("confirmed"), array(), "");
         echo $OUTPUT->box_start('generalbox centerpara boxwidthnormal boxaligncenter');
         echo "<h3>" . get_string("thanks") . ", " . fullname($USER) . "</h3>\n";
         echo "<p>" . get_string("confirmed") . "</p>\n";
         echo $OUTPUT->button(html_form::make_button("{$CFG->wwwroot}/course/", null, get_string('courses')));
         echo $OUTPUT->box_end();
Exemple #14
0
/**
 * 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;
}
Exemple #15
0
    $sessionstarted = optional_param('sessionstarted', 0, PARAM_BOOL);
    if (!$sessionstarted) {
        redirect("index.php?sessionstarted=1&lang={$CFG->lang}");
    } else {
        $sessionverify = optional_param('sessionverify', 0, PARAM_BOOL);
        if (!$sessionverify) {
            $SESSION->sessionverify = 1;
            redirect("index.php?sessionstarted=1&sessionverify=1&lang={$CFG->lang}");
        } else {
            if (empty($SESSION->sessionverify)) {
                print_error('installsessionerror', 'admin', "index.php?sessionstarted=1&lang={$CFG->lang}");
            }
            unset($SESSION->sessionverify);
        }
    }
    $adminuser = get_complete_user_data('username', 'admin');
    if ($adminuser->password === 'adminsetuppending') {
        // prevent installation hijacking
        if ($adminuser->lastip !== getremoteaddr()) {
            print_error('installhijacked', 'admin');
        }
        // login user and let him set password and admin details
        $adminuser->newadminuser = 1;
        message_set_default_message_preferences($adminuser);
        complete_user_login($adminuser, false);
        redirect("{$CFG->wwwroot}/user/editadvanced.php?id={$adminuser->id}");
        // Edit thyself
    } else {
        unset_config('adminsetuppending');
    }
} else {
}
$token = optional_param('token', '', PARAM_TEXT);
$tab = optional_param('tab', simplecertificate::DEFAULT_VIEW, PARAM_INT);
$sort = optional_param('sort', '', PARAM_RAW);
$type = optional_param('type', '', PARAM_ALPHA);
$page = optional_param('page', 0, PARAM_INT);
$perpage = optional_param('perpage', get_config('simplecertificate', 'perpage'), PARAM_INT);
$issuelist = optional_param('issuelist', null, PARAM_ALPHA);
$username = optional_param('username', '', PARAM_TEXT);
$username = strtolower($username);
$auth = new auth_plugin_joomdle();
$logged = $auth->call_method("confirmJoomlaSession", $username, $token);
if (!$logged) {
    return;
}
$USER = get_complete_user_data('username', $username);
complete_user_login($USER);
$context = context_module::instance($cm->id);
require_capability('mod/simplecertificate:view', $context);
$canmanage = has_capability('mod/simplecertificate:manage', $context);
$url = new moodle_url('/mod/simplecertificate/view.php', array('id' => $cm->id, 'tab' => $tab, 'page' => $page, 'perpage' => $perpage));
if ($type) {
    $url->param('type', $type);
}
if ($sort) {
    $url->param('sort', $sort);
}
if ($action) {
    $url->param('action', $action);
}
if ($issuelist) {
$PAGE->set_url('/blocks/demostudent/remove.php', array('viewrole' => $viewrole, 'courseid' => $courseid, 'confirm' => $confirm));
$coursecontext = context_course::instance($courseid);
if ($viewrole != 'instructor') {
    print get_string('errorremovenotinstructor', 'block_demostudent');
    require_logout();
    redirect(new moodle_url($url, array('redirect' => 1)));
}
// If we do not have the capability to add this block, we likely landed here by accident or malice.
if (!has_capability('block/demostudent:addinstance', $coursecontext)) {
    // Test this as above, but start from a student account instead of DemoStudent.
    print get_string('errormissingaddinstancecapability', 'block_demostudent');
    require_logout();
    redirect(new moodle_url($url, array('redirect' => 1)));
}
$demostudentusername = generate_demostudent_name($username);
$demostudentuser = get_complete_user_data('username', $demostudentusername);
if (!$demostudentuser) {
    redirect(new moodle_url($url, array('redirect' => 1)));
}
if ($confirm) {
    // Unenrol DemoStudent from the course.
    if (!enrol_is_enabled('manual')) {
        redirect(new moodle_url($url, array('redirect' => 1)));
    }
    if (!($enrol = enrol_get_plugin('manual'))) {
        redirect(new moodle_url($url, array('redirect' => 1)));
    }
    if (!($instances = $DB->get_records('enrol', array('enrol' => 'manual', 'courseid' => $courseid, 'status' => ENROL_INSTANCE_ENABLED), 'sortorder,id ASC'))) {
        redirect(new moodle_url($url, array('redirect' => 1)));
    }
    $instance = reset($instances);
Exemple #18
0
    if (empty($SESSION->lang)) {
        $CFG->lang = 'en';
    } else {
        $CFG->lang = $SESSION->lang;
    }
}
// Set the default site locale, a lot of the stuff may depend on this
// it is definitely too late to call this first in require_login()!
moodle_setlocale();
if (!empty($CFG->debugvalidators) and !empty($CFG->guestloginbutton)) {
    if ($CFG->theme == 'standard' or $CFG->theme == 'standardwhite') {
        // Temporary measure to help with XHTML validation
        if (isset($_SERVER['HTTP_USER_AGENT']) and empty($USER->id)) {
            // Allow W3CValidator in as user called w3cvalidator (or guest)
            if (strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false or strpos($_SERVER['HTTP_USER_AGENT'], 'Cynthia') !== false) {
                if ($user = get_complete_user_data("username", "w3cvalidator")) {
                    $user->ignoresesskey = true;
                } else {
                    $user = guest_user();
                }
                session_set_user($user);
            }
        }
    }
}
// Apache log integration. In apache conf file one can use ${MOODULEUSER}n in
// LogFormat to get the current logged in username in moodle.
if ($USER && function_exists('apache_note') && !empty($CFG->apacheloguser) && isset($USER->username)) {
    $apachelog_userid = $USER->id;
    $apachelog_username = clean_filename($USER->username);
    $apachelog_name = '';
         print_error('fail_match_secret', 'auth_openid');
     }
     break;
     // If the user's account is confirmed, set the secret to a random value and send
     // an email to the user - unless it's already set (in which case, send a
     // duplicate message)
 // If the user's account is confirmed, set the secret to a random value and send
 // an email to the user - unless it's already set (in which case, send a
 // duplicate message)
 case 'send_message':
     if (!confirm_sesskey()) {
         print_error('auth_openid_bad_session_key', 'auth_openid');
     }
     if (!empty($url)) {
         $userid = get_field('openid_urls', 'userid', 'url', $url);
         $user = get_complete_user_data('id', $userid);
         if (!$user || !$user->confirmed) {
             print_error('user_not_found', 'auth_openid');
         } else {
             // Create a secret in the database
             if (empty($user->secret)) {
                 $secret = random_string(15);
                 set_field('user', 'secret', $secret, 'id', $user->id);
                 $user->secret = $secret;
             }
             openid_send_fallback_email($user, $url);
             $redirmsg = get_string('fallback_message_sent', 'auth_openid');
             break;
         }
     }
     // Any other case, just display the fallback form
Exemple #20
0
         $newuser->firstname = $firstname;
         $newuser->lastname = $lastname;
         $newuser->email = $email;
         if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
             $newuser->lang = $CFG->lang;
         }
         $newuser->confirmed = 1;
         // don't want an email going out about this user
         $newuser->lastip = getremoteaddr();
         $newuser->timecreated = time();
         $newuser->timemodified = $newuser->timecreated;
         $newuser->mnethostid = $CFG->mnet_localhost_id;
         // make sure we haven't exceeded any field limits
         $newuser = truncate_user($newuser);
         $newuser->id = $DB->insert_record('user', $newuser);
         $user = get_complete_user_data('id', $newuser->id);
         \core\event\user_created::create_from_userid($user->id)->trigger();
     }
 }
 // if we can find a cohortid matching what we sent in, enrol this user in that cohort by adding a record to cohort_members
 if (!empty($cohort)) {
     $ids = explode(',', $cohort);
     foreach ($ids as $cohort) {
         if ($DB->record_exists('cohort', array('idnumber' => $cohort))) {
             $cohortrow = $DB->get_record('cohort', array('idnumber' => $cohort));
             if (!$DB->record_exists('cohort_members', array('cohortid' => $cohortrow->id, 'userid' => $user->id))) {
                 // internally triggers cohort_member_added event
                 cohort_add_member($cohortrow->id, $user->id);
             }
             // if the plugin auto-opens the course, then find the course this cohort enrols for and set it as the opener link
             if (get_config('auth/wp2moodle', 'autoopen') == 'yes') {
Exemple #21
0
/**
 * @global object
 * @param int $dataid
 * @param array $fields
 * @param array $selectedfields
 * @param int $currentgroup group ID of the current group. This is used for
 * exporting data while maintaining group divisions.
 * @param object $context the context in which the operation is performed (for capability checks)
 * @param bool $userdetails whether to include the details of the record author
 * @param bool $time whether to include time created/modified
 * @param bool $approval whether to include approval status
 * @return array
 */
function data_get_exportdata($dataid, $fields, $selectedfields, $currentgroup = 0, $context = null, $userdetails = false, $time = false, $approval = false)
{
    global $DB;
    if (is_null($context)) {
        $context = context_system::instance();
    }
    // exporting user data needs special permission
    $userdetails = $userdetails && has_capability('mod/data:exportuserinfo', $context);
    $exportdata = array();
    // populate the header in first row of export
    foreach ($fields as $key => $field) {
        if (!in_array($field->field->id, $selectedfields)) {
            // ignore values we aren't exporting
            unset($fields[$key]);
        } else {
            $exportdata[0][] = $field->field->name;
        }
    }
    if ($userdetails) {
        $exportdata[0][] = get_string('user');
        $exportdata[0][] = get_string('username');
        $exportdata[0][] = get_string('email');
    }
    if ($time) {
        $exportdata[0][] = get_string('timeadded', 'data');
        $exportdata[0][] = get_string('timemodified', 'data');
    }
    if ($approval) {
        $exportdata[0][] = get_string('approved', 'data');
    }
    $datarecords = $DB->get_records('data_records', array('dataid' => $dataid));
    ksort($datarecords);
    $line = 1;
    foreach ($datarecords as $record) {
        // get content indexed by fieldid
        if ($currentgroup) {
            $select = 'SELECT c.fieldid, c.content, c.content1, c.content2, c.content3, c.content4 FROM {data_content} c, {data_records} r WHERE c.recordid = ? AND r.id = c.recordid AND r.groupid = ?';
            $where = array($record->id, $currentgroup);
        } else {
            $select = 'SELECT fieldid, content, content1, content2, content3, content4 FROM {data_content} WHERE recordid = ?';
            $where = array($record->id);
        }
        if ($content = $DB->get_records_sql($select, $where)) {
            foreach ($fields as $field) {
                $contents = '';
                if (isset($content[$field->field->id])) {
                    $contents = $field->export_text_value($content[$field->field->id]);
                }
                $exportdata[$line][] = $contents;
            }
            if ($userdetails) {
                // Add user details to the export data
                $userdata = get_complete_user_data('id', $record->userid);
                $exportdata[$line][] = fullname($userdata);
                $exportdata[$line][] = $userdata->username;
                $exportdata[$line][] = $userdata->email;
            }
            if ($time) {
                // Add time added / modified
                $exportdata[$line][] = userdate($record->timecreated);
                $exportdata[$line][] = userdate($record->timemodified);
            }
            if ($approval) {
                // Add approval status
                $exportdata[$line][] = (int) $record->approved;
            }
        }
        $line++;
    }
    $line--;
    return $exportdata;
}
/**
 * Get the guest user information from the database
 *
 * @return object(user) An associative array with the details of the guest user account.
 * @todo Is object(user) a correct return type? Or is array the proper return type with a note that the contents include all details for a user.
 */
function get_guest()
{
    return get_complete_user_data('username', 'guest');
}
Exemple #23
0
 /**
  * Confirm the new user as registered.
  *
  * @param string $username
  * @param string $confirmsecret
  */
 function user_confirm($username, $confirmsecret)
 {
     global $DB;
     $user = get_complete_user_data('username', $username);
     if (!empty($user)) {
         if ($user->auth != $this->authtype) {
             return AUTH_CONFIRM_ERROR;
         } else {
             if ($user->secret == $confirmsecret && $user->confirmed) {
                 return AUTH_CONFIRM_ALREADY;
             } else {
                 if ($user->secret == $confirmsecret) {
                     // They have provided the secret key to get in
                     if (!$this->user_activate($username)) {
                         return AUTH_CONFIRM_FAIL;
                     }
                     $user->confirmed = 1;
                     user_update_user($user, false);
                     return AUTH_CONFIRM_OK;
                 }
             }
         }
     } else {
         return AUTH_CONFIRM_ERROR;
     }
 }
function update_authoriser($form, $data, $authoriser_id)
{
    // Update the stored authorisation requests
    read_form_auths($data->id, $auth);
    if ($authoriser_id == 0) {
        delete_form_auths($auth);
    } else {
        $auth->authoriser = $authoriser_id;
        $auth->request_date = time();
        write_form_auths($auth);
    }
    // Determine the URL to use to link to the form
    $program = new moodle_url('/local/obu_forms/process.php') . '?id=' . $data->id;
    // Email the new status to the author and to Student Central (if not the next authoriser)
    $author = get_complete_user_data('id', $data->author);
    $sc = get_complete_user_data('username', 'csa');
    $sc_id = $sc->id;
    if (!$form->modular) {
        // Use the default CSA Team contact and notification details (PG)
        $sc_contact = $sc;
        $sc_notifications = $sc;
    } else {
        // Use the SCAT contact and notification details (UMP)
        $sc_contact = get_complete_user_data('username', 'scat');
        $sc_notifications = get_complete_user_data('username', 'scat_notifications');
    }
    // Add email headers to help prevent auto-responders
    $author->customheaders = array('Precedence: Bulk', 'X-Auto-Response-Suppress: All', 'Auto-Submitted: auto-generated');
    $sc_contact->customheaders = array('Precedence: Bulk', 'X-Auto-Response-Suppress: All', 'Auto-Submitted: auto-generated');
    get_form_status($author->id, $form, $data, $text, $button_text);
    // get the status from the author's perspective
    // If a staff form, extract any given student number
    $student_number = '';
    if (!$form->student) {
        load_form_fields($data, $fields);
        if (array_key_exists('student_number', $fields)) {
            $student_number = ' [' . $fields['student_number'] . ']';
        }
    }
    $html = '<h4><a href="' . $program . '">' . $form->formref . ': ' . $form->name . $student_number . '</a></h4>' . $text;
    email_to_user($author, $sc_contact, 'The Status of Your Form ' . $form->formref . $student_number, html_to_text($html), $html);
    if ($authoriser_id != $sc_id) {
        get_form_status($sc_id, $form, $data, $text, $button_text);
        // get the status from the perspective of Student Central
        $html = '<h4><a href="' . $program . '">' . $form->formref . ': ' . $form->name . $student_number . '</a></h4>' . $text;
        email_to_user($sc_notifications, $author, 'Form ' . $form->formref . $student_number . ' Status Update (' . $author->username . ')', html_to_text($html), $html);
    }
    // Notify the next authoriser (if there is one)
    if ($authoriser_id) {
        if ($authoriser_id == $sc_id) {
            $authoriser = $sc_notifications;
        } else {
            $authoriser = get_complete_user_data('id', $authoriser_id);
        }
        if ($authoriser->username != 'csa-tbd') {
            // No notification possible if authoriser TBD
            $form_link = '<a href="' . $program . '">' . $form->formref . ' ' . get_string('form_title', 'local_obu_forms') . $student_number . '</a>';
            $email_link = '<a href="mailto:' . $sc_contact->email . '?Subject=' . get_string('auths', 'local_obu_forms') . '" target="_top">' . $sc_contact->email . '</a>';
            $html = get_string('request_authorisation', 'local_obu_forms', array('form' => $form_link, 'name' => $sc_contact->alternatename, 'phone' => $sc_contact->phone1, 'email' => $email_link));
            email_to_user($authoriser, $author, 'Request for Form ' . $form->formref . $student_number . ' Authorisation (' . $author->username . ')', html_to_text($html), $html);
        }
    }
}
 /**
  * Confirm the new user as registered.
  *
  * @param string $username
  * @param string $confirmsecret
  */
 public function user_confirm($username, $confirmsecret)
 {
     global $DB;
     $user = get_complete_user_data('username', $username);
     if (!empty($user)) {
         if ($user->auth != $this->authtype) {
             return AUTH_CONFIRM_ERROR;
         } else {
             if ($user->secret == $confirmsecret && $user->confirmed) {
                 return AUTH_CONFIRM_ALREADY;
             } else {
                 if ($user->secret == $confirmsecret) {
                     // They have provided the secret key to get in.
                     $DB->set_field("user", "confirmed", 1, array("id" => $user->id));
                     return AUTH_CONFIRM_OK;
                 }
             }
         }
     } else {
         return AUTH_CONFIRM_ERROR;
     }
 }
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;
}
Exemple #27
0
        redirect("index.php?sessionstarted=1&lang={$CFG->lang}");
    } else {
        $sessionverify = optional_param('sessionverify', 0, PARAM_BOOL);
        if (!$sessionverify) {
            $SESSION->sessionverify = 1;
            redirect("index.php?sessionstarted=1&sessionverify=1&lang={$CFG->lang}");
        } else {
            if (empty($SESSION->sessionverify)) {
                print_error('installsessionerror', 'admin', "index.php?sessionstarted=1&lang={$CFG->lang}");
            }
            unset($SESSION->sessionverify);
        }
    }
    // at this stage there can be only one admin unless more were added by install - users may change username, so do not rely on that
    $adminids = explode(',', $CFG->siteadmins);
    $adminuser = get_complete_user_data('id', reset($adminids));
    if ($adminuser->password === 'adminsetuppending') {
        // prevent installation hijacking
        if ($adminuser->lastip !== getremoteaddr()) {
            print_error('installhijacked', 'admin');
        }
        // login user and let him set password and admin details
        $adminuser->newadminuser = 1;
        complete_user_login($adminuser);
        redirect("{$CFG->wwwroot}/user/editadvanced.php?id={$adminuser->id}");
        // Edit thyself
    } else {
        unset_config('adminsetuppending');
    }
} else {
    // just make sure upgrade logging is properly terminated
Exemple #28
0
 /**
  * Create a Moodle user from Azure AD user data.
  *
  * @param array $aaddata Array of Azure AD user data.
  * @return \stdClass An object representing the created Moodle user.
  */
 public function create_user_from_aaddata($aaddata)
 {
     global $CFG;
     require_once $CFG->dirroot . '/user/profile/lib.php';
     require_once $CFG->dirroot . '/user/lib.php';
     $newuser = (object) ['auth' => 'oidc', 'username' => trim(\core_text::strtolower($aaddata['userPrincipalName'])), 'email' => isset($aaddata['mail']) ? $aaddata['mail'] : '', 'firstname' => isset($aaddata['givenName']) ? $aaddata['givenName'] : '', 'lastname' => isset($aaddata['surname']) ? $aaddata['surname'] : '', 'city' => isset($aaddata['city']) ? $aaddata['city'] : '', 'country' => isset($aaddata['country']) ? $aaddata['country'] : '', 'department' => isset($aaddata['department']) ? $aaddata['department'] : '', 'lang' => isset($aaddata['preferredLanguage']) ? substr($aaddata['preferredLanguage'], 0, 2) : 'en', 'confirmed' => 1, 'timecreated' => time(), 'mnethostid' => $CFG->mnet_localhost_id];
     $password = null;
     $newuser->idnumber = $newuser->username;
     if (!empty($newuser->email)) {
         if (email_is_not_allowed($newuser->email)) {
             unset($newuser->email);
         }
     }
     if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
         $newuser->lang = $CFG->lang;
     }
     $newuser->timemodified = $newuser->timecreated;
     $newuser->id = user_create_user($newuser, false, false);
     // Save user profile data.
     profile_save_data($newuser);
     $user = get_complete_user_data('id', $newuser->id);
     if (!empty($CFG->{'auth_' . $newuser->auth . '_forcechangepassword'})) {
         set_user_preference('auth_forcepasswordchange', 1, $user);
     }
     // Set the password.
     update_internal_user_password($user, $password);
     // Trigger event.
     \core\event\user_created::create_from_userid($newuser->id)->trigger();
     return $user;
 }
		function get_student_sections($cid){
		$context = context_course::instance($cid);
		$students = get_role_users(5 , $context);//getting all the students from a course level


		$stuarr=array();$stcnt=0;
		foreach($students as $student){
		if(get_complete_user_data(id,$student->id)->profile['section']){
		$stu_section=get_complete_user_data(id,$student->id)->profile['section'];
		$stuarr[$stcnt++]=array('stusec'=>$stu_section,'stid'=>$student->id);
		}
		}

		$ss=array_count_values(array_column($stuarr, 'stusec'));
		ksort($ss);

		$stu_sec_info=array();$seccount=0;
		foreach( $ss as $key => $value)
		{
		$stu_sec_info[$seccount++]=array("secname"=>$key,"seccount"=>$value);
		}
		return $stu_sec_info;//json_encode($stu_sec_info);

		}
Exemple #30
0
 /**
  * Return activities overview for the given courses.
  *
  * @param array $courseids a list of course ids
  * @return array of warnings and the activities overview
  * @since Moodle 3.2
  * @throws moodle_exception
  */
 public static function get_activities_overview($courseids)
 {
     global $USER;
     // Parameter validation.
     $params = self::validate_parameters(self::get_activities_overview_parameters(), array('courseids' => $courseids));
     $courseoverviews = array();
     list($courses, $warnings) = external_util::validate_courses($params['courseids']);
     if (!empty($courses)) {
         // Add lastaccess to each course (required by print_overview function).
         // We need the complete user data, the ws server does not load a complete one.
         $user = get_complete_user_data('id', $USER->id);
         foreach ($courses as $course) {
             if (isset($user->lastcourseaccess[$course->id])) {
                 $course->lastaccess = $user->lastcourseaccess[$course->id];
             } else {
                 $course->lastaccess = 0;
             }
         }
         $overviews = array();
         if ($modules = get_plugin_list_with_function('mod', 'print_overview')) {
             foreach ($modules as $fname) {
                 $fname($courses, $overviews);
             }
         }
         // Format output.
         foreach ($overviews as $courseid => $modules) {
             $courseoverviews[$courseid]['id'] = $courseid;
             $courseoverviews[$courseid]['overviews'] = array();
             foreach ($modules as $modname => $overviewtext) {
                 $courseoverviews[$courseid]['overviews'][] = array('module' => $modname, 'overviewtext' => $overviewtext);
             }
         }
     }
     $result = array('courses' => $courseoverviews, 'warnings' => $warnings);
     return $result;
 }