protected function checkAuthorization() { global $CFG; $CFG->current_app->requireMoodle(); if ($CFG->current_app->isHome()) { $CFG->current_app->requireLogin(); if ($CFG->current_app->hasPrivilege('GCHomeAdmin') && !session_is_loggedinas()) { return true; } } $CFG->current_app->gcError('Unprivileged attempted access to admin module!', 'gcpageaccessdenied'); }
/** * Checks if user has a capability to view the current repository. * * @return bool true when the user can, otherwise throws an exception. * @throws repository_exception when the user does not meet the requirements. */ public final function check_capability() { global $USER; // The context we are on. $currentcontext = $this->context; // Ensure that the user can view the repository in the current context. $can = has_capability('repository/'.$this->type.':view', $currentcontext); // Context in which the repository has been created. $repocontext = context::instance_by_id($this->instance->contextid); // Prevent access to private repositories when logged in as. if (session_is_loggedinas()) { $allowed = array('coursefiles', 'equella', 'filesystem', 'flickr_public', 'local', 'merlot', 'recent', 's3', 'upload', 'url', 'user', 'webdav', 'wikimedia', 'youtube'); // Are only accessible the repositories which do not contain private data (any data // that is not part of Moodle, "Private files" is not considered "Pivate"). And if they // do not contain private data, then it should not be a user instance, which is private by definition. if (!in_array($this->type, $allowed) || $repocontext->contextlevel == CONTEXT_USER) { $can = false; } } // We are going to ensure that the current context was legit, and reliable to check // the capability against. (No need to do that if we already cannot). if ($can) { if ($repocontext->contextlevel == CONTEXT_USER) { // The repository is a user instance, ensure we're the right user to access it! if ($repocontext->instanceid != $USER->id) { $can = false; } } else if ($repocontext->contextlevel == CONTEXT_COURSE) { // The repository is a course one. Let's check that we are on the right course. if (in_array($currentcontext->contextlevel, array(CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK))) { $coursecontext = $currentcontext->get_course_context(); if ($coursecontext->instanceid != $repocontext->instanceid) { $can = false; } } else { // We are on a parent context, therefore it's legit to check the permissions // in the current context. } } else { // Nothing to check here, system instances can have different permissions on different // levels. We do not want to prevent URL hack here, because it does not make sense to // prevent a user to access a repository in a context if it's accessible in another one. } } if ($can) { return true; } throw new repository_exception('nopermissiontoaccess', 'repository'); }
/** * Return the standard string that says whether you are logged in (and switched * roles/logged in as another user). * @param bool $withlinks if false, then don't include any links in the HTML produced. * If not set, the default is the nologinlinks option from the theme config.php file, * and if that is not set, then links are included. * @return string HTML fragment. */ public function login_info($withlinks = null) { global $USER, $CFG, $DB, $SESSION; if (right_to_left()) { $direction = array('left-side' => 'right', 'right-side' => 'left'); $dir = 'right'; } else { $direction = array('left-side' => 'left', 'right-side' => 'right'); $dir = ''; } // Check Page layout options for links // Obscure, but whatever... if (is_null($withlinks)) { $withlinks = empty($this->page->layout_options['nologinlinks']); } // Setup a check for if we're on the login page $loginurl = get_login_url(); $loginpage = (string) $this->page->url === $loginurl; $logouturl = $CFG->wwwroot . '/login/logout.php'; // This should be overridden with sesskey() info $logouturl = $CFG->wwwroot . '/login/logout.php?sesskey=' . sesskey(); $course = $this->page->course; if (during_initial_install() || empty($course->id)) { // $course->id is not defined during installation // Logins don't exist yet... return ''; } // Assume they're not logged in $loggedinas = ''; // Build some general output components // Divider $divider = html_writer::empty_tag('li', array('class' => 'divider ' . $dir)); // Start li $startli = html_writer::start_tag('li', array('class' => $dir)); $startdropdownli = html_writer::start_tag('li', array('class' => 'has-dropdown ' . $dir)); // End li $endli = html_writer::end_tag('li'); // Login button $loginbutton = $divider; $loginbutton .= html_writer::start_tag('li', array('class' => 'has-form')); $loginbutton .= html_writer::tag('a', get_string('login'), array('href' => $loginurl, 'class' => 'button')); $loginbutton .= html_writer::end_tag('li'); // Logout button $logoutbutton = html_writer::empty_tag('li', array('class' => 'divider')); $logoutbutton .= html_writer::start_tag('li', array('class' => 'has-form')); $logoutbutton .= html_writer::tag('a', get_string('logout'), array('href' => $logouturl, 'class' => 'button')); $logoutbutton .= html_writer::end_tag('li'); if (!$loginpage) { // Don't show any login info on the login page if (isloggedin()) { // Logged in users (MNET, guest, switched role, loggedinas, normal) $fullname = fullname($USER, true); $mnetuser = is_mnet_remote_user($USER) && ($idprovider = $DB->get_record('mnet_host', array('id' => $USER->mnethostid))); $mnetuserpanel = ''; $roleswitched = is_role_switched($course->id); $roleswitchedpanel = ''; $loggedinasuser = session_is_loggedinas(); $loggedinasuserpanel = ''; if ($mnetuser) { $providerurl = $idprovider->wwwroot; $providername = $idprovider->name; $providerlink = html_writer::tag('a', $providername, array('href' => $providerurl)); $roleswitched || $loggedinasuser ? $mnetuserpanel .= $divider : null; if ($withlinks) { $mnetuserpanel .= $startli; $mnetuserpanel .= html_writer::tag('label', get_string('yourhost', 'mnet') . ':'); $mnetuserpanel .= html_writer::tag('li', $providerlink); $mnetuserpanel .= $endli; } else { $mnetuserpanel .= $startli; $mnetuserpanel .= html_writer::tag('label', $providername); $mnetuserpanel .= $endli; } } if ($roleswitched) { $rolename = ''; $context = context_course::instance($course->id); if ($role = $DB->get_record('role', array('id' => $USER->access['rsw'][$context->path]))) { $rolename = format_string($role->name); } if (empty($rolename)) { // Specially for Admins - they have no original role Title... $rolename = get_string('admin'); } $returnrolelinkparams = array('id' => $course->id, 'sesskey' => sesskey(), 'switchrole' => 0, 'returnurl' => $this->page->url->out_as_local_url(false)); $returnrolelink = new moodle_url('/course/switchrole.php', $returnrolelinkparams); $returnrolelink = html_writer::tag('a', $rolename, array('href' => $returnrolelink)); // Add a divider if the user is also role switched or MNET $mnetuser || $loggedinasuser ? $roleswitchedpanel .= $divider : null; if ($withlinks) { $roleswitchedpanel .= $startli; $roleswitchedpanel .= html_writer::tag('label', get_string('switchrolereturn')); $roleswitchedpanel .= $endli; $roleswitchedpanel .= html_writer::tag('li', $returnrolelink); } else { $roleswitchedpanel .= $startli; $roleswitchedpanel .= html_writer::tag('label', get_string('role') . ': ' . $rolename); $roleswitchedpanel .= $endli; } } if ($loggedinasuser) { $realuser = session_get_realuser(); $realuser = fullname($realuser, true); $realuserprofilelink = $CFG->wwwroot . '/course/loginas.php?id=' . $course->id . '&sesskey=' . sesskey(); $realuserprofile = html_writer::tag('a', $realuser, array('href' => $realuserprofilelink)); // Add a divider if the user is also role switched or MNET $mnetuser || $roleswitched ? $loggedinasuserpanel .= $divider : null; if ($withlinks) { $loggedinasuserpanel .= $startli; $loggedinasuserpanel .= html_writer::tag('label', get_string('returntooriginaluser', '', $realuser)); $loggedinasuserpanel .= $endli; $loggedinasuserpanel .= html_writer::tag('li', $realuserprofile); } else { $loggedinasuserpanel .= $startli; $loggedinasuserpanel .= html_writer::tag('label', get_string('loggedinas', '', $realuser)); $loggedinasuserpanel .= $endli; } } $hasdropdown = $mnetuser || $roleswitched || $loggedinasuser; $dropdown = $mnetuserpanel . $roleswitchedpanel . $loggedinasuserpanel; $dropdown = html_writer::tag('ul', $dropdown, array('class' => 'dropdown')); if (isguestuser()) { // Guest user $fullname = html_writer::tag('span', $fullname); $loggedinas = $divider . $startli . $fullname . $endli; //@TODO: Write a style to swap tag for span if ($withlinks) { $loggedinas .= $loginbutton; } } else { // Normal User if ($withlinks) { //Link to profile page $userprofilelink = $CFG->wwwroot . '/user/profile.php?id=' . $USER->id; $userprofile = html_writer::tag('a', $fullname, array('href' => $userprofilelink)); // Check to see if we need a dropdown if ($hasdropdown) { $loggedinas = $divider . $startdropdownli . $userprofile . $dropdown . $endli . $logoutbutton; } else { // Normal User $loggedinas = $divider . $startli . $userprofile . $endli . $logoutbutton; } } else { $fullname = html_writer::tag('a', $fullname, array('href' => '#')); //@ TODO Write SPAN rules to show dropdown menu if ($hasdropdown) { $loggedinas = $divider . $startdropdownli . $fullname . $dropdown . $endli; } else { $loggedinas = $divider . $startli . $fullname . $endli; } } } } else { // All not logged in users if ($withlinks) { // Add a "login" button $loggedinas = $loginbutton; } else { // Don't need to output anything $loggedinas = ''; } } } if (isset($SESSION->justloggedin)) { unset($SESSION->justloggedin); if (!empty($CFG->displayloginfailures)) { if (!isguestuser()) { if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) { $loggedinas .= ' <div class="loginfailures">'; if (empty($count->accounts)) { $loggedinas .= get_string('failedloginattempts', '', $count); } else { $loggedinas .= get_string('failedloginattemptsall', '', $count); } if (file_exists("{$CFG->dirroot}/report/log/index.php") and has_capability('report/log:view', context_system::instance())) { $loggedinas .= ' (<a href="' . $CFG->wwwroot . '/report/log/index.php' . '?chooselog=1&id=1&modid=site_errors">' . get_string('logs') . '</a>)'; } $loggedinas .= '</div>'; } } } } return $loggedinas; }
} } } } // 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 = ''; if (isset($USER->firstname)) { // We can assume both will be set // - even if to empty. $apachelog_name = clean_filename($USER->firstname . " " . $USER->lastname); } if (session_is_loggedinas()) { $realuser = session_get_realuser(); $apachelog_username = clean_filename($realuser->username . " as " . $apachelog_username); $apachelog_name = clean_filename($realuser->firstname . " " . $realuser->lastname . " as " . $apachelog_name); $apachelog_userid = clean_filename($realuser->id . " as " . $apachelog_userid); } switch ($CFG->apacheloguser) { case 3: $logname = $apachelog_username; break; case 2: $logname = $apachelog_name; break; case 1: default: $logname = $apachelog_userid;
/** * Store user last access times - called when use enters a course or site * * @global object * @global object * @global object * @uses LASTACCESS_UPDATE_SECS * @uses SITEID * @param int $courseid, empty means site * @return void */ function user_accesstime_log($courseid = 0) { global $USER, $CFG, $DB; if (!isloggedin() or session_is_loggedinas()) { // no access tracking return; } if (empty($courseid)) { $courseid = SITEID; } $timenow = time(); /// Store site lastaccess time for the current user if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) { /// Update $USER->lastaccess for next checks $USER->lastaccess = $timenow; $last = new stdClass(); $last->id = $USER->id; $last->lastip = getremoteaddr(); $last->lastaccess = $timenow; $DB->update_record_raw('user', $last); } if ($courseid == SITEID) { /// no user_lastaccess for frontpage return; } /// Store course lastaccess times for the current user if (empty($USER->currentcourseaccess[$courseid]) or $timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS) { $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid' => $USER->id, 'courseid' => $courseid)); if ($lastaccess === false) { // Update course lastaccess for next checks $USER->currentcourseaccess[$courseid] = $timenow; $last = new stdClass(); $last->userid = $USER->id; $last->courseid = $courseid; $last->timeaccess = $timenow; $DB->insert_record_raw('user_lastaccess', $last, false); } else { if ($timenow - $lastaccess < LASTACCESS_UPDATE_SECS) { // no need to update now, it was updated recently in concurrent login ;-) } else { // Update course lastaccess for next checks $USER->currentcourseaccess[$courseid] = $timenow; $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid' => $USER->id, 'courseid' => $courseid)); } } } }
/** * 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); }
$links = array(); if ($CFG->bloglevel > 0) { $links[] = html_writer::link(new moodle_url('/blog/index.php?userid='.$user->id), get_string('blogs','blog')); } if (!empty($CFG->enablenotes) and (has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context))) { $links[] = html_writer::link(new moodle_url('/notes/index.php?course=' . $course->id. '&user='******'notes','notes')); } if (has_capability('moodle/site:viewreports', $context) or has_capability('moodle/user:viewuseractivitiesreport', $usercontext)) { $links[] = html_writer::link(new moodle_url('/course/user.php?id='. $course->id .'&user='******'activity')); } if ($USER->id != $user->id && !session_is_loggedinas() && has_capability('moodle/user:loginas', $context) && !is_siteadmin($user->id)) { $links[] = html_writer::link(new moodle_url('/course/loginas.php?id='. $course->id .'&user='******'&sesskey='. sesskey()), get_string('loginas')); } $links[] = html_writer::link(new moodle_url('/user/view.php?id='. $user->id .'&course='. $course->id), get_string('fullprofile') . '...'); $row->cells[2]->text .= implode('', $links); if (!empty($messageselect)) { $row->cells[2]->text .= '<br /><input type="checkbox" name="user'.$user->id.'" /> '; } $table->data = array($row); echo html_writer::table($table); } } else {
/** * Renders the header for the page * * @return string */ public function header() { global $USER, $CFG; if (session_is_loggedinas()) { $this->page->add_body_class('userloggedinas'); } $this->page->set_state(moodle_page::STATE_PRINTING_HEADER); // Find the appropriate page layout file, based on $this->page->pagelayout. $layoutfile = $this->page->theme->layout_file($this->page->pagelayout); // Render the layout using the layout file. $rendered = $this->render_page_layout($layoutfile); // Slice the rendered output into header and footer. $cutpos = strpos($rendered, $this->unique_main_content_token); if ($cutpos === false) { $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN); $token = self::MAIN_CONTENT_TOKEN; } else { $token = $this->unique_main_content_token; } if ($cutpos === false) { // TODO: Search for a better solution to this... check this is even needed? // The following code will lead to header containing nothing, and // footer containing all of the content for the template. // turned off error by john for ajax load of blocks without main content. // throw new coding_exception('page layout file ' . $layoutfile . // ' does not contain the string "' . self::MAIN_CONTENT_TOKEN . '".'); } $header = substr($rendered, 0, $cutpos); $footer = substr($rendered, $cutpos + strlen($token)); if (empty($this->contenttype)) { debugging('The page layout file did not call $OUTPUT->doctype()'); $header = $this->doctype() . $header; } send_headers($this->contenttype, $this->page->cacheable); $this->opencontainers->push('header/footer', $footer); $this->page->set_state(moodle_page::STATE_IN_BODY); return $header . $this->skip_link_target('maincontent'); }
/** * Start output by sending the HTTP headers, and printing the HTML <head> * and the start of the <body>. * * To control what is printed, you should set properties on $PAGE. If you * are familiar with the old {@link print_header()} function from Moodle 1.9 * you will find that there are properties on $PAGE that correspond to most * of the old parameters to could be passed to print_header. * * Not that, in due course, the remaining $navigation, $menu parameters here * will be replaced by more properties of $PAGE, but that is still to do. * * @return string HTML that you must output this, preferably immediately. */ public function header() { global $USER, $CFG; if (session_is_loggedinas()) { $this->page->add_body_class('userloggedinas'); } // Give themes a chance to init/alter the page object. $this->page->theme->init_page($this->page); $this->page->set_state(moodle_page::STATE_PRINTING_HEADER); // Find the appropriate page layout file, based on $this->page->pagelayout. $layoutfile = $this->page->theme->layout_file($this->page->pagelayout); // Render the layout using the layout file. $rendered = $this->render_page_layout($layoutfile); // Slice the rendered output into header and footer. $cutpos = strpos($rendered, $this->unique_main_content_token); if ($cutpos === false) { $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN); $token = self::MAIN_CONTENT_TOKEN; } else { $token = $this->unique_main_content_token; } if ($cutpos === false) { throw new coding_exception('page layout file ' . $layoutfile . ' does not contain the main content placeholder, please include "<?php echo $OUTPUT->main_content() ?>" in theme layout file.'); } $header = substr($rendered, 0, $cutpos); $footer = substr($rendered, $cutpos + strlen($token)); if (empty($this->contenttype)) { debugging('The page layout file did not call $OUTPUT->doctype()'); $header = $this->doctype() . $header; } // If this theme version is below 2.4 release and this is a course view page if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) && $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) { // check if course content header/footer have not been output during render of theme layout $coursecontentheader = $this->course_content_header(true); $coursecontentfooter = $this->course_content_footer(true); if (!empty($coursecontentheader)) { // display debug message and add header and footer right above and below main content // Please note that course header and footer (to be displayed above and below the whole page) // are not displayed in this case at all. // Besides the content header and footer are not displayed on any other course page debugging('The current theme is not optimised for 2.4, the course-specific header and footer defined in course format will not be output', DEBUG_DEVELOPER); $header .= $coursecontentheader; $footer = $coursecontentfooter . $footer; } } send_headers($this->contenttype, $this->page->cacheable); $this->opencontainers->push('header/footer', $footer); $this->page->set_state(moodle_page::STATE_IN_BODY); return $header . $this->skip_link_target('maincontent'); }
function get_content() { global $CFG, $USER, $DB, $OUTPUT; // shortcut - only for logged in users! if (!isloggedin() || isguestuser()) { return false; } if (session_is_loggedinas()) { $this->content = new stdClass(); $this->content->footer = html_writer::tag('span', get_string('notpermittedtojumpas', 'mnet')); return $this->content; } // according to start_jump_session, // remote users can't on-jump // so don't show this block to them if (is_mnet_remote_user($USER)) { if (debugging() and !empty($CFG->debugdisplay)) { $this->content = new stdClass(); $this->content->footer = html_writer::tag('span', get_string('error_localusersonly', 'block_mnet_hosts'), array('class' => 'error')); return $this->content; } else { return ''; } } if (!is_enabled_auth('mnet')) { if (debugging() and !empty($CFG->debugdisplay)) { $this->content = new stdClass(); $this->content->footer = html_writer::tag('span', get_string('error_authmnetneeded', 'block_mnet_hosts'), array('class' => 'error')); return $this->content; } else { return ''; } } if (!has_capability('moodle/site:mnetlogintoremote', context_system::instance(), NULL, false)) { if (debugging() and !empty($CFG->debugdisplay)) { $this->content = new stdClass(); $this->content->footer = html_writer::tag('span', get_string('error_roamcapabilityneeded', 'block_mnet_hosts'), array('class' => 'error')); return $this->content; } else { return ''; } } if ($this->content !== NULL) { return $this->content; } // TODO: Test this query - it's appropriate? It works? // get the hosts and whether we are doing SSO with them $sql = "\n SELECT DISTINCT\n h.id,\n h.name,\n h.wwwroot,\n a.name as application,\n a.display_name\n FROM\n {mnet_host} h,\n {mnet_application} a,\n {mnet_host2service} h2s_IDP,\n {mnet_service} s_IDP,\n {mnet_host2service} h2s_SP,\n {mnet_service} s_SP\n WHERE\n h.id <> ? AND\n h.id <> ? AND\n h.id = h2s_IDP.hostid AND\n h.deleted = 0 AND\n h.applicationid = a.id AND\n h2s_IDP.serviceid = s_IDP.id AND\n s_IDP.name = 'sso_idp' AND\n h2s_IDP.publish = '1' AND\n h.id = h2s_SP.hostid AND\n h2s_SP.serviceid = s_SP.id AND\n s_SP.name = 'sso_idp' AND\n h2s_SP.publish = '1'\n ORDER BY\n a.display_name,\n h.name"; $hosts = $DB->get_records_sql($sql, array($CFG->mnet_localhost_id, $CFG->mnet_all_hosts_id)); $this->content = new stdClass(); $this->content->items = array(); $this->content->icons = array(); $this->content->footer = ''; if ($hosts) { foreach ($hosts as $host) { $icon = '<img src="' . $OUTPUT->pix_url('i/' . $host->application . '_host') . '"' . ' class="icon" alt="' . get_string('server', 'block_mnet_hosts') . '" /> '; if ($host->id == $USER->mnethostid) { $this->content->items[] = "<a title=\"" . s($host->name) . "\" href=\"{$host->wwwroot}\">" . $icon . s($host->name) . "</a>"; } else { $this->content->items[] = "<a title=\"" . s($host->name) . "\" href=\"{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$host->id}\">" . $icon . s($host->name) . "</a>"; } } } return $this->content; }
require_capability(ATTENDANCEREGISTER_CAPABILITY_ADD_OWN_OFFLINE_SESSIONS, $context); } else { require_capability(ATTENDANCEREGISTER_CAPABILITY_ADD_OTHER_OFFLINE_SESSIONS, $context); } // Do save Offline Session $doSaveOfflineSession = true; } } } } /// Check capabilities to delete self cert // (in the meanwhile retrieve the record to delete) $doDeleteOfflineSession = false; if ($sessionToDelete) { // Check if logged-in-as Session Delete if (session_is_loggedinas() && !ATTENDANCEREGISTER_ACTION_SAVE_OFFLINE_SESSION) { print_error('onlyrealusercandeleteofflinesessions', 'attendanceregister'); } else { if (attendanceregister__isCurrentUser($userId)) { require_capability(ATTENDANCEREGISTER_CAPABILITY_DELETE_OWN_OFFLINE_SESSIONS, $context); $doDeleteOfflineSession = true; } else { require_capability(ATTENDANCEREGISTER_CAPABILITY_DELETE_OTHER_OFFLINE_SESSIONS, $context); $doDeleteOfflineSession = true; } } } // =========================== // Retrieve data to be shown // =========================== // Retrieve Course Completion info object
/** * Checks if user has a capability to view the current repository. * * @return bool true when the user can, otherwise throws an exception. * @throws repository_exception when the user does not meet the requirements. */ public final function check_capability() { global $USER; // The context we are on. $currentcontext = $this->context; // Ensure that the user can view the repository in the current context. $can = has_capability('repository/'.$this->get_typename().':view', $currentcontext); // Context in which the repository has been created. $repocontext = context::instance_by_id($this->instance->contextid); // Prevent access to private repositories when logged in as. if ($can && session_is_loggedinas()) { if ($this->contains_private_data() || $repocontext->contextlevel == CONTEXT_USER) { $can = false; } } // We are going to ensure that the current context was legit, and reliable to check // the capability against. (No need to do that if we already cannot). if ($can) { if ($repocontext->contextlevel == CONTEXT_USER) { // The repository is a user instance, ensure we're the right user to access it! if ($repocontext->instanceid != $USER->id) { $can = false; } } else if ($repocontext->contextlevel == CONTEXT_COURSE) { // The repository is a course one. Let's check that we are on the right course. if (in_array($currentcontext->contextlevel, array(CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK))) { $coursecontext = $currentcontext->get_course_context(); if ($coursecontext->instanceid != $repocontext->instanceid) { $can = false; } } else { // We are on a parent context, therefore it's legit to check the permissions // in the current context. } } else { // Nothing to check here, system instances can have different permissions on different // levels. We do not want to prevent URL hack here, because it does not make sense to // prevent a user to access a repository in a context if it's accessible in another one. } } if ($can) { return true; } throw new repository_exception('nopermissiontoaccess', 'repository'); }
<table id="header-table"> <tr> <td id="headertop_left"> <h1 id="site-logo"> <div id="banner"></div> </h1> </td> <td id="headertop_center"> <?php print $CFG->current_app->getConfigVar('gc_eschool_message'); ?> </td> <td id="headertop_right"> <?php if ($CFG->current_app->isLoggedIn()) { if ($gc_admin || session_is_loggedinas()) { ?> <div class="headermenu"> <?php echo $OUTPUT->login_info(); if (!empty($PAGE->layout_options['langmenu'])) { echo $OUTPUT->lang_menu(); } echo $PAGE->headingmenu; ?> </div> <?php } else { if ($is_guest) { ?> <div class="headermenu">
/** * Returns text to be displayed to the user which reflects their login status * * @global object * @global object * @global object * @global object * @uses CONTEXT_COURSE * @param course $course {@link $COURSE} object containing course information * @param user $user {@link $USER} object containing user information * @return string HTML */ function user_login_string($course = NULL, $user = NULL) { global $USER, $CFG, $SITE, $DB; if (during_initial_install()) { return ''; } if (empty($user) and !empty($USER->id)) { $user = $USER; } if (empty($course)) { $course = $SITE; } if (session_is_loggedinas()) { $realuser = session_get_realuser(); $fullname = fullname($realuser, true); $realuserinfo = " [<a {$CFG->frametarget}\n href=\"{$CFG->wwwroot}/course/loginas.php?id={$course->id}&return=1&sesskey=" . sesskey() . "\">{$fullname}</a>] "; } else { $realuserinfo = ''; } $loginurl = get_login_url(); if (empty($course->id)) { // $course->id is not defined during installation return ''; } else { if (!empty($user->id)) { $context = get_context_instance(CONTEXT_COURSE, $course->id); $fullname = fullname($user, true); $username = "******"{$CFG->wwwroot}/user/view.php?id={$user->id}&course={$course->id}\">{$fullname}</a>"; if (is_mnet_remote_user($user) and $idprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid))) { $username .= " from <a {$CFG->frametarget} href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>"; } if (isset($user->username) && $user->username == 'guest') { $loggedinas = $realuserinfo . get_string('loggedinasguest') . " (<a {$CFG->frametarget} href=\"{$loginurl}\">" . get_string('login') . '</a>)'; } else { if (!empty($user->access['rsw'][$context->path])) { $rolename = ''; if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) { $rolename = ': ' . format_string($role->name); } $loggedinas = get_string('loggedinas', 'moodle', $username) . $rolename . " (<a {$CFG->frametarget}\n href=\"{$CFG->wwwroot}/course/view.php?id={$course->id}&switchrole=0&sesskey=" . sesskey() . "\">" . get_string('switchrolereturn') . '</a>)'; } else { $loggedinas = $realuserinfo . get_string('loggedinas', 'moodle', $username) . ' ' . " (<a {$CFG->frametarget} href=\"{$CFG->wwwroot}/login/logout.php?sesskey=" . sesskey() . "\">" . get_string('logout') . '</a>)'; } } } else { $loggedinas = get_string('loggedinnot', 'moodle') . " (<a {$CFG->frametarget} href=\"{$loginurl}\">" . get_string('login') . '</a>)'; } } $loggedinas = '<div class="logininfo">' . $loggedinas . '</div>'; if (isset($SESSION->justloggedin)) { unset($SESSION->justloggedin); if (!empty($CFG->displayloginfailures)) { if (!empty($USER->username) and $USER->username != 'guest') { if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) { $loggedinas .= ' <div class="loginfailures">'; if (empty($count->accounts)) { $loggedinas .= get_string('failedloginattempts', '', $count); } else { $loggedinas .= get_string('failedloginattemptsall', '', $count); } if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) { $loggedinas .= ' (<a href="' . $CFG->wwwroot . '/course/report/log/index.php' . '?chooselog=1&id=1&modid=site_errors">' . get_string('logs') . '</a>)'; } $loggedinas .= '</div>'; } } } } return $loggedinas; }
protected function authorizeHomeAdmin() { return $this->current_user->getRoleManager()->hasPrivilege('GCHomeAdmin') && !session_is_loggedinas(); }
/** * Starts an RPC jump session and returns the jump redirect URL. * * @param int $mnethostid id of the mnet host to jump to * @param string $wantsurl url to redirect to after the jump (usually on remote system) * @param boolean $wantsurlbackhere defaults to false, means that the remote system should bounce us back here * rather than somewhere inside *its* wwwroot */ function start_jump_session($mnethostid, $wantsurl, $wantsurlbackhere = false) { global $CFG, $USER, $DB; require_once $CFG->dirroot . '/mnet/xmlrpc/client.php'; if (session_is_loggedinas()) { print_error('notpermittedtojumpas', 'mnet'); } // check remote login permissions if (!has_capability('moodle/site:mnetlogintoremote', get_system_context()) or is_mnet_remote_user($USER) or isguestuser() or !isloggedin()) { print_error('notpermittedtojump', 'mnet'); } // check for SSO publish permission first if ($this->has_service($mnethostid, 'sso_sp') == false) { print_error('hostnotconfiguredforsso', 'mnet'); } // set RPC timeout to 30 seconds if not configured if (empty($this->config->rpc_negotiation_timeout)) { $this->config->rpc_negotiation_timeout = 30; set_config('rpc_negotiation_timeout', '30', 'auth_mnet'); } // get the host info $mnet_peer = new mnet_peer(); $mnet_peer->set_id($mnethostid); // set up the session $mnet_session = $DB->get_record('mnet_session', array('userid' => $USER->id, 'mnethostid' => $mnethostid, 'useragent' => sha1($_SERVER['HTTP_USER_AGENT']))); if ($mnet_session == false) { $mnet_session = new stdClass(); $mnet_session->mnethostid = $mnethostid; $mnet_session->userid = $USER->id; $mnet_session->username = $USER->username; $mnet_session->useragent = sha1($_SERVER['HTTP_USER_AGENT']); $mnet_session->token = $this->generate_token(); $mnet_session->confirm_timeout = time() + $this->config->rpc_negotiation_timeout; $mnet_session->expires = time() + (int) ini_get('session.gc_maxlifetime'); $mnet_session->session_id = session_id(); $mnet_session->id = $DB->insert_record('mnet_session', $mnet_session); } else { $mnet_session->useragent = sha1($_SERVER['HTTP_USER_AGENT']); $mnet_session->token = $this->generate_token(); $mnet_session->confirm_timeout = time() + $this->config->rpc_negotiation_timeout; $mnet_session->expires = time() + (int) ini_get('session.gc_maxlifetime'); $mnet_session->session_id = session_id(); $DB->update_record('mnet_session', $mnet_session); } // construct the redirection URL //$transport = mnet_get_protocol($mnet_peer->transport); $wantsurl = urlencode($wantsurl); $url = "{$mnet_peer->wwwroot}{$mnet_peer->application->sso_land_url}?token={$mnet_session->token}&idp={$this->mnet->wwwroot}&wantsurl={$wantsurl}"; if ($wantsurlbackhere) { $url .= '&remoteurl=1'; } return $url; }
/** * Terminate login-as session * @return void */ function session_unloginas() { if (!session_is_loggedinas()) { return; } $_SESSION['SESSION'] = $_SESSION['REALSESSION']; unset($_SESSION['REALSESSION']); $_SESSION['USER'] = $_SESSION['REALUSER']; unset($_SESSION['REALUSER']); }
/** * This function checks that the current user is logged in and has the * required privileges * * This function checks that the current user is logged in, and optionally * whether they are allowed to be in a particular course and view a particular * course module. * If they are not logged in, then it redirects them to the site login unless * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which * case they are automatically logged in as guests. * If $courseid is given and the user is not enrolled in that course then the * user is redirected to the course enrolment page. * If $cm is given and the coursemodule is hidden and the user is not a teacher * in the course then the user is redirected to the course home page. * * @global object * @global object * @global object * @global object * @global string * @global object * @global object * @global object * @uses SITEID Define * @param mixed $courseorid id of the course or course object * @param bool $autologinguest default true * @param object $cm course module object * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to * true. Used to avoid (=false) some scripts (file.php...) to set that variable, * in order to keep redirects working properly. MDL-14495 * @return mixed Void, exit, and die depending on path */ function require_login($courseorid = 0, $autologinguest = true, $cm = null, $setwantsurltome = true) { global $CFG, $SESSION, $USER, $COURSE, $FULLME, $PAGE, $SITE, $DB, $OUTPUT; /// setup global $COURSE, themes, language and locale if (!empty($courseorid)) { if (is_object($courseorid)) { $course = $courseorid; } else { if ($courseorid == SITEID) { $course = clone $SITE; } else { $course = $DB->get_record('course', array('id' => $courseorid)); if (!$course) { throw new moodle_exception('invalidcourseid'); } } } if ($cm) { $PAGE->set_cm($cm, $course); } else { $PAGE->set_course($course); } } else { // If $PAGE->course, and hence $PAGE->context, have not already been set // up properly, set them up now. $PAGE->set_course($PAGE->course); } /// If the user is not even logged in yet then make sure they are if (!isloggedin()) { //NOTE: $USER->site check was obsoleted by session test cookie, // $USER->confirmed test is in login/index.php if ($setwantsurltome) { $SESSION->wantsurl = $FULLME; } if (!empty($_SERVER['HTTP_REFERER'])) { $SESSION->fromurl = $_SERVER['HTTP_REFERER']; } if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest)) { $loginguest = true; } else { $loginguest = false; } redirect(get_login_url($loginguest)); exit; // never reached } /// loginas as redirection if needed if ($COURSE->id != SITEID and session_is_loggedinas()) { if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) { if ($USER->loginascontext->instanceid != $COURSE->id) { print_error('loginasonecourse', '', $CFG->wwwroot . '/course/view.php?id=' . $USER->loginascontext->instanceid); } } } /// check whether the user should be changing password (but only if it is REALLY them) if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) { $userauth = get_auth_plugin($USER->auth); if ($userauth->can_change_password()) { $SESSION->wantsurl = $FULLME; if ($changeurl = $userauth->change_password_url()) { //use plugin custom url redirect($changeurl); } else { //use moodle internal method if (empty($CFG->loginhttps)) { redirect($CFG->wwwroot . '/login/change_password.php'); } else { $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot); redirect($wwwroot . '/login/change_password.php'); } } } else { print_error('nopasswordchangeforced', 'auth'); } } /// Check that the user account is properly set up if (user_not_fully_set_up($USER)) { $SESSION->wantsurl = $FULLME; redirect($CFG->wwwroot . '/user/edit.php?id=' . $USER->id . '&course=' . SITEID); } /// Make sure the USER has a sesskey set up. Used for checking script parameters. sesskey(); // Check that the user has agreed to a site policy if there is one if (!empty($CFG->sitepolicy)) { if (!$USER->policyagreed) { $SESSION->wantsurl = $FULLME; redirect($CFG->wwwroot . '/user/policy.php'); } } // Fetch the system context, we are going to use it a lot. $sysctx = get_context_instance(CONTEXT_SYSTEM); /// If the site is currently under maintenance, then print a message if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) { print_maintenance_message(); } /// groupmembersonly access control if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) { if (isguestuser() or !groups_has_membership($cm)) { print_error('groupmembersonlyerror', 'group', $CFG->wwwroot . '/course/view.php?id=' . $cm->course); } } // Fetch the course context, and prefetch its child contexts if (!isset($COURSE->context)) { if (!($COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id))) { print_error('nocontext'); } } if (!empty($cm) && !isset($cm->context)) { if (!($cm->context = get_context_instance(CONTEXT_MODULE, $cm->id))) { print_error('nocontext'); } } // Conditional activity access control if (!empty($CFG->enableavailability) and $cm) { // We cache conditional access in session if (!isset($SESSION->conditionaccessok)) { $SESSION->conditionaccessok = array(); } // If you have been allowed into the module once then you are allowed // in for rest of session, no need to do conditional checks if (!array_key_exists($cm->id, $SESSION->conditionaccessok)) { // Get condition info (does a query for the availability table) require_once $CFG->libdir . '/conditionlib.php'; $ci = new condition_info($cm, CONDITION_MISSING_EXTRATABLE); // Check condition for user (this will do a query if the availability // information depends on grade or completion information) if ($ci->is_available($junk) || has_capability('moodle/course:viewhiddenactivities', $cm->context)) { $SESSION->conditionaccessok[$cm->id] = true; } else { print_error('activityiscurrentlyhidden'); } } } if ($COURSE->id == SITEID) { /// Eliminate hidden site activities straight away if (!empty($cm) && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) { redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden')); } user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times return; } else { /// Check if the user can be in a particular course if (empty($USER->access['rsw'][$COURSE->context->path])) { // // MDL-13900 - If the course or the parent category are hidden // and the user hasn't the 'course:viewhiddencourses' capability, prevent access // if (!($COURSE->visible && course_parent_visible($COURSE)) && !has_capability('moodle/course:viewhiddencourses', $COURSE->context)) { print_header_simple(); notice(get_string('coursehidden'), $CFG->wwwroot . '/'); } } /// Non-guests who don't currently have access, check if they can be allowed in as a guest if ($USER->username != 'guest' and !has_capability('moodle/course:view', $COURSE->context)) { if ($COURSE->guest == 1) { // Temporarily assign them guest role for this context, if it fails later user is asked to enrol $USER->access = load_temp_role($COURSE->context, $CFG->guestroleid, $USER->access); } } /// If the user is a guest then treat them according to the course policy about guests if (has_capability('moodle/legacy:guest', $COURSE->context, NULL, false)) { if (has_capability('moodle/site:doanything', $sysctx)) { // administrators must be able to access any course - even if somebody gives them guest access user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times return; } switch ($COURSE->guest) { /// Check course policy about guest access case 1: /// Guests always allowed if (!has_capability('moodle/course:view', $COURSE->context)) { // Prohibited by capability print_header_simple(); notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), get_login_url()); } if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page redirect($CFG->wwwroot . '/course/view.php?id=' . $cm->course, get_string('activityiscurrentlyhidden')); } user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times return; // User is allowed to see this course break; case 2: /// Guests allowed with key if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times return true; } // otherwise drop through to logic below (--> enrol.php) break; default: /// Guests not allowed $strloggedinasguest = get_string('loggedinasguest'); print_header_simple('', '', build_navigation(array(array('name' => $strloggedinasguest, 'link' => null, 'type' => 'misc')))); if (empty($USER->access['rsw'][$COURSE->context->path])) { // Normal guest notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), get_login_url()); } else { echo $OUTPUT->notification(get_string('guestsnotallowed', '', format_string($COURSE->fullname))); echo '<div class="notifyproblem">' . switchroles_form($COURSE->id) . '</div>'; echo $OUTPUT->footer(); exit; } break; } /// For non-guests, check if they have course view access } else { if (has_capability('moodle/course:view', $COURSE->context)) { if (session_is_loggedinas()) { // Make sure the REAL person can also access this course $realuser = session_get_realuser(); if (!has_capability('moodle/course:view', $COURSE->context, $realuser->id)) { print_header_simple(); notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot . '/'); } } /// Make sure they can read this activity too, if specified if (!empty($cm) && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) { redirect($CFG->wwwroot . '/course/view.php?id=' . $cm->course, get_string('activityiscurrentlyhidden')); } user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times return; // User is allowed to see this course } } /// Currently not enrolled in the course, so see if they want to enrol $SESSION->wantsurl = $FULLME; redirect($CFG->wwwroot . '/course/enrol.php?id=' . $COURSE->id); die; } }
/** * This function checks that the current user is logged in and has the * required privileges * * This function checks that the current user is logged in, and optionally * whether they are allowed to be in a particular course and view a particular * course module. * If they are not logged in, then it redirects them to the site login unless * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which * case they are automatically logged in as guests. * If $courseid is given and the user is not enrolled in that course then the * user is redirected to the course enrolment page. * If $cm is given and the course module is hidden and the user is not a teacher * in the course then the user is redirected to the course home page. * * When $cm parameter specified, this function sets page layout to 'module'. * You need to change it manually later if some other layout needed. * * @param mixed $courseorid id of the course or course object * @param bool $autologinguest default true * @param object $cm course module object * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to * true. Used to avoid (=false) some scripts (file.php...) to set that variable, * in order to keep redirects working properly. MDL-14495 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions * @return mixed Void, exit, and die depending on path */ function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) { global $CFG, $SESSION, $USER, $FULLME, $PAGE, $SITE, $DB, $OUTPUT; // setup global $COURSE, themes, language and locale if (!empty($courseorid)) { if (is_object($courseorid)) { $course = $courseorid; } else { if ($courseorid == SITEID) { $course = clone $SITE; } else { $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST); } } if ($cm) { if ($cm->course != $course->id) { throw new coding_exception('course and cm parameters in require_login() call do not match!!'); } // make sure we have a $cm from get_fast_modinfo as this contains activity access details if (!$cm instanceof cm_info) { // note: nearly all pages call get_fast_modinfo anyway and it does not make any // db queries so this is not really a performance concern, however it is obviously // better if you use get_fast_modinfo to get the cm before calling this. $modinfo = get_fast_modinfo($course); $cm = $modinfo->get_cm($cm->id); } $PAGE->set_cm($cm, $course); // set's up global $COURSE $PAGE->set_pagelayout('incourse'); } else { $PAGE->set_course($course); // set's up global $COURSE } } else { // do not touch global $COURSE via $PAGE->set_course(), // the reasons is we need to be able to call require_login() at any time!! $course = $SITE; if ($cm) { throw new coding_exception('cm parameter in require_login() requires valid course parameter!'); } } // If the user is not even logged in yet then make sure they are if (!isloggedin()) { if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) { if (!($guest = get_complete_user_data('id', $CFG->siteguest))) { // misconfigured site guest, just redirect to login page redirect(get_login_url()); exit; // never reached } $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang; complete_user_login($guest, false); $USER->autologinguest = true; $SESSION->lang = $lang; } else { //NOTE: $USER->site check was obsoleted by session test cookie, // $USER->confirmed test is in login/index.php if ($preventredirect) { throw new require_login_exception('You are not logged in'); } if ($setwantsurltome) { // TODO: switch to PAGE->url $SESSION->wantsurl = $FULLME; } if (!empty($_SERVER['HTTP_REFERER'])) { $SESSION->fromurl = $_SERVER['HTTP_REFERER']; } redirect(get_login_url()); exit; // never reached } } // loginas as redirection if needed if ($course->id != SITEID and session_is_loggedinas()) { if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) { if ($USER->loginascontext->instanceid != $course->id) { print_error('loginasonecourse', '', $CFG->wwwroot . '/course/view.php?id=' . $USER->loginascontext->instanceid); } } } // check whether the user should be changing password (but only if it is REALLY them) if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) { $userauth = get_auth_plugin($USER->auth); if ($userauth->can_change_password() and !$preventredirect) { $SESSION->wantsurl = $FULLME; if ($changeurl = $userauth->change_password_url()) { //use plugin custom url redirect($changeurl); } else { //use moodle internal method if (empty($CFG->loginhttps)) { redirect($CFG->wwwroot . '/login/change_password.php'); } else { $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot); redirect($wwwroot . '/login/change_password.php'); } } } else { print_error('nopasswordchangeforced', 'auth'); } } // Check that the user account is properly set up if (user_not_fully_set_up($USER)) { if ($preventredirect) { throw new require_login_exception('User not fully set-up'); } $SESSION->wantsurl = $FULLME; redirect($CFG->wwwroot . '/user/edit.php?id=' . $USER->id . '&course=' . SITEID); } // Make sure the USER has a sesskey set up. Used for CSRF protection. sesskey(); // Do not bother admins with any formalities if (is_siteadmin()) { //set accesstime or the user will appear offline which messes up messaging user_accesstime_log($course->id); return; } // Check that the user has agreed to a site policy if there is one - do not test in case of admins if (!$USER->policyagreed and !is_siteadmin()) { if (!empty($CFG->sitepolicy) and !isguestuser()) { if ($preventredirect) { throw new require_login_exception('Policy not agreed'); } $SESSION->wantsurl = $FULLME; redirect($CFG->wwwroot . '/user/policy.php'); } else { if (!empty($CFG->sitepolicyguest) and isguestuser()) { if ($preventredirect) { throw new require_login_exception('Policy not agreed'); } $SESSION->wantsurl = $FULLME; redirect($CFG->wwwroot . '/user/policy.php'); } } } // Fetch the system context, the course context, and prefetch its child contexts $sysctx = get_context_instance(CONTEXT_SYSTEM); $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST); if ($cm) { $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST); } else { $cmcontext = null; } // If the site is currently under maintenance, then print a message if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) { if ($preventredirect) { throw new require_login_exception('Maintenance in progress'); } print_maintenance_message(); } // make sure the course itself is not hidden if ($course->id == SITEID) { // frontpage can not be hidden } else { if (is_role_switched($course->id)) { // when switching roles ignore the hidden flag - user had to be in course to do the switch } else { if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) { // originally there was also test of parent category visibility, // BUT is was very slow in complex queries involving "my courses" // now it is also possible to simply hide all courses user is not enrolled in :-) if ($preventredirect) { throw new require_login_exception('Course is hidden'); } notice(get_string('coursehidden'), $CFG->wwwroot . '/'); } } } // is the user enrolled? if ($course->id == SITEID) { // everybody is enrolled on the frontpage } else { if (session_is_loggedinas()) { // Make sure the REAL person can access this course first $realuser = session_get_realuser(); if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) { if ($preventredirect) { throw new require_login_exception('Invalid course login-as access'); } echo $OUTPUT->header(); notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot . '/'); } } // very simple enrolment caching - changes in course setting are not reflected immediately if (!isset($USER->enrol)) { $USER->enrol = array(); $USER->enrol['enrolled'] = array(); $USER->enrol['tempguest'] = array(); } $access = false; if (is_viewing($coursecontext, $USER)) { // ok, no need to mess with enrol $access = true; } else { if (isset($USER->enrol['enrolled'][$course->id])) { if ($USER->enrol['enrolled'][$course->id] == 0) { $access = true; } else { if ($USER->enrol['enrolled'][$course->id] > time()) { $access = true; } else { //expired unset($USER->enrol['enrolled'][$course->id]); } } } if (isset($USER->enrol['tempguest'][$course->id])) { if ($USER->enrol['tempguest'][$course->id] == 0) { $access = true; } else { if ($USER->enrol['tempguest'][$course->id] > time()) { $access = true; } else { //expired unset($USER->enrol['tempguest'][$course->id]); $USER->access = remove_temp_roles($coursecontext, $USER->access); } } } if ($access) { // cache ok } else { if (is_enrolled($coursecontext, $USER, '', true)) { // active participants may always access // TODO: refactor this into some new function $now = time(); $sql = "SELECT MAX(ue.timeend)\n FROM {user_enrolments} ue\n JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)\n JOIN {user} u ON u.id = ue.userid\n WHERE ue.userid = :userid AND ue.status = :active AND e.status = :enabled AND u.deleted = 0\n AND ue.timestart < :now1 AND (ue.timeend = 0 OR ue.timeend > :now2)"; $params = array('enabled' => ENROL_INSTANCE_ENABLED, 'active' => ENROL_USER_ACTIVE, 'userid' => $USER->id, 'courseid' => $coursecontext->instanceid, 'now1' => $now, 'now2' => $now); $until = $DB->get_field_sql($sql, $params); if (!$until or $until > time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD) { $until = time() + ENROL_REQUIRE_LOGIN_CACHE_PERIOD; } $USER->enrol['enrolled'][$course->id] = $until; $access = true; // remove traces of previous temp guest access $USER->access = remove_temp_roles($coursecontext, $USER->access); } else { $instances = $DB->get_records('enrol', array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED), 'sortorder, id ASC'); $enrols = enrol_get_plugins(true); // first ask all enabled enrol instances in course if they want to auto enrol user foreach ($instances as $instance) { if (!isset($enrols[$instance->enrol])) { continue; } // Get a duration for the guestaccess, a timestamp in the future or false. $until = $enrols[$instance->enrol]->try_autoenrol($instance); if ($until !== false) { $USER->enrol['enrolled'][$course->id] = $until; $USER->access = remove_temp_roles($coursecontext, $USER->access); $access = true; break; } } // if not enrolled yet try to gain temporary guest access if (!$access) { foreach ($instances as $instance) { if (!isset($enrols[$instance->enrol])) { continue; } // Get a duration for the guestaccess, a timestamp in the future or false. $until = $enrols[$instance->enrol]->try_guestaccess($instance); if ($until !== false) { $USER->enrol['tempguest'][$course->id] = $until; $access = true; break; } } } } } } if (!$access) { if ($preventredirect) { throw new require_login_exception('Not enrolled'); } $SESSION->wantsurl = $FULLME; redirect($CFG->wwwroot . '/enrol/index.php?id=' . $course->id); } } // Check visibility of activity to current user; includes visible flag, groupmembersonly, // conditional availability, etc if ($cm && !$cm->uservisible) { if ($preventredirect) { throw new require_login_exception('Activity is hidden'); } redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden')); } // Finally access granted, update lastaccess times user_accesstime_log($course->id); }
} } } } } if ($canunenrol) { echo '<form action="' . $CFG->wwwroot . '/course/unenrol.php" method="get">'; echo '<div>'; echo '<input type="hidden" name="id" value="' . $course->id . '" />'; echo '<input type="hidden" name="user" value="' . $user->id . '" />'; echo '<input type="submit" value="' . s(get_string('unenrolme', '', $course->shortname)) . '" />'; echo '</div>'; echo '</form>'; } } if (!$user->deleted and $USER->id != $user->id && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !has_capability('moodle/site:doanything', $coursecontext, $user->id, false)) { echo '<form action="' . $CFG->wwwroot . '/course/loginas.php" method="get">'; echo '<div>'; echo '<input type="hidden" name="id" value="' . $course->id . '" />'; echo '<input type="hidden" name="user" value="' . $user->id . '" />'; echo '<input type="hidden" name="sesskey" value="' . sesskey() . '" />'; echo '<input type="submit" value="' . get_string('loginas') . '" />'; echo '</div>'; echo '</form>'; } if (!$user->deleted and !empty($CFG->messaging) and !isguest() and has_capability('moodle/site:sendmessage', get_context_instance(CONTEXT_SYSTEM))) { if (!empty($USER->id) and $USER->id == $user->id) { if ($countmessages = $DB->count_records('message', array('useridto' => $user->id))) { $messagebuttonname = get_string("messages", "message") . "({$countmessages})"; } else { $messagebuttonname = get_string("messages", "message");
/** * Prints a summary of a user in a nice little box. * * @uses $CFG * @uses $USER * @param user $user A {@link $USER} object representing a user * @param course $course A {@link $COURSE} object representing a course */ function print_user($user, $course, $messageselect = false, $return = false) { global $CFG, $USER; $output = ''; static $string; static $datestring; static $countries; $context = get_context_instance(CONTEXT_COURSE, $course->id); if (isset($user->context->id)) { $usercontext = $user->context; } else { $usercontext = get_context_instance(CONTEXT_USER, $user->id); } if (empty($string)) { // Cache all the strings for the rest of the page $string->email = get_string('email'); $string->city = get_string('city'); $string->lastaccess = get_string('lastaccess'); $string->activity = get_string('activity'); $string->unenrol = get_string('unenrol'); $string->loginas = get_string('loginas'); $string->fullprofile = get_string('fullprofile'); $string->role = get_string('role'); $string->name = get_string('name'); $string->never = get_string('never'); $datestring->day = get_string('day'); $datestring->days = get_string('days'); $datestring->hour = get_string('hour'); $datestring->hours = get_string('hours'); $datestring->min = get_string('min'); $datestring->mins = get_string('mins'); $datestring->sec = get_string('sec'); $datestring->secs = get_string('secs'); $datestring->year = get_string('year'); $datestring->years = get_string('years'); $countries = get_list_of_countries(); } /// Get the hidden field list if (has_capability('moodle/course:viewhiddenuserfields', $context)) { $hiddenfields = array(); } else { $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields)); } $output .= '<table class="userinfobox">'; $output .= '<tr>'; $output .= '<td class="left side">'; $output .= print_user_picture($user, $course->id, $user->picture, true, true); $output .= '</td>'; $output .= '<td class="content">'; $output .= '<div class="username">' . fullname($user, has_capability('moodle/site:viewfullnames', $context)) . '</div>'; $output .= '<div class="info">'; if (!empty($user->role)) { $output .= $string->role . ': ' . $user->role . '<br />'; } if ($user->maildisplay == 1 or $user->maildisplay == 2 and $course->id != SITEID and !isguest() or has_capability('moodle/course:viewhiddenuserfields', $context)) { $output .= $string->email . ': <a href="mailto:' . $user->email . '">' . $user->email . '</a><br />'; } if (($user->city or $user->country) and (!isset($hiddenfields['city']) or !isset($hiddenfields['country']))) { $output .= $string->city . ': '; if ($user->city && !isset($hiddenfields['city'])) { $output .= $user->city; } if (!empty($countries[$user->country]) && !isset($hiddenfields['country'])) { if ($user->city && !isset($hiddenfields['city'])) { $output .= ', '; } $output .= $countries[$user->country]; } $output .= '<br />'; } if (!isset($hiddenfields['lastaccess'])) { if ($user->lastaccess) { $output .= $string->lastaccess . ': ' . userdate($user->lastaccess); $output .= ' (' . format_time(time() - $user->lastaccess, $datestring) . ')'; } else { $output .= $string->lastaccess . ': ' . $string->never; } } $output .= '</div></td><td class="links">'; //link to blogs if ($CFG->bloglevel > 0) { $output .= '<a href="' . $CFG->wwwroot . '/blog/index.php?userid=' . $user->id . '">' . get_string('blogs', 'blog') . '</a><br />'; } //link to notes if (!empty($CFG->enablenotes) and has_capability('moodle/notes:manage', $context) || has_capability('moodle/notes:view', $context)) { $output .= '<a href="' . $CFG->wwwroot . '/notes/index.php?course=' . $course->id . '&user='******'">' . get_string('notes', 'notes') . '</a><br />'; } if (has_capability('moodle/site:viewreports', $context) or has_capability('moodle/user:viewuseractivitiesreport', $usercontext)) { $output .= '<a href="' . $CFG->wwwroot . '/course/user.php?id=' . $course->id . '&user='******'">' . $string->activity . '</a><br />'; } if (has_capability('moodle/role:assign', $context) and get_user_roles($context, $user->id, false)) { // I can unassing and user has some role $output .= '<a href="' . $CFG->wwwroot . '/course/unenrol.php?id=' . $course->id . '&user='******'">' . $string->unenrol . '</a><br />'; } if ($USER->id != $user->id && !session_is_loggedinas() && has_capability('moodle/user:loginas', $context) && !has_capability('moodle/site:doanything', $context, $user->id, false)) { $output .= '<a href="' . $CFG->wwwroot . '/course/loginas.php?id=' . $course->id . '&user='******'&sesskey=' . sesskey() . '">' . $string->loginas . '</a><br />'; } $output .= '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $user->id . '&course=' . $course->id . '">' . $string->fullprofile . '...</a>'; if (!empty($messageselect)) { $output .= '<br /><input type="checkbox" name="user' . $user->id . '" /> '; } $output .= '</td></tr></table>'; if ($return) { return $output; } else { echo $output; } }
if (!isloggedin()) { // do not use require_login here because we are usually coming from it, // it would also mess up the SESSION->wantsurl redirect(get_login_url()); } $course = $DB->get_record('course', array('id' => $id), '*', MUST_EXIST); $context = context_course::instance($course->id, MUST_EXIST); // Everybody is enrolled on the frontpage if ($course->id == SITEID) { redirect("{$CFG->wwwroot}/"); } $PAGE->set_course($course); $PAGE->set_pagelayout('course'); $PAGE->set_url('/enrol/index.php', array('id' => $course->id)); // do not allow enrols when in login-as session if (session_is_loggedinas() and $USER->loginascontext->contextlevel == CONTEXT_COURSE) { print_error('loginasnoenrol', '', $CFG->wwwroot . '/course/view.php?id=' . $USER->loginascontext->instanceid); } // get all enrol forms available in this course $enrols = enrol_get_plugins(true); $enrolinstances = enrol_get_instances($course->id, true); $forms = array(); foreach ($enrolinstances as $instance) { if (!isset($enrols[$instance->enrol])) { continue; } $form = $enrols[$instance->enrol]->enrol_page_hook($instance); if ($form) { $forms[$instance->id] = $form; } }
/** * Start output by sending the HTTP headers, and printing the HTML <head> * and the start of the <body>. * * To control what is printed, you should set properties on $PAGE. If you * are familiar with the old {@link print_header()} function from Moodle 1.9 * you will find that there are properties on $PAGE that correspond to most * of the old parameters to could be passed to print_header. * * Not that, in due course, the remaining $navigation, $menu parameters here * will be replaced by more properties of $PAGE, but that is still to do. * * @return string HTML that you must output this, preferably immediately. */ public function header() { global $USER, $CFG; if (session_is_loggedinas()) { $this->page->add_body_class('userloggedinas'); } $this->page->set_state(moodle_page::STATE_PRINTING_HEADER); // Find the appropriate page layout file, based on $this->page->pagelayout. $layoutfile = $this->page->theme->layout_file($this->page->pagelayout); // Render the layout using the layout file. $rendered = $this->render_page_layout($layoutfile); // Slice the rendered output into header and footer. $cutpos = strpos($rendered, $this->unique_main_content_token); if ($cutpos === false) { $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN); $token = self::MAIN_CONTENT_TOKEN; } else { $token = $this->unique_main_content_token; } if ($cutpos === false) { throw new coding_exception('page layout file ' . $layoutfile . ' does not contain the main content placeholder, please include "<?php echo $OUTPUT->main_content() ?>" in theme layout file.'); } $header = substr($rendered, 0, $cutpos); $footer = substr($rendered, $cutpos + strlen($token)); if (empty($this->contenttype)) { debugging('The page layout file did not call $OUTPUT->doctype()'); $header = $this->doctype() . $header; } send_headers($this->contenttype, $this->page->cacheable); $this->opencontainers->push('header/footer', $footer); $this->page->set_state(moodle_page::STATE_IN_BODY); return $header . $this->skip_link_target('maincontent'); }
/** * This function checks that the current user is logged in and has the * required privileges * * This function checks that the current user is logged in, and optionally * whether they are allowed to be in a particular course and view a particular * course module. * If they are not logged in, then it redirects them to the site login unless * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which * case they are automatically logged in as guests. * If $courseid is given and the user is not enrolled in that course then the * user is redirected to the course enrolment page. * If $cm is given and the course module is hidden and the user is not a teacher * in the course then the user is redirected to the course home page. * * When $cm parameter specified, this function sets page layout to 'module'. * You need to change it manually later if some other layout needed. * * @package core_access * @category access * * @param mixed $courseorid id of the course or course object * @param bool $autologinguest default true * @param object $cm course module object * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to * true. Used to avoid (=false) some scripts (file.php...) to set that variable, * in order to keep redirects working properly. MDL-14495 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions * @return mixed Void, exit, and die depending on path */ function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) { global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT; // Must not redirect when byteserving already started. if (!empty($_SERVER['HTTP_RANGE'])) { $preventredirect = true; } // setup global $COURSE, themes, language and locale if (!empty($courseorid)) { if (is_object($courseorid)) { $course = $courseorid; } else { if ($courseorid == SITEID) { $course = clone $SITE; } else { $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST); } } if ($cm) { if ($cm->course != $course->id) { throw new coding_exception('course and cm parameters in require_login() call do not match!!'); } // make sure we have a $cm from get_fast_modinfo as this contains activity access details if (!$cm instanceof cm_info) { // note: nearly all pages call get_fast_modinfo anyway and it does not make any // db queries so this is not really a performance concern, however it is obviously // better if you use get_fast_modinfo to get the cm before calling this. $modinfo = get_fast_modinfo($course); $cm = $modinfo->get_cm($cm->id); } $PAGE->set_cm($cm, $course); // set's up global $COURSE $PAGE->set_pagelayout('incourse'); } else { $PAGE->set_course($course); // set's up global $COURSE } } else { // do not touch global $COURSE via $PAGE->set_course(), // the reasons is we need to be able to call require_login() at any time!! $course = $SITE; if ($cm) { throw new coding_exception('cm parameter in require_login() requires valid course parameter!'); } } // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false. // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future // risk leading the user back to the AJAX request URL. if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) { $setwantsurltome = false; } // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour. if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) { if ($setwantsurltome) { $SESSION->wantsurl = qualified_me(); } redirect(get_login_url()); } // If the user is not even logged in yet then make sure they are if (!isloggedin()) { if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) { if (!($guest = get_complete_user_data('id', $CFG->siteguest))) { // misconfigured site guest, just redirect to login page redirect(get_login_url()); exit; // never reached } $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang; complete_user_login($guest); $USER->autologinguest = true; $SESSION->lang = $lang; } else { //NOTE: $USER->site check was obsoleted by session test cookie, // $USER->confirmed test is in login/index.php if ($preventredirect) { throw new require_login_exception('You are not logged in'); } if ($setwantsurltome) { $SESSION->wantsurl = qualified_me(); } if (!empty($_SERVER['HTTP_REFERER'])) { $SESSION->fromurl = $_SERVER['HTTP_REFERER']; } redirect(get_login_url()); exit; // never reached } } // loginas as redirection if needed if ($course->id != SITEID and session_is_loggedinas()) { if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) { if ($USER->loginascontext->instanceid != $course->id) { print_error('loginasonecourse', '', $CFG->wwwroot . '/course/view.php?id=' . $USER->loginascontext->instanceid); } } } // check whether the user should be changing password (but only if it is REALLY them) if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) { $userauth = get_auth_plugin($USER->auth); if ($userauth->can_change_password() and !$preventredirect) { if ($setwantsurltome) { $SESSION->wantsurl = qualified_me(); } if ($changeurl = $userauth->change_password_url()) { //use plugin custom url redirect($changeurl); } else { //use moodle internal method if (empty($CFG->loginhttps)) { redirect($CFG->wwwroot . '/login/change_password.php'); } else { $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot); redirect($wwwroot . '/login/change_password.php'); } } } else { print_error('nopasswordchangeforced', 'auth'); } } // Check that the user account is properly set up if (user_not_fully_set_up($USER)) { if ($preventredirect) { throw new require_login_exception('User not fully set-up'); } if ($setwantsurltome) { $SESSION->wantsurl = qualified_me(); } redirect($CFG->wwwroot . '/user/edit.php?id=' . $USER->id . '&course=' . SITEID); } // Make sure the USER has a sesskey set up. Used for CSRF protection. sesskey(); // Do not bother admins with any formalities if (is_siteadmin()) { //set accesstime or the user will appear offline which messes up messaging user_accesstime_log($course->id); return; } // Check that the user has agreed to a site policy if there is one - do not test in case of admins if (!$USER->policyagreed and !is_siteadmin()) { if (!empty($CFG->sitepolicy) and !isguestuser()) { if ($preventredirect) { throw new require_login_exception('Policy not agreed'); } if ($setwantsurltome) { $SESSION->wantsurl = qualified_me(); } redirect($CFG->wwwroot . '/user/policy.php'); } else { if (!empty($CFG->sitepolicyguest) and isguestuser()) { if ($preventredirect) { throw new require_login_exception('Policy not agreed'); } if ($setwantsurltome) { $SESSION->wantsurl = qualified_me(); } redirect($CFG->wwwroot . '/user/policy.php'); } } } // Fetch the system context, the course context, and prefetch its child contexts $sysctx = context_system::instance(); $coursecontext = context_course::instance($course->id, MUST_EXIST); if ($cm) { $cmcontext = context_module::instance($cm->id, MUST_EXIST); } else { $cmcontext = null; } // If the site is currently under maintenance, then print a message if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) { if ($preventredirect) { throw new require_login_exception('Maintenance in progress'); } print_maintenance_message(); } // make sure the course itself is not hidden if ($course->id == SITEID) { // frontpage can not be hidden } else { if (is_role_switched($course->id)) { // when switching roles ignore the hidden flag - user had to be in course to do the switch } else { if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) { // originally there was also test of parent category visibility, // BUT is was very slow in complex queries involving "my courses" // now it is also possible to simply hide all courses user is not enrolled in :-) if ($preventredirect) { throw new require_login_exception('Course is hidden'); } // We need to override the navigation URL as the course won't have // been added to the navigation and thus the navigation will mess up // when trying to find it. navigation_node::override_active_url(new moodle_url('/')); notice(get_string('coursehidden'), $CFG->wwwroot . '/'); } } } // is the user enrolled? if ($course->id == SITEID) { // everybody is enrolled on the frontpage } else { if (session_is_loggedinas()) { // Make sure the REAL person can access this course first $realuser = session_get_realuser(); if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) { if ($preventredirect) { throw new require_login_exception('Invalid course login-as access'); } echo $OUTPUT->header(); notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot . '/'); } } $access = false; if (is_role_switched($course->id)) { // ok, user had to be inside this course before the switch $access = true; } else { if (is_viewing($coursecontext, $USER)) { // ok, no need to mess with enrol $access = true; } else { if (isset($USER->enrol['enrolled'][$course->id])) { if ($USER->enrol['enrolled'][$course->id] > time()) { $access = true; if (isset($USER->enrol['tempguest'][$course->id])) { unset($USER->enrol['tempguest'][$course->id]); remove_temp_course_roles($coursecontext); } } else { //expired unset($USER->enrol['enrolled'][$course->id]); } } if (isset($USER->enrol['tempguest'][$course->id])) { if ($USER->enrol['tempguest'][$course->id] == 0) { $access = true; } else { if ($USER->enrol['tempguest'][$course->id] > time()) { $access = true; } else { //expired unset($USER->enrol['tempguest'][$course->id]); remove_temp_course_roles($coursecontext); } } } if ($access) { // cache ok } else { $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id); if ($until !== false) { // active participants may always access, a timestamp in the future, 0 (always) or false. if ($until == 0) { $until = ENROL_MAX_TIMESTAMP; } $USER->enrol['enrolled'][$course->id] = $until; $access = true; } else { $instances = $DB->get_records('enrol', array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED), 'sortorder, id ASC'); $enrols = enrol_get_plugins(true); // first ask all enabled enrol instances in course if they want to auto enrol user foreach ($instances as $instance) { if (!isset($enrols[$instance->enrol])) { continue; } // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false. $until = $enrols[$instance->enrol]->try_autoenrol($instance); if ($until !== false) { if ($until == 0) { $until = ENROL_MAX_TIMESTAMP; } $USER->enrol['enrolled'][$course->id] = $until; $access = true; break; } } // if not enrolled yet try to gain temporary guest access if (!$access) { foreach ($instances as $instance) { if (!isset($enrols[$instance->enrol])) { continue; } // Get a duration for the guest access, a timestamp in the future or false. $until = $enrols[$instance->enrol]->try_guestaccess($instance); if ($until !== false and $until > time()) { $USER->enrol['tempguest'][$course->id] = $until; $access = true; break; } } } } } } } if (!$access) { if ($preventredirect) { throw new require_login_exception('Not enrolled'); } if ($setwantsurltome) { $SESSION->wantsurl = qualified_me(); } redirect($CFG->wwwroot . '/enrol/index.php?id=' . $course->id); } } // Check visibility of activity to current user; includes visible flag, groupmembersonly, // conditional availability, etc if ($cm && !$cm->uservisible) { if ($preventredirect) { throw new require_login_exception('Activity is hidden'); } if ($course->id != SITEID) { $url = new moodle_url('/course/view.php', array('id' => $course->id)); } else { $url = new moodle_url('/'); } redirect($url, get_string('activityiscurrentlyhidden')); } // Finally access granted, update lastaccess times user_accesstime_log($course->id); }
</head> <body id="<?php p($PAGE->bodyid); ?> " class="<?php p($PAGE->bodyclasses . ' ' . join(' ', $bodyclasses)); ?> "> <?php echo $OUTPUT->standard_top_of_body_html(); if (empty($PAGE->layout_options['noawesomebar'])) { ?> <div id="awesomebar" class="krystle-awesome-bar"> <?php if ($this->page->pagelayout != 'maintenance' && !(get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas())) { echo $awesome_nav; if ($hascustommenu && !empty($PAGE->theme->settings->custommenuinawesomebar) && empty($PAGE->theme->settings->custommenuafterawesomebar)) { echo $custommenu; } echo $awesome_settings; if ($hascustommenu && !empty($PAGE->theme->settings->custommenuinawesomebar) && !empty($PAGE->theme->settings->custommenuafterawesomebar)) { echo $custommenu; } echo $topsettings->settings_search_box(); } ?> </div> <?php } ?>
public function login_info() { global $USER, $CFG, $DB, $SESSION; if (during_initial_install()) { return ''; } $course = $this->page->course; if (empty($course->id)) { // $course->id is not defined during installation return ''; } if (session_is_loggedinas()) { $real_user = session_get_realuser(); $real['name'] = fullname($real_user, true); $real['link'] = html::url("{$CFG->wwwroot}/course/loginas.php", array('id' => $course->id, 'sesskey' => sesskey())); } else { $real = null; } if (!isloggedin()) { return bootsnipp::sign_up_sign_in(new moodle_url('/login/index.php')); } $logout['link'] = html::url("{$CFG->wwwroot}/login/logout.php", array('sesskey' => sesskey())); $logout['name'] = get_string('logout'); $context = get_context_instance(CONTEXT_COURSE, $course->id); $user['name'] = fullname($USER, true); $user['link'] = html::url("{$CFG->wwwroot}/user/profile.php", array('id' => $USER->id)); if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id' => $USER->mnethostid))) { $mnet['link'] = $idprovider->wwwroot; $mnet['name'] = $idprovider->name; } else { $mnet = null; } if (isguestuser()) { $guest['link'] = get_login_url(); $guest['name'] = get_string('login'); return bootsnipp::guest_user($user['name'], $guest, $logout); } if (is_role_switched($course->id)) { if ($role = $DB->get_record('role', array('id' => $USER->access['rsw'][$context->path]))) { $user['name'] .= ': ' . format_string($role->name); } $role_switch['link'] = "{$CFG->wwwroot}/course/view.php?id={$course->id}&switchrole=0&sesskey=" . sesskey(); $role_switch['name'] = get_string('switchrolereturn'); } else { $role_switch = null; } $loginfailures = null; if (isset($SESSION->justloggedin)) { unset($SESSION->justloggedin); if (!empty($CFG->displayloginfailures) && !isguestuser()) { if (file_exists("{$CFG->dirroot}/report/log/index.php") and has_capability('report/log:view', get_context_instance(CONTEXT_SYSTEM))) { if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) { $loginfailures['link'] = "{$CFG->wwwroot}/report/log/index.php?chooselog=1&id=1&modid=site_errors"; if (empty($count->accounts)) { $loginfailures['name'] = get_string('failedloginattempts', '', $count); } else { $loginfailures['name'] = get_string('failedloginattemptsall', '', $count); } } } } } return bootsnipp::signed_in($user, $loginfailures, $mnet, $real, $role_switch, $logout); }
/** * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out * what can be shown/done * * @param int $courseid The current course' id * @param int $userid The user id to load for * @param string $gstitle The string to pass to get_string for the branch title * @return navigation_node|false */ protected function generate_user_settings($courseid, $userid, $gstitle = 'usercurrentsettings') { global $DB, $CFG, $USER, $SITE; if ($courseid != $SITE->id) { if (!empty($this->page->course->id) && $this->page->course->id == $courseid) { $course = $this->page->course; } else { $select = context_helper::get_preload_record_columns_sql('ctx'); $sql = "SELECT c.*, {$select}\n FROM {course} c\n JOIN {context} ctx ON c.id = ctx.instanceid\n WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel"; $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE); $course = $DB->get_record_sql($sql, $params, MUST_EXIST); context_helper::preload_from_record($course); } } else { $course = $SITE; } $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Course context $systemcontext = get_system_context(); $currentuser = $USER->id == $userid; if ($currentuser) { $user = $USER; $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context } else { $select = context_helper::get_preload_record_columns_sql('ctx'); $sql = "SELECT u.*, {$select}\n FROM {user} u\n JOIN {context} ctx ON u.id = ctx.instanceid\n WHERE u.id = :userid AND ctx.contextlevel = :contextlevel"; $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER); $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING); if (!$user) { return false; } context_helper::preload_from_record($user); // Check that the user can view the profile $usercontext = get_context_instance(CONTEXT_USER, $user->id); // User context $canviewuser = has_capability('moodle/user:viewdetails', $usercontext); if ($course->id == $SITE->id) { if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) { // Reduce possibility of "browsing" userbase at site level // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366) return false; } } else { $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext); $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext); if (!$canviewusercourse && !$canviewuser || !can_access_course($course, $user->id)) { return false; } if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS) { // If groups are in use, make sure we can see that group return false; } } } $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context)); $key = $gstitle; if ($gstitle != 'usercurrentsettings') { $key .= $userid; } // Add a user setting branch $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key); $usersetting->id = 'usersettings'; if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) { // Automatically start by making it active $usersetting->make_active(); } // Check if the user has been deleted if ($user->deleted) { if (!has_capability('moodle/user:update', $coursecontext)) { // We can't edit the user so just show the user deleted message $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING); } else { // We can edit the user so show the user deleted message and link it to the profile if ($course->id == $SITE->id) { $profileurl = new moodle_url('/user/profile.php', array('id' => $user->id)); } else { $profileurl = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $course->id)); } $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING); } return true; } $userauthplugin = false; if (!empty($user->auth)) { $userauthplugin = get_auth_plugin($user->auth); } // Add the profile edit link if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) { if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) { $url = new moodle_url('/user/editadvanced.php', array('id' => $user->id, 'course' => $course->id)); $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING); } else { if (has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user) || $currentuser && has_capability('moodle/user:editownprofile', $systemcontext)) { if ($userauthplugin && $userauthplugin->can_edit_profile()) { $url = $userauthplugin->edit_profile_url(); if (empty($url)) { $url = new moodle_url('/user/edit.php', array('id' => $user->id, 'course' => $course->id)); } $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING); } } } } // Change password link if ($userauthplugin && $currentuser && !session_is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) { $passwordchangeurl = $userauthplugin->change_password_url(); if (empty($passwordchangeurl)) { $passwordchangeurl = new moodle_url('/login/change_password.php', array('id' => $course->id)); } $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING); } // View the roles settings if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:manage'), $usercontext)) { $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING); $url = new moodle_url('/admin/roles/usersroles.php', array('userid' => $user->id, 'courseid' => $course->id)); $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING); $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH); if (!empty($assignableroles)) { $url = new moodle_url('/admin/roles/assign.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING); } if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH)) > 0) { $url = new moodle_url('/admin/roles/permissions.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING); } $url = new moodle_url('/admin/roles/check.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id)); $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING); } // Portfolio if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) { require_once $CFG->libdir . '/portfoliolib.php'; if (portfolio_instances(true, false)) { $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING); $url = new moodle_url('/user/portfolio.php', array('courseid' => $course->id)); $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING); $url = new moodle_url('/user/portfoliologs.php', array('courseid' => $course->id)); $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING); } } $enablemanagetokens = false; if (!empty($CFG->enablerssfeeds)) { $enablemanagetokens = true; } else { if (!is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', get_system_context())) { $enablemanagetokens = true; } } // Security keys if ($currentuser && $enablemanagetokens) { $url = new moodle_url('/user/managetoken.php', array('sesskey' => sesskey())); $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING); } // Repository if (!$currentuser && $usercontext->contextlevel == CONTEXT_USER) { if (!$this->cache->cached('contexthasrepos' . $usercontext->id)) { require_once $CFG->dirroot . '/repository/lib.php'; $editabletypes = repository::get_editable_types($usercontext); $haseditabletypes = !empty($editabletypes); unset($editabletypes); $this->cache->set('contexthasrepos' . $usercontext->id, $haseditabletypes); } else { $haseditabletypes = $this->cache->{'contexthasrepos' . $usercontext->id}; } if ($haseditabletypes) { $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)); $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING); } } // Messaging if ($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext) || !isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id)) { $url = new moodle_url('/message/edit.php', array('id' => $user->id)); $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING); } // Blogs if ($currentuser && !empty($CFG->bloglevel)) { $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs'); $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING); if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM))) { $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING); $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING); } } // Login as ... if (!$user->deleted and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) { $url = new moodle_url('/course/loginas.php', array('id' => $course->id, 'user' => $user->id, 'sesskey' => sesskey())); $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING); } return $usersetting; }
public function login_info($withlinks = null) { global $USER, $CFG, $DB, $SESSION; if (during_initial_install()) { return ''; } if (is_null($withlinks)) { $withlinks = empty($this->page->layout_options['nologinlinks']); } $loginpage = (string) $this->page->url === get_login_url(); $course = $this->page->course; if (session_is_loggedinas()) { $realuser = session_get_realuser(); $fullname = fullname($realuser, true); if ($withlinks) { $realuserinfo = " [<a href=\"{$CFG->wwwroot}/course/loginas.php?id={$course->id}&sesskey=" . sesskey() . "\">{$fullname}</a>] "; } else { $realuserinfo = " "; } } else { $realuserinfo = ''; } $loginurl = get_login_url(); if (empty($course->id)) { // $course->id is not defined during installation return ''; } else { if (isloggedin()) { $context = context_course::instance($course->id); $fullname = fullname($USER, true); // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page) if ($withlinks) { $username = "******"{$CFG->wwwroot}/user/profile.php?id={$USER->id}\">{$fullname}</a>"; } else { $username = $fullname; } if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id' => $USER->mnethostid))) { if ($withlinks) { $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>"; } else { $username .= " from {$idprovider->name}"; } } if (isguestuser()) { $loggedinas = $realuserinfo . get_string('loggedinasguest'); if (!$loginpage && $withlinks) { $loggedinas .= " (<a href=\"{$loginurl}\">" . get_string('login') . '</a>)'; } } else { if (is_role_switched($course->id)) { // Has switched roles $rolename = ''; if ($role = $DB->get_record('role', array('id' => $USER->access['rsw'][$context->path]))) { $rolename = ': ' . format_string($role->name); } $loggedinas = get_string('loggedinas', 'moodle', $username) . $rolename; if ($withlinks) { $loggedinas .= " (<a href=\"{$CFG->wwwroot}/course/view.php?id={$course->id}&switchrole=0&sesskey=" . sesskey() . "\">" . get_string('switchrolereturn') . '</a>)'; } } else { $loggedinas = $realuserinfo . $username; $logouticon = html_writer::empty_tag('img', array('alt' => get_string('logout'), 'src' => $this->pix_url('logout_icon', 'theme'))); if ($withlinks) { $loggedinas .= " <a href=\"{$CFG->wwwroot}/login/logout.php?sesskey=" . sesskey() . "\">{$logouticon}</a>"; } } } } else { $loggedinas = get_string('loggedinnot', 'moodle'); if (!$loginpage && $withlinks) { $loggedinas .= " (<a href=\"{$loginurl}\">" . get_string('login') . '</a>)'; } } } $loggedinas = '<div class="logininfo">' . $loggedinas . '</div>'; if (isset($SESSION->justloggedin)) { unset($SESSION->justloggedin); if (!empty($CFG->displayloginfailures)) { if (!isguestuser()) { if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) { $loggedinas .= ' <div class="loginfailures">'; if (empty($count->accounts)) { $loggedinas .= get_string('failedloginattempts', '', $count); } else { $loggedinas .= get_string('failedloginattemptsall', '', $count); } if (file_exists("{$CFG->dirroot}/report/log/index.php") and has_capability('report/log:view', context_system::instance())) { $loggedinas .= ' (<a href="' . $CFG->wwwroot . '/report/log/index.php' . '?chooselog=1&id=1&modid=site_errors">' . get_string('logs') . '</a>)'; } $loggedinas .= '</div>'; } } } } return $loggedinas; }