/** * Get a list of essential user navigation items. * * @param stdclass $user user object. * @param moodle_page $page page object. * @return stdClass $returnobj navigation information object, where: * * $returnobj->navitems array array of links where each link is a * stdClass with fields url, title, and * pix * $returnobj->metadata array array of useful user metadata to be * used when constructing navigation; * fields include: * * ROLE FIELDS * asotherrole bool whether viewing as another role * rolename string name of the role * * USER FIELDS * These fields are for the currently-logged in user, or for * the user that the real user is currently logged in as. * * userid int the id of the user in question * userfullname string the user's full name * userprofileurl moodle_url the url of the user's profile * useravatar string a HTML fragment - the rendered * user_picture for this user * userloginfail string an error string denoting the number * of login failures since last login * * "REAL USER" FIELDS * These fields are for when asotheruser is true, and * correspond to the underlying "real user". * * asotheruser bool whether viewing as another user * realuserid int the id of the user in question * realuserfullname string the user's full name * realuserprofileurl moodle_url the url of the user's profile * realuseravatar string a HTML fragment - the rendered * user_picture for this user * * MNET PROVIDER FIELDS * asmnetuser bool whether viewing as a user from an * MNet provider * mnetidprovidername string name of the MNet provider * mnetidproviderwwwroot string URL of the MNet provider */ function user_get_user_navigation_info($user, $page) { global $OUTPUT, $DB, $SESSION, $CFG; $returnobject = new stdClass(); $returnobject->navitems = array(); $returnobject->metadata = array(); $course = $page->course; // Query the environment. $context = context_course::instance($course->id); // Get basic user metadata. $returnobject->metadata['userid'] = $user->id; $returnobject->metadata['userfullname'] = fullname($user, true); $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array('id' => $user->id)); $returnobject->metadata['useravatar'] = $OUTPUT->user_picture($user, array('link' => false, 'visibletoscreenreaders' => false)); // Build a list of items for a regular user. // Query MNet status. if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) { $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid)); $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name; $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot; } // Did the user just log in? if (isset($SESSION->justloggedin)) { // Don't unset this flag as login_info still needs it. if (!empty($CFG->displayloginfailures)) { // We're already in /user/lib.php, so we don't need to include. if ($count = user_count_login_failures($user)) { // Get login failures string. $a = new stdClass(); $a->attempts = html_writer::tag('span', $count, array('class' => 'value')); $returnobject->metadata['userloginfail'] = get_string('failedloginattempts', '', $a); } } } // Links: Dashboard. $myhome = new stdClass(); $myhome->itemtype = 'link'; $myhome->url = new moodle_url('/my/'); $myhome->title = get_string('mymoodle', 'admin'); $myhome->pix = "i/course"; $returnobject->navitems[] = $myhome; // Links: My Profile. $myprofile = new stdClass(); $myprofile->itemtype = 'link'; $myprofile->url = new moodle_url('/user/profile.php', array('id' => $user->id)); $myprofile->title = get_string('profile'); $myprofile->pix = "i/user"; $returnobject->navitems[] = $myprofile; // Links: Role-return or logout link. $lastobj = null; $buildlogout = true; $returnobject->metadata['asotherrole'] = false; if (is_role_switched($course->id)) { if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) { // Build role-return link instead of logout link. $rolereturn = new stdClass(); $rolereturn->itemtype = 'link'; $rolereturn->url = new moodle_url('/course/switchrole.php', array('id' => $course->id, 'sesskey' => sesskey(), 'switchrole' => 0, 'returnurl' => $page->url->out_as_local_url(false))); $rolereturn->pix = "a/logout"; $rolereturn->title = get_string('switchrolereturn'); $lastobj = $rolereturn; $returnobject->metadata['asotherrole'] = true; $returnobject->metadata['rolename'] = role_get_name($role, $context); $buildlogout = false; } } if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) { $realuser = \core\session\manager::get_realuser(); // Save values for the real user, as $user will be full of data for the // user the user is disguised as. $returnobject->metadata['realuserid'] = $realuser->id; $returnobject->metadata['realuserfullname'] = fullname($realuser, true); $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', array('id' => $realuser->id)); $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, array('link' => false, 'visibletoscreenreaders' => false)); // Build a user-revert link. $userrevert = new stdClass(); $userrevert->itemtype = 'link'; $userrevert->url = new moodle_url('/course/loginas.php', array('id' => $course->id, 'sesskey' => sesskey())); $userrevert->pix = "a/logout"; $userrevert->title = get_string('logout'); $lastobj = $userrevert; $buildlogout = false; } if ($buildlogout) { // Build a logout link. $logout = new stdClass(); $logout->itemtype = 'link'; $logout->url = new moodle_url('/login/logout.php', array('sesskey' => sesskey())); $logout->pix = "a/logout"; $logout->title = get_string('logout'); $lastobj = $logout; } // Before we add the last item (usually a logout link), add any // custom-defined items. $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page); foreach ($customitems as $item) { $returnobject->navitems[] = $item; } // Add the last item to the list. if (!is_null($lastobj)) { $returnobject->navitems[] = $lastobj; } return $returnobject; }
/** * 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 (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 (\core\session\manager::is_loggedinas()) { $realuser = \core\session\manager::get_realuser(); $fullname = fullname($realuser, true); if ($withlinks) { $loginastitle = get_string('loginas'); $realuserinfo = " [<a href=\"{$CFG->wwwroot}/course/loginas.php?id={$course->id}&sesskey=" . sesskey() . "\""; $realuserinfo .= "title =\"" . $loginastitle . "\">{$fullname}</a>] "; } else { $realuserinfo = " [{$fullname}] "; } } 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) { $linktitle = get_string('viewprofile'); $username = "******"{$CFG->wwwroot}/user/profile.php?id={$USER->id}\" title=\"{$linktitle}\">{$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 = ': ' . role_get_name($role, $context); } $loggedinas = get_string('loggedinas', 'moodle', $username) . $rolename; if ($withlinks) { $url = new moodle_url('/course/switchrole.php', array('id' => $course->id, 'sesskey' => sesskey(), 'switchrole' => 0, 'returnurl' => $this->page->url->out_as_local_url(false))); $loggedinas .= '(' . html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)) . ')'; } } else { $loggedinas = $realuserinfo . get_string('loggedinas', 'moodle', $username); if ($withlinks) { echo "<i class='fa fa-user hide979 mywhite'></i> "; //****************$loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)'; $loggedinas .= " <span class=\"line-trans\">|</span><a class=\"logtop\" href=\"{$CFG->wwwroot}/login/logout.php?sesskey=" . sesskey() . "\"> " . get_string('logout') . '</a><span class="line-trans"> |</span>'; } } } } else { $loggedinas = get_string('loggedinnot', 'moodle'); if (!$loginpage && $withlinks) { //****************$loggedinas $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)'; echo "<i class='fa fa-lock hide979 mywhite'></i> "; $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; }
/** * 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 (during_initial_install()) { return ''; } if (is_null($withlinks)) { $withlinks = empty($this->page->layout_options['nologinlinks']); } $course = $this->page->course; if (\core\session\manager::is_loggedinas()) { $realuser = \core\session\manager::get_realuser(); $fullname = fullname($realuser, true); if ($withlinks) { $loginastitle = get_string('loginas'); $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&sesskey=".sesskey()."\""; $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] "; } else { $realuserinfo = " [$fullname] "; } } else { $realuserinfo = ''; } $loginpage = $this->is_login_page(); $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) { $linktitle = get_string('viewprofile'); $username = "******"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$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 = ': '.role_get_name($role, $context); } $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename; if ($withlinks) { $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false))); $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')'; } } else { $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username); if ($withlinks) { $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</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()) { // Include this file only when required. require_once($CFG->dirroot . '/user/lib.php'); if ($count = user_count_login_failures($USER)) { $loggedinas .= '<div class="loginfailures">'; $a = new stdClass(); $a->attempts = $count; $loggedinas .= get_string('failedloginattempts', '', $a); if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) { $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1, 'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')'; } $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 (\core\session\manager::is_loggedinas()) { $realuser = \core\session\manager::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; break;
/** * Returns the $USER object ignoring current login-as session * @deprecated since 2.6 * @return stdClass user object */ function session_get_realuser() { debugging('session_get_realuser() is deprecated, use \\core\\session\\manager::get_realuser() instead', DEBUG_DEVELOPER); return \core\session\manager::get_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 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 * @throws coding_exception * @throws require_login_exception */ 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; } if (AJAX_SCRIPT) { // We cannot redirect for AJAX scripts either. $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); } } } 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) && !empty($CFG->dbsessions)) { if ($preventredirect) { throw new require_login_session_timeout_exception(); } else { 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(); } $referer = get_local_referer(false); if (!empty($referer)) { $SESSION->fromurl = $referer; } // Give auth plugins an opportunity to authenticate or redirect to an external login page $authsequence = get_enabled_auth_plugins(true); // auths, in sequence foreach ($authsequence as $authname) { $authplugin = get_auth_plugin($authname); $authplugin->pre_loginpage_hook(); if (isloggedin()) { break; } } // If we're still not logged in then go to the login page if (!isloggedin()) { redirect(get_login_url()); exit; // Never reached. } } } // Loginas as redirection if needed. if ($course->id != SITEID and \core\session\manager::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') && !\core\session\manager::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 { if ($userauth->can_change_password()) { throw new moodle_exception('forcepasswordchangenotice'); } else { throw new moodle_exception('nopasswordchangeforced', 'auth'); } } } // Check that the user account is properly set up. If we can't redirect to // edit their profile, perform just the lax check. It will allow them to // use filepicker on the profile edit page. if ($preventredirect) { $usernotfullysetup = user_not_fully_set_up($USER, false); } else { $usernotfullysetup = user_not_fully_set_up($USER, true); } if ($usernotfullysetup) { if ($preventredirect) { throw new moodle_exception('usernotfullysetup'); } 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 the global $COURSE. if ($cm) { $PAGE->set_cm($cm, $course); $PAGE->set_pagelayout('incourse'); } else { if (!empty($courseorid)) { $PAGE->set_course($course); } } // 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 moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicy); } if ($setwantsurltome) { $SESSION->wantsurl = qualified_me(); } redirect($CFG->wwwroot . '/user/policy.php'); } else { if (!empty($CFG->sitepolicyguest) and isguestuser()) { if ($preventredirect) { throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicyguest); } 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:maintenanceaccess', $sysctx)) { if ($preventredirect) { throw new require_login_exception('Maintenance in progress'); } $PAGE->set_context(null); 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'); } $PAGE->set_context(null); // 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 (\core\session\manager::is_loggedinas()) { // Make sure the REAL person can access this course first. $realuser = \core\session\manager::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'); } $PAGE->set_context(null); 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 not ok. $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 { $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED); $instances = $DB->get_records('enrol', $params, '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, 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')); } // Set the global $COURSE. if ($cm) { $PAGE->set_cm($cm, $course); $PAGE->set_pagelayout('incourse'); } else { if (!empty($courseorid)) { $PAGE->set_course($course); } } // Finally access granted, update lastaccess times. user_accesstime_log($course->id); }
/** * Initialise the settings navigation based on the current context * * This function initialises the settings navigation tree for a given context * by calling supporting functions to generate major parts of the tree. * */ public function initialise() { global $DB, $SESSION, $SITE; if (during_initial_install()) { return false; } else { if ($this->initialised) { return true; } } $this->id = 'settingsnav'; $this->context = $this->page->context; $context = $this->context; if ($context->contextlevel == CONTEXT_BLOCK) { $this->load_block_settings(); $context = $context->get_parent_context(); } switch ($context->contextlevel) { case CONTEXT_SYSTEM: if ($this->page->url->compare(new moodle_url('/admin/settings.php', array('section' => 'frontpagesettings')))) { $this->load_front_page_settings($context->id == $this->context->id); } break; case CONTEXT_COURSECAT: $this->load_category_settings(); break; case CONTEXT_COURSE: if ($this->page->course->id != $SITE->id) { $this->load_course_settings($context->id == $this->context->id); } else { $this->load_front_page_settings($context->id == $this->context->id); } break; case CONTEXT_MODULE: $this->load_module_settings(); $this->load_course_settings(); break; case CONTEXT_USER: if ($this->page->course->id != $SITE->id) { $this->load_course_settings(); } break; } $usersettings = $this->load_user_settings($this->page->course->id); $adminsettings = false; if (isloggedin() && !isguestuser() && (!isset($SESSION->load_navigation_admin) || $SESSION->load_navigation_admin)) { $isadminpage = $this->is_admin_tree_needed(); if (has_capability('moodle/site:config', context_system::instance())) { // Make sure this works even if config capability changes on the fly // and also make it fast for admin right after login. $SESSION->load_navigation_admin = 1; if ($isadminpage) { $adminsettings = $this->load_administration_settings(); } } else { if (!isset($SESSION->load_navigation_admin)) { $adminsettings = $this->load_administration_settings(); $SESSION->load_navigation_admin = (int) ($adminsettings->children->count() > 0); } else { if ($SESSION->load_navigation_admin) { if ($isadminpage) { $adminsettings = $this->load_administration_settings(); } } } } // Print empty navigation node, if needed. if ($SESSION->load_navigation_admin && !$isadminpage) { if ($adminsettings) { // Do not print settings tree on pages that do not need it, this helps with performance. $adminsettings->remove(); $adminsettings = false; } $siteadminnode = $this->add(get_string('administrationsite'), new moodle_url('/admin'), self::TYPE_SITE_ADMIN, null, 'siteadministration'); $siteadminnode->id = 'expandable_branch_' . $siteadminnode->type . '_' . clean_param($siteadminnode->key, PARAM_ALPHANUMEXT); $this->page->requires->data_for_js('siteadminexpansion', $siteadminnode); } } if ($context->contextlevel == CONTEXT_SYSTEM && $adminsettings) { $adminsettings->force_open(); } else { if ($context->contextlevel == CONTEXT_USER && $usersettings) { $usersettings->force_open(); } } // Check if the user is currently logged in as another user if (\core\session\manager::is_loggedinas()) { // Get the actual user, we need this so we can display an informative return link $realuser = \core\session\manager::get_realuser(); // Add the informative return to original user link $url = new moodle_url('/course/loginas.php', array('id' => $this->page->course->id, 'return' => 1, 'sesskey' => sesskey())); $this->add(get_string('returntooriginaluser', 'moodle', fullname($realuser, true)), $url, self::TYPE_SETTING, null, null, new pix_icon('t/left', '')); } // At this point we give any local plugins the ability to extend/tinker with the navigation settings. $this->load_local_plugin_settings(); foreach ($this->children as $key => $node) { if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count() === 0) { // Site administration is shown as link. if (!empty($SESSION->load_navigation_admin) && $node->type === self::TYPE_SITE_ADMIN) { continue; } $node->remove(); } } $this->initialised = true; }
/** * Outputs the user menu. * @return custom_menu object */ public function custom_menu_user() { // Die if executed during install. if (during_initial_install()) { return false; } global $USER, $CFG, $DB; $loginurl = get_login_url(); $usermenu = html_writer::start_tag('ul', array('class' => 'nav')); $usermenu .= html_writer::start_tag('li', array('class' => 'dropdown')); if (!isloggedin()) { if ($this->page->pagelayout != 'login') { $userpic = '<em><i class="fa fa-sign-in"></i>' . get_string('login') . '</em>'; $usermenu .= html_writer::link($loginurl, $userpic, array('class' => 'loginurl')); } } else { if (isguestuser()) { $userurl = new moodle_url('#'); $userpic = parent::user_picture($USER, array('link' => false)); $caret = '<i class="fa fa-caret-right"></i>'; $userclass = array('class' => 'dropdown-toggle', 'data-toggle' => 'dropdown'); $usermenu .= html_writer::link($userurl, $userpic . get_string('guest') . $caret, $userclass); // Render direct logout link. $usermenu .= html_writer::start_tag('ul', array('class' => 'dropdown-menu pull-right')); $branchlabel = '<em><i class="fa fa-sign-out"></i>' . get_string('logout') . '</em>'; $branchurl = new moodle_url('/login/logout.php'); $branchurl->param('sesskey', sesskey()); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); // Render Help Link. $usermenu .= $this->theme_essential_render_helplink(); $usermenu .= html_writer::end_tag('ul'); } else { $course = $this->page->course; $context = context_course::instance($course->id); // Output Profile link. $userurl = new moodle_url('#'); $userpic = parent::user_picture($USER, array('link' => false)); $caret = '<i class="fa fa-caret-right"></i>'; $userclass = array('class' => 'dropdown-toggle', 'data-toggle' => 'dropdown'); if (!empty($USER->alternatename)) { $usermenu .= html_writer::link($userurl, $userpic . $USER->alternatename . $caret, $userclass); } else { $usermenu .= html_writer::link($userurl, $userpic . $USER->firstname . $caret, $userclass); } // Start dropdown menu items. $usermenu .= html_writer::start_tag('ul', array('class' => 'dropdown-menu pull-right')); if (\core\session\manager::is_loggedinas()) { $realuser = \core\session\manager::get_realuser(); $branchlabel = '<em><i class="fa fa-key"></i>' . fullname($realuser, true) . get_string('loggedinas', 'theme_essential') . fullname($USER, true) . '</em>'; } else { $branchlabel = '<em><i class="fa fa-user"></i>' . fullname($USER, true) . '</em>'; } $branchurl = new moodle_url('/user/profile.php', array('id' => $USER->id)); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); if (is_mnet_remote_user($USER) && ($idprovider = $DB->get_record('mnet_host', array('id' => $USER->mnethostid)))) { $branchlabel = '<em><i class="fa fa-users"></i>' . get_string('loggedinfrom', 'theme_essential') . $idprovider->name . '</em>'; $branchurl = new moodle_url($idprovider->wwwroot); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } if (is_role_switched($course->id)) { // Has switched roles. $branchlabel = '<em><i class="fa fa-users"></i>' . get_string('switchrolereturn') . '</em>'; $branchurl = new moodle_url('/course/switchrole.php', array('id' => $course->id, 'sesskey' => sesskey(), 'switchrole' => 0, 'returnurl' => $this->page->url->out_as_local_url(false))); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } // Add preferences submenu. $usermenu .= $this->theme_essential_render_preferences($context); $usermenu .= html_writer::empty_tag('hr', array('class' => 'sep')); // Output Calendar link if user is allowed to edit own calendar entries. if (has_capability('moodle/calendar:manageownentries', $context)) { $branchlabel = '<em><i class="fa fa-calendar"></i>' . get_string('pluginname', 'block_calendar_month') . '</em>'; $branchurl = new moodle_url('/calendar/view.php'); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } // Check if messaging is enabled. if (!empty($CFG->messaging)) { $branchlabel = '<em><i class="fa fa-envelope"></i>' . get_string('pluginname', 'block_messages') . '</em>'; $branchurl = new moodle_url('/message/index.php'); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } // Check if user is allowed to manage files. if (has_capability('moodle/user:manageownfiles', $context)) { $branchlabel = '<em><i class="fa fa-file"></i>' . get_string('privatefiles', 'block_private_files') . '</em>'; $branchurl = new moodle_url('/user/files.php'); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } // Check if user is allowed to view discussions. if (has_capability('mod/forum:viewdiscussion', $context)) { $branchlabel = '<em><i class="fa fa-list-alt"></i>' . get_string('forumposts', 'mod_forum') . '</em>'; $branchurl = new moodle_url('/mod/forum/user.php', array('id' => $USER->id)); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); $branchlabel = '<em><i class="fa fa-list"></i>' . get_string('discussions', 'mod_forum') . '</em>'; $branchurl = new moodle_url('/mod/forum/user.php', array('id' => $USER->id, 'mode' => 'discussions')); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); $usermenu .= html_writer::empty_tag('hr', array('class' => 'sep')); } // Output user grade links course sensitive, workaround for frontpage, selecting first enrolled course. if ($course->id == SITEID) { $branchlabel = '<em><i class="fa fa-list-alt"></i>' . get_string('mygrades', 'theme_essential') . '</em>'; $branchurl = new moodle_url('/grade/report/overview/index.php', array('id' => $course->id, 'userid' => $USER->id)); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } else { if (has_capability('gradereport/overview:view', $context)) { $branchlabel = '<em><i class="fa fa-list-alt"></i>' . get_string('mygrades', 'theme_essential') . '</em>'; $branchurl = new moodle_url('/grade/report/overview/index.php', array('id' => $course->id, 'userid' => $USER->id)); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } if (has_capability('gradereport/user:view', $context)) { // In Course also output Course grade links. $branchlabel = '<em><i class="fa fa-list-alt"></i>' . get_string('coursegrades', 'theme_essential') . '</em>'; $branchurl = new moodle_url('/grade/report/user/index.php', array('id' => $course->id, 'userid' => $USER->id)); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } } // Check if badges are enabled. if (!empty($CFG->enablebadges) && has_capability('moodle/badges:manageownbadges', $context)) { $branchlabel = '<em><i class="fa fa-certificate"></i>' . get_string('badges') . '</em>'; $branchurl = new moodle_url('/badges/mybadges.php'); $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); } $usermenu .= html_writer::empty_tag('hr', array('class' => 'sep')); // Render direct logout link. $branchlabel = '<em><i class="fa fa-sign-out"></i>' . get_string('logout') . '</em>'; if (\core\session\manager::is_loggedinas()) { $branchurl = new moodle_url('/course/loginas.php', array('id' => $course->id, 'sesskey' => sesskey())); } else { $branchurl = new moodle_url('/login/logout.php', array('sesskey' => sesskey())); } $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel)); // Render Help Link. $usermenu .= $this->theme_essential_render_helplink(); $usermenu .= html_writer::end_tag('ul'); } } $usermenu .= html_writer::end_tag('li'); $usermenu .= html_writer::end_tag('ul'); return $usermenu; }
public function test_get_realuser() { $this->resetAfterTest(); $user1 = $this->getDataGenerator()->create_user(); $user2 = $this->getDataGenerator()->create_user(); $this->setUser($user1); $normal = \core\session\manager::get_realuser(); $this->assertSame($GLOBALS['USER'], $normal); \core\session\manager::loginas($user2->id, context_system::instance()); $real = \core\session\manager::get_realuser(); unset($real->password); unset($real->description); unset($real->sesskey); unset($user1->password); unset($user1->description); unset($user1->sesskey); $this->assertEquals($real, $user1); $this->assertSame($_SESSION['REALUSER'], $real); }
/** * The "fixy" overlay that drops down when the link in the top right corner is clicked. It will say either * "login" or "menu" (for signed in users). * */ public function fixed_menu() { global $CFG, $USER; $logout = get_string('logout'); $isguest = isguestuser(); $courseservice = course::service(); $output = ''; if (!isloggedin() || $isguest) { $login = get_string('login'); $cancel = get_string('cancel'); if (!empty($CFG->loginpasswordautocomplete)) { $autocomplete = 'autocomplete="off"'; } else { $autocomplete = ''; } if (empty($CFG->authloginviaemail)) { $username = get_string('username'); } else { $username = get_string('usernameemail'); } if (empty($CFG->loginhttps)) { $wwwroot = $CFG->wwwroot; } else { $wwwroot = str_replace("http://", "https://", $CFG->wwwroot); } $password = get_string('password'); $loginform = get_string('loginform', 'theme_snap'); $helpstr = ''; if (empty($CFG->forcelogin) || $isguest || !isloggedin() || !empty($CFG->registerauth) || is_enabled_auth('none') || !empty($CFG->auth_instructions)) { if ($isguest) { $helpstr = '<p class="text-center">' . get_string('loggedinasguest', 'theme_snap') . '</p>'; $helpstr .= '<p class="text-center">' . '<a class="btn btn-primary" href="' . s($CFG->wwwroot) . '/login/logout.php?sesskey=' . sesskey() . '">' . $logout . '</a></p>'; $helpstr .= '<p class="text-center">' . '<a href="' . s($wwwroot) . '/login/index.php">' . get_string('helpwithloginandguest', 'theme_snap') . '</a></p>'; } else { if (empty($CFG->forcelogin)) { $help = get_string('helpwithloginandguest', 'theme_snap'); } else { $help = get_string('helpwithlogin', 'theme_snap'); } $helpstr = "<p class='text-center'><a href='" . s($wwwroot) . "/login/index.php'>{$help}</a></p>"; } } if (local::current_url_path() != '/login/index.php') { $output .= $this->login_button(); $altlogins = $this->render_login_alternative_methods(new login_alternative_methods()); $output .= "<div class='fixy' id='snap-login' role='dialog' aria-label='{$loginform}' tabindex='-1'>\n <form action='{$wwwroot}/login/index.php' method='post'>\n <div class=fixy-inner>\n <div class=fixy-header>\n <a id='fixy-close' class='js-personal-menu-trigger pull-right snap-action-icon' href='#'>\n <i class='icon icon-close'></i><small>{$cancel}</small>\n </a>\n <h1>{$login}</h1>\n </div>\n <label for='username'>{$username}</label>\n <input autocapitalize='off' type='text' name='username' id='username'>\n <label for='password'>{$password}</label>\n <input type='password' name='password' id='password' {$autocomplete}>\n <br>\n <input type='submit' value='" . s($login) . "'>\n {$helpstr}\n {$altlogins}\n </div>\n </form></div>"; } } else { $courselist = ""; $userpicture = new user_picture($USER); $userpicture->link = false; $userpicture->alttext = false; $userpicture->size = 100; $picture = $this->render($userpicture); list($favorited, $notfavorited) = $courseservice->my_courses_split_by_favorites(); // Create courses array with favorites first. $mycourses = $favorited + $notfavorited; $courselist .= '<section id="fixy-my-courses"><div class="clearfix"><h2>' . get_string('courses') . '</h2>'; $courselist .= '<div id="fixy-visible-courses">'; // Default text when no courses. if (!$mycourses) { $courselist .= "<p>" . get_string('coursefixydefaulttext', 'theme_snap') . "</p>"; } // Visible / hidden course vars. $visiblecoursecount = 0; // How many courses are in the hidden section (hidden and not favorited). $hiddencoursecount = 0; $hiddencourselist = ''; // How many courses are actually hidden. $actualhiddencount = 0; foreach ($mycourses as $course) { $ccard = new course_card($course->id); $coursecard = $this->render($ccard); // If course is not visible. if (!$course->visible) { $actualhiddencount++; // Only add to list of hidden courses if not favorited. if (!isset($favorited[$course->id])) { $hiddencoursecount++; $hiddencourselist .= $coursecard; } else { // OK, this is hidden but it's favorited, so technically visible. $visiblecoursecount++; $courselist .= $coursecard; } } else { $visiblecoursecount++; $courselist .= $coursecard; } } $courselist .= '</div>'; $courselist .= $this->browse_all_courses_button(); $courselist .= '</div>'; if ($actualhiddencount && $visiblecoursecount) { // Output hidden courses toggle when there are visible courses. $togglevisstate = !empty($hiddencourselist) ? ' state-visible' : ''; $hiddencourses = '<div class="clearfix"><h2 class="header-hidden-courses' . $togglevisstate . '"><a id="js-toggle-hidden-courses" href="#">' . get_string('hiddencoursestoggle', 'theme_snap', $hiddencoursecount) . '</a></h2>'; $hiddencourses .= '<div id="fixy-hidden-courses" class="clearfix" tabindex="-1">' . $hiddencourselist . '</div>'; $hiddencourses .= '</div>'; $courselist .= $hiddencourses; } else { if (!$visiblecoursecount && $hiddencoursecount) { $hiddencourses = '<div id="fixy-hidden-courses" class="clearfix state-visible">' . $hiddencourselist . '</div>'; $courselist .= $hiddencourses; } } $courselist .= '</section>'; $menu = get_string('menu', 'theme_snap'); $badge = $this->render_badge_count(); $linkcontent = $menu . $picture . $badge; $attributes = array('aria-haspopup' => 'true', 'class' => 'js-personal-menu-trigger snap-my-courses-menu', 'id' => 'fixy-trigger', 'aria-controls' => 'primary-nav'); $output .= html_writer::link('#', $linkcontent, $attributes); $close = get_string('close', 'theme_snap'); $viewyourprofile = get_string('viewyourprofile', 'theme_snap'); $realuserinfo = ''; if (\core\session\manager::is_loggedinas()) { $realuser = \core\session\manager::get_realuser(); $via = get_string('via', 'theme_snap'); $fullname = fullname($realuser, true); $realuserinfo = html_writer::span($via . ' ' . html_writer::span($fullname, 'real-user-name'), 'real-user-info'); } $output .= '<nav id="primary-nav" class="fixy toggle-details" tabindex="-1"> <div class="fixy-inner"> <div class="fixy-header"> <a id="fixy-close" class="js-personal-menu-trigger pull-right snap-action-icon" href="#"> <i class="icon icon-close"></i><small>' . $close . '</small> </a> <div id="fixy-user">' . $picture . ' <div id="fixy-user-details"> <a title="' . s($viewyourprofile) . '" href="' . s($CFG->wwwroot) . '/user/profile.php" >' . '<span class="h1" role="heading" aria-level="1">' . format_string(fullname($USER)) . '</span> </a> ' . $realuserinfo . ' <a id="fixy-logout" href="' . s($CFG->wwwroot) . '/login/logout.php?sesskey=' . sesskey() . '">' . $logout . '</a> </div> </div> </div> <div id="fixy-content">' . $courselist . $this->render_callstoaction() . ' </div><!-- end fixy-content --> </div><!-- end fixy-inner --> </nav><!-- end primary nav -->'; } return $output; }
/** Function to build the user's menu for the top navigation bar @param bool $withlinks - not sure if we want this @return string HTML fragment **/ public function user_menu($user = NULL, $withlinks = NULL) { global $USER, $CFG, $DB, $SESSION, $PAGE; // if we are during install return an empty string if (during_initial_install()) { return ''; } $course = $this->page->course; // at certain times - i.e. installation course id will be empty or null if (empty($course->id)) { return ''; } // this is the login page so return nothing $loginurl = get_login_url(); if ((string) $this->page->url === $loginurl) { return ''; } // user not logged in so return login link if (!isloggedin()) { return "<li><a href=\"{$loginurl}\">" . get_string('login') . '</a></li>'; } // begin building the user's display name $user_string = ""; // check if the user is logged in as someone else #if (session_is_loggedinas()) { # $realuser = session_get_realuser(); if (\core\session\manager::is_loggedinas()) { $realuser = \core\session\manager::get_realuser(); $user_string = fullname($realuser, true) . " pretending to be "; } $user_string .= fullname($USER, true); $role_switched = false; if (is_role_switched($course->id)) { // Has switched roles $context = context_course::instance($course->id); $role_switched = true; $rolename = ''; if ($role = $DB->get_record('role', array('id' => $USER->access['rsw'][$context->path]))) { $rolename = ': ' . role_get_name($role, $context); } $user_string .= $rolename; } $user_picture = new user_picture($USER); $userimgsrc = $user_picture->get_url($PAGE); $user_menu = array("<li class='dropdown'>"); $user_menu[] = "<a class='dropdown-toggle' data-toggle='dropdown' href='#' style='min-height: 50px'>"; $user_menu[] = "<img class='nav-avatar' src='" . $userimgsrc . "'>"; $user_menu[] = "<span class='hidden-xs'>" . $user_string . "</span>"; $user_menu[] = "</a>"; $user_menu[] = "<ul class='dropdown-menu dropdown-menu-right'>"; if ($role_switched) { $url = new moodle_url('/course/switchrole.php', array('id' => $course->id, 'sesskey' => sesskey(), 'switchrole' => 0, 'returnurl' => $this->page->url->out_as_local_url(false))); $user_menu[] = "<li><a href='" . $url . "'>" . get_string('switchrolereturn') . "</a></li>"; } $user_menu[] = "<li><a href='" . $CFG->wwwroot . "/user/profile.php?id=" . $USER->id . "'>My Profile</a></li>"; $user_menu[] = "<li class='menu-item-resources'><a href='/'>My Modules</a></li>"; $user_menu[] = "<li id='student-email-link' style='display: none'><a href='http://studentmail.falmouth.ac.uk/'>My Email</a></li>"; $user_menu[] = "<li id='staff-email-link' style='display: none'><a href='http://mailspace.falmouth.ac.uk/'>My Email</a></li>"; $user_menu[] = "<li><a href='http://mytimetable.falmouth.ac.uk/'>My Timetable</a></li>"; $user_menu[] = "<li class='divider'></li>"; $user_menu[] = "<li><a href='" . $CFG->wwwroot . "/login/logout.php?sesskey=" . sesskey() . "'>" . get_string('logout') . '</a></li>'; $user_menu[] = "</ul></li>"; return implode("", $user_menu); }
/** * Course section deletion, using an adhoc task for deletion of the modules it contains. * 1. Schedule all modules within the section for adhoc removal. * 2. Move all modules to course section 0. * 3. Delete the resulting empty section. * * @param \stdClass $section the section to schedule for deletion. * @param bool $forcedeleteifnotempty whether to force section deletion if it contains modules. * @return bool true if the section was scheduled for deletion, false otherwise. */ function course_delete_section_async($section, $forcedeleteifnotempty = true) { global $DB, $USER; // Objects only, and only valid ones. if (!is_object($section) || empty($section->id)) { return false; } // Does the object currently exist in the DB for removal (check for stale objects). $section = $DB->get_record('course_sections', array('id' => $section->id)); if (!$section || !$section->section) { // No section exists, or the section is 0. Can't proceed. return false; } // Check whether the section can be removed. if (!$forcedeleteifnotempty && (!empty($section->sequence) || !empty($section->summary))) { return false; } $format = course_get_format($section->course); $sectionname = $format->get_section_name($section); // Flag those modules having no existing deletion flag. Some modules may have been scheduled for deletion manually, and we don't // want to create additional adhoc deletion tasks for these. Moving them to section 0 will suffice. $affectedmods = $DB->get_records_select('course_modules', 'course = ? AND section = ? AND deletioninprogress <> ?', [$section->course, $section->id, 1], '', 'id'); $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $section->course, 'section' => $section->id]); // Move all modules to section 0. $modules = $DB->get_records('course_modules', ['section' => $section->id], ''); $sectionzero = $DB->get_record('course_sections', ['course' => $section->course, 'section' => '0']); foreach ($modules as $mod) { moveto_module($mod, $sectionzero); } // Create and queue an adhoc task for the deletion of the modules. $removaltask = new \core_course\task\course_delete_modules(); $data = array('cms' => $affectedmods, 'userid' => $USER->id, 'realuserid' => \core\session\manager::get_realuser()->id); $removaltask->set_custom_data($data); \core\task\manager::queue_adhoc_task($removaltask); // Delete the now empty section, passing in only the section number, which forces the function to fetch a new object. // The refresh is needed because the section->sequence is now stale. $result = $format->delete_section($section->section, $forcedeleteifnotempty); // Trigger an event for course section deletion. if ($result) { $context = \context_course::instance($section->course); $event = \core\event\course_section_deleted::create(array('objectid' => $section->id, 'courseid' => $section->course, 'context' => $context, 'other' => array('sectionnum' => $section->section, 'sectionname' => $sectionname))); $event->add_record_snapshot('course_sections', $section); $event->trigger(); } rebuild_course_cache($section->course, true); return $result; }
/** * Print fixy (login or menu for signed in users) * */ public function print_fixed_menu() { global $CFG, $USER, $PAGE, $DB; $logout = get_string('logout'); $isguest = isguestuser(); if (!isloggedin() || $isguest) { $login = get_string('login'); $cancel = get_string('cancel'); $username = get_string('username'); $password = get_string('password'); $loginform = get_string('loginform', 'theme_snap'); $helpstr = ''; if (empty($CFG->forcelogin) || $isguest || !isloggedin() || !empty($CFG->registerauth) || is_enabled_auth('none') || !empty($CFG->auth_instructions)) { if ($isguest) { $helpstr = '<p class="text-center">' . get_string('loggedinasguest', 'theme_snap') . '</p>'; $helpstr .= '<p class="text-center">' . '<a class="btn btn-primary" href="' . s($CFG->wwwroot) . '/login/logout.php?sesskey=' . sesskey() . '">' . $logout . '</a></p>'; $helpstr .= '<p class="text-center">' . '<a href="' . s($CFG->wwwroot) . '/login/index.php">' . get_string('helpwithloginandguest', 'theme_snap') . '</a></p>'; } else { if (empty($CFG->forcelogin)) { $help = get_string('helpwithloginandguest', 'theme_snap'); } else { $help = get_string('helpwithlogin', 'theme_snap'); } $helpstr = "<p class='text-center'><a href='" . s($CFG->wwwroot) . "/login/index.php'>{$help}</a></p>"; } } echo $this->print_login_button(); echo "<form class=fixy action='{$CFG->wwwroot}/login/' method='post' id='login'>\n <a id='fixy-close' class='pull-right snap-action-icon' href='#'>\n <i class='icon icon-office-52'></i><small>{$cancel}</small>\n </a>\n <div class=fixy-inner>\n <legend>{$loginform}</legend>\n <label for='username'>{$username}</label>\n <input autocapitalize='off' type='text' name='username' id='username' placeholder='" . s($username) . "'>\n <label for='password'>{$password}</label>\n <input type='password' name='password' id='password' placeholder='" . s($password) . "'>\n <br>\n <input type='submit' id='loginbtn' value='" . s($login) . "'>\n {$helpstr}\n </div>\n </form>"; } else { $courselist = ""; $userpicture = new user_picture($USER); $userpicture->link = false; $userpicture->alttext = false; $userpicture->size = 100; $picture = $this->render($userpicture); $mycourses = enrol_get_my_courses(null, 'visible DESC, fullname ASC, id DESC'); $courselist .= "<section id='fixy-my-courses'><div class='clearfix'><h2>" . get_string('courses') . "</h2>"; foreach ($mycourses as $c) { $pubstatus = ""; if (!$c->visible) { $notpublished = get_string('notpublished', 'theme_snap'); $pubstatus = "<small class='published-status'>" . $notpublished . "</small>"; } $bgcolor = local::get_course_color($c->id); $courseimagecss = "background-color: #{$bgcolor};"; $bgimage = local::course_coverimage_url($c->id); if (!empty($bgimage)) { $courseimagecss .= "background-image: url({$bgimage});"; } $dynamicinfo = '<div data-courseid="' . $c->id . '" class=dynamicinfo></div>'; $teachers = ''; $courseteachers = ''; $clist = new course_in_list($c); $teachers = $clist->get_course_contacts(); if (!empty($teachers)) { $courseteachers = "<div class='sr-only'>" . get_string('coursecontacts', 'theme_snap') . "</div>"; // Get all teacher user records in one go. $teacherids = array(); foreach ($teachers as $teacher) { $teacherids[] = $teacher['user']->id; } $teacherusers = $DB->get_records_list('user', 'id', $teacherids); foreach ($teachers as $teacher) { if (!isset($teacherusers[$teacher['user']->id])) { continue; } $teacheruser = $teacherusers[$teacher['user']->id]; $userpicture = new user_picture($teacheruser); $userpicture->link = false; $userpicture->size = 100; $teacherpicture = $this->render($userpicture); $courseteachers .= $teacherpicture; } } $clink = '<div data-href="' . $CFG->wwwroot . '/course/view.php?id=' . $c->id . '" class="courseinfo" style="' . $courseimagecss . '"> <div class="courseinfo-body"><h3><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $c->id . '">' . format_string($c->fullname) . '</a></h3>' . $dynamicinfo . $courseteachers . $pubstatus . '</div></div>'; $courselist .= $clink; } $courselist .= "</div>"; $courselist .= '<div class="row fixy-browse-search-courses"><br>'; if (has_capability('moodle/site:config', context_system::instance())) { $courserenderer = $PAGE->get_renderer('core', 'course'); $courselist .= '<div class="col-md-6">'; $courselist .= $courserenderer->course_search_form(null, 'fixy'); $courselist .= '</div>'; } $courselist .= '<div class="col-md-6">'; $courselist .= $this->print_view_all_courses(); $courselist .= '</div>'; $courselist .= '</div></section>'; // Close row. $menu = get_string('menu', 'theme_snap'); echo '<a href="#primary-nav" aria-haspopup="true" class="fixy-trigger" id="js-personal-menu-trigger" ' . 'aria-controls="primary-nav" title="' . get_string('sitenavigation', 'theme_snap') . '" data-toggle="tooltip" data-placement="bottom">' . $menu . $picture . $this->render_badge_count() . '</a>'; $close = get_string('close', 'theme_snap'); $viewyourprofile = get_string('viewyourprofile', 'theme_snap'); $realuserinfo = ''; if (\core\session\manager::is_loggedinas()) { $realuser = \core\session\manager::get_realuser(); $via = get_string('via', 'theme_snap'); $fullname = fullname($realuser, true); $realuserinfo = html_writer::span($via . ' ' . html_writer::span($fullname, 'real-user-name'), 'real-user-info'); } echo '<nav id="primary-nav" class="fixy toggle-details" tabindex="0"> <a id="fixy-close" class="pull-right snap-action-icon" href="#"> <i class="icon icon-office-52"></i><small>' . $close . '</small> </a> <div class=fixy-inner> <h1 id="fixy-profile-link"> <a title="' . s($viewyourprofile) . '" href="' . s($CFG->wwwroot) . '/user/profile.php" >' . $picture . '<span id="fixy-username">' . format_string(fullname($USER)) . '</span> </a> </h1>' . $realuserinfo . $courselist . $this->render_callstoaction() . ' <div class="fixy-logout-footer clearfix text-center"> <a class="btn btn-default logout" href="' . s($CFG->wwwroot) . '/login/logout.php?sesskey=' . sesskey() . '">' . $logout . '</a> </div> </div><!-- end fixy-inner --> </nav><!-- end primary nav -->'; } }
/** * this function used checked logged in user having costcenter privileges or not * * @package custom * @method require_costcenter_login * @param int $courseodir (holds the course id) * @return int */ function require_costcenter_login($courseorid) { global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT, $COSTCENTER; 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); } $coursecontext = context_course::instance($course->id, MUST_EXIST); if ($COSTCENTER) { if (!in_array($course->id, $COSTCENTER->courses)) throw new coding_exception('course is not belongs to your costcenter, Dont have permission to access'); else if (\core\session\manager::is_loggedinas()) { // Make sure the REAL person can access this course first. $realuser = \core\session\manager::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 . '/'); } } // else if(! in_array($course->id,$COSTCENTER->enroledcourses)){ // throw new coding_exception('Dont have permission to access'); // } else { return true; } } } return true; }
/** * 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, $asmenu = false) { 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 (\core\session\manager::is_loggedinas()) { $realuser = \core\session\manager::get_realuser(); $fullname = fullname($realuser, true); if ($withlinks) { $loginastitle = get_string('loginas'); $realuserinfo = " <small>[</small><a href=\"{$CFG->wwwroot}/course/loginas.php?id={$course->id}&sesskey=" . sesskey() . "\""; $realuserinfo .= "title =\"" . $loginastitle . "\">{$fullname}</a> <small>]</small> "; } else { $realuserinfo = " <small>[</small> {$fullname} <small>]</small> "; } } else { $realuserinfo = ''; } $loginurl = get_login_url(); $loggedinas = ''; if (empty($course->id)) { // The $course->id is not defined during installation. return ''; } else { if (isloggedin()) { $context = context_course::instance($course->id); $fullname = fullname($USER, true); $linktitle = get_string('viewprofile'); $userpicture = ''; if (!empty($USER->id)) { $userpicture = $this->user_picture($USER, array('size' => 35, 'link' => false, 'class' => 'nav_userpicture')); } $username = "******"{$CFG->wwwroot}/user/profile.php?id={$USER->id}\" " . "title=\"{$linktitle}\" class='userloginprofile'>{$userpicture}{$fullname}</a>"; if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id' => $USER->mnethostid))) { $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>"; } $loggedinas = $username; if (isguestuser()) { $loggedinas = $realuserinfo . get_string('loggedinasguest'); if (!$loginpage) { $loggedinas .= " <small>(</small> <a href=\"{$loginurl}\">" . get_string('login') . '</a> <small>)</small>'; } } 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 = '<span class="role-name">: ' . role_get_name($role, $context) . '</span>'; } $loggedinas .= $rolename; $url = new moodle_url('/course/switchrole.php', array('id' => $course->id, 'sesskey' => sesskey(), 'switchrole' => 0, 'returnurl' => $this->page->url->out_as_local_url(false))); $loggedinas .= html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)); } else { $loggedinas .= " <small>(</small> <a href=\"{$CFG->wwwroot}/login/logout.php?sesskey=" . sesskey() . "\">" . get_string('logout') . '</a> <small>)</small>'; } } } else { if (!$loginpage) { $loggedinas = " <small>(</small> <a href=\"{$loginurl}\">" . get_string('login') . '</a> <small>)</small>'; } } } $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; }