Exemplo n.º 1
0
 function get_content()
 {
     global $USER, $CFG, $SESSION;
     $wwwroot = '';
     $signup = '';
     if ($this->content !== NULL) {
         return $this->content;
     }
     if (empty($CFG->loginhttps)) {
         $wwwroot = $CFG->wwwroot;
     } else {
         // This actually is not so secure ;-), 'cause we're
         // in unencrypted connection...
         $wwwroot = str_replace("http://", "https://", $CFG->wwwroot);
     }
     if (!empty($CFG->registerauth)) {
         $authplugin = get_auth_plugin($CFG->registerauth);
         if ($authplugin->can_signup()) {
             $signup = $wwwroot . '/login/signup.php';
         }
     }
     // TODO: now that we have multiauth it is hard to find out if there is a way to change password
     $forgot = $wwwroot . '/login/forgot_password.php';
     if (!empty($CFG->loginpasswordautocomplete)) {
         $autocomplete = 'autocomplete="off"';
     } else {
         $autocomplete = '';
     }
     $username = get_moodle_cookie();
     $this->content = new stdClass();
     $this->content->footer = '';
     $this->content->text = '';
     if (!isloggedin() or isguestuser()) {
         // Show the block
         if (empty($CFG->authloginviaemail)) {
             $strusername = get_string('username');
         } else {
             $strusername = get_string('usernameemail');
         }
         $this->content->text .= "\n" . '<form class="loginform" id="login" method="post" action="' . get_login_url() . '" ' . $autocomplete . '>';
         $this->content->text .= '<div class="c1 fld username"><label for="login_username">' . $strusername . '</label>';
         $this->content->text .= '<input type="text" name="username" id="login_username" value="' . s($username) . '" /></div>';
         $this->content->text .= '<div class="c1 fld password"><label for="login_password">' . get_string('password') . '</label>';
         $this->content->text .= '<input type="password" name="password" id="login_password" value="" ' . $autocomplete . ' /></div>';
         if (isset($CFG->rememberusername) and $CFG->rememberusername == 2) {
             $checked = $username ? 'checked="checked"' : '';
             $this->content->text .= '<div class="c1 rememberusername"><input type="checkbox" name="rememberusername" id="rememberusername" value="1" ' . $checked . '/>';
             $this->content->text .= ' <label for="rememberusername">' . get_string('rememberusername', 'admin') . '</label></div>';
         }
         $this->content->text .= '<div class="c1 btn"><input type="submit" value="' . get_string('login') . '" /></div>';
         $this->content->text .= "</form>\n";
         if (!empty($signup)) {
             $this->content->footer .= '<div><a href="' . $signup . '">' . get_string('startsignup') . '</a></div>';
         }
         if (!empty($forgot)) {
             $this->content->footer .= '<div><a href="' . $forgot . '">' . get_string('forgotaccount') . '</a></div>';
         }
     }
     return $this->content;
 }
Exemplo n.º 2
0
 function execute($requests)
 {
     $url = get_login_url();
     if ($requests['login_params']) {
         if (strrpos($url, '?') !== false) {
             $url .= '&';
         } else {
             $url .= '?';
         }
         $url .= 'login_params=' . urlencode($requests['login_params']);
     }
     // リダイレクト
     header('Refresh: 3; URL=' . $url);
     //---- inc_ テンプレート用 変数 ----//
     $this->set('inc_page_header', fetch_inc_page_header('public'));
     $msg = '';
     switch ($requests['msg_code']) {
         case 'login_failed':
             $msg = 'ログインに失敗しました。再度、ログイン操作を行ってください。';
             break;
         case 'logout':
             $msg = 'ログアウトしました。';
             break;
         case 'password_reset_timeout':
             $msg = 'パスワード再設定の有効期限が過ぎています。';
             break;
         case 'change_mailaddress':
             $msg = 'メールアドレスが変更されました。';
             break;
         case 'change_password':
             $msg = 'パスワードを変更しました。新しいパスワードで再ログインしてください。';
             break;
         case 'taikai':
             $msg = '退会完了しました。ご利用ありがとうございました。';
             break;
         case 'invalid_url':
             $msg = 'このURLは既に無効になっています。';
             break;
         case 'regist_mail':
             $msg = 'メールアドレスを登録しました。';
             break;
         case 'login_rejected':
             $msg = 'ログインできませんでした。';
             break;
     }
     $this->set('msg', $msg);
     $this->set('login_url', $url);
     return 'success';
 }
Exemplo n.º 3
0
 function execute($requests)
 {
     //<PCKTAI
     if (OPENPNE_AUTH_MODE == 'slavepne' || !(OPENPNE_REGIST_FROM & OPENPNE_REGIST_FROM_PC)) {
         client_redirect_login();
     }
     //>
     //---- inc_ テンプレート用 変数 ----//
     $this->set('inc_page_header', fetch_inc_page_header('regist'));
     //アフィリエイトタグ用変数
     $aftag = str_replace(array('({$ID})', '({$DATETIME})'), array($requests['c_member_id'], date("YmdHis")), AFFILIATE_TAG);
     $this->set('aftag', $aftag);
     $this->set('login_url', get_login_url());
     return 'success';
 }
 protected function do_save($action)
 {
     global $user;
     if (!$user->is_logged_in()) {
         if (VISIBILITY == 'private') {
             header('Location: ' . get_login_url($action->page));
         } else {
             header('Location: ' . get_base_url($action->page));
         }
         exit;
     }
     $this->file = new File($this->format_page_name($action->page, true));
     if ($_POST['updated'] == $this->file->time) {
         $this->file->save($_POST['text']);
     } else {
         header('Location: ' . $this->get_base_url(str_replace(DOC, '', rtrim($action->page, '/')) . '/edit/'));
         exit;
     }
     header('Location: ' . $this->get_base_url(str_replace(DOC, '', $action->page)));
     exit;
 }
Exemplo n.º 5
0
/**
 * Default exception handler, uncaught exceptions are equivalent to error() in 1.9 and earlier
 *
 * @param Exception $ex
 * @return void -does not return. Terminates execution!
 */
function default_exception_handler($ex)
{
    global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION, $PAGE;
    // detect active db transactions, rollback and log as error
    abort_all_db_transactions();
    if ($ex instanceof required_capability_exception && !CLI_SCRIPT && !AJAX_SCRIPT && !empty($CFG->autologinguests) && !empty($USER->autologinguest)) {
        $SESSION->wantsurl = qualified_me();
        redirect(get_login_url());
    }
    $info = get_exception_info($ex);
    if (debugging('', DEBUG_MINIMAL)) {
        $logerrmsg = "Default exception handler: " . $info->message . ' Debug: ' . $info->debuginfo . "\n" . format_backtrace($info->backtrace, true);
        error_log($logerrmsg);
    }
    if (is_early_init($info->backtrace)) {
        echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
    } else {
        try {
            if ($DB) {
                // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
                $DB->set_debug(0);
            }
            echo $OUTPUT->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
        } catch (Exception $out_ex) {
            // default exception handler MUST not throw any exceptions!!
            // the problem here is we do not know if page already started or not, we only know that somebody messed up in outputlib or theme
            // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
            if (CLI_SCRIPT or AJAX_SCRIPT) {
                // just ignore the error and send something back using the safest method
                echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
            } else {
                echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
                $outinfo = get_exception_info($out_ex);
                echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
            }
        }
    }
    exit(1);
    // General error code
}
Exemplo n.º 6
0
 /**
  * Outputs an error message for any guests accessing the quiz
  *
  * @param int $course The course ID
  * @param array $quiz Array contingin quiz data
  * @param int $cm Course Module ID
  * @param int $context The page contect ID
  * @param array $messages Array containing any messages
  */
 public function view_page_guest($course, $quiz, $cm, $context, $messages) {
     $output = '';
     $output .= $this->view_information($quiz, $cm, $context, $messages);
     $guestno = html_writer::tag('p', get_string('guestsno', 'quiz'));
     $liketologin = html_writer::tag('p', get_string('liketologin'));
     $output .= $this->confirm($guestno."\n\n".$liketologin."\n", get_login_url(),
             get_referer(false));
     return $output;
 }
 /**
  * Return the standard string that says whether you are logged in (and switched
  * roles/logged in as another user).
  * @param bool $withlinks if false, then don't include any links in the HTML produced.
  * If not set, the default is the nologinlinks option from the theme config.php file,
  * and if that is not set, then links are included.
  * @return string HTML fragment.
  */
 public function login_info($withlinks = null)
 {
     global $USER, $CFG, $DB, $SESSION;
     if (during_initial_install()) {
         return '';
     }
     if (is_null($withlinks)) {
         $withlinks = empty($this->page->layout_options['nologinlinks']);
     }
     $loginpage = (string) $this->page->url === get_login_url();
     $course = $this->page->course;
     if (\core\session\manager::is_loggedinas()) {
         $realuser = \core\session\manager::get_realuser();
         $fullname = fullname($realuser, true);
         if ($withlinks) {
             $loginastitle = get_string('loginas');
             $realuserinfo = " [<a href=\"{$CFG->wwwroot}/course/loginas.php?id={$course->id}&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) {
                         echo "<i class='fa fa-user hide979 mywhite'></i> ";
                         //****************$loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
                         $loggedinas .= " <span class=\"line-trans\">|</span><a class=\"logtop\" href=\"{$CFG->wwwroot}/login/logout.php?sesskey=" . sesskey() . "\"> " . get_string('logout') . '</a><span class="line-trans"> |</span>';
                     }
                 }
             }
         } else {
             $loggedinas = get_string('loggedinnot', 'moodle');
             if (!$loginpage && $withlinks) {
                 //****************$loggedinas $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
                 echo "<i class='fa fa-lock hide979 mywhite'></i> ";
                 $loggedinas .= " | <a href=\"{$loginurl}\">" . get_string('login') . '</a> |';
             }
         }
     }
     $loggedinas = '<div class="logininfo">' . $loggedinas . '</div>';
     if (isset($SESSION->justloggedin)) {
         unset($SESSION->justloggedin);
         if (!empty($CFG->displayloginfailures)) {
             if (!isguestuser()) {
                 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
                     $loggedinas .= '&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;
 }
Exemplo n.º 8
0
if (user_has_role_assignment($USER->id,5)  ) {
$PAGE->requires->css('/student/custom.css');
}
$userid         = optional_param('id', 0, PARAM_INT);
$edit           = optional_param('edit', null, PARAM_BOOL);    // Turn editing on and off.
$reset          = optional_param('reset', null, PARAM_BOOL);

$PAGE->set_url('/user/profile.php', array('id' => $userid));

if (!empty($CFG->forceloginforprofiles)) {
    require_login();
    if (isguestuser()) {
        $PAGE->set_context(context_system::instance());
        echo $OUTPUT->header();
        echo $OUTPUT->confirm(get_string('guestcantaccessprofiles', 'error'),
                              get_login_url(),
                              $CFG->wwwroot);
        echo $OUTPUT->footer();
        die;
    }
} else if (!empty($CFG->forcelogin)) {
    require_login();
}

$userid = $userid ? $userid : $USER->id;       // Owner of the page.
if ((!$user = $DB->get_record('user', array('id' => $userid))) || ($user->deleted)) {
    $PAGE->set_context(context_system::instance());
    echo $OUTPUT->header();
    if (!$user) {
        echo $OUTPUT->notification(get_string('invaliduser', 'error'));
    } else {
Exemplo n.º 9
0
        unset($SESSION->info);
    }
    if (isset($SESSION->backupprefs)) {
        unset($SESSION->backupprefs);
    }
    if (isset($SESSION->restore)) {
        unset($SESSION->restore);
    }
    if (isset($SESSION->import_preferences)) {
        unset($SESSION->import_preferences);
    }
}
if (!$to && isset($SESSION->restore->restoreto) && isset($SESSION->restore->importing) && isset($SESSION->restore->course_id)) {
    $to = $SESSION->restore->course_id;
}
$loginurl = get_login_url();
if (!empty($id)) {
    require_login($id);
    if (!has_capability('moodle/site:restore', get_context_instance(CONTEXT_COURSE, $id))) {
        if (empty($to)) {
            print_error("cannotuseadminadminorteacher", '', $loginurl);
        } else {
            if (!has_capability('moodle/site:restore', get_context_instance(CONTEXT_COURSE, $to)) && !has_capability('moodle/site:import', get_context_instance(CONTEXT_COURSE, $to))) {
                print_error("cannotuseadminadminorteacher", '', $loginurl);
            }
        }
    }
} else {
    if (!has_capability('moodle/site:restore', get_context_instance(CONTEXT_SYSTEM))) {
        print_error("cannotuseadmin", '', $loginurl);
    }
Exemplo n.º 10
0
    if (! $cm = get_coursemodule_from_instance('chat', $chat->id, $course->id)) {
        print_error('invalidcoursemodule');
    }
}

require_course_login($course, true, $cm);

$context = context_module::instance($cm->id);
$PAGE->set_context($context);

// show some info for guests
if (isguestuser()) {
    $PAGE->set_title(format_string($chat->name));
    echo $OUTPUT->header();
    echo $OUTPUT->confirm('<p>'.get_string('noguests', 'chat').'</p>'.get_string('liketologin'),
            get_login_url(), $CFG->wwwroot.'/course/view.php?id='.$course->id);

    echo $OUTPUT->footer();
    exit;
}

add_to_log($course->id, 'chat', 'view', "view.php?id=$cm->id", $chat->id, $cm->id);

$strenterchat    = get_string('enterchat', 'chat');
$stridle         = get_string('idle', 'chat');
$strcurrentusers = get_string('currentusers', 'chat');
$strnextsession  = get_string('nextsession', 'chat');

$courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
$title = $courseshortname . ': ' . format_string($chat->name);
 /**
  * Outputs the user menu.
  * @return custom_menu object
  */
 public function custom_menu_user()
 {
     // Die if executed during install.
     if (during_initial_install()) {
         return false;
     }
     global $USER, $CFG, $DB;
     $loginurl = get_login_url();
     $usermenu = html_writer::start_tag('ul', array('class' => 'nav'));
     $usermenu .= html_writer::start_tag('li', array('class' => 'dropdown'));
     if (!isloggedin()) {
         if ($this->page->pagelayout != 'login') {
             $userpic = '<em><i class="fa fa-sign-in"></i>' . get_string('login') . '</em>';
             $usermenu .= html_writer::link($loginurl, $userpic, array('class' => 'loginurl'));
         }
     } else {
         if (isguestuser()) {
             $userurl = new moodle_url('#');
             $userpic = parent::user_picture($USER, array('link' => false));
             $caret = '<i class="fa fa-caret-right"></i>';
             $userclass = array('class' => 'dropdown-toggle', 'data-toggle' => 'dropdown');
             $usermenu .= html_writer::link($userurl, $userpic . get_string('guest') . $caret, $userclass);
             // Render direct logout link.
             $usermenu .= html_writer::start_tag('ul', array('class' => 'dropdown-menu pull-right'));
             $branchlabel = '<em><i class="fa fa-sign-out"></i>' . get_string('logout') . '</em>';
             $branchurl = new moodle_url('/login/logout.php');
             $branchurl->param('sesskey', sesskey());
             $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel));
             // Render Help Link.
             $usermenu .= $this->theme_essential_render_helplink();
             $usermenu .= html_writer::end_tag('ul');
         } else {
             $course = $this->page->course;
             $context = context_course::instance($course->id);
             // Output Profile link.
             $userurl = new moodle_url('#');
             $userpic = parent::user_picture($USER, array('link' => false));
             $caret = '<i class="fa fa-caret-right"></i>';
             $userclass = array('class' => 'dropdown-toggle', 'data-toggle' => 'dropdown');
             if (!empty($USER->alternatename)) {
                 $usermenu .= html_writer::link($userurl, $userpic . $USER->alternatename . $caret, $userclass);
             } else {
                 $usermenu .= html_writer::link($userurl, $userpic . $USER->firstname . $caret, $userclass);
             }
             // Start dropdown menu items.
             $usermenu .= html_writer::start_tag('ul', array('class' => 'dropdown-menu pull-right'));
             if (\core\session\manager::is_loggedinas()) {
                 $realuser = \core\session\manager::get_realuser();
                 $branchlabel = '<em><i class="fa fa-key"></i>' . fullname($realuser, true) . get_string('loggedinas', 'theme_essential') . fullname($USER, true) . '</em>';
             } else {
                 $branchlabel = '<em><i class="fa fa-user"></i>' . fullname($USER, true) . '</em>';
             }
             $branchurl = new moodle_url('/user/profile.php', array('id' => $USER->id));
             $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel));
             if (is_mnet_remote_user($USER) && ($idprovider = $DB->get_record('mnet_host', array('id' => $USER->mnethostid)))) {
                 $branchlabel = '<em><i class="fa fa-users"></i>' . get_string('loggedinfrom', 'theme_essential') . $idprovider->name . '</em>';
                 $branchurl = new moodle_url($idprovider->wwwroot);
                 $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel));
             }
             if (is_role_switched($course->id)) {
                 // Has switched roles.
                 $branchlabel = '<em><i class="fa fa-users"></i>' . get_string('switchrolereturn') . '</em>';
                 $branchurl = new moodle_url('/course/switchrole.php', array('id' => $course->id, 'sesskey' => sesskey(), 'switchrole' => 0, 'returnurl' => $this->page->url->out_as_local_url(false)));
                 $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel));
             }
             // Add preferences submenu.
             $usermenu .= $this->theme_essential_render_preferences($context);
             $usermenu .= html_writer::empty_tag('hr', array('class' => 'sep'));
             // Output Calendar link if user is allowed to edit own calendar entries.
             if (has_capability('moodle/calendar:manageownentries', $context)) {
                 $branchlabel = '<em><i class="fa fa-calendar"></i>' . get_string('pluginname', 'block_calendar_month') . '</em>';
                 $branchurl = new moodle_url('/calendar/view.php');
                 $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel));
             }
             // Check if messaging is enabled.
             if (!empty($CFG->messaging)) {
                 $branchlabel = '<em><i class="fa fa-envelope"></i>' . get_string('pluginname', 'block_messages') . '</em>';
                 $branchurl = new moodle_url('/message/index.php');
                 $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel));
             }
             // Check if user is allowed to manage files.
             if (has_capability('moodle/user:manageownfiles', $context)) {
                 $branchlabel = '<em><i class="fa fa-file"></i>' . get_string('privatefiles', 'block_private_files') . '</em>';
                 $branchurl = new moodle_url('/user/files.php');
                 $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel));
             }
             // Check if user is allowed to view discussions.
             if (has_capability('mod/forum:viewdiscussion', $context)) {
                 $branchlabel = '<em><i class="fa fa-list-alt"></i>' . get_string('forumposts', 'mod_forum') . '</em>';
                 $branchurl = new moodle_url('/mod/forum/user.php', array('id' => $USER->id));
                 $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel));
                 $branchlabel = '<em><i class="fa fa-list"></i>' . get_string('discussions', 'mod_forum') . '</em>';
                 $branchurl = new moodle_url('/mod/forum/user.php', array('id' => $USER->id, 'mode' => 'discussions'));
                 $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel));
                 $usermenu .= html_writer::empty_tag('hr', array('class' => 'sep'));
             }
             // Output user grade links course sensitive, workaround for frontpage, selecting first enrolled course.
             if ($course->id == SITEID) {
                 $branchlabel = '<em><i class="fa fa-list-alt"></i>' . get_string('mygrades', 'theme_essential') . '</em>';
                 $branchurl = new moodle_url('/grade/report/overview/index.php', array('id' => $course->id, 'userid' => $USER->id));
                 $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel));
             } else {
                 if (has_capability('gradereport/overview:view', $context)) {
                     $branchlabel = '<em><i class="fa fa-list-alt"></i>' . get_string('mygrades', 'theme_essential') . '</em>';
                     $branchurl = new moodle_url('/grade/report/overview/index.php', array('id' => $course->id, 'userid' => $USER->id));
                     $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel));
                 }
                 if (has_capability('gradereport/user:view', $context)) {
                     // In Course also output Course grade links.
                     $branchlabel = '<em><i class="fa fa-list-alt"></i>' . get_string('coursegrades', 'theme_essential') . '</em>';
                     $branchurl = new moodle_url('/grade/report/user/index.php', array('id' => $course->id, 'userid' => $USER->id));
                     $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel));
                 }
             }
             // Check if badges are enabled.
             if (!empty($CFG->enablebadges) && has_capability('moodle/badges:manageownbadges', $context)) {
                 $branchlabel = '<em><i class="fa fa-certificate"></i>' . get_string('badges') . '</em>';
                 $branchurl = new moodle_url('/badges/mybadges.php');
                 $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel));
             }
             $usermenu .= html_writer::empty_tag('hr', array('class' => 'sep'));
             // Render direct logout link.
             $branchlabel = '<em><i class="fa fa-sign-out"></i>' . get_string('logout') . '</em>';
             if (\core\session\manager::is_loggedinas()) {
                 $branchurl = new moodle_url('/course/loginas.php', array('id' => $course->id, 'sesskey' => sesskey()));
             } else {
                 $branchurl = new moodle_url('/login/logout.php', array('sesskey' => sesskey()));
             }
             $usermenu .= html_writer::tag('li', html_writer::link($branchurl, $branchlabel));
             // Render Help Link.
             $usermenu .= $this->theme_essential_render_helplink();
             $usermenu .= html_writer::end_tag('ul');
         }
     }
     $usermenu .= html_writer::end_tag('li');
     $usermenu .= html_writer::end_tag('ul');
     return $usermenu;
 }
Exemplo n.º 12
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>';
}
Exemplo n.º 13
0
if (!($cm = get_coursemodule_from_instance("quora", $quora->id, $course->id))) {
    print_error('invalidcoursemodule');
}
$user = $USER;
require_login($course, false, $cm);
if ($returnpage == 'index.php') {
    $returnto = quora_go_back_to($returnpage . '?id=' . $course->id);
} else {
    $returnto = quora_go_back_to($returnpage . '?f=' . $quora->id);
}
if (isguestuser()) {
    // Guests can't change quora
    $PAGE->set_title($course->shortname);
    $PAGE->set_heading($course->fullname);
    echo $OUTPUT->header();
    echo $OUTPUT->confirm(get_string('noguesttracking', 'quora') . '<br /><br />' . get_string('liketologin'), get_login_url(), $returnto);
    echo $OUTPUT->footer();
    exit;
}
$info = new stdClass();
$info->name = fullname($user);
$info->quora = format_string($quora->name);
if ($mark == 'read') {
    if (!empty($d)) {
        if (!($discussion = $DB->get_record('quora_discussions', array('id' => $d, 'quora' => $quora->id)))) {
            print_error('invaliddiscussionid', 'quora');
        }
        quora_tp_mark_discussion_read($user, $d);
    } else {
        // Mark all messages read in current group
        $currentgroup = groups_get_activity_group($cm);
Exemplo n.º 14
0
$messages = $accessmanager->describe_rules();
if ($quiz->attempts != 1) {
    $messages[] = get_string('gradingmethod', 'quiz', quiz_get_grading_option_name($quiz->grademethod));
}
echo $OUTPUT->box_start('quizinfo');
$accessmanager->print_messages($messages);
echo $OUTPUT->box_end();
/// Show number of attempts summary to those who can view reports.
if (has_capability('mod/quiz:viewreports', $context)) {
    if ($strattemptnum = quiz_num_attempt_summary($quiz, $cm)) {
        echo '<div class="quizattemptcounts"><a href="report.php?mode=overview&amp;id=' . $cm->id . '">' . $strattemptnum . "</a></div>\n";
    }
}
/// Guests can't do a quiz, so offer them a choice of logging in or going back.
if (isguestuser()) {
    echo $OUTPUT->confirm('<p>' . get_string('guestsno', 'quiz') . "</p>\n\n<p>" . get_string('liketologin') . "</p>\n", get_login_url(), get_referer(false));
    echo $OUTPUT->footer();
    exit;
}
/// If they are not enrolled in this course in a good enough role, tell them to enrol.
if (!($canattempt || $canpreview || $canreviewmine)) {
    echo $OUTPUT->box('<p>' . get_string('youneedtoenrol', 'quiz') . "</p>\n\n<p>" . $OUTPUT->continue_button($CFG->wwwroot . '/course/view.php?id=' . $course->id) . "</p>\n", 'generalbox', 'notice');
    echo $OUTPUT->footer();
    exit;
}
/// Get this user's attempts.
$attempts = quiz_get_user_attempts($quiz->id, $USER->id);
$lastfinishedattempt = end($attempts);
$unfinished = false;
if ($unfinishedattempt = quiz_get_user_attempt_unfinished($quiz->id, $USER->id)) {
    $attempts[] = $unfinishedattempt;
Exemplo n.º 15
0
/**
 *  Processes a user's request to set a new password in the event they forgot the old one.
 *  If no user identifier has been supplied, it displays a form where they can submit their identifier.
 *  Where they have supplied identifier, the function will check their status, and send email as appropriate.
 */
function core_login_process_password_reset_request()
{
    global $DB, $OUTPUT, $CFG, $PAGE;
    $systemcontext = context_system::instance();
    $mform = new login_forgot_password_form();
    if ($mform->is_cancelled()) {
        redirect(get_login_url());
    } else {
        if ($data = $mform->get_data()) {
            // Requesting user has submitted form data.
            // Next find the user account in the database which the requesting user claims to own.
            if (!empty($data->username)) {
                // Username has been specified - load the user record based on that.
                $username = core_text::strtolower($data->username);
                // Mimic the login page process.
                $userparams = array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 0, 'suspended' => 0);
                $user = $DB->get_record('user', $userparams);
            } else {
                // Try to load the user record based on email address.
                // this is tricky because
                // 1/ the email is not guaranteed to be unique - TODO: send email with all usernames to select the account for pw reset
                // 2/ mailbox may be case sensitive, the email domain is case insensitive - let's pretend it is all case-insensitive.
                $select = $DB->sql_like('email', ':email', false, true, false, '|') . " AND mnethostid = :mnethostid AND deleted=0 AND suspended=0";
                $params = array('email' => $DB->sql_like_escape($data->email, '|'), 'mnethostid' => $CFG->mnet_localhost_id);
                $user = $DB->get_record_select('user', $select, $params, '*', IGNORE_MULTIPLE);
            }
            // Target user details have now been identified, or we know that there is no such account.
            // Send email address to account's email address if appropriate.
            $pwresetstatus = PWRESET_STATUS_NOEMAILSENT;
            if ($user and !empty($user->confirmed)) {
                $userauth = get_auth_plugin($user->auth);
                if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth) or !has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
                    if (send_password_change_info($user)) {
                        $pwresetstatus = PWRESET_STATUS_OTHEREMAILSENT;
                    } else {
                        print_error('cannotmailconfirm');
                    }
                } else {
                    // The account the requesting user claims to be is entitled to change their password.
                    // Next, check if they have an existing password reset in progress.
                    $resetinprogress = $DB->get_record('user_password_resets', array('userid' => $user->id));
                    if (empty($resetinprogress)) {
                        // Completely new reset request - common case.
                        $resetrecord = core_login_generate_password_reset($user);
                        $sendemail = true;
                    } else {
                        if ($resetinprogress->timerequested < time() - $CFG->pwresettime) {
                            // Preexisting, but expired request - delete old record & create new one.
                            // Uncommon case - expired requests are cleaned up by cron.
                            $DB->delete_records('user_password_resets', array('id' => $resetinprogress->id));
                            $resetrecord = core_login_generate_password_reset($user);
                            $sendemail = true;
                        } else {
                            if (empty($resetinprogress->timererequested)) {
                                // Preexisting, valid request. This is the first time user has re-requested the reset.
                                // Re-sending the same email once can actually help in certain circumstances
                                // eg by reducing the delay caused by greylisting.
                                $resetinprogress->timererequested = time();
                                $DB->update_record('user_password_resets', $resetinprogress);
                                $resetrecord = $resetinprogress;
                                $sendemail = true;
                            } else {
                                // Preexisting, valid request. User has already re-requested email.
                                $pwresetstatus = PWRESET_STATUS_ALREADYSENT;
                                $sendemail = false;
                            }
                        }
                    }
                    if ($sendemail) {
                        $sendresult = send_password_change_confirmation_email($user, $resetrecord);
                        if ($sendresult) {
                            $pwresetstatus = PWRESET_STATUS_TOKENSENT;
                        } else {
                            print_error('cannotmailconfirm');
                        }
                    }
                }
            }
            // Any email has now been sent.
            // Next display results to requesting user if settings permit.
            echo $OUTPUT->header();
            if (!empty($CFG->protectusernames)) {
                // Neither confirm, nor deny existance of any username or email address in database.
                // Print general (non-commital) message.
                notice(get_string('emailpasswordconfirmmaybesent'), $CFG->wwwroot . '/index.php');
                die;
                // Never reached.
            } else {
                if (empty($user)) {
                    // Protect usernames is off, and we couldn't find the user with details specified.
                    // Print failure advice.
                    notice(get_string('emailpasswordconfirmnotsent'), $CFG->wwwroot . '/forgot_password.php');
                    die;
                    // Never reached.
                } else {
                    if (empty($user->email)) {
                        // User doesn't have an email set - can't send a password change confimation email.
                        notice(get_string('emailpasswordconfirmnoemail'), $CFG->wwwroot . '/index.php');
                        die;
                        // Never reached.
                    } else {
                        if ($pwresetstatus == PWRESET_STATUS_ALREADYSENT) {
                            // User found, protectusernames is off, but user has already (re) requested a reset.
                            // Don't send a 3rd reset email.
                            $stremailalreadysent = get_string('emailalreadysent');
                            notice($stremailalreadysent, $CFG->wwwroot . '/index.php');
                            die;
                            // Never reached.
                        } else {
                            if ($pwresetstatus == PWRESET_STATUS_NOEMAILSENT) {
                                // User found, protectusernames is off, but user is not confirmed.
                                // Pretend we sent them an email.
                                // This is a big usability problem - need to tell users why we didn't send them an email.
                                // Obfuscate email address to protect privacy.
                                $protectedemail = preg_replace('/([^@]*)@(.*)/', '******@$2', $user->email);
                                $stremailpasswordconfirmsent = get_string('emailpasswordconfirmsent', '', $protectedemail);
                                notice($stremailpasswordconfirmsent, $CFG->wwwroot . '/index.php');
                                die;
                                // Never reached.
                            } else {
                                // Confirm email sent. (Obfuscate email address to protect privacy).
                                $protectedemail = preg_replace('/([^@]*)@(.*)/', '******@$2', $user->email);
                                // This is a small usability problem - may be obfuscating the email address which the user has just supplied.
                                $stremailresetconfirmsent = get_string('emailresetconfirmsent', '', $protectedemail);
                                notice($stremailresetconfirmsent, $CFG->wwwroot . '/index.php');
                                die;
                                // Never reached.
                            }
                        }
                    }
                }
            }
            die;
            // Never reached.
        }
    }
    // Make sure we really are on the https page when https login required.
    $PAGE->verify_https_required();
    // DISPLAY FORM.
    echo $OUTPUT->header();
    //echo $OUTPUT->box(get_string('passwordforgotteninstructions2'), 'generalbox boxwidthnormal boxaligncenter'); // GWL - Forgot Pwd page remove header content
    echo '<div class="loginbox clearfix onecolumn forgot-password">';
    echo '<div class="loginpanel">';
    echo get_string('passwordforgotten2');
    echo get_string('cantaccessaccount2');
    echo get_string('dontpanic2');
    $mform->display();
    echo '</div>';
    echo '</div>';
    echo $OUTPUT->footer();
}
Exemplo n.º 16
0
    }
    if (!($course = $DB->get_record('course', array('id' => $forum->course)))) {
        print_error('invalidcourseid');
    }
    if (!($cm = get_coursemodule_from_instance('forum', $forum->id, $course->id))) {
        // For the logs
        print_error('invalidcoursemodule');
    } else {
        $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
    }
    $PAGE->set_cm($cm, $course, $forum);
    $PAGE->set_context($modcontext);
    $PAGE->set_title($course->shortname);
    $PAGE->set_heading($course->fullname);
    echo $OUTPUT->header();
    echo $OUTPUT->confirm(get_string('noguestpost', 'forum') . '<br /><br />' . get_string('liketologin'), get_login_url(), get_referer(false));
    echo $OUTPUT->footer();
    exit;
}
require_login(0, false);
// Script is useless unless they're logged in
if (!empty($forum)) {
    // User is starting a new discussion in a forum
    if (!($forum = $DB->get_record("forum", array("id" => $forum)))) {
        print_error('invalidforumid', 'forum');
    }
    if (!($course = $DB->get_record("course", array("id" => $forum->course)))) {
        print_error('invalidcourseid');
    }
    if (!($cm = get_coursemodule_from_instance("forum", $forum->id, $course->id))) {
        print_error("invalidcoursemodule");
Exemplo n.º 17
0
 $ADMIN->add('messageoutputs', new admin_page_managemessageoutputs());
 $ADMIN->add('messageoutputs', new admin_page_defaultmessageoutputs());
 foreach (core_plugin_manager::instance()->get_plugins_of_type('message') as $plugin) {
     /** @var \core\plugininfo\message $plugin */
     $plugin->load_settings($ADMIN, 'messageoutputs', $hassiteconfig);
 }
 // authentication plugins
 $ADMIN->add('modules', new admin_category('authsettings', new lang_string('authentication', 'admin')));
 $temp = new admin_settingpage('manageauths', new lang_string('authsettings', 'admin'));
 $temp->add(new admin_setting_manageauths());
 $temp->add(new admin_setting_heading('manageauthscommonheading', new lang_string('commonsettings', 'admin'), ''));
 $temp->add(new admin_setting_special_registerauth());
 $temp->add(new admin_setting_configcheckbox('authpreventaccountcreation', new lang_string('authpreventaccountcreation', 'admin'), new lang_string('authpreventaccountcreation_help', 'admin'), 0));
 $temp->add(new admin_setting_configcheckbox('loginpageautofocus', new lang_string('loginpageautofocus', 'admin'), new lang_string('loginpageautofocus_help', 'admin'), 0));
 $temp->add(new admin_setting_configselect('guestloginbutton', new lang_string('guestloginbutton', 'auth'), new lang_string('showguestlogin', 'auth'), '1', array('0' => new lang_string('hide'), '1' => new lang_string('show'))));
 $temp->add(new admin_setting_configtext('alternateloginurl', new lang_string('alternateloginurl', 'auth'), new lang_string('alternatelogin', 'auth', htmlspecialchars(get_login_url())), ''));
 $temp->add(new admin_setting_configtext('forgottenpasswordurl', new lang_string('forgottenpasswordurl', 'auth'), new lang_string('forgottenpassword', 'auth'), ''));
 $temp->add(new admin_setting_confightmleditor('auth_instructions', new lang_string('instructions', 'auth'), new lang_string('authinstructions', 'auth'), ''));
 $temp->add(new admin_setting_configtext('allowemailaddresses', new lang_string('allowemailaddresses', 'admin'), new lang_string('configallowemailaddresses', 'admin'), '', PARAM_NOTAGS));
 $temp->add(new admin_setting_configtext('denyemailaddresses', new lang_string('denyemailaddresses', 'admin'), new lang_string('configdenyemailaddresses', 'admin'), '', PARAM_NOTAGS));
 $temp->add(new admin_setting_configcheckbox('verifychangedemail', new lang_string('verifychangedemail', 'admin'), new lang_string('configverifychangedemail', 'admin'), 1));
 $temp->add(new admin_setting_configtext('recaptchapublickey', new lang_string('recaptchapublickey', 'admin'), new lang_string('configrecaptchapublickey', 'admin'), '', PARAM_NOTAGS));
 $temp->add(new admin_setting_configtext('recaptchaprivatekey', new lang_string('recaptchaprivatekey', 'admin'), new lang_string('configrecaptchaprivatekey', 'admin'), '', PARAM_NOTAGS));
 $ADMIN->add('authsettings', $temp);
 $temp = new admin_externalpage('authtestsettings', get_string('testsettings', 'core_auth'), new moodle_url("/auth/test_settings.php"), 'moodle/site:config', true);
 $ADMIN->add('authsettings', $temp);
 foreach (core_plugin_manager::instance()->get_plugins_of_type('auth') as $plugin) {
     /** @var \core\plugininfo\auth $plugin */
     $plugin->load_settings($ADMIN, 'authsettings', $hassiteconfig);
 }
 // Enrolment plugins
Exemplo n.º 18
0
}
// Check if user already enrolled
if (is_enrolled($context, $USER, '', true)) {
    if (!empty($SESSION->wantsurl)) {
        $destination = $SESSION->wantsurl;
        unset($SESSION->wantsurl);
    } else {
        $destination = "{$CFG->wwwroot}/course/view.php?id={$course->id}";
    }
    redirect($destination);
    // Bye!
}
$PAGE->set_title($course->shortname);
$PAGE->set_heading($course->fullname);
$PAGE->navbar->add(get_string('enrolmentoptions', 'enrol'));
echo $OUTPUT->header();
echo $OUTPUT->heading(get_string('enrolmentoptions', 'enrol'));
$courserenderer = $PAGE->get_renderer('core', 'course');
echo $courserenderer->course_info_box($course);
//TODO: find if future enrolments present and display some info
foreach ($forms as $form) {
    echo $form;
}
if (!$forms) {
    if (isguestuser()) {
        notice(get_string('noguestaccess', 'enrol'), get_login_url());
    } else {
        notice(get_string('notenrollable', 'enrol'), "{$CFG->wwwroot}/index.php");
    }
}
echo $OUTPUT->footer();
Exemplo n.º 19
0
                $ADMIN->add('messageoutputs', $settings);
            }
        }
    }

    // authentication plugins
    $ADMIN->add('modules', new admin_category('authsettings', get_string('authentication', 'admin')));

    $temp = new admin_settingpage('manageauths', get_string('authsettings', 'admin'));
    $temp->add(new admin_setting_manageauths());
    $temp->add(new admin_setting_heading('manageauthscommonheading', get_string('commonsettings', 'admin'), ''));
    $temp->add(new admin_setting_special_registerauth());
    $temp->add(new admin_setting_configselect('guestloginbutton', get_string('guestloginbutton', 'auth'),
                                              get_string('showguestlogin', 'auth'), '1', array('0'=>get_string('hide'), '1'=>get_string('show'))));
    $temp->add(new admin_setting_configtext('alternateloginurl', get_string('alternateloginurl', 'auth'),
                                            get_string('alternatelogin', 'auth', htmlspecialchars(get_login_url())), ''));
    $temp->add(new admin_setting_configtext('forgottenpasswordurl', get_string('forgottenpasswordurl', 'auth'),
                                            get_string('forgottenpassword', 'auth'), ''));
    $temp->add(new admin_setting_confightmleditor('auth_instructions', get_string('instructions', 'auth'),
                                                get_string('authinstructions', 'auth'), ''));
    $temp->add(new admin_setting_configtext('allowemailaddresses', get_string('allowemailaddresses', 'admin'), get_string('configallowemailaddresses', 'admin'), '', PARAM_NOTAGS));
    $temp->add(new admin_setting_configtext('denyemailaddresses', get_string('denyemailaddresses', 'admin'), get_string('configdenyemailaddresses', 'admin'), '', PARAM_NOTAGS));
    $temp->add(new admin_setting_configcheckbox('verifychangedemail', get_string('verifychangedemail', 'admin'), get_string('configverifychangedemail', 'admin'), 1));

    $temp->add(new admin_setting_configtext('recaptchapublickey', get_string('recaptchapublickey', 'admin'), get_string('configrecaptchapublickey', 'admin'), '', PARAM_NOTAGS));
    $temp->add(new admin_setting_configtext('recaptchaprivatekey', get_string('recaptchaprivatekey', 'admin'), get_string('configrecaptchaprivatekey', 'admin'), '', PARAM_NOTAGS));
    $ADMIN->add('authsettings', $temp);


    $auths = get_plugin_list('auth');
    $authsenabled = get_enabled_auth_plugins();
Exemplo n.º 20
0
/**
 * Performs the common access checks and page setup for all
 * user preference pages.
 *
 * @param int $userid The user id to edit taken from the page params.
 * @param int $courseid The optional course id if we came from a course context.
 * @return array containing the user and course records.
 */
function useredit_setup_preference_page($userid, $courseid)
{
    global $PAGE, $SESSION, $DB, $CFG, $OUTPUT, $USER;
    // Guest can not edit.
    if (isguestuser()) {
        print_error('guestnoeditprofile');
    }
    if (!($course = $DB->get_record('course', array('id' => $courseid)))) {
        print_error('invalidcourseid');
    }
    if ($course->id != SITEID) {
        require_login($course);
    } else {
        if (!isloggedin()) {
            if (empty($SESSION->wantsurl)) {
                $SESSION->wantsurl = $CFG->httpswwwroot . '/user/preferences.php';
            }
            redirect(get_login_url());
        } else {
            $PAGE->set_context(context_system::instance());
        }
    }
    // The user profile we are editing.
    if (!($user = $DB->get_record('user', array('id' => $userid)))) {
        print_error('invaliduserid');
    }
    // Guest can not be edited.
    if (isguestuser($user)) {
        print_error('guestnoeditprofile');
    }
    // Remote users cannot be edited.
    if (is_mnet_remote_user($user)) {
        if (user_not_fully_set_up($user, false)) {
            $hostwwwroot = $DB->get_field('mnet_host', 'wwwroot', array('id' => $user->mnethostid));
            print_error('usernotfullysetup', 'mnet', '', $hostwwwroot);
        }
        redirect($CFG->wwwroot . "/user/view.php?course={$course->id}");
    }
    $systemcontext = context_system::instance();
    $personalcontext = context_user::instance($user->id);
    // Check access control.
    if ($user->id == $USER->id) {
        // Editing own profile - require_login() MUST NOT be used here, it would result in infinite loop!
        if (!has_capability('moodle/user:editownprofile', $systemcontext)) {
            print_error('cannotedityourprofile');
        }
    } else {
        // Teachers, parents, etc.
        require_capability('moodle/user:editprofile', $personalcontext);
        // No editing of primary admin!
        if (is_siteadmin($user) and !is_siteadmin($USER)) {
            // Only admins may edit other admins.
            print_error('useradmineditadmin');
        }
    }
    if ($user->deleted) {
        echo $OUTPUT->header();
        echo $OUTPUT->heading(get_string('userdeleted'));
        echo $OUTPUT->footer();
        die;
    }
    $PAGE->set_pagelayout('admin');
    $PAGE->set_context($personalcontext);
    if ($USER->id != $user->id) {
        $PAGE->navigation->extend_for_user($user);
    } else {
        if ($node = $PAGE->navigation->find('myprofile', navigation_node::TYPE_ROOTNODE)) {
            $node->force_open();
        }
    }
    return array($user, $course);
}
Exemplo n.º 21
0
                echo $OUTPUT->header();
                echo $OUTPUT->confirm(get_string('auth_passwordwillexpire', 'auth', $days2expire), $passwordchangeurl, $urltogo);
                echo $OUTPUT->footer();
                exit;
            } elseif (intval($days2expire) < 0) {
                echo $OUTPUT->header();
                echo $OUTPUT->confirm(get_string('auth_passwordisexpired', 'auth'), $passwordchangeurl, $urltogo);
                echo $OUTPUT->footer();
                exit;
            }
        }
        // Discard any errors before the last redirect.
        unset($SESSION->loginerrormsg);
        // test the session actually works by redirecting to self
        $SESSION->wantsurl = $urltogo;
        redirect(new moodle_url(get_login_url(), array('testsession' => $USER->id)));
    } else {
        if (empty($errormsg)) {
            if ($errorcode == AUTH_LOGIN_UNAUTHORISED) {
                $errormsg = get_string("unauthorisedlogin", "", $frm->username);
            } else {
                $errormsg = get_string("invalidlogin");
                $errorcode = 3;
            }
        }
    }
}
/// Detect problems with timedout sessions
if ($session_has_timed_out and !data_submitted()) {
    $errormsg = get_string('sessionerroruser', 'error');
    $errorcode = 4;
Exemplo n.º 22
0
<?php

// $Id: index.php,v 1.28 2009/05/06 09:29:06 tjhunt Exp $
// this is the 'my moodle' page
require_once dirname(__FILE__) . '/../config.php';
require_once $CFG->dirroot . '/course/lib.php';
require_login();
$strmymoodle = get_string('mymoodle', 'my');
if (isguest()) {
    print_header($strmymoodle);
    notice_yesno(get_string('noguest', 'my') . '<br /><br />' . get_string('liketologin'), get_login_url(), $CFG->wwwroot);
    print_footer();
    die;
}
$edit = optional_param('edit', -1, PARAM_BOOL);
$blockaction = optional_param('blockaction', '', PARAM_ALPHA);
$PAGE->set_context(get_context_instance(CONTEXT_USER, $USER->id));
$PAGE->set_url('my/index.php');
$PAGE->set_blocks_editing_capability('moodle/my:manageblocks');
// Note: MDL-19010 there will be further changes to printing header and blocks.
// The code will be much nicer than this eventually.
$pageblocks = blocks_setup($PAGE, BLOCKS_PINNED_BOTH);
if ($edit != -1 and $PAGE->user_allowed_editing()) {
    $USER->editing = $edit;
}
$button = update_mymoodle_icon($USER->id);
$header = $SITE->shortname . ': ' . $strmymoodle;
$navigation = build_navigation($strmymoodle);
$loggedinas = user_login_string();
if (empty($CFG->langmenu)) {
    $langmenu = '';
Exemplo n.º 23
0
    }
}
if ((!$current or $choice->allowupdate) and $choiceopen and is_enrolled($context, NULL, 'mod/choice:choose')) {
    // They haven't made their choice yet or updates allowed and choice is open
    $options = choice_prepare_options($choice, $USER, $cm, $allresponses);
    $renderer = $PAGE->get_renderer('mod_choice');
    echo $renderer->display_options($options, $cm->id, $choice->display, $choice->allowmultiple);
    $choiceformshown = true;
} else {
    $choiceformshown = false;
}
if (!$choiceformshown) {
    $sitecontext = context_system::instance();
    if (isguestuser()) {
        // Guest account
        echo $OUTPUT->confirm(get_string('noguestchoose', 'choice') . '<br /><br />' . get_string('liketologin'), get_login_url(), new moodle_url('/course/view.php', array('id' => $course->id)));
    } else {
        if (!is_enrolled($context)) {
            // Only people enrolled can make a choice
            $SESSION->wantsurl = qualified_me();
            $SESSION->enrolcancel = get_local_referer(false);
            $coursecontext = context_course::instance($course->id);
            $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
            echo $OUTPUT->box_start('generalbox', 'notice');
            echo '<p align="center">' . get_string('notenrolledchoose', 'choice') . '</p>';
            echo $OUTPUT->container_start('continuebutton');
            echo $OUTPUT->single_button(new moodle_url('/enrol/index.php?', array('id' => $course->id)), get_string('enrolme', 'core_enrol', $courseshortname));
            echo $OUTPUT->container_end();
            echo $OUTPUT->box_end();
        }
    }
Exemplo n.º 24
0
/**
 * Initialize internal states for the most common skin displays.
 *
 * For more specific skins, this function may not be called and
 * equivalent code may be customized within the skin.
 *
 * @param string What are we going to display. Most of the time the global $disp should be passed.
 */
function skin_init($disp)
{
    /**
     * @var Blog
     */
    global $Blog;
    /**
     * @var Item
     */
    global $Item;
    /**
     * @var Skin
     */
    global $Skin;
    global $robots_index;
    global $seo_page_type;
    global $redir, $ReqURL, $ReqURI, $m, $w, $preview;
    global $Chapter;
    global $Debuglog;
    /**
     * @var ItemList2
     */
    global $MainList;
    /**
     * This will give more detail when $disp == 'posts'; otherwise it will have the same content as $disp
     * @var string
     */
    global $disp_detail, $Settings;
    global $Timer;
    global $Messages, $PageCache;
    global $Session, $current_User;
    $Timer->resume('skin_init');
    if (empty($disp_detail)) {
        $disp_detail = $disp;
    }
    $Debuglog->add('skin_init: $disp=' . $disp, 'skins');
    // This is the main template; it may be used to display very different things.
    // Do inits depending on current $disp:
    switch ($disp) {
        case 'front':
        case 'posts':
        case 'single':
        case 'page':
        case 'terms':
        case 'download':
        case 'feedback-popup':
            // We need to load posts for this display:
            if ($disp == 'terms') {
                // Initialize the redirect param to know what page redirect after accepting of terms:
                param('redirect_to', 'url', '');
            }
            // Note: even if we request the same post as $Item above, the following will do more restrictions (dates, etc.)
            // Init the MainList object:
            init_MainList($Blog->get_setting('posts_per_page'));
            // Init post navigation
            $post_navigation = $Skin->get_post_navigation();
            if (empty($post_navigation)) {
                $post_navigation = $Blog->get_setting('post_navigation');
            }
            if (!empty($MainList) && $MainList->single_post && ($single_Item =& mainlist_get_item())) {
                // If we are currently viewing a single post
                // We assume the current user will have read the entire post and all its current comments:
                $single_Item->update_read_timestamps(true, true);
                // Restart the items list:
                $MainList->restart();
            }
            break;
        case 'search':
            // Searching post, comments and categories
            load_funcs('collections/_search.funcs.php');
            // Check previous search keywords so it can be displayed in the search input box
            param('s', 'string', '', true);
            break;
    }
    // SEO stuff & redirects if necessary:
    $seo_page_type = NULL;
    switch ($disp) {
        // CONTENT PAGES:
        case 'single':
        case 'page':
        case 'terms':
            if ($disp == 'terms' && !$Item) {
                // Wrong post ID for terms page:
                global $disp;
                $disp = '404';
                $Messages->add(sprintf(T_('Terms not found. (post ID #%s)'), get_param('p')), 'error');
                break;
            }
            if (!$preview && empty($Item)) {
                // No Item, incorrect request and incorrect state of the application, a 404 redirect should have already happened
                //debug_die( 'Invalid page URL!' );
            }
            if ($disp == 'single') {
                $seo_page_type = 'Single post page';
            } else {
                $seo_page_type = '"Page" page';
            }
            if (!$preview) {
                // Check if item has a goal to insert a hit into DB
                $Item->check_goal();
            }
            // Check if the post has 'redirected' status:
            if (!$preview && $Item->status == 'redirected' && $redir == 'yes') {
                // $redir=no here allows to force a 'single post' URL for commenting
                // Redirect to the URL specified in the post:
                $Debuglog->add('Redirecting to post URL [' . $Item->url . '].');
                header_redirect($Item->url, true, true);
            }
            // Check if we want to redirect to a canonical URL for the post
            // Please document encountered problems.
            if (!$preview && ($Blog->get_setting('canonical_item_urls') && $redir == 'yes' || $Blog->get_setting('relcanonical_item_urls'))) {
                // We want to redirect to the Item's canonical URL:
                $canonical_url = $Item->get_permanent_url('', '', '&');
                if (preg_match('|[&?](page=\\d+)|', $ReqURI, $page_param)) {
                    // A certain post page has been requested, keep only this param and discard all others:
                    $canonical_url = url_add_param($canonical_url, $page_param[1], '&');
                }
                if (preg_match('|[&?](mode=quote&[qcp]+=\\d+)|', $ReqURI, $page_param)) {
                    // A quote of comment/post, keep only these params and discard all others:
                    $canonical_url = url_add_param($canonical_url, $page_param[1], '&');
                }
                if (!is_same_url($ReqURL, $canonical_url)) {
                    // The requested URL does not look like the canonical URL for this post...
                    // url difference was resolved
                    $url_resolved = false;
                    // Check if the difference is because of an allowed post navigation param
                    if (preg_match('|[&?]cat=(\\d+)|', $ReqURI, $cat_param)) {
                        // A category post navigation param is set
                        $extended_url = '';
                        if ($post_navigation == 'same_category' && isset($cat_param[1])) {
                            // navigatie through posts from the same category
                            $category_ids = postcats_get_byID($Item->ID);
                            if (in_array($cat_param[1], $category_ids)) {
                                // cat param is one of this Item categories
                                $extended_url = $Item->add_navigation_param($canonical_url, $post_navigation, $cat_param[1], '&');
                                // Set MainList navigation target to the requested category
                                $MainList->nav_target = $cat_param[1];
                            }
                        }
                        $url_resolved = is_same_url($ReqURL, $extended_url);
                    }
                    if (preg_match('|[&?]tag=([^&A-Z]+)|', $ReqURI, $tag_param)) {
                        // A tag post navigation param is set
                        $extended_url = '';
                        if ($post_navigation == 'same_tag' && isset($tag_param[1])) {
                            // navigatie through posts from the same tag
                            $tag_names = $Item->get_tags();
                            if (in_array($tag_param[1], $tag_names)) {
                                // tag param is one of this Item tags
                                $extended_url = $Item->add_navigation_param($canonical_url, $post_navigation, $tag_param[1], '&');
                                // Set MainList navigation target to the requested tag
                                $MainList->nav_target = $tag_param[1];
                            }
                        }
                        $url_resolved = is_same_url($ReqURL, $extended_url);
                    }
                    if (!$url_resolved && $Blog->get_setting('canonical_item_urls') && $redir == 'yes' && !$Item->check_cross_post_nav('auto', $Blog->ID)) {
                        // REDIRECT TO THE CANONICAL URL:
                        $Debuglog->add('Redirecting to canonical URL [' . $canonical_url . '].');
                        header_redirect($canonical_url, true);
                    } else {
                        // Use rel="canoncial":
                        add_headline('<link rel="canonical" href="' . $canonical_url . '" />');
                    }
                    // EXITED.
                }
            }
            if (!$MainList->result_num_rows) {
                // There is nothing to display for this page, don't index it!
                $robots_index = false;
            }
            break;
        case 'download':
            if (empty($Item)) {
                // No Item, incorrect request and incorrect state of the application, a 404 redirect should have already happened
                debug_die('Invalid page URL!');
            }
            $download_link_ID = param('download', 'integer', 0);
            // Check if we can allow to download the selected file
            $LinkCache =& get_LinkCache();
            if (!(($download_Link =& $LinkCache->get_by_ID($download_link_ID, false, false)) && ($LinkItem =& $download_Link->get_LinkOwner()) && ($LinkItem->Item && $LinkItem->Item->ID == $Item->ID) && ($download_File =& $download_Link->get_File()) && $download_File->exists())) {
                // Bad request, Redirect to Item permanent url
                $Messages->add(T_('The requested file is not available for download.'), 'error');
                $canonical_url = $Item->get_permanent_url('', '', '&');
                $Debuglog->add('Redirecting to canonical URL [' . $canonical_url . '].');
                header_redirect($canonical_url, true);
            }
            // Save the downloading Link to the global vars
            $GLOBALS['download_Link'] =& $download_Link;
            // Save global $Item to $download_Item, because $Item can be rewritten by function get_featured_Item() in some skins
            $GLOBALS['download_Item'] =& $Item;
            init_ajax_forms('blog');
            // auto requires jQuery
            // Initialize JavaScript to download file after X seconds
            add_js_headline('
jQuery( document ).ready( function ()
{
	jQuery( "#download_timer_js" ).show();
} );

var b2evo_download_timer = ' . intval($Blog->get_setting('download_delay')) . ';
var downloadInterval = setInterval( function()
{
	jQuery( "#download_timer" ).html( b2evo_download_timer );
	if( b2evo_download_timer == 0 )
	{ // Stop timer and download a file
		clearInterval( downloadInterval );
		jQuery( "#download_help_url" ).show();
	}
	b2evo_download_timer--;
}, 1000 );');
            // Use meta tag to download file when JavaScript is NOT enabled
            add_headline('<meta http-equiv="refresh" content="' . intval($Blog->get_setting('download_delay')) . '; url=' . $download_Link->get_download_url(array('type' => 'action')) . '" />');
            $seo_page_type = 'Download page';
            if ($Blog->get_setting($disp . '_noindex')) {
                // We prefer robots not to index these pages:
                $robots_index = false;
            }
            break;
        case 'posts':
            init_ajax_forms('blog');
            // auto requires jQuery
            // fp> if we add this here, we have to exetnd the inner if()
            // init_ratings_js( 'blog' );
            // Get list of active filters:
            $active_filters = $MainList->get_active_filters();
            if (!empty($active_filters)) {
                // The current page is being filtered...
                if (array_diff($active_filters, array('page')) == array()) {
                    // This is just a follow "paged" page
                    $disp_detail = 'posts-next';
                    $seo_page_type = 'Next page';
                    if ($Blog->get_setting('paged_noindex')) {
                        // We prefer robots not to index category pages:
                        $robots_index = false;
                    }
                } elseif (array_diff($active_filters, array('cat_array', 'cat_modifier', 'cat_focus', 'posts', 'page')) == array()) {
                    // This is a category page
                    $disp_detail = 'posts-cat';
                    $seo_page_type = 'Category page';
                    if ($Blog->get_setting('chapter_noindex')) {
                        // We prefer robots not to index category pages:
                        $robots_index = false;
                    }
                    global $cat, $catsel;
                    if (empty($catsel) && preg_match('~^[0-9]+$~', $cat)) {
                        // We are on a single cat page:
                        // NOTE: we must have selected EXACTLY ONE CATEGORY through the cat parameter
                        // BUT: - this can resolve to including children
                        //      - selecting exactly one cat through catsel[] is NOT OK since not equivalent (will exclude children)
                        // echo 'SINGLE CAT PAGE';
                        if ($Blog->get_setting('canonical_cat_urls') && $redir == 'yes' || $Blog->get_setting('relcanonical_cat_urls')) {
                            // Check if the URL was canonical:
                            if (!isset($Chapter)) {
                                $ChapterCache =& get_ChapterCache();
                                /**
                                 * @var Chapter
                                 */
                                $Chapter =& $ChapterCache->get_by_ID($MainList->filters['cat_array'][0], false);
                            }
                            if ($Chapter) {
                                if ($Chapter->parent_ID) {
                                    // This is a sub-category page (i-e: not a level 1 category)
                                    $disp_detail = 'posts-subcat';
                                }
                                $canonical_url = $Chapter->get_permanent_url(NULL, NULL, $MainList->get_active_filter('page'), NULL, '&');
                                if (!is_same_url($ReqURL, $canonical_url)) {
                                    // fp> TODO: we're going to lose the additional params, it would be better to keep them...
                                    // fp> what additional params actually?
                                    if ($Blog->get_setting('canonical_cat_urls') && $redir == 'yes') {
                                        // REDIRECT TO THE CANONICAL URL:
                                        header_redirect($canonical_url, true);
                                    } else {
                                        // Use rel="canonical":
                                        add_headline('<link rel="canonical" href="' . $canonical_url . '" />');
                                    }
                                }
                            } else {
                                // If the requested chapter was not found display 404 page
                                $Messages->add(T_('The requested chapter was not found'));
                                global $disp;
                                $disp = '404';
                                break;
                            }
                        }
                        if ($post_navigation == 'same_category') {
                            // Category is set and post navigation should go through the same category, set navigation target param
                            $MainList->nav_target = $cat;
                        }
                    }
                } elseif (array_diff($active_filters, array('tags', 'posts', 'page')) == array()) {
                    // This is a tag page
                    $disp_detail = 'posts-tag';
                    $seo_page_type = 'Tag page';
                    if ($Blog->get_setting('tag_noindex')) {
                        // We prefer robots not to index tag pages:
                        $robots_index = false;
                    }
                    if ($Blog->get_setting('canonical_tag_urls') && $redir == 'yes' || $Blog->get_setting('relcanonical_tag_urls')) {
                        // Check if the URL was canonical:
                        $canonical_url = $Blog->gen_tag_url($MainList->get_active_filter('tags'), $MainList->get_active_filter('page'), '&');
                        if (!is_same_url($ReqURL, $canonical_url)) {
                            if ($Blog->get_setting('canonical_tag_urls') && $redir == 'yes') {
                                // REDIRECT TO THE CANONICAL URL:
                                header_redirect($canonical_url, true);
                            } else {
                                // Use rel="canoncial":
                                add_headline('<link rel="canonical" href="' . $canonical_url . '" />');
                            }
                        }
                    }
                    $tag = $MainList->get_active_filter('tags');
                    if ($post_navigation == 'same_tag' && !empty($tag)) {
                        // Tag is set and post navigation should go through the same tag, set navigation target param
                        $MainList->nav_target = $tag;
                    }
                } elseif (array_diff($active_filters, array('ymdhms', 'week', 'posts', 'page')) == array()) {
                    // This is an archive page
                    // echo 'archive page';
                    $disp_detail = 'posts-date';
                    $seo_page_type = 'Date archive page';
                    if ($Blog->get_setting('canonical_archive_urls') && $redir == 'yes' || $Blog->get_setting('relcanonical_archive_urls')) {
                        // Check if the URL was canonical:
                        $canonical_url = $Blog->gen_archive_url(substr($m, 0, 4), substr($m, 4, 2), substr($m, 6, 2), $w, '&', $MainList->get_active_filter('page'));
                        if (!is_same_url($ReqURL, $canonical_url)) {
                            if ($Blog->get_setting('canonical_archive_urls') && $redir == 'yes') {
                                // REDIRECT TO THE CANONICAL URL:
                                header_redirect($canonical_url, true);
                            } else {
                                // Use rel="canoncial":
                                add_headline('<link rel="canonical" href="' . $canonical_url . '" />');
                            }
                        }
                    }
                    if ($Blog->get_setting('archive_noindex')) {
                        // We prefer robots not to index archive pages:
                        $robots_index = false;
                    }
                } else {
                    // Other filtered pages:
                    // pre_dump( $active_filters );
                    $disp_detail = 'posts-filtered';
                    $seo_page_type = 'Other filtered page';
                    if ($Blog->get_setting('filtered_noindex')) {
                        // We prefer robots not to index other filtered pages:
                        $robots_index = false;
                    }
                }
            } elseif ($Blog->get_setting('front_disp') == 'posts') {
                // This is the default blog page only if the 'front_disp' is set to 'posts'
                $disp_detail = 'posts-default';
                $seo_page_type = 'Default page';
                if ($Blog->get_setting('default_noindex')) {
                    // We prefer robots not to index archive pages:
                    $robots_index = false;
                }
            }
            break;
        case 'search':
            $seo_page_type = 'Search page';
            if ($Blog->get_setting('filtered_noindex')) {
                // We prefer robots not to index these pages:
                $robots_index = false;
            }
            break;
            // SPECIAL FEATURE PAGES:
        // SPECIAL FEATURE PAGES:
        case 'feedback-popup':
            $seo_page_type = 'Comment popup';
            if ($Blog->get_setting($disp . '_noindex')) {
                // We prefer robots not to index these pages:
                $robots_index = false;
            }
            break;
        case 'arcdir':
            $seo_page_type = 'Date archive directory';
            if ($Blog->get_setting($disp . '_noindex')) {
                // We prefer robots not to index these pages:
                $robots_index = false;
            }
            break;
        case 'catdir':
            $seo_page_type = 'Category directory';
            if ($Blog->get_setting($disp . '_noindex')) {
                // We prefer robots not to index these pages:
                $robots_index = false;
            }
            break;
        case 'msgform':
            global $disp;
            // get expected message form type
            $msg_type = param('msg_type', 'string', '');
            // initialize
            $recipient_User = NULL;
            $Comment = NULL;
            $allow_msgform = NULL;
            // get possible params
            $recipient_id = param('recipient_id', 'integer', 0, true);
            $comment_id = param('comment_id', 'integer', 0, true);
            $post_id = param('post_id', 'integer', 0, true);
            $subject = param('subject', 'string', '');
            // try to init recipient_User
            if (!empty($recipient_id)) {
                $UserCache =& get_UserCache();
                $recipient_User =& $UserCache->get_by_ID($recipient_id);
            } elseif (!empty($comment_id)) {
                // comment id is set, try to get comment author user
                $CommentCache =& get_CommentCache();
                $Comment = $CommentCache->get_by_ID($comment_id, false);
                if ($Comment = $CommentCache->get_by_ID($comment_id, false)) {
                    $recipient_User =& $Comment->get_author_User();
                    if (empty($recipient_User) && $Comment->allow_msgform && is_email($Comment->get_author_email())) {
                        // set allow message form to email because comment author (not registered) accepts email
                        $allow_msgform = 'email';
                        param('recipient_address', 'string', $Comment->get_author_email());
                        param('recipient_name', 'string', $Comment->get_author_name());
                    }
                }
            } else {
                // Recipient was not defined, try set the blog owner as recipient
                global $Blog;
                if (empty($Blog)) {
                    // Blog is not set, this is an invalid request
                    debug_die('Invalid send message request!');
                }
                $recipient_User = $Blog->get_owner_User();
            }
            if ($recipient_User) {
                // recipient User is set
                // get_msgform_possibility returns NULL (false), only if there is no messaging option between current_User and recipient user
                $allow_msgform = $recipient_User->get_msgform_possibility();
                if ($msg_type == 'email' && $recipient_User->get_msgform_possibility(NULL, 'email') != 'email') {
                    // User doesn't want to receive email messages, Restrict if this was requested by wrong url:
                    $msg_type = '';
                }
                if ($allow_msgform == 'login') {
                    // user must login first to be able to send a message to this User
                    $disp = 'login';
                    param('action', 'string', 'req_login');
                    // override redirect to param
                    param('redirect_to', 'url', regenerate_url(), true, true);
                    if (($msg_Blog =& get_setting_Blog('msg_blog_ID')) && $Blog->ID != $msg_Blog->ID) {
                        // Redirect to special blog for messaging actions if it is defined in general settings
                        header_redirect(url_add_param($msg_Blog->get('msgformurl', array('glue' => '&')), 'redirect_to=' . rawurlencode($redirect_to), '&'));
                    }
                    $Messages->add(T_('You must log in before you can contact this user'));
                } elseif ($allow_msgform == 'PM' && check_user_status('can_be_validated')) {
                    // user is not activated
                    if ($recipient_User->accepts_email()) {
                        // recipient User accepts email allow to send email
                        $allow_msgform = 'email';
                        $msg_type = 'email';
                        $activateinfo_link = 'href="' . get_activate_info_url(NULL, '&amp;') . '"';
                        $Messages->add(sprintf(T_('You must activate your account before you can send a private message to %s. However you can send them an email if you\'d like. <a %s>More info &raquo;</a>'), $recipient_User->get('login'), $activateinfo_link), 'warning');
                    } else {
                        // Redirect to the activate info page for not activated users
                        $Messages->add(T_('You must activate your account before you can contact a user. <b>See below:</b>'));
                        header_redirect(get_activate_info_url(), 302);
                        // will have exited
                    }
                } elseif ($msg_type == 'PM' && $allow_msgform == 'email') {
                    // only email is allowed but user expect private message form
                    if (!empty($current_User) && $recipient_id == $current_User->ID) {
                        $Messages->add(T_('You cannot send a private message to yourself. However you can send yourself an email if you\'d like.'), 'warning');
                    } else {
                        $Messages->add(sprintf(T_('You cannot send a private message to %s. However you can send them an email if you\'d like.'), $recipient_User->get('login')), 'warning');
                    }
                } elseif ($msg_type != 'email' && $allow_msgform == 'PM') {
                    // private message form should be displayed, change display to create new individual thread with the given recipient user
                    // check if creating new PM is allowed
                    if (check_create_thread_limit(true)) {
                        // thread limit reached
                        header_redirect();
                        // exited here
                    }
                    global $edited_Thread, $edited_Message, $recipients_selected;
                    // Load classes
                    load_class('messaging/model/_thread.class.php', 'Thread');
                    load_class('messaging/model/_message.class.php', 'Message');
                    // Set global variable to auto define the FB autocomplete plugin field
                    $recipients_selected = array(array('id' => $recipient_User->ID, 'title' => $recipient_User->login));
                    init_tokeninput_js('blog');
                    $disp = 'threads';
                    $edited_Thread = new Thread();
                    $edited_Message = new Message();
                    $edited_Message->Thread =& $edited_Thread;
                    $edited_Thread->recipients = $recipient_User->login;
                    param('action', 'string', 'new', true);
                    param('thrdtype', 'string', 'individual', true);
                }
                if ($allow_msgform == 'email') {
                    // set recippient user param
                    set_param('recipient_id', $recipient_User->ID);
                }
            }
            if ($allow_msgform == NULL) {
                // should be Prevented by UI
                if (!empty($recipient_User)) {
                    $Messages->add(sprintf(T_('The user "%s" does not want to be contacted through the message form.'), $recipient_User->get('login')), 'error');
                } elseif (!empty($Comment)) {
                    $Messages->add(T_('This commentator does not want to get contacted through the message form.'), 'error');
                }
                $blogurl = $Blog->gen_blogurl();
                // If it was a front page request or the front page is set to 'msgform' then we must not redirect to the front page because it is forbidden for the current User
                $redirect_to = is_front_page() || $Blog->get_setting('front_disp') == 'msgform' ? url_add_param($blogurl, 'disp=403', '&') : $blogurl;
                header_redirect($redirect_to, 302);
                // exited here
            }
            if ($allow_msgform == 'PM' || $allow_msgform == 'email') {
                // Some message form is available
                // Get the suggested subject for the email:
                if (empty($subject)) {
                    // no subject provided by param:
                    global $DB;
                    if (!empty($comment_id)) {
                        // fp>TODO there should be NO SQL in this file. Make a $ItemCache->get_by_comment_ID().
                        $row = $DB->get_row('
							SELECT post_title
								FROM T_items__item, T_comments
							 WHERE comment_ID = ' . $DB->quote($comment_id) . '
								 AND post_ID = comment_item_ID');
                        if ($row) {
                            $subject = T_('Re:') . ' ' . sprintf(T_('Comment on %s'), $row->post_title);
                        }
                    }
                    if (empty($subject) && !empty($post_id)) {
                        // fp>TODO there should be NO SQL in this file. Use $ItemCache->get_by_ID.
                        $row = $DB->get_row('
								SELECT post_title
									FROM T_items__item
								 WHERE post_ID = ' . $post_id);
                        if ($row) {
                            $subject = T_('Re:') . ' ' . $row->post_title;
                        }
                    }
                }
                if ($allow_msgform == 'PM' && isset($edited_Thread)) {
                    $edited_Thread->title = $subject;
                } else {
                    param('subject', 'string', $subject, true);
                }
            }
            if (($msg_Blog =& get_setting_Blog('msg_blog_ID')) && $Blog->ID != $msg_Blog->ID) {
                // Redirect to special blog for messaging actions if it is defined in general settings
                header_redirect($msg_Blog->get('msgformurl', array('glue' => '&')));
            }
            $seo_page_type = 'Contact form';
            if ($Blog->get_setting($disp . '_noindex')) {
                // We prefer robots not to index these pages:
                $robots_index = false;
            }
            break;
        case 'messages':
        case 'contacts':
        case 'threads':
            switch ($disp) {
                case 'messages':
                    // Actions ONLY for disp=messages
                    // fp> The correct place to get thrd_ID is here, because we want it in redirect_to in case we need to ask for login.
                    $thrd_ID = param('thrd_ID', 'integer', '', true);
                    if (!is_logged_in()) {
                        // Redirect to the login page for anonymous users
                        $Messages->add(T_('You must log in to read your messages.'));
                        header_redirect(get_login_url('cannot see messages'), 302);
                        // will have exited
                    }
                    // check if user status allow to view messages
                    if (!$current_User->check_status('can_view_messages')) {
                        // user status does not allow to view messages
                        if ($current_User->check_status('can_be_validated')) {
                            // user is logged in but his/her account is not activate yet
                            $Messages->add(T_('You must activate your account before you can read & send messages. <b>See below:</b>'));
                            header_redirect(get_activate_info_url(), 302);
                            // will have exited
                        }
                        $Messages->add('You are not allowed to view Messages!');
                        header_redirect($Blog->gen_blogurl(), 302);
                        // will have exited
                    }
                    // check if user permissions allow to view messages
                    if (!$current_User->check_perm('perm_messaging', 'reply')) {
                        // Redirect to the blog url for users without messaging permission
                        $Messages->add('You are not allowed to view Messages!');
                        header_redirect($Blog->gen_blogurl(), 302);
                        // will have exited
                    }
                    if (!empty($thrd_ID)) {
                        // if this thread exists and current user is part of this thread update status because won't be any unread messages on this conversation
                        // we need to mark this early to make sure the unread message count will be correct in the evobar
                        mark_as_read_by_user($thrd_ID, $current_User->ID);
                    }
                    if (($unsaved_message_params = get_message_params_from_session()) !== NULL) {
                        // set Message and Thread saved params from Session
                        global $edited_Message, $action;
                        load_class('messaging/model/_message.class.php', 'Message');
                        $edited_Message = new Message();
                        $edited_Message->text = $unsaved_message_params['message'];
                        $edited_Message->original_text = $unsaved_message_params['message_original'];
                        $edited_Message->set_renderers($unsaved_message_params['renderers']);
                        $edited_Message->thread_ID = $thrd_ID;
                        $action = $unsaved_message_params['action'];
                    }
                    break;
                case 'contacts':
                    // Actions ONLY for disp=contacts
                    if (!is_logged_in()) {
                        // Redirect to the login page for anonymous users
                        $Messages->add(T_('You must log in to manage your contacts.'));
                        header_redirect(get_login_url('cannot see contacts'), 302);
                        // will have exited
                    }
                    if (!$current_User->check_status('can_view_contacts')) {
                        // user is logged in, but his status doesn't allow to view contacts
                        if ($current_User->check_status('can_be_validated')) {
                            // user is logged in but his/her account was not activated yet
                            // Redirect to the account activation page
                            $Messages->add(T_('You must activate your account before you can manage your contacts. <b>See below:</b>'));
                            header_redirect(get_activate_info_url(), 302);
                            // will have exited
                        }
                        // Redirect to the blog url for users without messaging permission
                        $Messages->add('You are not allowed to view Contacts!');
                        $blogurl = $Blog->gen_blogurl();
                        // If it was a front page request or the front page is set to display 'contacts' then we must not redirect to the front page because it is forbidden for the current User
                        $redirect_to = is_front_page() || $Blog->get_setting('front_disp') == 'contacts' ? url_add_param($blogurl, 'disp=403', '&') : $blogurl;
                        header_redirect($redirect_to, 302);
                    }
                    if (has_cross_country_restriction('any') && empty($current_User->ctry_ID)) {
                        // User may browse/contact other users only from the same country
                        $Messages->add(T_('Please specify your country before attempting to contact other users.'));
                        header_redirect(get_user_profile_url());
                    }
                    // Get action parameter from request:
                    $action = param_action();
                    if (!$current_User->check_perm('perm_messaging', 'reply')) {
                        // Redirect to the blog url for users without messaging permission
                        $Messages->add('You are not allowed to view Contacts!');
                        $blogurl = $Blog->gen_blogurl();
                        // If it was a front page request or the front page is set to display 'contacts' then we must not redirect to the front page because it is forbidden for the current User
                        $redirect_to = is_front_page() || $Blog->get_setting('front_disp') == 'contacts' ? url_add_param($blogurl, 'disp=403', '&') : $blogurl;
                        header_redirect($redirect_to, 302);
                        // will have exited
                    }
                    switch ($action) {
                        case 'add_user':
                            // Add user to contacts list
                            // Check that this action request is not a CSRF hacked request:
                            $Session->assert_received_crumb('messaging_contacts');
                            $user_ID = param('user_ID', 'integer', 0);
                            if ($user_ID > 0) {
                                // Add user to contacts
                                if (create_contacts_user($user_ID)) {
                                    // Add user to the group
                                    $group_ID = param('group_ID', 'string', '');
                                    if ($result = create_contacts_group_users($group_ID, $user_ID, 'group_ID_combo')) {
                                        // User has been added to the group
                                        $Messages->add(sprintf(T_('User has been added to the &laquo;%s&raquo; group.'), $result['group_name']), 'success');
                                    } else {
                                        // User has been added ONLY to the contacts list
                                        $Messages->add('User has been added to your contacts.', 'success');
                                    }
                                }
                                header_redirect($Blog->get('userurl', array('url_suffix' => 'user_ID=' . $user_ID, 'glue' => '&')));
                            }
                            break;
                        case 'unblock':
                            // Unblock user
                            // Check that this action request is not a CSRF hacked request:
                            $Session->assert_received_crumb('messaging_contacts');
                            $user_ID = param('user_ID', 'integer', 0);
                            if ($user_ID > 0) {
                                set_contact_blocked($user_ID, 0);
                                $Messages->add(T_('Contact was unblocked.'), 'success');
                            }
                            break;
                        case 'remove_user':
                            // Remove user from contacts group
                            // Check that this action request is not a CSRF hacked request:
                            $Session->assert_received_crumb('messaging_contacts');
                            $view = param('view', 'string', 'profile');
                            $user_ID = param('user_ID', 'integer', 0);
                            $group_ID = param('group_ID', 'integer', 0);
                            if ($user_ID > 0 && $group_ID > 0) {
                                // Remove user from selected group
                                if (remove_contacts_group_user($group_ID, $user_ID)) {
                                    // User has been removed from the group
                                    if ($view == 'contacts') {
                                        // Redirect to the contacts list
                                        header_redirect($Blog->get('contactsurl', array('glue' => '&')));
                                    } else {
                                        // Redirect to the user profile page
                                        header_redirect($Blog->get('userurl', array('url_suffix' => 'user_ID=' . $user_ID, 'glue' => '&')));
                                    }
                                }
                            }
                            break;
                        case 'add_group':
                            // Add users to the group
                            // Check that this action request is not a CSRF hacked request:
                            $Session->assert_received_crumb('messaging_contacts');
                            $group = param('group', 'string', '');
                            $users = param('users', 'string', '');
                            if ($result = create_contacts_group_users($group, $users)) {
                                // Users have been added to the group
                                $Messages->add(sprintf(T_('%d contacts have been added to the &laquo;%s&raquo; group.'), $result['count_users'], $result['group_name']), 'success');
                                $redirect_to = $Blog->get('contactsurl', array('glue' => '&'));
                                $item_ID = param('item_ID', 'integer', 0);
                                if ($item_ID > 0) {
                                    $redirect_to = url_add_param($redirect_to, 'item_ID=' . $item_ID, '&');
                                }
                                header_redirect($redirect_to);
                            }
                            break;
                        case 'rename_group':
                            // Rename the group
                            // Check that this action request is not a CSRF hacked request:
                            $Session->assert_received_crumb('messaging_contacts');
                            $group_ID = param('group_ID', 'integer', true);
                            if (rename_contacts_group($group_ID)) {
                                $item_ID = param('item_ID', 'integer', 0);
                                $redirect_to = url_add_param($Blog->get('contactsurl', array('glue' => '&')), 'g=' . $group_ID, '&');
                                if ($item_ID > 0) {
                                    $redirect_to = url_add_param($redirect_to, 'item_ID=' . $item_ID, '&');
                                }
                                $Messages->add(T_('The group has been renamed.'), 'success');
                                header_redirect($redirect_to);
                            }
                            break;
                        case 'delete_group':
                            // Delete the group
                            // Check that this action request is not a CSRF hacked request:
                            $Session->assert_received_crumb('messaging_contacts');
                            $group_ID = param('group_ID', 'integer', true);
                            if (delete_contacts_group($group_ID)) {
                                $item_ID = param('item_ID', 'integer', 0);
                                $redirect_to = $Blog->get('contactsurl', array('glue' => '&'));
                                if ($item_ID > 0) {
                                    $redirect_to = url_add_param($redirect_to, 'item_ID=' . $item_ID, '&');
                                }
                                $Messages->add(T_('The group has been deleted.'), 'success');
                                header_redirect($redirect_to);
                            }
                            break;
                    }
                    modules_call_method('switch_contacts_actions', array('action' => $action));
                    break;
                case 'threads':
                    // Actions ONLY for disp=threads
                    if (!is_logged_in()) {
                        // Redirect to the login page for anonymous users
                        $Messages->add(T_('You must log in to read your messages.'));
                        header_redirect(get_login_url('cannot see messages'), 302);
                        // will have exited
                    }
                    if (!$current_User->check_status('can_view_threads')) {
                        // user status does not allow to view threads
                        if ($current_User->check_status('can_be_validated')) {
                            // user is logged in but his/her account is not activate yet
                            $Messages->add(T_('You must activate your account before you can read & send messages. <b>See below:</b>'));
                            header_redirect(get_activate_info_url(), 302);
                            // will have exited
                        }
                        $Messages->add('You are not allowed to view Messages!');
                        $blogurl = $Blog->gen_blogurl();
                        // If it was a front page request or the front page is set to display 'threads' then we must not redirect to the front page because it is forbidden for the current User
                        $redirect_to = is_front_page() || $Blog->get_setting('front_disp') == 'threads' ? url_add_param($blogurl, 'disp=404', '&') : $blogurl;
                        header_redirect($redirect_to, 302);
                        // will have exited
                    }
                    if (!$current_User->check_perm('perm_messaging', 'reply')) {
                        // Redirect to the blog url for users without messaging permission
                        $Messages->add('You are not allowed to view Messages!');
                        $blogurl = $Blog->gen_blogurl();
                        // If it was a front page request or the front page is set to display 'threads' then we must not redirect to the front page because it is forbidden for the current User
                        $redirect_to = is_front_page() || $Blog->get_setting('front_disp') == 'threads' ? url_add_param($blogurl, 'disp=403', '&') : $blogurl;
                        header_redirect($redirect_to, 302);
                        // will have exited
                    }
                    $action = param('action', 'string', 'view');
                    if ($action == 'new') {
                        // Before new message form is displayed ...
                        if (has_cross_country_restriction('contact') && empty($current_User->ctry_ID)) {
                            // Cross country contact restriction is enabled, but user country is not set yet
                            $Messages->add(T_('Please specify your country before attempting to contact other users.'));
                            header_redirect(get_user_profile_url());
                        } elseif (check_create_thread_limit(true)) {
                            // don't allow to create new thread, because the new thread limit was already reached
                            set_param('action', 'view');
                        }
                    }
                    // Load classes
                    load_class('messaging/model/_thread.class.php', 'Thread');
                    load_class('messaging/model/_message.class.php', 'Message');
                    // Get action parameter from request:
                    $action = param_action('view');
                    switch ($action) {
                        case 'new':
                            // Check permission:
                            $current_User->check_perm('perm_messaging', 'reply', true);
                            global $edited_Thread, $edited_Message;
                            $edited_Thread = new Thread();
                            $edited_Message = new Message();
                            $edited_Message->Thread =& $edited_Thread;
                            modules_call_method('update_new_thread', array('Thread' => &$edited_Thread));
                            if (($unsaved_message_params = get_message_params_from_session()) !== NULL) {
                                // set Message and Thread saved params from Session
                                $edited_Message->text = $unsaved_message_params['message'];
                                $edited_Message->original_text = $unsaved_message_params['message_original'];
                                $edited_Message->set_renderers($unsaved_message_params['renderers']);
                                $edited_Thread->title = $unsaved_message_params['subject'];
                                $edited_Thread->recipients = $unsaved_message_params['thrd_recipients'];
                                $edited_Message->Thread = $edited_Thread;
                                global $thrd_recipients_array, $thrdtype, $action, $creating_success;
                                $thrd_recipients_array = $unsaved_message_params['thrd_recipients_array'];
                                $thrdtype = $unsaved_message_params['thrdtype'];
                                $action = $unsaved_message_params['action'];
                                $creating_success = !empty($unsaved_message_params['creating_success']) ? $unsaved_message_params['creating_success'] : false;
                            } else {
                                if (empty($edited_Thread->recipients)) {
                                    $edited_Thread->recipients = param('thrd_recipients', 'string', '');
                                }
                                if (empty($edited_Thread->title)) {
                                    $edited_Thread->title = param('subject', 'string', '');
                                }
                            }
                            break;
                        default:
                            // Check permission:
                            $current_User->check_perm('perm_messaging', 'reply', true);
                            break;
                    }
                    break;
            }
            // Actions for disp = messages, contacts, threads:
            if (($msg_Blog =& get_setting_Blog('msg_blog_ID')) && $Blog->ID != $msg_Blog->ID) {
                // Redirect to special blog for messaging actions if it is defined in general settings
                $blog_url_params = array('glue' => '&');
                if (!empty($thrd_ID)) {
                    // Don't forget the important param on redirect
                    $blog_url_params['url_suffix'] = 'thrd_ID=' . $thrd_ID;
                }
                header_redirect($msg_Blog->get($disp . 'url', $blog_url_params));
            }
            // just in case some robot would be logged in:
            $seo_page_type = 'Messaging module';
            $robots_index = false;
            // Display messages depending on user email status
            display_user_email_status_message();
            break;
        case 'login':
            global $Plugins, $transmit_hashed_password;
            if (is_logged_in()) {
                // User is already logged in
                if ($current_User->check_status('can_be_validated')) {
                    // account is not active yet, redirect to the account activation page
                    $Messages->add(T_('You are logged in but your account is not activated. You will find instructions about activating your account below:'));
                    header_redirect(get_activate_info_url(), 302);
                    // will have exited
                }
                // User is already logged in, redirect to "redirect_to" page
                $Messages->add(T_('You are already logged in.'), 'note');
                $redirect_to = param('redirect_to', 'url', NULL);
                if (empty($redirect_to)) {
                    // If empty redirect to referer page
                    $redirect_to = '';
                }
                header_redirect($redirect_to, 302);
                // will have exited
            }
            if (($login_Blog =& get_setting_Blog('login_blog_ID')) && $Blog->ID != $login_Blog->ID) {
                // Redirect to special blog for login/register actions if it is defined in general settings
                header_redirect($login_Blog->get('loginurl', array('glue' => '&')));
            }
            $seo_page_type = 'Login form';
            $robots_index = false;
            break;
        case 'register':
            if (is_logged_in()) {
                // If user is logged in the register form should not be displayed. In this case redirect to the blog home page.
                $Messages->add(T_('You are already logged in.'), 'note');
                header_redirect($Blog->gen_blogurl(), false);
            }
            if (($login_Blog =& get_setting_Blog('login_blog_ID')) && $Blog->ID != $login_Blog->ID) {
                // Redirect to special blog for login/register actions if it is defined in general settings
                header_redirect($login_Blog->get('registerurl', array('glue' => '&')));
            }
            $seo_page_type = 'Register form';
            $robots_index = false;
            // Check invitation code if it exists and registration is enabled
            global $display_invitation;
            $display_invitation = check_invitation_code();
            break;
        case 'lostpassword':
            if (is_logged_in()) {
                // If user is logged in the lost password form should not be displayed. In this case redirect to the blog home page.
                $Messages->add(T_('You are already logged in.'), 'note');
                header_redirect($Blog->gen_blogurl(), false);
            }
            if (($login_Blog =& get_setting_Blog('login_blog_ID')) && $Blog->ID != $login_Blog->ID) {
                // Redirect to special blog for login/register actions if it is defined in general settings
                header_redirect($login_Blog->get('lostpasswordurl', array('glue' => '&')));
            }
            $seo_page_type = 'Lost password form';
            $robots_index = false;
            break;
        case 'activateinfo':
            if (!is_logged_in()) {
                // Redirect to the login page for anonymous users
                $Messages->add(T_('You must log in before you can activate your account.'));
                header_redirect(get_login_url('cannot see messages'), 302);
                // will have exited
            }
            if (!$current_User->check_status('can_be_validated')) {
                // don't display activateinfo screen
                $after_email_validation = $Settings->get('after_email_validation');
                if ($after_email_validation == 'return_to_original') {
                    // we want to return to original page after account activation
                    // check if Session 'validatemail.redirect_to' param is still set
                    $redirect_to = $Session->get('core.validatemail.redirect_to');
                    if (empty($redirect_to)) {
                        // Session param is empty try to get general redirect_to param
                        $redirect_to = param('redirect_to', 'url', '');
                    } else {
                        // cleanup validateemail.redirect_to param from session
                        $Session->delete('core.validatemail.redirect_to');
                    }
                } else {
                    // go to after email validation url which is set in the user general settings form
                    $redirect_to = $after_email_validation;
                }
                if (empty($redirect_to) || preg_match('#disp=activateinfo#', $redirect_to)) {
                    // redirect_to is pointing to the activate info display or is empty
                    // redirect to referer page
                    $redirect_to = '';
                }
                if ($current_User->check_status('is_validated')) {
                    $Messages->add(T_('Your account has already been activated.'));
                }
                header_redirect($redirect_to, 302);
                // will have exited
            }
            if (($login_Blog =& get_setting_Blog('login_blog_ID')) && $Blog->ID != $login_Blog->ID) {
                // Redirect to special blog for login/register actions if it is defined in general settings
                header_redirect($login_Blog->get('activateinfourl', array('glue' => '&')));
            }
            break;
        case 'profile':
        case 'avatar':
            $action = param_action();
            if ($action == 'crop' && is_logged_in()) {
                // Check data for crop action:
                global $current_User, $cropped_File;
                $file_ID = param('file_ID', 'integer');
                if (!($cropped_File = $current_User->get_File_by_ID($file_ID, $error_code))) {
                    // Current user cannot crop this file
                    set_param('action', '');
                }
            }
        case 'pwdchange':
        case 'userprefs':
        case 'subs':
            $seo_page_type = 'Special feature page';
            if ($Blog->get_setting('special_noindex')) {
                // We prefer robots not to index these pages:
                $robots_index = false;
            }
            // Display messages depending on user email status
            display_user_email_status_message();
            break;
        case 'users':
            if (!is_logged_in() && !$Settings->get('allow_anonymous_user_list')) {
                // Redirect to the login page if not logged in and allow anonymous user setting is OFF
                $Messages->add(T_('You must log in to view the user directory.'));
                header_redirect(get_login_url('cannot see user'), 302);
                // will have exited
            }
            if (is_logged_in() && !check_user_status('can_view_users')) {
                // user status doesn't permit to view users list
                if (check_user_status('can_be_validated')) {
                    // user is logged in but his/her account is not active yet
                    // Redirect to the account activation page
                    $Messages->add(T_('You must activate your account before you can view the user directory. <b>See below:</b>'));
                    header_redirect(get_activate_info_url(), 302);
                    // will have exited
                }
                // set where to redirect
                $error_redirect_to = empty($Blog) ? $baseurl : $Blog->gen_blogurl();
                $Messages->add(T_('Your account status currently does not permit to view the user directory.'));
                header_redirect($error_redirect_to, 302);
                // will have exited
            }
            if (has_cross_country_restriction('users', 'list') && empty($current_User->ctry_ID)) {
                // User may browse other users only from the same country
                $Messages->add(T_('Please specify your country before attempting to contact other users.'));
                header_redirect(get_user_profile_url());
            }
            $seo_page_type = 'Users list';
            $robots_index = false;
            break;
        case 'user':
            // get user_ID because we want it in redirect_to in case we need to ask for login.
            $user_ID = param('user_ID', 'integer', '', true);
            // set where to redirect in case of error
            $error_redirect_to = empty($Blog) ? $baseurl : $Blog->gen_blogurl();
            if (!is_logged_in()) {
                // Redirect to the login page if not logged in and allow anonymous user setting is OFF
                $user_available_by_group_level = true;
                if (!empty($user_ID)) {
                    $UserCache =& get_UserCache();
                    if ($User =& $UserCache->get_by_ID($user_ID, false)) {
                        // If user exists we can check if the anonymous users have an access to view the user by group level limitation
                        $User->get_Group();
                        $user_available_by_group_level = $User->Group->level >= $Settings->get('allow_anonymous_user_level_min') && $User->Group->level <= $Settings->get('allow_anonymous_user_level_max');
                    }
                }
                if (!$Settings->get('allow_anonymous_user_profiles') || !$user_available_by_group_level || empty($user_ID)) {
                    // If this user is not available for anonymous users
                    $Messages->add(T_('You must log in to view this user profile.'));
                    header_redirect(get_login_url('cannot see user'), 302);
                    // will have exited
                }
            }
            if (is_logged_in() && !check_user_status('can_view_user', $user_ID)) {
                // user is logged in, but his/her status doesn't permit to view user profile
                if (check_user_status('can_be_validated')) {
                    // user is logged in but his/her account is not active yet
                    // Redirect to the account activation page
                    $Messages->add(T_('You must activate your account before you can view this user profile. <b>See below:</b>'));
                    header_redirect(get_activate_info_url(), 302);
                    // will have exited
                }
                $Messages->add(T_('Your account status currently does not permit to view this user profile.'));
                header_redirect($error_redirect_to, 302);
                // will have exited
            }
            if (!empty($user_ID)) {
                $UserCache =& get_UserCache();
                $User =& $UserCache->get_by_ID($user_ID, false);
                if (empty($User)) {
                    $Messages->add(T_('The requested user does not exist!'));
                    header_redirect($error_redirect_to);
                    // will have exited
                }
                if ($User->check_status('is_closed')) {
                    $Messages->add(T_('The requested user account is closed!'));
                    header_redirect($error_redirect_to);
                    // will have exited
                }
                if (has_cross_country_restriction('any')) {
                    if (empty($current_User->ctry_ID)) {
                        // Current User country is not set
                        $Messages->add(T_('Please specify your country before attempting to contact other users.'));
                        header_redirect(get_user_profile_url());
                        // will have exited
                    }
                    if (has_cross_country_restriction('users', 'profile') && $current_User->ctry_ID !== $User->ctry_ID) {
                        // Current user country is different then edited user country and cross country user browsing is not enabled.
                        $Messages->add(T_('You don\'t have permission to view this user profile.'));
                        header_redirect(url_add_param($error_redirect_to, 'disp=403', '&'));
                        // will have exited
                    }
                }
            }
            // Initialize users list from session cache in order to display prev/next links:
            // It is used to navigate between users
            load_class('users/model/_userlist.class.php', 'UserList');
            global $UserList;
            $UserList = new UserList();
            $UserList->memorize = false;
            $UserList->load_from_Request();
            $seo_page_type = 'User display';
            break;
        case 'edit':
            global $current_User, $post_ID;
            // Post ID, go from $_GET when we edit a post from Front-office
            //          or from $_POST when we switch from Back-office
            $post_ID = param('p', 'integer', empty($post_ID) ? 0 : $post_ID, true);
            if (!is_logged_in()) {
                // Redirect to the login page if not logged in and allow anonymous user setting is OFF
                $redirect_to = url_add_param($Blog->gen_blogurl(), 'disp=edit');
                $Messages->add(T_('You must log in to create & edit posts.'));
                header_redirect(get_login_url('cannot edit posts', $redirect_to), 302);
                // will have exited
            }
            if (!$current_User->check_status('can_edit_post')) {
                if ($current_User->check_status('can_be_validated')) {
                    // user is logged in but his/her account was not activated yet
                    // Redirect to the account activation page
                    $Messages->add(T_('You must activate your account before you can create & edit posts. <b>See below:</b>'));
                    header_redirect(get_activate_info_url(), 302);
                    // will have exited
                }
                // Redirect to the blog url for users without messaging permission
                $Messages->add(T_('You are not allowed to create & edit posts!'));
                header_redirect($Blog->gen_blogurl(), 302);
            }
            // user logged in and the account was activated
            check_item_perm_edit($post_ID);
            if (!blog_has_cats($Blog->ID)) {
                // No categories are in this blog
                $error_message = T_('Since this blog has no categories, you cannot post into it.');
                if ($current_User->check_perm('blog_cats', 'edit', false, $Blog->ID)) {
                    // If current user has a permission to create a category
                    global $admin_url;
                    $error_message .= ' ' . sprintf(T_('You must <a %s>create categories</a> first.'), 'href="' . $admin_url . '?ctrl=chapters&amp;blog=' . $Blog->ID . '"');
                }
                $Messages->add($error_message, 'error');
                header_redirect($Blog->gen_blogurl(), 302);
            }
            // Prepare the 'In-skin editing':
            init_inskin_editing();
            break;
        case 'edit_comment':
            global $current_User, $edited_Comment, $comment_Item, $Item, $comment_title, $comment_content, $display_params;
            // comment ID
            $comment_ID = param('c', 'integer', 0, true);
            if (!is_logged_in()) {
                // Redirect to the login page if not logged in and allow anonymous user setting is OFF
                $redirect_to = url_add_param($Blog->gen_blogurl(), 'disp=edit_comment');
                $Messages->add(T_('You must log in to edit comments.'));
                header_redirect(get_login_url('cannot edit comments', $redirect_to), 302);
                // will have exited
            }
            if (!$current_User->check_status('can_edit_comment')) {
                if ($current_User->check_status('can_be_validated')) {
                    // user is logged in but his/her account was not activated yet
                    // Redirect to the account activation page
                    $Messages->add(T_('You must activate your account before you can edit comments. <b>See below:</b>'));
                    header_redirect(get_activate_info_url(), 302);
                    // will have exited
                }
                // Redirect to the blog url for users without messaging permission
                $Messages->add('You are not allowed to edit comments!');
                header_redirect($Blog->gen_blogurl(), 302);
            }
            if (empty($comment_ID)) {
                // Can't edit a not exisiting comment
                $Messages->add('Invalid comment edit URL!');
                global $disp;
                $disp = 404;
                break;
            }
            $CommentCache =& get_CommentCache();
            $edited_Comment = $CommentCache->get_by_ID($comment_ID);
            $comment_Item = $edited_Comment->get_Item();
            if (!$current_User->check_perm('comment!CURSTATUS', 'edit', false, $edited_Comment)) {
                // If User has no permission to edit comments with this comment status:
                $Messages->add('You are not allowed to edit the previously selected comment!');
                header_redirect($Blog->gen_blogurl(), 302);
            }
            $comment_title = '';
            $comment_content = htmlspecialchars_decode($edited_Comment->content);
            // Format content for editing, if we were not already in editing...
            $Plugins_admin =& get_Plugins_admin();
            $comment_Item->load_Blog();
            $params = array('object_type' => 'Comment', 'object_Blog' => &$comment_Item->Blog);
            $Plugins_admin->unfilter_contents($comment_title, $comment_content, $edited_Comment->get_renderers_validated(), $params);
            $Item = $comment_Item;
            $display_params = array();
            break;
        case 'useritems':
        case 'usercomments':
            global $display_params, $viewed_User;
            // get user_ID because we want it in redirect_to in case we need to ask for login.
            $user_ID = param('user_ID', 'integer', true, true);
            if (empty($user_ID)) {
                bad_request_die(sprintf(T_('Parameter &laquo;%s&raquo; is required!'), 'user_ID'));
            }
            // set where to redirect in case of error
            $error_redirect_to = empty($Blog) ? $baseurl : $Blog->gen_blogurl();
            if (!is_logged_in()) {
                // Redirect to the login page if not logged in and allow anonymous user setting is OFF
                $Messages->add(T_('You must log in to view this user profile.'));
                header_redirect(get_login_url('cannot see user'), 302);
                // will have exited
            }
            if (is_logged_in() && !check_user_status('can_view_user', $user_ID)) {
                // user is logged in, but his/her status doesn't permit to view user profile
                if (check_user_status('can_be_validated')) {
                    // user is logged in but his/her account is not active yet
                    // Redirect to the account activation page
                    $Messages->add(T_('You must activate your account before you can view this user profile. <b>See below:</b>'));
                    header_redirect(get_activate_info_url(), 302);
                    // will have exited
                }
                $Messages->add(T_('Your account status currently does not permit to view this user profile.'));
                header_redirect($error_redirect_to, 302);
                // will have exited
            }
            if (!empty($user_ID)) {
                $UserCache =& get_UserCache();
                $viewed_User = $UserCache->get_by_ID($user_ID, false);
                if (empty($viewed_User)) {
                    $Messages->add(T_('The requested user does not exist!'));
                    header_redirect($error_redirect_to);
                    // will have exited
                }
                if ($viewed_User->check_status('is_closed')) {
                    $Messages->add(T_('The requested user account is closed!'));
                    header_redirect($error_redirect_to);
                    // will have exited
                }
            }
            $display_params = !empty($Skin) ? $Skin->get_template('Results') : NULL;
            if ($disp == 'useritems') {
                // Init items list
                global $user_ItemList;
                $useritems_Blog = NULL;
                $user_ItemList = new ItemList2($useritems_Blog, NULL, NULL, NULL, 'ItemCache', 'useritems_');
                $user_ItemList->load_from_Request();
                $user_ItemList->set_filters(array('authors' => $user_ID), true, true);
                $user_ItemList->query();
            } else {
                // Init comments list
                global $user_CommentList;
                $user_CommentList = new CommentList2(NULL, NULL, 'CommentCache', 'usercmts_');
                $user_CommentList->load_from_Request();
                $user_CommentList->set_filters(array('author_IDs' => $user_ID), true, true);
                $user_CommentList->query();
            }
            break;
        case 'comments':
            if (!$Blog->get_setting('comments_latest')) {
                // If latest comments page is disabled - Display 404 page with error message
                $Messages->add(T_('This feature is disabled.'), 'error');
                global $disp;
                $disp = '404';
            }
            break;
        case 'closeaccount':
            global $current_User;
            if (!$Settings->get('account_close_enabled') || is_logged_in() && $current_User->check_perm('users', 'edit', false) || !is_logged_in() && !$Session->get('account_closing_success')) {
                // If an account closing page is disabled - Display 404 page with error message
                // Don't allow admins close own accounts from front office
                // Don't display this message for not logged in users, except of one case to display a bye message after account closing
                global $disp;
                $disp = '404';
            } elseif ($Session->get('account_closing_success')) {
                // User has closed the account
                global $account_closing_success;
                $account_closing_success = $Session->get('account_closing_success');
                // Unset this temp session var to don't display the message twice
                $Session->delete('account_closing_success');
                if (is_logged_in()) {
                    // log out current User
                    logout();
                }
            }
            break;
        case 'tags':
            $seo_page_type = 'Tags';
            if ($Blog->get_setting($disp . '_noindex')) {
                // We prefer robots not to index these pages:
                $robots_index = false;
            }
            break;
    }
    $Debuglog->add('skin_init: $disp=' . $disp . ' / $disp_detail=' . $disp_detail . ' / $seo_page_type=' . $seo_page_type, 'skins');
    // Make this switch block special only for 404 page
    switch ($disp) {
        case '404':
            // We have a 404 unresolved content error
            // How do we want do deal with it?
            skin_404_header();
            // This MAY or MAY not have exited -- will exit on 30x redirect, otherwise will return here.
            // Just in case some dumb robot needs extra directives on this:
            $robots_index = false;
            break;
    }
    global $Hit, $check_browser_version;
    if ($check_browser_version && $Hit->get_browser_version() > 0 && $Hit->is_IE(9, '<')) {
        // Display info message if browser IE < 9 version and it is allowed by config var:
        global $debug;
        $Messages->add(T_('Your web browser is too old. For this site to work correctly, we recommend you use a more recent browser.'), 'note');
        if ($debug) {
            $Messages->add('User Agent: ' . $Hit->get_user_agent(), 'note');
        }
    }
    // dummy var for backward compatibility with versions < 2.4.1 -- prevents "Undefined variable"
    global $global_Cache, $credit_links;
    $credit_links = $global_Cache->get('creds');
    $Timer->pause('skin_init');
    // Check if user is logged in with a not active account, and display an error message if required
    check_allow_disp($disp);
    // initialize Blog enabled widgets, before displaying anything
    init_blog_widgets($Blog->ID);
    // Initialize displaying....
    $Timer->start('Skin:display_init');
    $Skin->display_init();
    $Timer->pause('Skin:display_init');
    // Send default headers:
    // See comments inside of this function:
    headers_content_mightcache('text/html');
    // In most situations, you do NOT want to cache dynamic content!
    // Never allow Messages to be cached!
    if ($Messages->count() && !empty($PageCache)) {
        // Abort PageCache collect
        $PageCache->abort_collect();
    }
}
Exemplo n.º 25
0
/**
 * Returns posts made by the selected user in the requested courses.
 *
 * This method can be used to return all of the posts made by the requested user
 * within the given courses.
 * For each course the access of the current user and requested user is checked
 * and then for each post access to the post and forum is checked as well.
 *
 * This function is safe to use with usercapabilities.
 *
 * @global moodle_database $DB
 * @param stdClass $user The user whose posts we want to get
 * @param array $courses The courses to search
 * @param bool $musthaveaccess If set to true errors will be thrown if the user
 *                             cannot access one or more of the courses to search
 * @param bool $discussionsonly If set to true only discussion starting posts
 *                              will be returned.
 * @param int $limitfrom The offset of records to return
 * @param int $limitnum The number of records to return
 * @return stdClass An object the following properties
 *               ->totalcount: the total number of posts made by the requested user
 *                             that the current user can see.
 *               ->courses: An array of courses the current user can see that the
 *                          requested user has posted in.
 *               ->forums: An array of forums relating to the posts returned in the
 *                         property below.
 *               ->posts: An array containing the posts to show for this request.
 */
function forum_get_posts_by_user($user, array $courses, $musthaveaccess = false, $discussionsonly = false, $limitfrom = 0, $limitnum = 50) {
    global $DB, $USER, $CFG;

    $return = new stdClass;
    $return->totalcount = 0;    // The total number of posts that the current user is able to view
    $return->courses = array(); // The courses the current user can access
    $return->forums = array();  // The forums that the current user can access that contain posts
    $return->posts = array();   // The posts to display

    // First up a small sanity check. If there are no courses to check we can
    // return immediately, there is obviously nothing to search.
    if (empty($courses)) {
        return $return;
    }

    // A couple of quick setups
    $isloggedin = isloggedin();
    $isguestuser = $isloggedin && isguestuser();
    $iscurrentuser = $isloggedin && $USER->id == $user->id;

    // Checkout whether or not the current user has capabilities over the requested
    // user and if so they have the capabilities required to view the requested
    // users content.
    $usercontext = context_user::instance($user->id, MUST_EXIST);
    $hascapsonuser = !$iscurrentuser && $DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id));
    $hascapsonuser = $hascapsonuser && has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), $usercontext);

    // Before we actually search each course we need to check the user's access to the
    // course. If the user doesn't have the appropraite access then we either throw an
    // error if a particular course was requested or we just skip over the course.
    foreach ($courses as $course) {
        $coursecontext = context_course::instance($course->id, MUST_EXIST);
        if ($iscurrentuser || $hascapsonuser) {
            // If it is the current user, or the current user has capabilities to the
            // requested user then all we need to do is check the requested users
            // current access to the course.
            // Note: There is no need to check group access or anything of the like
            // as either the current user is the requested user, or has granted
            // capabilities on the requested user. Either way they can see what the
            // requested user posted, although its VERY unlikely in the `parent` situation
            // that the current user will be able to view the posts in context.
            if (!is_viewing($coursecontext, $user) && !is_enrolled($coursecontext, $user)) {
                // Need to have full access to a course to see the rest of own info
                if ($musthaveaccess) {
                    print_error('errorenrolmentrequired', 'forum');
                }
                continue;
            }
        } else {
            // Check whether the current user is enrolled or has access to view the course
            // if they don't we immediately have a problem.
            if (!can_access_course($course)) {
                if ($musthaveaccess) {
                    print_error('errorenrolmentrequired', 'forum');
                }
                continue;
            }

            // Check whether the requested user is enrolled or has access to view the course
            // if they don't we immediately have a problem.
            if (!can_access_course($course, $user)) {
                if ($musthaveaccess) {
                    print_error('notenrolled', 'forum');
                }
                continue;
            }

            // If groups are in use and enforced throughout the course then make sure
            // we can meet in at least one course level group.
            // Note that we check if either the current user or the requested user have
            // the capability to access all groups. This is because with that capability
            // a user in group A could post in the group B forum. Grrrr.
            if (groups_get_course_groupmode($course) == SEPARATEGROUPS && $course->groupmodeforce
              && !has_capability('moodle/site:accessallgroups', $coursecontext) && !has_capability('moodle/site:accessallgroups', $coursecontext, $user->id)) {
                // If its the guest user to bad... the guest user cannot access groups
                if (!$isloggedin or $isguestuser) {
                    // do not use require_login() here because we might have already used require_login($course)
                    if ($musthaveaccess) {
                        redirect(get_login_url());
                    }
                    continue;
                }
                // Get the groups of the current user
                $mygroups = array_keys(groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid, 'g.id, g.name'));
                // Get the groups the requested user is a member of
                $usergroups = array_keys(groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name'));
                // Check whether they are members of the same group. If they are great.
                $intersect = array_intersect($mygroups, $usergroups);
                if (empty($intersect)) {
                    // But they're not... if it was a specific course throw an error otherwise
                    // just skip this course so that it is not searched.
                    if ($musthaveaccess) {
                        print_error("groupnotamember", '', $CFG->wwwroot."/course/view.php?id=$course->id");
                    }
                    continue;
                }
            }
        }
        // Woo hoo we got this far which means the current user can search this
        // this course for the requested user. Although this is only the course accessibility
        // handling that is complete, the forum accessibility tests are yet to come.
        $return->courses[$course->id] = $course;
    }
    // No longer beed $courses array - lose it not it may be big
    unset($courses);

    // Make sure that we have some courses to search
    if (empty($return->courses)) {
        // If we don't have any courses to search then the reality is that the current
        // user doesn't have access to any courses is which the requested user has posted.
        // Although we do know at this point that the requested user has posts.
        if ($musthaveaccess) {
            print_error('permissiondenied');
        } else {
            return $return;
        }
    }

    // Next step: Collect all of the forums that we will want to search.
    // It is important to note that this step isn't actually about searching, it is
    // about determining which forums we can search by testing accessibility.
    $forums = forum_get_forums_user_posted_in($user, array_keys($return->courses), $discussionsonly);

    // Will be used to build the where conditions for the search
    $forumsearchwhere = array();
    // Will be used to store the where condition params for the search
    $forumsearchparams = array();
    // Will record forums where the user can freely access everything
    $forumsearchfullaccess = array();
    // DB caching friendly
    $now = round(time(), -2);
    // For each course to search we want to find the forums the user has posted in
    // and providing the current user can access the forum create a search condition
    // for the forum to get the requested users posts.
    foreach ($return->courses as $course) {
        // Now we need to get the forums
        $modinfo = get_fast_modinfo($course);
        if (empty($modinfo->instances['forum'])) {
            // hmmm, no forums? well at least its easy... skip!
            continue;
        }
        // Iterate
        foreach ($modinfo->get_instances_of('forum') as $forumid => $cm) {
            if (!$cm->uservisible or !isset($forums[$forumid])) {
                continue;
            }
            // Get the forum in question
            $forum = $forums[$forumid];
            // This is needed for functionality later on in the forum code....
            $forum->cm = $cm;

            // Check that either the current user can view the forum, or that the
            // current user has capabilities over the requested user and the requested
            // user can view the discussion
            if (!has_capability('mod/forum:viewdiscussion', $cm->context) && !($hascapsonuser && has_capability('mod/forum:viewdiscussion', $cm->context, $user->id))) {
                continue;
            }

            // This will contain forum specific where clauses
            $forumsearchselect = array();
            if (!$iscurrentuser && !$hascapsonuser) {
                // Make sure we check group access
                if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $cm->context)) {
                    $groups = $modinfo->get_groups($cm->groupingid);
                    $groups[] = -1;
                    list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
                    $forumsearchparams = array_merge($forumsearchparams, $groupid_params);
                    $forumsearchselect[] = "d.groupid $groupid_sql";
                }

                // hidden timed discussions
                if (!empty($CFG->forum_enabletimedposts) && !has_capability('mod/forum:viewhiddentimedposts', $cm->context)) {
                    $forumsearchselect[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
                    $forumsearchparams['userid'.$forumid] = $user->id;
                    $forumsearchparams['timestart'.$forumid] = $now;
                    $forumsearchparams['timeend'.$forumid] = $now;
                }

                // qanda access
                if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $cm->context)) {
                    // We need to check whether the user has posted in the qanda forum.
                    $discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $user->id);
                    if (!empty($discussionspostedin)) {
                        $forumonlydiscussions = array();  // Holds discussion ids for the discussions the user is allowed to see in this forum.
                        foreach ($discussionspostedin as $d) {
                            $forumonlydiscussions[] = $d->id;
                        }
                        list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forumonlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
                        $forumsearchparams = array_merge($forumsearchparams, $discussionid_params);
                        $forumsearchselect[] = "(d.id $discussionid_sql OR p.parent = 0)";
                    } else {
                        $forumsearchselect[] = "p.parent = 0";
                    }

                }

                if (count($forumsearchselect) > 0) {
                    $forumsearchwhere[] = "(d.forum = :forum{$forumid} AND ".implode(" AND ", $forumsearchselect).")";
                    $forumsearchparams['forum'.$forumid] = $forumid;
                } else {
                    $forumsearchfullaccess[] = $forumid;
                }
            } else {
                // The current user/parent can see all of their own posts
                $forumsearchfullaccess[] = $forumid;
            }
        }
    }

    // If we dont have any search conditions, and we don't have any forums where
    // the user has full access then we just return the default.
    if (empty($forumsearchwhere) && empty($forumsearchfullaccess)) {
        return $return;
    }

    // Prepare a where condition for the full access forums.
    if (count($forumsearchfullaccess) > 0) {
        list($fullidsql, $fullidparams) = $DB->get_in_or_equal($forumsearchfullaccess, SQL_PARAMS_NAMED, 'fula');
        $forumsearchparams = array_merge($forumsearchparams, $fullidparams);
        $forumsearchwhere[] = "(d.forum $fullidsql)";
    }

    // Prepare SQL to both count and search.
    // We alias user.id to useridx because we forum_posts already has a userid field and not aliasing this would break
    // oracle and mssql.
    $userfields = user_picture::fields('u', null, 'useridx');
    $countsql = 'SELECT COUNT(*) ';
    $selectsql = 'SELECT p.*, d.forum, d.name AS discussionname, '.$userfields.' ';
    $wheresql = implode(" OR ", $forumsearchwhere);

    if ($discussionsonly) {
        if ($wheresql == '') {
            $wheresql = 'p.parent = 0';
        } else {
            $wheresql = 'p.parent = 0 AND ('.$wheresql.')';
        }
    }

    $sql = "FROM {forum_posts} p
            JOIN {forum_discussions} d ON d.id = p.discussion
            JOIN {user} u ON u.id = p.userid
           WHERE ($wheresql)
             AND p.userid = :userid ";
    $orderby = "ORDER BY p.modified DESC";
    $forumsearchparams['userid'] = $user->id;

    // Set the total number posts made by the requested user that the current user can see
    $return->totalcount = $DB->count_records_sql($countsql.$sql, $forumsearchparams);
    // Set the collection of posts that has been requested
    $return->posts = $DB->get_records_sql($selectsql.$sql.$orderby, $forumsearchparams, $limitfrom, $limitnum);

    // We need to build an array of forums for which posts will be displayed.
    // We do this here to save the caller needing to retrieve them themselves before
    // printing these forums posts. Given we have the forums already there is
    // practically no overhead here.
    foreach ($return->posts as $post) {
        if (!array_key_exists($post->forum, $return->forums)) {
            $return->forums[$post->forum] = $forums[$post->forum];
        }
    }

    return $return;
}
Exemplo n.º 26
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
 * @throws coding_exception
 * @throws require_login_exception
 */
function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false)
{
    global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
    // Must not redirect when byteserving already started.
    if (!empty($_SERVER['HTTP_RANGE'])) {
        $preventredirect = true;
    }
    if (AJAX_SCRIPT) {
        // We cannot redirect for AJAX scripts either.
        $preventredirect = true;
    }
    // Setup global $COURSE, themes, language and locale.
    if (!empty($courseorid)) {
        if (is_object($courseorid)) {
            $course = $courseorid;
        } else {
            if ($courseorid == SITEID) {
                $course = clone $SITE;
            } else {
                $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
            }
        }
        if ($cm) {
            if ($cm->course != $course->id) {
                throw new coding_exception('course and cm parameters in require_login() call do not match!!');
            }
            // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
            if (!$cm instanceof cm_info) {
                // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
                // db queries so this is not really a performance concern, however it is obviously
                // better if you use get_fast_modinfo to get the cm before calling this.
                $modinfo = get_fast_modinfo($course);
                $cm = $modinfo->get_cm($cm->id);
            }
        }
    } else {
        // Do not touch global $COURSE via $PAGE->set_course(),
        // the reasons is we need to be able to call require_login() at any time!!
        $course = $SITE;
        if ($cm) {
            throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
        }
    }
    // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
    // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
    // risk leading the user back to the AJAX request URL.
    if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
        $setwantsurltome = false;
    }
    // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
    if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
        if ($preventredirect) {
            throw new require_login_session_timeout_exception();
        } else {
            if ($setwantsurltome) {
                $SESSION->wantsurl = qualified_me();
            }
            redirect(get_login_url());
        }
    }
    // If the user is not even logged in yet then make sure they are.
    if (!isloggedin()) {
        if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
            if (!($guest = get_complete_user_data('id', $CFG->siteguest))) {
                // Misconfigured site guest, just redirect to login page.
                redirect(get_login_url());
                exit;
                // Never reached.
            }
            $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
            complete_user_login($guest);
            $USER->autologinguest = true;
            $SESSION->lang = $lang;
        } else {
            // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
            if ($preventredirect) {
                throw new require_login_exception('You are not logged in');
            }
            if ($setwantsurltome) {
                $SESSION->wantsurl = qualified_me();
            }
            $referer = get_local_referer(false);
            if (!empty($referer)) {
                $SESSION->fromurl = $referer;
            }
            // Give auth plugins an opportunity to authenticate or redirect to an external login page
            $authsequence = get_enabled_auth_plugins(true);
            // auths, in sequence
            foreach ($authsequence as $authname) {
                $authplugin = get_auth_plugin($authname);
                $authplugin->pre_loginpage_hook();
                if (isloggedin()) {
                    break;
                }
            }
            // If we're still not logged in then go to the login page
            if (!isloggedin()) {
                redirect(get_login_url());
                exit;
                // Never reached.
            }
        }
    }
    // Loginas as redirection if needed.
    if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
        if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
            if ($USER->loginascontext->instanceid != $course->id) {
                print_error('loginasonecourse', '', $CFG->wwwroot . '/course/view.php?id=' . $USER->loginascontext->instanceid);
            }
        }
    }
    // Check whether the user should be changing password (but only if it is REALLY them).
    if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
        $userauth = get_auth_plugin($USER->auth);
        if ($userauth->can_change_password() and !$preventredirect) {
            if ($setwantsurltome) {
                $SESSION->wantsurl = qualified_me();
            }
            if ($changeurl = $userauth->change_password_url()) {
                // Use plugin custom url.
                redirect($changeurl);
            } else {
                // Use moodle internal method.
                if (empty($CFG->loginhttps)) {
                    redirect($CFG->wwwroot . '/login/change_password.php');
                } else {
                    $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
                    redirect($wwwroot . '/login/change_password.php');
                }
            }
        } else {
            if ($userauth->can_change_password()) {
                throw new moodle_exception('forcepasswordchangenotice');
            } else {
                throw new moodle_exception('nopasswordchangeforced', 'auth');
            }
        }
    }
    // Check that the user account is properly set up. If we can't redirect to
    // edit their profile, perform just the lax check. It will allow them to
    // use filepicker on the profile edit page.
    if ($preventredirect) {
        $usernotfullysetup = user_not_fully_set_up($USER, false);
    } else {
        $usernotfullysetup = user_not_fully_set_up($USER, true);
    }
    if ($usernotfullysetup) {
        if ($preventredirect) {
            throw new moodle_exception('usernotfullysetup');
        }
        if ($setwantsurltome) {
            $SESSION->wantsurl = qualified_me();
        }
        redirect($CFG->wwwroot . '/user/edit.php?id=' . $USER->id . '&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 the global $COURSE.
        if ($cm) {
            $PAGE->set_cm($cm, $course);
            $PAGE->set_pagelayout('incourse');
        } else {
            if (!empty($courseorid)) {
                $PAGE->set_course($course);
            }
        }
        // Set accesstime or the user will appear offline which messes up messaging.
        user_accesstime_log($course->id);
        return;
    }
    // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
    if (!$USER->policyagreed and !is_siteadmin()) {
        if (!empty($CFG->sitepolicy) and !isguestuser()) {
            if ($preventredirect) {
                throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicy);
            }
            if ($setwantsurltome) {
                $SESSION->wantsurl = qualified_me();
            }
            redirect($CFG->wwwroot . '/user/policy.php');
        } else {
            if (!empty($CFG->sitepolicyguest) and isguestuser()) {
                if ($preventredirect) {
                    throw new moodle_exception('sitepolicynotagreed', 'error', '', $CFG->sitepolicyguest);
                }
                if ($setwantsurltome) {
                    $SESSION->wantsurl = qualified_me();
                }
                redirect($CFG->wwwroot . '/user/policy.php');
            }
        }
    }
    // Fetch the system context, the course context, and prefetch its child contexts.
    $sysctx = context_system::instance();
    $coursecontext = context_course::instance($course->id, MUST_EXIST);
    if ($cm) {
        $cmcontext = context_module::instance($cm->id, MUST_EXIST);
    } else {
        $cmcontext = null;
    }
    // If the site is currently under maintenance, then print a message.
    if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
        if ($preventredirect) {
            throw new require_login_exception('Maintenance in progress');
        }
        $PAGE->set_context(null);
        print_maintenance_message();
    }
    // Make sure the course itself is not hidden.
    if ($course->id == SITEID) {
        // Frontpage can not be hidden.
    } else {
        if (is_role_switched($course->id)) {
            // When switching roles ignore the hidden flag - user had to be in course to do the switch.
        } else {
            if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
                // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
                // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
                if ($preventredirect) {
                    throw new require_login_exception('Course is hidden');
                }
                $PAGE->set_context(null);
                // We need to override the navigation URL as the course won't have been added to the navigation and thus
                // the navigation will mess up when trying to find it.
                navigation_node::override_active_url(new moodle_url('/'));
                notice(get_string('coursehidden'), $CFG->wwwroot . '/');
            }
        }
    }
    // Is the user enrolled?
    if ($course->id == SITEID) {
        // Everybody is enrolled on the frontpage.
    } else {
        if (\core\session\manager::is_loggedinas()) {
            // Make sure the REAL person can access this course first.
            $realuser = \core\session\manager::get_realuser();
            if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
                if ($preventredirect) {
                    throw new require_login_exception('Invalid course login-as access');
                }
                $PAGE->set_context(null);
                echo $OUTPUT->header();
                notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot . '/');
            }
        }
        $access = false;
        if (is_role_switched($course->id)) {
            // Ok, user had to be inside this course before the switch.
            $access = true;
        } else {
            if (is_viewing($coursecontext, $USER)) {
                // Ok, no need to mess with enrol.
                $access = true;
            } else {
                if (isset($USER->enrol['enrolled'][$course->id])) {
                    if ($USER->enrol['enrolled'][$course->id] > time()) {
                        $access = true;
                        if (isset($USER->enrol['tempguest'][$course->id])) {
                            unset($USER->enrol['tempguest'][$course->id]);
                            remove_temp_course_roles($coursecontext);
                        }
                    } else {
                        // Expired.
                        unset($USER->enrol['enrolled'][$course->id]);
                    }
                }
                if (isset($USER->enrol['tempguest'][$course->id])) {
                    if ($USER->enrol['tempguest'][$course->id] == 0) {
                        $access = true;
                    } else {
                        if ($USER->enrol['tempguest'][$course->id] > time()) {
                            $access = true;
                        } else {
                            // Expired.
                            unset($USER->enrol['tempguest'][$course->id]);
                            remove_temp_course_roles($coursecontext);
                        }
                    }
                }
                if (!$access) {
                    // Cache not ok.
                    $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
                    if ($until !== false) {
                        // Active participants may always access, a timestamp in the future, 0 (always) or false.
                        if ($until == 0) {
                            $until = ENROL_MAX_TIMESTAMP;
                        }
                        $USER->enrol['enrolled'][$course->id] = $until;
                        $access = true;
                    } else {
                        $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
                        $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
                        $enrols = enrol_get_plugins(true);
                        // First ask all enabled enrol instances in course if they want to auto enrol user.
                        foreach ($instances as $instance) {
                            if (!isset($enrols[$instance->enrol])) {
                                continue;
                            }
                            // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
                            $until = $enrols[$instance->enrol]->try_autoenrol($instance);
                            if ($until !== false) {
                                if ($until == 0) {
                                    $until = ENROL_MAX_TIMESTAMP;
                                }
                                $USER->enrol['enrolled'][$course->id] = $until;
                                $access = true;
                                break;
                            }
                        }
                        // If not enrolled yet try to gain temporary guest access.
                        if (!$access) {
                            foreach ($instances as $instance) {
                                if (!isset($enrols[$instance->enrol])) {
                                    continue;
                                }
                                // Get a duration for the guest access, a timestamp in the future or false.
                                $until = $enrols[$instance->enrol]->try_guestaccess($instance);
                                if ($until !== false and $until > time()) {
                                    $USER->enrol['tempguest'][$course->id] = $until;
                                    $access = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        if (!$access) {
            if ($preventredirect) {
                throw new require_login_exception('Not enrolled');
            }
            if ($setwantsurltome) {
                $SESSION->wantsurl = qualified_me();
            }
            redirect($CFG->wwwroot . '/enrol/index.php?id=' . $course->id);
        }
    }
    // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
    if ($cm && !$cm->uservisible) {
        if ($preventredirect) {
            throw new require_login_exception('Activity is hidden');
        }
        if ($course->id != SITEID) {
            $url = new moodle_url('/course/view.php', array('id' => $course->id));
        } else {
            $url = new moodle_url('/');
        }
        redirect($url, get_string('activityiscurrentlyhidden'));
    }
    // Set the global $COURSE.
    if ($cm) {
        $PAGE->set_cm($cm, $course);
        $PAGE->set_pagelayout('incourse');
    } else {
        if (!empty($courseorid)) {
            $PAGE->set_course($course);
        }
    }
    // Finally access granted, update lastaccess times.
    user_accesstime_log($course->id);
}
Exemplo n.º 27
0
 /**
  * Checks if user can self enrol.
  *
  * @param stdClass $instance enrolment instance
  * @param bool $checkuserenrolment if true will check if user enrolment is inactive.
  *             used by navigation to improve performance.
  * @return bool|string true if successful, else error message or false.
  */
 public function can_self_enrol(stdClass $instance, $checkuserenrolment = true)
 {
     global $CFG, $DB, $OUTPUT, $USER;
     if ($checkuserenrolment) {
         if (isguestuser()) {
             // Can not enrol guest.
             return get_string('noguestaccess', 'enrol') . $OUTPUT->continue_button(get_login_url());
         }
         // Check if user is already enroled.
         if ($DB->get_record('user_enrolments', array('userid' => $USER->id, 'enrolid' => $instance->id))) {
             return get_string('canntenrol', 'enrol_self');
         }
     }
     if ($instance->status != ENROL_INSTANCE_ENABLED) {
         return get_string('canntenrol', 'enrol_self');
     }
     if ($instance->enrolstartdate != 0 and $instance->enrolstartdate > time()) {
         return get_string('canntenrolearly', 'enrol_self', userdate($instance->enrolstartdate));
     }
     if ($instance->enrolenddate != 0 and $instance->enrolenddate < time()) {
         return get_string('canntenrollate', 'enrol_self', userdate($instance->enrolenddate));
     }
     if (!$instance->customint6) {
         // New enrols not allowed.
         return get_string('canntenrol', 'enrol_self');
     }
     if ($DB->record_exists('user_enrolments', array('userid' => $USER->id, 'enrolid' => $instance->id))) {
         return get_string('canntenrol', 'enrol_self');
     }
     if ($instance->customint3 > 0) {
         // Max enrol limit specified.
         $count = $DB->count_records('user_enrolments', array('enrolid' => $instance->id));
         if ($count >= $instance->customint3) {
             // Bad luck, no more self enrolments here.
             return get_string('maxenrolledreached', 'enrol_self');
         }
     }
     if ($instance->customint5) {
         require_once "{$CFG->dirroot}/cohort/lib.php";
         if (!cohort_is_member($instance->customint5, $USER->id)) {
             $cohort = $DB->get_record('cohort', array('id' => $instance->customint5));
             if (!$cohort) {
                 return null;
             }
             $a = format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)));
             return markdown_to_html(get_string('cohortnonmemberinfo', 'enrol_self', $a));
         }
     }
     return true;
 }
Exemplo n.º 28
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;
 }
Exemplo n.º 29
0
$returnto = optional_param('returnto', null, PARAM_ALPHA);
// Code determining where to return to after save.
$cancelemailchange = optional_param('cancelemailchange', 0, PARAM_INT);
// Course id (defaults to Site).
$PAGE->set_url('/user/edit.php', array('course' => $course, 'id' => $userid));
if (!($course = $DB->get_record('course', array('id' => $course)))) {
    print_error('invalidcourseid');
}
if ($course->id != SITEID) {
    require_login($course);
} else {
    if (!isloggedin()) {
        if (empty($SESSION->wantsurl)) {
            $SESSION->wantsurl = $CFG->httpswwwroot . '/user/edit.php';
        }
        redirect(get_login_url());
    } else {
        $PAGE->set_context(context_system::instance());
    }
}
// Guest can not edit.
if (isguestuser()) {
    print_error('guestnoeditprofile');
}
// The user profile we are editing.
if (!($user = $DB->get_record('user', array('id' => $userid)))) {
    print_error('invaliduserid');
}
// Guest can not be edited.
if (isguestuser($user)) {
    print_error('guestnoeditprofile');
Exemplo n.º 30
0
    /**
     * Construct a user menu, returning HTML that can be echoed out by a
     * layout file.
     *
     * @param stdClass $user A user object, usually $USER.
     * @param bool $withlinks true if a dropdown should be built.
     * @return string HTML fragment.
     */
    public function user_menu($user = null, $withlinks = null) {
        global $USER, $CFG;
        require_once($CFG->dirroot . '/user/lib.php');

        if (is_null($user)) {
            $user = $USER;
        }

        // Note: this behaviour is intended to match that of core_renderer::login_info,
        // but should not be considered to be good practice; layout options are
        // intended to be theme-specific. Please don't copy this snippet anywhere else.
        if (is_null($withlinks)) {
            $withlinks = empty($this->page->layout_options['nologinlinks']);
        }

        // Add a class for when $withlinks is false.
        $usermenuclasses = 'usermenu';
        if (!$withlinks) {
            $usermenuclasses .= ' withoutlinks';
        }

        $returnstr = "";

        // If during initial install, return the empty return string.
        if (during_initial_install()) {
            return $returnstr;
        }

        $loginpage = $this->is_login_page();
        $loginurl = get_login_url();
        // If not logged in, show the typical not-logged-in string.
        if (!isloggedin()) {
            $returnstr = get_string('loggedinnot', 'moodle');
            if (!$loginpage) {
                $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
            }
            return html_writer::div(
                html_writer::span(
                    $returnstr,
                    'login'
                ),
                $usermenuclasses
            );

        }

        // If logged in as a guest user, show a string to that effect.
        if (isguestuser()) {
            $returnstr = get_string('loggedinasguest');
            if (!$loginpage && $withlinks) {
                $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
            }

            return html_writer::div(
                html_writer::span(
                    $returnstr,
                    'login'
                ),
                $usermenuclasses
            );
        }

        // Get some navigation opts.
        $opts = user_get_user_navigation_info($user, $this->page);

        $avatarclasses = "avatars";
        $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
        $usertextcontents = $opts->metadata['userfullname'];

        // Other user.
        if (!empty($opts->metadata['asotheruser'])) {
            $avatarcontents .= html_writer::span(
                $opts->metadata['realuseravatar'],
                'avatar realuser'
            );
            $usertextcontents = $opts->metadata['realuserfullname'];
            $usertextcontents .= html_writer::tag(
                'span',
                get_string(
                    'loggedinas',
                    'moodle',
                    html_writer::span(
                        $opts->metadata['userfullname'],
                        'value'
                    )
                ),
                array('class' => 'meta viewingas')
            );
        }

        // Role.
        if (!empty($opts->metadata['asotherrole'])) {
            $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
            $usertextcontents .= html_writer::span(
                $opts->metadata['rolename'],
                'meta role role-' . $role
            );
        }

        // User login failures.
        if (!empty($opts->metadata['userloginfail'])) {
            $usertextcontents .= html_writer::span(
                $opts->metadata['userloginfail'],
                'meta loginfailures'
            );
        }

        // MNet.
        if (!empty($opts->metadata['asmnetuser'])) {
            $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
            $usertextcontents .= html_writer::span(
                $opts->metadata['mnetidprovidername'],
                'meta mnet mnet-' . $mnet
            );
        }

        $returnstr .= html_writer::span(
            html_writer::span($usertextcontents, 'usertext') .
            html_writer::span($avatarcontents, $avatarclasses),
            'userbutton'
        );

        // Create a divider (well, a filler).
        $divider = new action_menu_filler();
        $divider->primary = false;

        $am = new action_menu();
        $am->initialise_js($this->page);
        $am->set_menu_trigger(
            $returnstr
        );
        $am->set_alignment(action_menu::TR, action_menu::BR);
        $am->set_nowrap_on_items();
        if ($withlinks) {
            $navitemcount = count($opts->navitems);
            $idx = 0;
            foreach ($opts->navitems as $key => $value) {

                switch ($value->itemtype) {
                    case 'divider':
                        // If the nav item is a divider, add one and skip link processing.
                        $am->add($divider);
                        break;

                    case 'invalid':
                        // Silently skip invalid entries (should we post a notification?).
                        break;

                    case 'link':
                        // Process this as a link item.
                        $pix = null;
                        if (isset($value->pix) && !empty($value->pix)) {
                            $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall'));
                        } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
                            $value->title = html_writer::img(
                                $value->imgsrc,
                                $value->title,
                                array('class' => 'iconsmall')
                            ) . $value->title;
                        }
                        $al = new action_menu_link_secondary(
                            $value->url,
                            $pix,
                            $value->title,
                            array('class' => 'icon')
                        );
                        $am->add($al);
                        break;
                }

                $idx++;

                // Add dividers after the first item and before the last item.
                if ($idx == 1 || $idx == $navitemcount - 1) {
                    $am->add($divider);
                }
            }
        }

        return html_writer::div(
            $this->render($am),
            $usermenuclasses
        );
    }