コード例 #1
0
 /**
  * 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;
     }
     $settings = $this->load_user_settings($this->page->course->id);
     if (isloggedin() && !isguestuser() && (!property_exists($SESSION, 'load_navigation_admin') || $SESSION->load_navigation_admin)) {
         $admin = $this->load_administration_settings();
         $SESSION->load_navigation_admin = $admin->has_children();
     } else {
         $admin = false;
     }
     if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
         $admin->force_open();
     } else {
         if ($context->contextlevel == CONTEXT_USER && $settings) {
             $settings->force_open();
         }
     }
     // Check if the user is currently logged in as another user
     if (session_is_loggedinas()) {
         // Get the actual user, we need this so we can display an informative return link
         $realuser = session_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) {
             $node->remove();
         }
     }
     $this->initialised = true;
 }
コード例 #2
0
 /**
  * Return the standard string that says whether you are logged in (and switched
  * roles/logged in as another user).
  *
  * @return string HTML fragment.
  */
 public function login_info()
 {
     global $USER, $CFG, $DB, $SESSION;
     if (during_initial_install()) {
         return '';
     }
     $loginpage = (string) $this->page->url === get_login_url();
     $course = $this->page->course;
     if (session_is_loggedinas()) {
         $realuser = session_get_realuser();
         $fullname = fullname($realuser, true);
         $realuserinfo = " [<a href=\"{$CFG->wwwroot}/course/loginas.php?id={$course->id}&amp;sesskey=" . sesskey() . "\">{$fullname}</a>] ";
     } else {
         $realuserinfo = '';
     }
     $loginurl = get_login_url();
     if (empty($course->id)) {
         // $course->id is not defined during installation
         return '';
     } else {
         if (isloggedin()) {
             $context = get_context_instance(CONTEXT_COURSE, $course->id);
             $fullname = fullname($USER, true);
             // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
             $username = "******"{$CFG->wwwroot}/user/profile.php?id={$USER->id}\">{$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>";
             }
             if (isguestuser()) {
                 $loggedinas = $realuserinfo . get_string('loggedinasguest');
                 if (!$loginpage) {
                     $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 . " (<a href=\"{$CFG->wwwroot}/course/view.php?id={$course->id}&amp;switchrole=0&amp;sesskey=" . sesskey() . "\">" . get_string('switchrolereturn') . '</a>)';
                 } else {
                     $loggedinas = $realuserinfo . get_string('loggedinas', 'moodle', $username) . ' ' . " (<a href=\"{$CFG->wwwroot}/login/logout.php?sesskey=" . sesskey() . "\">" . get_string('logout') . '</a>)';
                 }
             }
         } else {
             $loggedinas = get_string('loggedinnot', 'moodle');
             if (!$loginpage) {
                 $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 .= '&nbsp;<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', get_context_instance(CONTEXT_SYSTEM))) {
                         $loggedinas .= ' (<a href="' . $CFG->wwwroot . '/report/log/index.php' . '?chooselog=1&amp;id=1&amp;modid=site_errors">' . get_string('logs') . '</a>)';
                     }
                     $loggedinas .= '</div>';
                 }
             }
         }
     }
     return $loggedinas;
 }
コード例 #3
0
ファイル: setup.php プロジェクト: hatone/moodle
        }
    }
}
// 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;
            break;
コード例 #4
0
ファイル: moodlelib.php プロジェクト: hitphp/moodle
/**
 * 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 . '&amp;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);
}
コード例 #5
0
ファイル: weblib.php プロジェクト: nicolasconnault/moodle2.0
/**
 * Returns text to be displayed to the user which reflects their login status
 *
 * @uses $CFG
 * @uses $USER
 * @param course $course {@link $COURSE} object containing course information
 * @param user $user {@link $USER} object containing user information
 * @return string
 */
function user_login_string($course = NULL, $user = NULL)
{
    global $USER, $CFG, $SITE, $DB;
    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}&amp;return=1&amp;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}&amp;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}&amp;switchrole=0&amp;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>)';
        }
    }
    return '<div class="logininfo">' . $loggedinas . '</div>';
}
コード例 #6
0
/**
 * 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 . '&amp;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);
}
コード例 #7
0
 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);
 }
コード例 #8
0
ファイル: moodlelib.php プロジェクト: ajv/Offline-Caching
/**
 * 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 . '&amp;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;
    }
}
コード例 #9
0
ファイル: navigationlib.php プロジェクト: vuchannguyen/web
 /**
  * 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;
     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 = $DB->get_record_sql('SELECT ctx.* FROM {block_instances} bi LEFT JOIN {context} ctx ON ctx.id=bi.parentcontextid WHERE bi.id=?', array($context->instanceid));
     }
     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 != SITEID) {
                 $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 != SITEID) {
                 $this->load_course_settings();
             }
             break;
     }
     $settings = $this->load_user_settings($this->page->course->id);
     $admin = $this->load_administration_settings();
     if ($context->contextlevel == CONTEXT_SYSTEM && $admin) {
         $admin->force_open();
     } else {
         if ($context->contextlevel == CONTEXT_USER && $settings) {
             $settings->force_open();
         }
     }
     // Check if the user is currently logged in as another user
     if (session_is_loggedinas()) {
         // Get the actual user, we need this so we can display an informative return link
         $realuser = session_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', ''));
     }
     // Make sure the first child doesnt have proceed with hr set to true
     foreach ($this->children as $key => $node) {
         if ($node->nodetype != self::NODETYPE_BRANCH || $node->children->count() === 0) {
             $node->remove();
         }
     }
     $this->initialised = true;
 }
コード例 #10
0
 /**
  * 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 (session_is_loggedinas()) {
         $realuser = session_get_realuser();
         $fullname = fullname($realuser, true);
         if ($withlinks) {
             $loginastitle = get_string('loginas');
             $realuserinfo = " [<a href=\"{$CFG->wwwroot}/course/loginas.php?id={$course->id}&amp;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) {
                         $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()) {
                 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
                     $loggedinas .= '&nbsp;<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&amp;id=1&amp;modid=site_errors">' . get_string('logs') . '</a>)';
                     }
                     $loggedinas .= '</div>';
                 }
             }
         }
     }
     return $loggedinas;
 }
コード例 #11
0
ファイル: renderers.php プロジェクト: anilch/Personel
    public function login_info($withlinks = null) {
        global $USER, $CFG, $DB, $SESSION,$OUTPUT;

        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 = session_get_realuser();
            $fullname = fullname($realuser, true);
            if ($withlinks) {
                $loginastitle = get_string('loginas');
                $realuserinfo = " <a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;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/view.php?id=$USER->id&course=$course->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 = get_string('loggedinasguest','theme_colms');
                $loggout = "<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\" id='logout'>".get_string('logout').'</a>';
                if (!$loginpage && $withlinks) {
                    $loggedinas .= " (<a href=\"$loginurl\" style=\"vertical-align:middle;margin:0;\">".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);
					$rolename = '';
                }
                $loggedinas = get_string('loggedinas', 'theme_colms', $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', 'theme_colms', $username);
                if ($withlinks) {
                    $loggout = "<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\" id='logout'>".get_string('logout').'</a>';
                }
            }
        } else {
            $loggedinas = get_string('loggedinnot', 'theme_colms');
            if (!$loginpage && $withlinks) {
                $loggedinas = "<a href='javascript:void(0)' id='login_button'>".get_string('login').'</a>';
            }
        }
        // if(isloggedin() || isguestuser()){
        // $loggedinas = '<div class="logininfo"><div id="logoutlink">'. $loggedinas .'<a href="javascript:void(0)" id="pop_logout"><img src=' . $OUTPUT->pix_url("down_arrow","theme") .'  /></a></div>', array("class"=>"userimg")) . ''.$loggout.'</div>';
        // }
		if(isloggedin() || isguestuser()){
		$loggout = "<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\" class='box_log'>".get_string('logout').'</a>';
        $loggedinas = '<div class="logininfo"><div class="logoutlink">'. $loggedinas .'</div><div class="box_log">'.$loggout.'</div></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 .= '&nbsp;<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&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
                        }
                        $loggedinas .= '</div>';
                    }
                }
            }
        }
        
        return $loggedinas;
    }
コード例 #12
0
ファイル: weblib.php プロジェクト: ajv/Offline-Caching
/**
 * 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}&amp;return=1&amp;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}&amp;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}&amp;switchrole=0&amp;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 .= '&nbsp;<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&amp;id=1&amp;modid=site_errors">' . get_string('logs') . '</a>)';
                    }
                    $loggedinas .= '</div>';
                }
            }
        }
    }
    return $loggedinas;
}
コード例 #13
0
 /**
  * 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 .= '&nbsp;<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&amp;id=1&amp;modid=site_errors">' . get_string('logs') . '</a>)';
                     }
                     $loggedinas .= '</div>';
                 }
             }
         }
     }
     return $loggedinas;
 }
コード例 #14
0
 /**
  * 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 = session_get_realuser();
         $fullname = fullname($realuser, true);
         if ($withlinks) {
             $realuserinfo = " [<a href=\"{$CFG->wwwroot}/course/loginas.php?id={$course->id}&amp;sesskey=" . sesskey() . "\">{$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) {
                 $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 class="btn btn-small btn-default" href="' . $loginurl . '"><i class="fa fa-sign-in"></i> ' . 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&amp;switchrole=0&amp;sesskey=' . sesskey() . '">' . get_string('switchrolereturn') . '</a>)';
                     }
                 } else {
                     $loggedinas = $realuserinfo . get_string('loggedinas', 'moodle', $username);
                     if ($withlinks) {
                         $loggedinas .= '&nbsp;&nbsp;<a class="btn btn-small" href="' . $CFG->wwwroot . '/login/logout.php?sesskey=' . sesskey() . '"><i class="fa fa-sign-out"></i> ' . get_string('logout') . '</a>';
                     }
                 }
             }
         } else {
             $loggedinas = get_string('loggedinnot', 'moodle');
             if (!$loginpage && $withlinks) {
                 $loggedinas .= ' <a class="btn btn-small btn-default" href="' . $loginurl . '"><i class="fa fa-sign-in"></i> ' . 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;
 }