function get_content()
 {
     global $CFG, $USER, $DB, $OUTPUT;
     // shortcut -  only for logged in users!
     if (!isloggedin() || isguestuser()) {
         return false;
     }
     // according to start_jump_session,
     // remote users can't on-jump
     // so don't show this block to them
     if (is_mnet_remote_user($USER)) {
         if (debugging() and !empty($CFG->debugdisplay)) {
             $this->content = new stdClass();
             $this->content->footer = html_writer::tag('span', get_string('error_localusersonly', 'block_mnet_hosts'), array('class' => 'error'));
             return $this->content;
         } else {
             return '';
         }
     }
     if (!is_enabled_auth('mnet')) {
         if (debugging() and !empty($CFG->debugdisplay)) {
             $this->content = new stdClass();
             $this->content->footer = html_writer::tag('span', get_string('error_authmnetneeded', 'block_mnet_hosts'), array('class' => 'error'));
             return $this->content;
         } else {
             return '';
         }
     }
     if (!has_capability('moodle/site:mnetlogintoremote', get_context_instance(CONTEXT_SYSTEM), NULL, false)) {
         if (debugging() and !empty($CFG->debugdisplay)) {
             $this->content = new stdClass();
             $this->content->footer = html_writer::tag('span', get_string('error_roamcapabilityneeded', 'block_mnet_hosts'), array('class' => 'error'));
             return $this->content;
         } else {
             return '';
         }
     }
     if ($this->content !== NULL) {
         return $this->content;
     }
     // TODO: Test this query - it's appropriate? It works?
     // get the hosts and whether we are doing SSO with them
     $sql = "\n             SELECT DISTINCT\n                 h.id,\n                 h.name,\n                 h.wwwroot,\n                 a.name as application,\n                 a.display_name\n             FROM\n                 {mnet_host} h,\n                 {mnet_application} a,\n                 {mnet_host2service} h2s_IDP,\n                 {mnet_service} s_IDP,\n                 {mnet_host2service} h2s_SP,\n                 {mnet_service} s_SP\n             WHERE\n                 h.id <> ? AND\n                 h.id <> ? AND\n                 h.id = h2s_IDP.hostid AND\n                 h.deleted = 0 AND\n                 h.applicationid = a.id AND\n                 h2s_IDP.serviceid = s_IDP.id AND\n                 s_IDP.name = 'sso_idp' AND\n                 h2s_IDP.publish = '1' AND\n                 h.id = h2s_SP.hostid AND\n                 h2s_SP.serviceid = s_SP.id AND\n                 s_SP.name = 'sso_idp' AND\n                 h2s_SP.publish = '1'\n             ORDER BY\n                 a.display_name,\n                 h.name";
     $hosts = $DB->get_records_sql($sql, array($CFG->mnet_localhost_id, $CFG->mnet_all_hosts_id));
     $this->content = new stdClass();
     $this->content->items = array();
     $this->content->icons = array();
     $this->content->footer = '';
     if ($hosts) {
         foreach ($hosts as $host) {
             $icon = '<img src="' . $OUTPUT->pix_url('i/' . $host->application . '_host') . '"' . ' class="icon" alt="' . get_string('server', 'block_mnet_hosts') . '" />&nbsp;';
             if ($host->id == $USER->mnethostid) {
                 $this->content->items[] = "<a title=\"" . s($host->name) . "\" href=\"{$host->wwwroot}\">" . $icon . s($host->name) . "</a>";
             } else {
                 $this->content->items[] = "<a title=\"" . s($host->name) . "\" href=\"{$CFG->wwwroot}/auth/mnet/jump.php?hostid={$host->id}\">" . $icon . s($host->name) . "</a>";
             }
         }
     }
     return $this->content;
 }
 public function __sendPassword($email)
 {
     global $CFG, $DB;
     $systemcontext = context_system::instance();
     $response = new CliniqueServiceResponce();
     if (!empty($email) || !$email) {
         $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($email, '|'), 'mnethostid' => $CFG->mnet_localhost_id);
         $user = $DB->get_record_select('user', $select, $params, '*', IGNORE_MULTIPLE);
         if ($user and ($user->auth === 'nologin' or !is_enabled_auth($user->auth))) {
             // bad luck - user is not able to login, do not let them reset password
             $user = false;
             $response->response(true, 'fp_nologin');
             die;
         }
         if (!empty($user)) {
             if (is_mnet_remote_user($user)) {
                 add_to_log(-1, 'custom_webservice', 'mnet_user', null, 'Forgot password - mnet user trying to access.', 0, $user->id);
                 $response->response(true, 'cp_mnet_user');
                 die;
             }
             if (isguestuser($user)) {
                 add_to_log(-1, 'custom_webservice', 'guest_user', null, 'Forgot password - guest user credential supplied.', 0, $user->id);
                 $response->response(true, 'fp_guest');
                 die;
             }
             // make sure user is allowed to change password
             require_capability('moodle/user:changeownpassword', $systemcontext, $user->id);
             if (!ForgotPassword::__app_reset_password_and_mail($user)) {
                 add_to_log(-1, 'custom_webservice', 'trigger_mail', null, 'Forgot password - email triggering failure.', 0, $user->id);
                 $response->response(true, 'fp_email_failure');
             } else {
                 set_user_preference('auth_forcepasswordchange', true, $user->id);
                 $response->response(true, 'fp_email_success');
             }
         } else {
             $response->response(false, 'fp_no_record');
         }
     } else {
         add_to_log(-1, 'custom_webservice', 'input_parameters', null, 'Forgot password - input parameters missing.', 0, $user->id);
     }
 }
 public function __getPassword($username, $email, $old_password, $new_password)
 {
     global $CFG, $DB;
     $systemcontext = context_system::instance();
     $response = new CliniqueServiceResponce();
     if (!empty($username) && !empty($old_password) && !empty($new_password)) {
         $user = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 0, 'suspended' => 0));
         if (!empty($user)) {
             if (is_mnet_remote_user($user)) {
                 add_to_log(-1, 'custom_webservice', 'mnet_user', null, 'Change password - mnet user trying to access.', 0, $user->id);
                 $response->response(true, 'cp_mnet_user');
                 die;
             }
             if (isguestuser($user)) {
                 add_to_log(-1, 'custom_webservice', 'mnet_user', null, 'Change password - guest user credential supplied.', 0, $user->id);
                 $response->response(true, 'cp_guest');
                 die;
             }
             // make sure user is allowed to change password
             require_capability('moodle/user:changeownpassword', $systemcontext, $user->id);
             // $generatePasswordResult = generatePassword::app_validate_internal_user_password($user, $old_password);
             if (!ChangePassword::__app_validate_internal_user_password($user, $old_password)) {
                 $response->response(true, 'cp_wrong_oldpwd');
             } else {
                 $userauth = get_auth_plugin($user->auth);
                 if ($userauth->user_update_password($user, $new_password)) {
                     unset_user_preference('auth_forcepasswordchange', $user);
                     unset_user_preference('create_password', $user);
                     $response->response(false, 'cp_success');
                 } else {
                     add_to_log(-1, 'custom_webservice', 'trigger_mail', null, 'Change password - password change updation failure.', 0, $user->id);
                     $response->response(true, 'cp_failure');
                 }
             }
         } else {
             $response->response(false, 'cp_no_mail_record');
         }
     } else {
         add_to_log(-1, 'custom_webservice', 'input_parameters', null, 'Change password - input parameters missing.', 0, $user->id);
     }
 }
Example #4
0
/**
 * Create a link that allows for displaying embedded Jasper reports
 * on an HTML page
 *
 * @param   $uri        The resource id of the necessary report
 * @param   $parameters Additional parameters to be passed to the report
 * @param   $print      If true, prints iframe on page
 * @return              The HTML of the iframe containing the report
 *
 */
function embeddedreports_generate_link($uri, $parameters = array(), $print = true)
{
    global $USER;
    $parameters['elisembedded'] = 'true';
    if (!is_enabled_auth('mnet')) {
        error('mnet is disabled');
    }
    // check remote login permissions
    if (!has_capability('moodle/site:mnetlogintoremote', get_context_instance(CONTEXT_SYSTEM)) or is_mnet_remote_user($USER) or $USER->username == 'guest' or empty($USER->id)) {
        print_error('notpermittedtojump', 'mnet');
    }
    $mnet_auth = get_auth_plugin('mnet');
    // check for SSO publish permission first
    if ($mnet_auth->has_service(jasper_mnet_hostid(), 'sso_sp') == false) {
        print_error('hostnotconfiguredforsso', 'mnet');
    }
    $mnet_link = jasper_mnet_link(jasper_report_link($uri, $parameters));
    $result = '<iframe id="reportframe" name="reportframe" src="' . $mnet_link . '"></iframe>';
    if ($print) {
        echo $result;
    }
    return $result;
}
Example #5
0
}
// 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');
}
// User interests separated by commas.
$user->interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id);
// Remote users cannot be edited. We have to perform the strict
// user_not_fully_set_up() check, otherwise the remote user could end up in
// endless loop between user/view.php and herein. Note that required custom
// fields are not supported in MNet environment anyway.
if (is_mnet_remote_user($user)) {
    if (user_not_fully_set_up($user, true)) {
        $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}");
}
// Load the appropriate auth plugin.
$userauth = get_auth_plugin($user->auth);
if (!$userauth->can_edit_profile()) {
    print_error('noprofileedit', 'auth');
}
if ($editurl = $userauth->edit_profile_url()) {
    // This internal script not used.
    redirect($editurl);
}
Example #6
0
 /**
  * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
  * what can be shown/done
  *
  * @param int $courseid The current course' id
  * @param int $userid The user id to load for
  * @param string $gstitle The string to pass to get_string for the branch title
  * @return navigation_node|false
  */
 protected function generate_user_settings($courseid, $userid, $gstitle = 'usercurrentsettings')
 {
     global $DB, $CFG, $USER, $SITE;
     if ($courseid != $SITE->id) {
         if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
             $course = $this->page->course;
         } else {
             $select = context_helper::get_preload_record_columns_sql('ctx');
             $sql = "SELECT c.*, {$select}\n                          FROM {course} c\n                          JOIN {context} ctx ON c.id = ctx.instanceid\n                         WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
             $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
             $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
             context_helper::preload_from_record($course);
         }
     } else {
         $course = $SITE;
     }
     $coursecontext = context_course::instance($course->id);
     // Course context
     $systemcontext = context_system::instance();
     $currentuser = $USER->id == $userid;
     if ($currentuser) {
         $user = $USER;
         $usercontext = context_user::instance($user->id);
         // User context
     } else {
         $select = context_helper::get_preload_record_columns_sql('ctx');
         $sql = "SELECT u.*, {$select}\n                      FROM {user} u\n                      JOIN {context} ctx ON u.id = ctx.instanceid\n                     WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
         $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
         $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
         if (!$user) {
             return false;
         }
         context_helper::preload_from_record($user);
         // Check that the user can view the profile
         $usercontext = context_user::instance($user->id);
         // User context
         $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
         if ($course->id == $SITE->id) {
             if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) {
                 // Reduce possibility of "browsing" userbase at site level
                 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
                 return false;
             }
         } else {
             $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
             $userisenrolled = is_enrolled($coursecontext, $user->id, '', true);
             if (!$canviewusercourse && !$canviewuser || !$userisenrolled) {
                 return false;
             }
             $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
             if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS && !$canviewuser) {
                 // If groups are in use, make sure we can see that group (MDL-45874). That does not apply to parents.
                 if ($courseid == $this->page->course->id) {
                     $mygroups = get_fast_modinfo($this->page->course)->groups;
                 } else {
                     $mygroups = groups_get_user_groups($courseid);
                 }
                 $usergroups = groups_get_user_groups($courseid, $userid);
                 if (!array_intersect_key($mygroups[0], $usergroups[0])) {
                     return false;
                 }
             }
         }
     }
     $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
     $key = $gstitle;
     $prefurl = new moodle_url('/user/preferences.php');
     if ($gstitle != 'usercurrentsettings') {
         $key .= $userid;
         $prefurl->param('userid', $userid);
     }
     // Add a user setting branch.
     if ($gstitle == 'usercurrentsettings') {
         $dashboard = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_CONTAINER, null, 'dashboard');
         // This should be set to false as we don't want to show this to the user. It's only for generating the correct
         // breadcrumb.
         $dashboard->display = false;
         if (get_home_page() == HOMEPAGE_MY) {
             $dashboard->mainnavonly = true;
         }
         $iscurrentuser = $user->id == $USER->id;
         $baseargs = array('id' => $user->id);
         if ($course->id != $SITE->id && !$iscurrentuser) {
             $baseargs['course'] = $course->id;
             $issitecourse = false;
         } else {
             // Load all categories and get the context for the system.
             $issitecourse = true;
         }
         // Add the user profile to the dashboard.
         $profilenode = $dashboard->add(get_string('profile'), new moodle_url('/user/profile.php', array('id' => $user->id)), self::TYPE_SETTING, null, 'myprofile');
         if (!empty($CFG->navadduserpostslinks)) {
             // Add nodes for forum posts and discussions if the user can view either or both
             // There are no capability checks here as the content of the page is based
             // purely on the forums the current user has access too.
             $forumtab = $profilenode->add(get_string('forumposts', 'forum'));
             $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs), null, 'myposts');
             $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode' => 'discussions'))), null, 'mydiscussions');
         }
         // Add blog nodes.
         if (!empty($CFG->enableblogs)) {
             if (!$this->cache->cached('userblogoptions' . $user->id)) {
                 require_once $CFG->dirroot . '/blog/lib.php';
                 // Get all options for the user.
                 $options = blog_get_options_for_user($user);
                 $this->cache->set('userblogoptions' . $user->id, $options);
             } else {
                 $options = $this->cache->{'userblogoptions' . $user->id};
             }
             if (count($options) > 0) {
                 $blogs = $profilenode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER);
                 foreach ($options as $type => $option) {
                     if ($type == "rss") {
                         $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
                     } else {
                         $blogs->add($option['string'], $option['link'], self::TYPE_SETTING, null, 'blog' . $type);
                     }
                 }
             }
         }
         // Add the messages link.
         // It is context based so can appear in the user's profile and in course participants information.
         if (!empty($CFG->messaging)) {
             $messageargs = array('user1' => $USER->id);
             if ($USER->id != $user->id) {
                 $messageargs['user2'] = $user->id;
             }
             if ($course->id != $SITE->id) {
                 $messageargs['viewing'] = MESSAGE_VIEW_COURSE . $course->id;
             }
             $url = new moodle_url('/message/index.php', $messageargs);
             $dashboard->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages');
         }
         // Add the "My private files" link.
         // This link doesn't have a unique display for course context so only display it under the user's profile.
         if ($issitecourse && $iscurrentuser && has_capability('moodle/user:manageownfiles', $usercontext)) {
             $url = new moodle_url('/user/files.php');
             $dashboard->add(get_string('privatefiles'), $url, self::TYPE_SETTING);
         }
         // Add a node to view the users notes if permitted.
         if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $coursecontext)) {
             $url = new moodle_url('/notes/index.php', array('user' => $user->id));
             if ($coursecontext->instanceid != SITEID) {
                 $url->param('course', $coursecontext->instanceid);
             }
             $profilenode->add(get_string('notes', 'notes'), $url);
         }
         // Show the grades node.
         if ($issitecourse && $iscurrentuser || has_capability('moodle/user:viewdetails', $usercontext)) {
             require_once $CFG->dirroot . '/user/lib.php';
             // Set the grades node to link to the "Grades" page.
             if ($course->id == SITEID) {
                 $url = user_mygrades_url($user->id, $course->id);
             } else {
                 // Otherwise we are in a course and should redirect to the user grade report (Activity report version).
                 $url = new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $user->id));
             }
             $dashboard->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'mygrades');
         }
         // Let plugins hook into user navigation.
         $pluginsfunction = get_plugins_with_function('extend_navigation_user', 'lib.php');
         foreach ($pluginsfunction as $plugintype => $plugins) {
             if ($plugintype != 'report') {
                 foreach ($plugins as $pluginfunction) {
                     $pluginfunction($profilenode, $user, $usercontext, $course, $coursecontext);
                 }
             }
         }
         $usersetting = navigation_node::create(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
         $dashboard->add_node($usersetting);
     } else {
         $usersetting = $this->add(get_string('preferences', 'moodle'), $prefurl, self::TYPE_CONTAINER, null, $key);
         $usersetting->display = false;
     }
     $usersetting->id = 'usersettings';
     // Check if the user has been deleted.
     if ($user->deleted) {
         if (!has_capability('moodle/user:update', $coursecontext)) {
             // We can't edit the user so just show the user deleted message.
             $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
         } else {
             // We can edit the user so show the user deleted message and link it to the profile.
             if ($course->id == $SITE->id) {
                 $profileurl = new moodle_url('/user/profile.php', array('id' => $user->id));
             } else {
                 $profileurl = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $course->id));
             }
             $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
         }
         return true;
     }
     $userauthplugin = false;
     if (!empty($user->auth)) {
         $userauthplugin = get_auth_plugin($user->auth);
     }
     $useraccount = $usersetting->add(get_string('useraccount'), null, self::TYPE_CONTAINER, null, 'useraccount');
     // Add the profile edit link.
     if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
             $url = new moodle_url('/user/editadvanced.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
         } else {
             if (has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user) || $currentuser && has_capability('moodle/user:editownprofile', $systemcontext)) {
                 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
                     $url = $userauthplugin->edit_profile_url();
                     if (empty($url)) {
                         $url = new moodle_url('/user/edit.php', array('id' => $user->id, 'course' => $course->id));
                     }
                     $useraccount->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
                 }
             }
         }
     }
     // Change password link.
     if ($userauthplugin && $currentuser && !\core\session\manager::is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
         $passwordchangeurl = $userauthplugin->change_password_url();
         if (empty($passwordchangeurl)) {
             $passwordchangeurl = new moodle_url('/login/change_password.php', array('id' => $course->id));
         }
         $useraccount->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING, null, 'changepassword');
     }
     if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
             $url = new moodle_url('/user/language.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('preferredlanguage'), $url, self::TYPE_SETTING, null, 'preferredlanguage');
         }
     }
     $pluginmanager = core_plugin_manager::instance();
     $enabled = $pluginmanager->get_enabled_plugins('mod');
     if (isset($enabled['forum']) && isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
             $url = new moodle_url('/user/forum.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('forumpreferences'), $url, self::TYPE_SETTING);
         }
     }
     $editors = editors_get_enabled();
     if (count($editors) > 1) {
         if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
             if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
                 $url = new moodle_url('/user/editor.php', array('id' => $user->id, 'course' => $course->id));
                 $useraccount->add(get_string('editorpreferences'), $url, self::TYPE_SETTING);
             }
         }
     }
     // Add "Course preferences" link.
     if (isloggedin() && !isguestuser($user)) {
         if ($currentuser && has_capability('moodle/user:editownprofile', $systemcontext) || has_capability('moodle/user:editprofile', $usercontext)) {
             $url = new moodle_url('/user/course.php', array('id' => $user->id, 'course' => $course->id));
             $useraccount->add(get_string('coursepreferences'), $url, self::TYPE_SETTING, null, 'coursepreferences');
         }
     }
     // View the roles settings.
     if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:manage'), $usercontext)) {
         $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
         $url = new moodle_url('/admin/roles/usersroles.php', array('userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
         $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
         if (!empty($assignableroles)) {
             $url = new moodle_url('/admin/roles/assign.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
         }
         if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH)) > 0) {
             $url = new moodle_url('/admin/roles/permissions.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
         }
         $url = new moodle_url('/admin/roles/check.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
     }
     // Repositories.
     if (!$this->cache->cached('contexthasrepos' . $usercontext->id)) {
         require_once $CFG->dirroot . '/repository/lib.php';
         $editabletypes = repository::get_editable_types($usercontext);
         $haseditabletypes = !empty($editabletypes);
         unset($editabletypes);
         $this->cache->set('contexthasrepos' . $usercontext->id, $haseditabletypes);
     } else {
         $haseditabletypes = $this->cache->{'contexthasrepos' . $usercontext->id};
     }
     if ($haseditabletypes) {
         $repositories = $usersetting->add(get_string('repositories', 'repository'), null, self::TYPE_SETTING);
         $repositories->add(get_string('manageinstances', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id)));
     }
     // Portfolio.
     if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
         require_once $CFG->libdir . '/portfoliolib.php';
         if (portfolio_has_visible_instances()) {
             $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfolio.php', array('courseid' => $course->id));
             $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfoliologs.php', array('courseid' => $course->id));
             $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
         }
     }
     $enablemanagetokens = false;
     if (!empty($CFG->enablerssfeeds)) {
         $enablemanagetokens = true;
     } else {
         if (!is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', context_system::instance())) {
             $enablemanagetokens = true;
         }
     }
     // Security keys.
     if ($currentuser && $enablemanagetokens) {
         $url = new moodle_url('/user/managetoken.php', array('sesskey' => sesskey()));
         $useraccount->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
     }
     // Messaging.
     if ($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext) || !isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id)) {
         $url = new moodle_url('/message/edit.php', array('id' => $user->id));
         $useraccount->add(get_string('messaging', 'message'), $url, self::TYPE_SETTING);
     }
     // Blogs.
     if ($currentuser && !empty($CFG->enableblogs)) {
         $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
         if (has_capability('moodle/blog:view', $systemcontext)) {
             $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
         }
         if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', $systemcontext)) {
             $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
             $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
         }
         // Remove the blog node if empty.
         $blog->trim_if_empty();
     }
     // Badges.
     if ($currentuser && !empty($CFG->enablebadges)) {
         $badges = $usersetting->add(get_string('badges'), null, navigation_node::TYPE_CONTAINER, null, 'badges');
         if (has_capability('moodle/badges:manageownbadges', $usercontext)) {
             $url = new moodle_url('/badges/mybadges.php');
             $badges->add(get_string('managebadges', 'badges'), $url, self::TYPE_SETTING);
         }
         $badges->add(get_string('preferences', 'badges'), new moodle_url('/badges/preferences.php'), navigation_node::TYPE_SETTING);
         if (!empty($CFG->badges_allowexternalbackpack)) {
             $badges->add(get_string('backpackdetails', 'badges'), new moodle_url('/badges/mybackpack.php'), navigation_node::TYPE_SETTING);
         }
     }
     // Let plugins hook into user settings navigation.
     $pluginsfunction = get_plugins_with_function('extend_navigation_user_settings', 'lib.php');
     foreach ($pluginsfunction as $plugintype => $plugins) {
         foreach ($plugins as $pluginfunction) {
             $pluginfunction($usersetting, $user, $usercontext, $course, $coursecontext);
         }
     }
     return $usersetting;
 }
Example #7
0
} else {
    // Editing existing user.
    require_capability('moodle/user:update', $systemcontext);
    $user = $DB->get_record('user', array('id' => $id), '*', MUST_EXIST);
    $PAGE->set_context(context_user::instance($user->id));
    $PAGE->navbar->includesettingsbase = true;
    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();
        }
    }
}
// Remote users cannot be edited.
if ($user->id != -1 and is_mnet_remote_user($user)) {
    redirect($CFG->wwwroot . "/user/view.php?id={$id}&course={$course->id}");
}
if ($user->id != $USER->id and is_siteadmin($user) and !is_siteadmin($USER)) {
    // Only admins may edit other admins.
    print_error('useradmineditadmin');
}
if (isguestuser($user->id)) {
    // The real guest user can not be edited.
    print_error('guestnoeditprofileother');
}
if ($user->deleted) {
    echo $OUTPUT->header();
    echo $OUTPUT->heading(get_string('userdeleted'));
    echo $OUTPUT->footer();
    die;
 /**
  * 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;
 }
Example #9
0
/**
 * Send an email to a specified user
 *
 * @param stdClass $user  A {@link $USER} object
 * @param stdClass $from A {@link $USER} object
 * @param string $subject plain text subject line of the email
 * @param string $messagetext plain text version of the message
 * @param string $messagehtml complete html version of the message (optional)
 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
 * @param string $attachname the name of the file (extension indicates MIME)
 * @param bool $usetrueaddress determines whether $from email address should
 *          be sent out. Will be overruled by user profile setting for maildisplay
 * @param string $replyto Email address to reply to
 * @param string $replytoname Name of reply to recipient
 * @param int $wordwrapwidth custom word wrap width, default 79
 * @return bool Returns true if mail was sent OK and false if there was an error.
 */
function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '', $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79)
{
    global $CFG;
    if (empty($user) or empty($user->id)) {
        debugging('Can not send email to null user', DEBUG_DEVELOPER);
        return false;
    }
    if (empty($user->email)) {
        debugging('Can not send email to user without email: ' . $user->id, DEBUG_DEVELOPER);
        return false;
    }
    if (!empty($user->deleted)) {
        debugging('Can not send email to deleted user: '******'BEHAT_SITE_RUNNING')) {
        // Fake email sending in behat.
        return true;
    }
    if (!empty($CFG->noemailever)) {
        // Hidden setting for development sites, set in config.php if needed.
        debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
        return true;
    }
    if (!empty($CFG->divertallemailsto)) {
        $subject = "[DIVERTED {$user->email}] {$subject}";
        $user = clone $user;
        $user->email = $CFG->divertallemailsto;
    }
    // Skip mail to suspended users.
    if (isset($user->auth) && $user->auth == 'nologin' or isset($user->suspended) && $user->suspended) {
        return true;
    }
    if (!validate_email($user->email)) {
        // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
        debugging("email_to_user: User {$user->id} (" . fullname($user) . ") email ({$user->email}) is invalid! Not sending.");
        return false;
    }
    if (over_bounce_threshold($user)) {
        debugging("email_to_user: User {$user->id} (" . fullname($user) . ") is over bounce threshold! Not sending.");
        return false;
    }
    // TLD .invalid  is specifically reserved for invalid domain names.
    // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
    if (substr($user->email, -8) == '.invalid') {
        debugging("email_to_user: User {$user->id} (" . fullname($user) . ") email domain ({$user->email}) is invalid! Not sending.");
        return true;
        // This is not an error.
    }
    // If the user is a remote mnet user, parse the email text for URL to the
    // wwwroot and modify the url to direct the user's browser to login at their
    // home site (identity provider - idp) before hitting the link itself.
    if (is_mnet_remote_user($user)) {
        require_once $CFG->dirroot . '/mnet/lib.php';
        $jumpurl = mnet_get_idp_jump_url($user);
        $callback = partial('mnet_sso_apply_indirection', $jumpurl);
        $messagetext = preg_replace_callback("%({$CFG->wwwroot}[^[:space:]]*)%", $callback, $messagetext);
        $messagehtml = preg_replace_callback("%href=[\"'`]({$CFG->wwwroot}[\\w_:\\?=#&@/;.~-]*)[\"'`]%", $callback, $messagehtml);
    }
    $mail = get_mailer();
    if (!empty($mail->SMTPDebug)) {
        echo '<pre>' . "\n";
    }
    $temprecipients = array();
    $tempreplyto = array();
    $supportuser = core_user::get_support_user();
    // Make up an email address for handling bounces.
    if (!empty($CFG->handlebounces)) {
        $modargs = 'B' . base64_encode(pack('V', $user->id)) . substr(md5($user->email), 0, 16);
        $mail->Sender = generate_email_processing_address(0, $modargs);
    } else {
        $mail->Sender = $supportuser->email;
    }
    if (!empty($CFG->emailonlyfromnoreplyaddress)) {
        $usetrueaddress = false;
        if (empty($replyto) && $from->maildisplay) {
            $replyto = $from->email;
            $replytoname = fullname($from);
        }
    }
    if (is_string($from)) {
        // So we can pass whatever we want if there is need.
        $mail->From = $CFG->noreplyaddress;
        $mail->FromName = $from;
    } else {
        if ($usetrueaddress and $from->maildisplay) {
            $mail->From = $from->email;
            $mail->FromName = fullname($from);
        } else {
            $mail->From = $CFG->noreplyaddress;
            $mail->FromName = fullname($from);
            if (empty($replyto)) {
                $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
            }
        }
    }
    if (!empty($replyto)) {
        $tempreplyto[] = array($replyto, $replytoname);
    }
    $mail->Subject = substr($subject, 0, 900);
    $temprecipients[] = array($user->email, fullname($user));
    // Set word wrap.
    $mail->WordWrap = $wordwrapwidth;
    if (!empty($from->customheaders)) {
        // Add custom headers.
        if (is_array($from->customheaders)) {
            foreach ($from->customheaders as $customheader) {
                $mail->addCustomHeader($customheader);
            }
        } else {
            $mail->addCustomHeader($from->customheaders);
        }
    }
    if (!empty($from->priority)) {
        $mail->Priority = $from->priority;
    }
    if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
        // Don't ever send HTML to users who don't want it.
        $mail->isHTML(true);
        $mail->Encoding = 'quoted-printable';
        $mail->Body = $messagehtml;
        $mail->AltBody = "\n{$messagetext}\n";
    } else {
        $mail->IsHTML(false);
        $mail->Body = "\n{$messagetext}\n";
    }
    if ($attachment && $attachname) {
        if (preg_match("~\\.\\.~", $attachment)) {
            // Security check for ".." in dir path.
            $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
            $mail->addStringAttachment('Error in attachment.  User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
        } else {
            require_once $CFG->libdir . '/filelib.php';
            $mimetype = mimeinfo('type', $attachname);
            $attachmentpath = $attachment;
            // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
            $attachpath = str_replace('\\', '/', $attachmentpath);
            // Make sure both variables are normalised before comparing.
            $temppath = str_replace('\\', '/', $CFG->tempdir);
            // If the attachment is a full path to a file in the tempdir, use it as is,
            // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
            if (strpos($attachpath, realpath($temppath)) !== 0) {
                $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
            }
            $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
        }
    }
    // Check if the email should be sent in an other charset then the default UTF-8.
    if (!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset)) {
        // Use the defined site mail charset or eventually the one preferred by the recipient.
        $charset = $CFG->sitemailcharset;
        if (!empty($CFG->allowusermailcharset)) {
            if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
                $charset = $useremailcharset;
            }
        }
        // Convert all the necessary strings if the charset is supported.
        $charsets = get_list_of_charsets();
        unset($charsets['UTF-8']);
        if (in_array($charset, $charsets)) {
            $mail->CharSet = $charset;
            $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
            $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
            $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
            $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
            foreach ($temprecipients as $key => $values) {
                $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
            }
            foreach ($tempreplyto as $key => $values) {
                $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
            }
        }
    }
    foreach ($temprecipients as $values) {
        $mail->addAddress($values[0], $values[1]);
    }
    foreach ($tempreplyto as $values) {
        $mail->addReplyTo($values[0], $values[1]);
    }
    if ($mail->send()) {
        set_send_count($user);
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return true;
    } else {
        // Trigger event for failing to send email.
        $event = \core\event\email_failed::create(array('context' => context_system::instance(), 'userid' => $from->id, 'relateduserid' => $user->id, 'other' => array('subject' => $subject, 'message' => $messagetext, 'errorinfo' => $mail->ErrorInfo)));
        $event->trigger();
        if (CLI_SCRIPT) {
            mtrace('Error: lib/moodlelib.php email_to_user(): ' . $mail->ErrorInfo);
        }
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return false;
    }
}
Example #10
0
         if (!empty($user->suspended)) {
             $suspendbutton = "<a href=\"editusers.php?unsuspend={$user->id}&amp;sesskey=" . sesskey() . "\">{$strunsuspend}</a>";
         } else {
             $suspendbutton = "<a href=\"editusers.php?suspend={$user->id}&amp;sesskey=" . sesskey() . "\">{$strsuspend}</a>";
         }
     } else {
         $deletebutton = "";
         $suspendbutton = "";
     }
 }
 if ((iomad::has_capability('block/iomad_company_admin:editusers', $systemcontext) or iomad::has_capability('block/iomad_company_admin:editallusers', $systemcontext)) and ($user->id == $USER->id or $user->id != $mainadmin->id) and !is_mnet_remote_user($user)) {
     $editbutton = "<a href=\"{$securewwwroot}/blocks/iomad_company_admin/editadvanced.php?id={$user->id}\">{$stredit}</a>";
 } else {
     $editbutton = "";
 }
 if ((iomad::has_capability('block/iomad_company_admin:company_course_users', $systemcontext) or iomad::has_capability('block/iomad_company_admin:editallusers', $systemcontext)) and ($user->id == $USER->id or $user->id != $mainadmin->id) and !is_mnet_remote_user($user)) {
     $enrolmentbutton = "<a href=\"company_users_course_form.php?userid={$user->id}\">{$strenrolment}</a>";
 } else {
     $enrolmentbutton = "";
 }
 if ($user->lastaccess) {
     $strlastaccess = format_time(time() - $user->lastaccess);
 } else {
     $strlastaccess = get_string('never');
 }
 $fullname = fullname($user, true);
 // Is this a suspended user?
 if (!empty($user->suspended)) {
     $fullname .= " (S)";
 }
 // Get the users department.
Example #11
0
 /**
  * Extend the form definition after data has been parsed.
  */
 public function definition_after_data()
 {
     global $USER, $CFG, $DB, $OUTPUT;
     $mform = $this->_form;
     // Trim required name fields.
     foreach (useredit_get_required_name_fields() as $field) {
         $mform->applyFilter($field, 'trim');
     }
     if ($userid = $mform->getElementValue('id')) {
         $user = $DB->get_record('user', array('id' => $userid));
     } else {
         $user = false;
     }
     // User can not change own auth method.
     if ($userid == $USER->id) {
         $mform->hardFreeze('auth');
         $mform->hardFreeze('preference_auth_forcepasswordchange');
     }
     // Admin must choose some password and supply correct email.
     if (!empty($USER->newadminuser)) {
         $mform->addRule('newpassword', get_string('required'), 'required', null, 'client');
         if ($mform->elementExists('suspended')) {
             $mform->removeElement('suspended');
         }
     }
     // Require password for new users.
     if ($userid > 0) {
         if ($mform->elementExists('createpassword')) {
             $mform->removeElement('createpassword');
         }
     }
     if ($user and is_mnet_remote_user($user)) {
         // Only local accounts can be suspended.
         if ($mform->elementExists('suspended')) {
             $mform->removeElement('suspended');
         }
     }
     if ($user and ($user->id == $USER->id or is_siteadmin($user))) {
         // Prevent self and admin mess ups.
         if ($mform->elementExists('suspended')) {
             $mform->hardFreeze('suspended');
         }
     }
     // Print picture.
     if (empty($USER->newadminuser)) {
         if ($user) {
             $context = context_user::instance($user->id, MUST_EXIST);
             $fs = get_file_storage();
             $hasuploadedpicture = $fs->file_exists($context->id, 'user', 'icon', 0, '/', 'f2.png') || $fs->file_exists($context->id, 'user', 'icon', 0, '/', 'f2.jpg');
             if (!empty($user->picture) && $hasuploadedpicture) {
                 $imagevalue = $OUTPUT->user_picture($user, array('courseid' => SITEID, 'size' => 64));
             } else {
                 $imagevalue = get_string('none');
             }
         } else {
             $imagevalue = get_string('none');
         }
         $imageelement = $mform->getElement('currentpicture');
         $imageelement->setValue($imagevalue);
         if ($user && $mform->elementExists('deletepicture') && !$hasuploadedpicture) {
             $mform->removeElement('deletepicture');
         }
     }
     // Next the customisable profile fields.
     profile_definition_after_data($mform, $userid);
 }
Example #12
0
 /**
  * Show current user forum subscription info
  * Show link to change profile email preferences (if allowed to change profile)
  * @param $context context_module
  * @return string output html
  */
 public function render_subscribe_info($context)
 {
     global $USER;
     $output = '';
     $link = '';
     $course = $context->get_course_context(true)->instanceid;
     $userauthplugin = false;
     if (!empty($USER->auth)) {
         $userauthplugin = get_auth_plugin($USER->auth);
     }
     // Add the profile edit link (partial copy from navigationlib).
     if (isloggedin() && !isguestuser($USER) && !is_mnet_remote_user($USER)) {
         if (has_capability('moodle/user:editownprofile', $context)) {
             if ($userauthplugin && $userauthplugin->can_edit_profile()) {
                 $url = $userauthplugin->edit_profile_url();
                 if (empty($url)) {
                     $url = new moodle_url('/user/edit.php', array('id' => $USER->id, 'course' => $course));
                 }
                 $link = ' (' . html_writer::link($url, get_string('subscribestate_info_link', 'forumng')) . ')';
             }
         }
     }
     $output = get_string('subscribestate_info', 'forumng', $link);
     $info = ' ';
     switch ($USER->maildigest) {
         case 0:
             $info .= get_string('emaildigestoff');
             break;
         case 1:
             $info .= get_string('emaildigestcomplete');
             break;
         case 2:
             $info .= get_string('emaildigestsubjects');
             break;
     }
     $info .= ', ';
     switch ($USER->mailformat) {
         case 0:
             $info .= get_string('textformat');
             break;
         case 1:
             $info .= get_string('htmlformat');
             break;
     }
     $infodiv = html_writer::span($info, 'forumng_subinfo_mail');
     return html_writer::div($output . $infodiv, 'forumng_subinfo');
 }
Example #13
0
 /**
  * Starts an RPC jump session and returns the jump redirect URL.
  */
 function start_jump_session($mnethostid, $wantsurl)
 {
     global $CFG;
     global $USER;
     global $MNET;
     require_once $CFG->dirroot . '/mnet/xmlrpc/client.php';
     // check remote login permissions
     if (!has_capability('moodle/site:mnetlogintoremote', get_context_instance(CONTEXT_SYSTEM)) or is_mnet_remote_user($USER) or $USER->username == 'guest' or empty($USER->id)) {
         print_error('notpermittedtojump', 'mnet');
     }
     // check for SSO publish permission first
     if ($this->has_service($mnethostid, 'sso_sp') == false) {
         print_error('hostnotconfiguredforsso', 'mnet');
     }
     // set RPC timeout to 30 seconds if not configured
     // TODO: Is this needed/useful/problematic?
     if (empty($this->config->rpc_negotiation_timeout)) {
         set_config('rpc_negotiation_timeout', '30', 'auth/mnet');
     }
     // get the host info
     $mnet_peer = new mnet_peer();
     $mnet_peer->set_id($mnethostid);
     // set up the session
     $mnet_session = get_record('mnet_session', 'userid', $USER->id, 'mnethostid', $mnethostid, 'useragent', sha1($_SERVER['HTTP_USER_AGENT']));
     if ($mnet_session == false) {
         $mnet_session = new object();
         $mnet_session->mnethostid = $mnethostid;
         $mnet_session->userid = $USER->id;
         $mnet_session->username = $USER->username;
         $mnet_session->useragent = sha1($_SERVER['HTTP_USER_AGENT']);
         $mnet_session->token = $this->generate_token();
         $mnet_session->confirm_timeout = time() + $this->config->rpc_negotiation_timeout;
         $mnet_session->expires = time() + (int) ini_get('session.gc_maxlifetime');
         $mnet_session->session_id = session_id();
         if (!($mnet_session->id = insert_record('mnet_session', addslashes_recursive($mnet_session)))) {
             print_error('databaseerror', 'mnet');
         }
     } else {
         $mnet_session->useragent = sha1($_SERVER['HTTP_USER_AGENT']);
         $mnet_session->token = $this->generate_token();
         $mnet_session->confirm_timeout = time() + $this->config->rpc_negotiation_timeout;
         $mnet_session->expires = time() + (int) ini_get('session.gc_maxlifetime');
         $mnet_session->session_id = session_id();
         if (false == update_record('mnet_session', addslashes_recursive($mnet_session))) {
             print_error('databaseerror', 'mnet');
         }
     }
     // construct the redirection URL
     //$transport = mnet_get_protocol($mnet_peer->transport);
     $wantsurl = urlencode($wantsurl);
     $url = "{$mnet_peer->wwwroot}{$mnet_peer->application->sso_land_url}?token={$mnet_session->token}&idp={$MNET->wwwroot}&wantsurl={$wantsurl}";
     return $url;
 }
Example #14
0
 /**
  * Update or delete the user picture in the site
  *
  * @param  int  $draftitemid id of the user draft file to use as image
  * @param  bool $delete      if we should delete the user picture
  * @param  int $userid       id of the user, 0 for current user
  * @return array warnings and success status
  * @since Moodle 3.2
  * @throws moodle_exception
  */
 public static function update_picture($draftitemid, $delete = false, $userid = 0)
 {
     global $CFG, $USER, $PAGE;
     $params = self::validate_parameters(self::update_picture_parameters(), array('draftitemid' => $draftitemid, 'delete' => $delete, 'userid' => $userid));
     $context = context_system::instance();
     self::validate_context($context);
     if (!empty($CFG->disableuserimages)) {
         throw new moodle_exception('userimagesdisabled', 'admin');
     }
     if (empty($params['userid']) or $params['userid'] == $USER->id) {
         $user = $USER;
         require_capability('moodle/user:editownprofile', $context);
     } else {
         $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
         core_user::require_active_user($user);
         $personalcontext = context_user::instance($user->id);
         require_capability('moodle/user:editprofile', $personalcontext);
         if (is_siteadmin($user) and !is_siteadmin($USER)) {
             // Only admins may edit other admins.
             throw new moodle_exception('useradmineditadmin');
         }
     }
     // Load the appropriate auth plugin.
     $userauth = get_auth_plugin($user->auth);
     if (is_mnet_remote_user($user) or !$userauth->can_edit_profile() or $userauth->edit_profile_url()) {
         throw new moodle_exception('noprofileedit', 'auth');
     }
     $filemanageroptions = array('maxbytes' => $CFG->maxbytes, 'subdirs' => 0, 'maxfiles' => 1, 'accepted_types' => 'web_image');
     $user->deletepicture = $params['delete'];
     $user->imagefile = $params['draftitemid'];
     $success = core_user::update_picture($user, $filemanageroptions);
     $result = array('success' => $success, 'warnings' => array());
     if ($success) {
         $userpicture = new user_picture(core_user::get_user($user->id));
         $userpicture->size = 1;
         // Size f1.
         $result['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
     }
     return $result;
 }
Example #15
0
    public function login_info($withlinks = null) {
        global $USER, $CFG, $DB, $SESSION,$OUTPUT;

        if (during_initial_install()) {
            return '';
        }

        if (is_null($withlinks)) {
            $withlinks = empty($this->page->layout_options['nologinlinks']);
        }

        $loginpage = ((string)$this->page->url === get_login_url());
        $course = $this->page->course;
        if (\core\session\manager::is_loggedinas()) {
            $realuser = session_get_realuser();
            $fullname = fullname($realuser, true);
            if ($withlinks) {
                $loginastitle = get_string('loginas');
                $realuserinfo = " <a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
                $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>";
            } else {
                $realuserinfo = "$fullname";
            }
        } else {
            $realuserinfo = '';
        }

        $loginurl = get_login_url();

        if (empty($course->id)) {
            // $course->id is not defined during installation
            return '';
        } else if (isloggedin()) {
            $context = context_course::instance($course->id);

            $fullname = fullname($USER, true);
            // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
            if ($withlinks) {
                $linktitle = get_string('viewprofile');
                $username = "******"$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id\" title=\"$linktitle\">$fullname</a>";
            } else {
                $username = $fullname;
            }
            if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
                if ($withlinks) {
                    $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
                } else {
                    $username .= " from {$idprovider->name}";
                }
            }
            if (isguestuser()) {
                $loggedinas = get_string('loggedinasguest','theme_colms');
                $loggout = "<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\" id='logout'>".get_string('logout').'</a>';
                if (!$loginpage && $withlinks) {
                    $loggedinas .= " (<a href=\"$loginurl\" style=\"vertical-align:middle;margin:0;\">".get_string('login').'</a>)';
                }
            } else if (is_role_switched($course->id)) { // Has switched roles
                $rolename = '';
                if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
                    // $rolename = ': '.role_get_name($role, $context);
					$rolename = '';
                }
                $loggedinas = get_string('loggedinas', 'theme_colms', $username).$rolename;
                if ($withlinks) {
                    $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
                    // $loggedinas .= '('.html_writer::tag('a', get_string('switchrolereturn'), array('href'=>$url)).')';
                }
            } else {
                $loggedinas = $realuserinfo.get_string('loggedinas', 'theme_colms', $username);
                if ($withlinks) {
                    $loggout = "<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\" id='logout'>".get_string('logout').'</a>';
                }
            }
        } else {
            $loggedinas = get_string('loggedinnot', 'theme_colms');
            if (!$loginpage && $withlinks) {
                $loggedinas = "<a href='javascript:void(0)' id='login_button'>".get_string('login').'</a>';
            }
        }
        // if(isloggedin() || isguestuser()){
        // $loggedinas = '<div class="logininfo"><div id="logoutlink">'. $loggedinas .'<a href="javascript:void(0)" id="pop_logout"><img src=' . $OUTPUT->pix_url("down_arrow","theme") .'  /></a></div>', array("class"=>"userimg")) . ''.$loggout.'</div>';
        // }
		if(isloggedin() || isguestuser()){
		$loggout = "<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\" class='box_log'>".get_string('logout').'</a>';
        $loggedinas = '<div class="logininfo"><div class="logoutlink">'. $loggedinas .'</div><div class="box_log">'.$loggout.'</div></div>';
        }
        if (isset($SESSION->justloggedin)) {
            unset($SESSION->justloggedin);
            if (!empty($CFG->displayloginfailures)) {
                if (!isguestuser()) {
                    if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
                        $loggedinas .= '&nbsp;<div class="loginfailures">';
                        if (empty($count->accounts)) {
                            $loggedinas .= get_string('failedloginattempts', '', $count);
                        } else {
                            $loggedinas .= get_string('failedloginattemptsall', '', $count);
                        }
                        if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
                            $loggedinas .= ' (<a href="'.$CFG->wwwroot.'/report/log/index.php'.
                                                 '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
                        }
                        $loggedinas .= '</div>';
                    }
                }
            }
        }
        
        return $loggedinas;
    }
 /**
  * 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;
 }
 /**
  * Starts an RPC jump session and returns the jump redirect URL.
  *
  * @param int $mnethostid id of the mnet host to jump to
  * @param string $wantsurl url to redirect to after the jump (usually on remote system)
  * @param boolean $wantsurlbackhere defaults to false, means that the remote system should bounce us back here
  *                                  rather than somewhere inside *its* wwwroot
  */
 function start_jump_session($mnethostid, $wantsurl, $wantsurlbackhere = false)
 {
     global $CFG, $USER, $DB;
     require_once $CFG->dirroot . '/mnet/xmlrpc/client.php';
     // check remote login permissions
     if (!has_capability('moodle/site:mnetlogintoremote', get_system_context()) or is_mnet_remote_user($USER) or isguestuser() or !isloggedin()) {
         print_error('notpermittedtojump', 'mnet');
     }
     // check for SSO publish permission first
     if ($this->has_service($mnethostid, 'sso_sp') == false) {
         print_error('hostnotconfiguredforsso', 'mnet');
     }
     // set RPC timeout to 30 seconds if not configured
     if (empty($this->config->rpc_negotiation_timeout)) {
         $this->config->rpc_negotiation_timeout = 30;
         set_config('rpc_negotiation_timeout', '30', 'auth_mnet');
     }
     // get the host info
     $mnet_peer = new mnet_peer();
     $mnet_peer->set_id($mnethostid);
     // set up the session
     $mnet_session = $DB->get_record('mnet_session', array('userid' => $USER->id, 'mnethostid' => $mnethostid, 'useragent' => sha1($_SERVER['HTTP_USER_AGENT'])));
     if ($mnet_session == false) {
         $mnet_session = new stdClass();
         $mnet_session->mnethostid = $mnethostid;
         $mnet_session->userid = $USER->id;
         $mnet_session->username = $USER->username;
         $mnet_session->useragent = sha1($_SERVER['HTTP_USER_AGENT']);
         $mnet_session->token = $this->generate_token();
         $mnet_session->confirm_timeout = time() + $this->config->rpc_negotiation_timeout;
         $mnet_session->expires = time() + (int) ini_get('session.gc_maxlifetime');
         $mnet_session->session_id = session_id();
         $mnet_session->id = $DB->insert_record('mnet_session', $mnet_session);
     } else {
         $mnet_session->useragent = sha1($_SERVER['HTTP_USER_AGENT']);
         $mnet_session->token = $this->generate_token();
         $mnet_session->confirm_timeout = time() + $this->config->rpc_negotiation_timeout;
         $mnet_session->expires = time() + (int) ini_get('session.gc_maxlifetime');
         $mnet_session->session_id = session_id();
         $DB->update_record('mnet_session', $mnet_session);
     }
     // construct the redirection URL
     //$transport = mnet_get_protocol($mnet_peer->transport);
     $wantsurl = urlencode($wantsurl);
     $url = "{$mnet_peer->wwwroot}{$mnet_peer->application->sso_land_url}?token={$mnet_session->token}&idp={$this->mnet->wwwroot}&wantsurl={$wantsurl}";
     if ($wantsurlbackhere) {
         $url .= '&remoteurl=1';
     }
     return $url;
 }
 public function login_info()
 {
     global $USER, $CFG, $DB, $SESSION;
     if (during_initial_install()) {
         return '';
     }
     $course = $this->page->course;
     if (empty($course->id)) {
         // $course->id is not defined during installation
         return '';
     }
     if (session_is_loggedinas()) {
         $real_user = session_get_realuser();
         $real['name'] = fullname($real_user, true);
         $real['link'] = html::url("{$CFG->wwwroot}/course/loginas.php", array('id' => $course->id, 'sesskey' => sesskey()));
     } else {
         $real = null;
     }
     if (!isloggedin()) {
         return bootsnipp::sign_up_sign_in(new moodle_url('/login/index.php'));
     }
     $logout['link'] = html::url("{$CFG->wwwroot}/login/logout.php", array('sesskey' => sesskey()));
     $logout['name'] = get_string('logout');
     $context = get_context_instance(CONTEXT_COURSE, $course->id);
     $user['name'] = fullname($USER, true);
     $user['link'] = html::url("{$CFG->wwwroot}/user/profile.php", array('id' => $USER->id));
     if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id' => $USER->mnethostid))) {
         $mnet['link'] = $idprovider->wwwroot;
         $mnet['name'] = $idprovider->name;
     } else {
         $mnet = null;
     }
     if (isguestuser()) {
         $guest['link'] = get_login_url();
         $guest['name'] = get_string('login');
         return bootsnipp::guest_user($user['name'], $guest, $logout);
     }
     if (is_role_switched($course->id)) {
         if ($role = $DB->get_record('role', array('id' => $USER->access['rsw'][$context->path]))) {
             $user['name'] .= ': ' . format_string($role->name);
         }
         $role_switch['link'] = "{$CFG->wwwroot}/course/view.php?id={$course->id}&switchrole=0&sesskey=" . sesskey();
         $role_switch['name'] = get_string('switchrolereturn');
     } else {
         $role_switch = null;
     }
     $loginfailures = null;
     if (isset($SESSION->justloggedin)) {
         unset($SESSION->justloggedin);
         if (!empty($CFG->displayloginfailures) && !isguestuser()) {
             if (file_exists("{$CFG->dirroot}/report/log/index.php") and has_capability('report/log:view', get_context_instance(CONTEXT_SYSTEM))) {
                 if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
                     $loginfailures['link'] = "{$CFG->wwwroot}/report/log/index.php?chooselog=1&id=1&modid=site_errors";
                     if (empty($count->accounts)) {
                         $loginfailures['name'] = get_string('failedloginattempts', '', $count);
                     } else {
                         $loginfailures['name'] = get_string('failedloginattemptsall', '', $count);
                     }
                 }
             }
         }
     }
     return bootsnipp::signed_in($user, $loginfailures, $mnet, $real, $role_switch, $logout);
 }
Example #19
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);
}
Example #20
0
/**
 * Defines core nodes for my profile navigation tree.
 *
 * @param \core_user\output\myprofile\tree $tree Tree object
 * @param stdClass $user user object
 * @param bool $iscurrentuser is the user viewing profile, current user ?
 * @param stdClass $course course object
 *
 * @return bool
 */
function core_myprofile_navigation(core_user\output\myprofile\tree $tree, $user, $iscurrentuser, $course)
{
    global $CFG, $USER, $DB;
    $usercontext = context_user::instance($user->id, MUST_EXIST);
    $systemcontext = context_system::instance();
    $context = !empty($course) ? context_course::instance($course->id) : $systemcontext;
    $courseid = !empty($course) ? $course->id : SITEID;
    $contactcategory = new core_user\output\myprofile\category('contact', get_string('userdetails'));
    $coursedetailscategory = new core_user\output\myprofile\category('coursedetails', get_string('coursedetails'), 'contact');
    $miscategory = new core_user\output\myprofile\category('miscellaneous', get_string('miscellaneous'), 'coursedetails');
    $reportcategory = new core_user\output\myprofile\category('reports', get_string('reports'), 'miscellaneous');
    $admincategory = new core_user\output\myprofile\category('administration', get_string('administration'), 'reports');
    $loginactivitycategory = new core_user\output\myprofile\category('loginactivity', get_string('loginactivity'), 'administration');
    // Add categories.
    $tree->add_category($contactcategory);
    $tree->add_category($coursedetailscategory);
    $tree->add_category($miscategory);
    $tree->add_category($reportcategory);
    $tree->add_category($admincategory);
    $tree->add_category($loginactivitycategory);
    // Add core nodes.
    // Full profile node.
    if (!empty($course)) {
        if (empty($CFG->forceloginforprofiles) || $iscurrentuser || has_capability('moodle/user:viewdetails', context_user::instance($user->id)) || has_coursecontact_role($user->id)) {
            $url = new moodle_url('/user/profile.php', array('id' => $user->id));
            $node = new core_user\output\myprofile\node('miscellaneous', 'fullprofile', get_string('fullprofile'), null, $url);
            $tree->add_node($node);
        }
    }
    // Edit profile.
    if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
        if (($iscurrentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
            $url = new moodle_url('/user/editadvanced.php', array('id' => $user->id, 'course' => $courseid));
            $node = new core_user\output\myprofile\node('contact', 'editprofile', get_string('editmyprofile'), null, $url);
            $tree->add_node($node);
        } else {
            if (has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user) || $iscurrentuser && has_capability('moodle/user:editownprofile', $systemcontext)) {
                $userauthplugin = false;
                if (!empty($user->auth)) {
                    $userauthplugin = get_auth_plugin($user->auth);
                }
                if ($userauthplugin && $userauthplugin->can_edit_profile()) {
                    $url = $userauthplugin->edit_profile_url();
                    if (empty($url)) {
                        if (empty($course)) {
                            $url = new moodle_url('/user/edit.php', array('userid' => $user->id));
                        } else {
                            $url = new moodle_url('/user/edit.php', array('userid' => $user->id, 'course' => $course->id));
                        }
                    }
                    $node = new core_user\output\myprofile\node('contact', 'editprofile', get_string('editmyprofile'), null, $url);
                    $tree->add_node($node);
                }
            }
        }
    }
    // Preference page. Only visible by administrators.
    if (is_siteadmin()) {
        $url = new moodle_url('/user/preferences.php', array('userid' => $user->id));
        $title = $iscurrentuser ? get_string('mypreferences') : get_string('userspreferences', 'moodle', fullname($user));
        $node = new core_user\output\myprofile\node('administration', 'preferences', $title, null, $url);
        $tree->add_node($node);
    }
    // Login as ...
    if (!$user->deleted && !$iscurrentuser && !\core\session\manager::is_loggedinas() && has_capability('moodle/user:loginas', $context) && !is_siteadmin($user->id)) {
        $url = new moodle_url('/course/loginas.php', array('id' => $courseid, 'user' => $user->id, 'sesskey' => sesskey()));
        $node = new core_user\output\myprofile\node('administration', 'loginas', get_string('loginas'), null, $url);
        $tree->add_node($node);
    }
    // Contact details.
    if (has_capability('moodle/user:viewhiddendetails', $usercontext)) {
        $hiddenfields = array();
    } else {
        $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
    }
    if (has_capability('moodle/site:viewuseridentity', $context)) {
        $identityfields = array_flip(explode(',', $CFG->showuseridentity));
    } else {
        $identityfields = array();
    }
    if (is_mnet_remote_user($user)) {
        $sql = "SELECT h.id, h.name, h.wwwroot,\n                       a.name as application, a.display_name\n                  FROM {mnet_host} h, {mnet_application} a\n                 WHERE h.id = ? AND h.applicationid = a.id";
        $remotehost = $DB->get_record_sql($sql, array($user->mnethostid));
        $remoteuser = new stdclass();
        $remoteuser->remotetype = $remotehost->display_name;
        $hostinfo = new stdclass();
        $hostinfo->remotename = $remotehost->name;
        $hostinfo->remoteurl = $remotehost->wwwroot;
        $node = new core_user\output\myprofile\node('contact', 'mnet', get_string('remoteuser', 'mnet', $remoteuser), null, null, get_string('remoteuserinfo', 'mnet', $hostinfo), null, 'remoteuserinfo');
        $tree->add_node($node);
    }
    if (isset($identityfields['email']) and ($iscurrentuser or $user->maildisplay == 1 or has_capability('moodle/course:useremail', $usercontext) or $user->maildisplay == 2 and enrol_sharing_course($user, $USER))) {
        $node = new core_user\output\myprofile\node('contact', 'email', get_string('email'), null, null, obfuscate_mailto($user->email, ''));
        $tree->add_node($node);
    }
    if (!isset($hiddenfields['country']) && $user->country) {
        $node = new core_user\output\myprofile\node('contact', 'country', get_string('country'), null, null, get_string($user->country, 'countries'));
        $tree->add_node($node);
    }
    if (!isset($hiddenfields['city']) && $user->city) {
        $node = new core_user\output\myprofile\node('contact', 'city', get_string('city'), null, null, $user->city);
        $tree->add_node($node);
    }
    if (isset($identityfields['address']) && $user->address) {
        $node = new core_user\output\myprofile\node('contact', 'address', get_string('address'), null, null, $user->address);
        $tree->add_node($node);
    }
    if (isset($identityfields['phone1']) && $user->phone1) {
        $node = new core_user\output\myprofile\node('contact', 'phone1', get_string('phone'), null, null, $user->phone1);
        $tree->add_node($node);
    }
    if (isset($identityfields['phone2']) && $user->phone2) {
        $node = new core_user\output\myprofile\node('contact', 'phone2', get_string('phone2'), null, null, $user->phone2);
        $tree->add_node($node);
    }
    if (isset($identityfields['institution']) && $user->institution) {
        $node = new core_user\output\myprofile\node('contact', 'institution', get_string('institution'), null, null, $user->institution);
        $tree->add_node($node);
    }
    if (isset($identityfields['department']) && $user->department) {
        $node = new core_user\output\myprofile\node('contact', 'department', get_string('department'), null, null, $user->institution);
        $tree->add_node($node);
    }
    if (isset($identityfields['idnumber']) && $user->idnumber) {
        $node = new core_user\output\myprofile\node('contact', 'idnumber', get_string('idnumber'), null, null, $user->institution);
        $tree->add_node($node);
    }
    if ($user->url && !isset($hiddenfields['webpage'])) {
        $url = $user->url;
        if (strpos($user->url, '://') === false) {
            $url = 'http://' . $url;
        }
        $webpageurl = new moodle_url($url);
        $node = new core_user\output\myprofile\node('contact', 'webpage', get_string('webpage'), null, null, html_writer::link($url, $webpageurl));
        $tree->add_node($node);
    }
    // Printing tagged interests. We want this only for full profile.
    if (!empty($CFG->usetags) && empty($course)) {
        if ($interests = tag_get_tags_csv('user', $user->id)) {
            $node = new core_user\output\myprofile\node('contact', 'interests', get_string('interests'), null, null, $interests);
            $tree->add_node($node);
        }
    }
    if (!isset($hiddenfields['mycourses'])) {
        $showallcourses = optional_param('showallcourses', 0, PARAM_INT);
        if ($mycourses = enrol_get_all_users_courses($user->id, true, null, 'visible DESC, sortorder ASC')) {
            $shown = 0;
            $courselisting = html_writer::start_tag('ul');
            foreach ($mycourses as $mycourse) {
                if ($mycourse->category) {
                    context_helper::preload_from_record($mycourse);
                    $ccontext = context_course::instance($mycourse->id);
                    if (!isset($course) || $mycourse->id != $course->id) {
                        $linkattributes = null;
                        if ($mycourse->visible == 0) {
                            if (!has_capability('moodle/course:viewhiddencourses', $ccontext)) {
                                continue;
                            }
                            $linkattributes['class'] = 'dimmed';
                        }
                        $params = array('id' => $user->id, 'course' => $mycourse->id);
                        if ($showallcourses) {
                            $params['showallcourses'] = 1;
                        }
                        $url = new moodle_url('/user/view.php', $params);
                        $courselisting .= html_writer::tag('li', html_writer::link($url, $ccontext->get_context_name(false), $linkattributes));
                    } else {
                        $courselisting .= html_writer::tag('li', $course->fullname);
                    }
                }
                $shown++;
                if (!$showallcourses && $shown == $CFG->navcourselimit) {
                    $url = null;
                    if (isset($course)) {
                        $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $course->id, 'showallcourses' => 1));
                    } else {
                        $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1));
                    }
                    $courselisting .= html_writer::tag('li', html_writer::link($url, get_string('viewmore'), array('title' => get_string('viewmore'))));
                    break;
                }
            }
            $courselisting .= html_writer::end_tag('ul');
            if (!empty($mycourses)) {
                // Add this node only if there are courses to display.
                $node = new core_user\output\myprofile\node('coursedetails', 'courseprofiles', get_string('courseprofiles'), null, null, rtrim($courselisting, ', '));
                $tree->add_node($node);
            }
        }
    }
    if (!empty($course)) {
        // Show roles in this course.
        if ($rolestring = get_user_roles_in_course($user->id, $course->id)) {
            $node = new core_user\output\myprofile\node('coursedetails', 'roles', get_string('roles'), null, null, $rolestring);
            $tree->add_node($node);
        }
        // Show groups this user is in.
        if (!isset($hiddenfields['groups']) && !empty($course)) {
            $accessallgroups = has_capability('moodle/site:accessallgroups', $context);
            if ($usergroups = groups_get_all_groups($course->id, $user->id)) {
                $groupstr = '';
                foreach ($usergroups as $group) {
                    if ($course->groupmode == SEPARATEGROUPS and !$accessallgroups and $user->id != $USER->id) {
                        if (!groups_is_member($group->id, $user->id)) {
                            continue;
                        }
                    }
                    if ($course->groupmode != NOGROUPS) {
                        $groupstr .= ' <a href="' . $CFG->wwwroot . '/user/index.php?id=' . $course->id . '&amp;group=' . $group->id . '">' . format_string($group->name) . '</a>,';
                    } else {
                        // The user/index.php shows groups only when course in group mode.
                        $groupstr .= ' ' . format_string($group->name);
                    }
                }
                if ($groupstr !== '') {
                    $node = new core_user\output\myprofile\node('coursedetails', 'groups', get_string('group'), null, null, rtrim($groupstr, ', '));
                    $tree->add_node($node);
                }
            }
        }
        if (!isset($hiddenfields['suspended'])) {
            if ($user->suspended) {
                $node = new core_user\output\myprofile\node('coursedetails', 'suspended', null, null, null, get_string('suspended', 'auth'));
                $tree->add_node($node);
            }
        }
        echo html_writer::end_tag('dl');
    }
    if ($user->icq && !isset($hiddenfields['icqnumber'])) {
        $imurl = new moodle_url('http://web.icq.com/wwp', array('uin' => $user->icq));
        $iconurl = new moodle_url('http://web.icq.com/whitepages/online', array('icq' => $user->icq, 'img' => '5'));
        $statusicon = html_writer::tag('img', '', array('src' => $iconurl, 'class' => 'icon icon-post', 'alt' => get_string('status')));
        $node = new core_user\output\myprofile\node('contact', 'icqnumber', get_string('icqnumber'), null, null, html_writer::link($imurl, s($user->icq) . $statusicon));
        $tree->add_node($node);
    }
    if ($user->skype && !isset($hiddenfields['skypeid'])) {
        $imurl = 'skype:' . urlencode($user->skype) . '?call';
        $iconurl = new moodle_url('http://mystatus.skype.com/smallicon/' . urlencode($user->skype));
        if (is_https()) {
            // Bad luck, skype devs are lazy to set up SSL on their servers - see MDL-37233.
            $statusicon = '';
        } else {
            $statusicon = html_writer::empty_tag('img', array('src' => $iconurl, 'class' => 'icon icon-post', 'alt' => get_string('status')));
        }
        $node = new core_user\output\myprofile\node('contact', 'skypeid', get_string('skypeid'), null, null, html_writer::link($imurl, s($user->skype) . $statusicon));
        $tree->add_node($node);
    }
    if ($user->yahoo && !isset($hiddenfields['yahooid'])) {
        $imurl = new moodle_url('http://edit.yahoo.com/config/send_webmesg', array('.target' => $user->yahoo, '.src' => 'pg'));
        $iconurl = new moodle_url('http://opi.yahoo.com/online', array('u' => $user->yahoo, 'm' => 'g', 't' => '0'));
        $statusicon = html_writer::tag('img', '', array('src' => $iconurl, 'class' => 'iconsmall icon-post', 'alt' => get_string('status')));
        $node = new core_user\output\myprofile\node('contact', 'yahooid', get_string('yahooid'), null, null, html_writer::link($imurl, s($user->yahoo) . $statusicon));
        $tree->add_node($node);
    }
    if ($user->aim && !isset($hiddenfields['aimid'])) {
        $imurl = 'aim:goim?screenname=' . urlencode($user->aim);
        $node = new core_user\output\myprofile\node('contact', 'aimid', get_string('aimid'), null, null, html_writer::link($imurl, s($user->aim)));
        $tree->add_node($node);
    }
    if ($user->msn && !isset($hiddenfields['msnid'])) {
        $node = new core_user\output\myprofile\node('contact', 'msnid', get_string('msnid'), null, null, s($user->msn));
        $tree->add_node($node);
    }
    if ($categories = $DB->get_records('user_info_category', null, 'sortorder ASC')) {
        foreach ($categories as $category) {
            if ($fields = $DB->get_records('user_info_field', array('categoryid' => $category->id), 'sortorder ASC')) {
                foreach ($fields as $field) {
                    require_once $CFG->dirroot . '/user/profile/field/' . $field->datatype . '/field.class.php';
                    $newfield = 'profile_field_' . $field->datatype;
                    $formfield = new $newfield($field->id, $user->id);
                    if ($formfield->is_visible() and !$formfield->is_empty()) {
                        $node = new core_user\output\myprofile\node('contact', $formfield->field->shortname, format_string($formfield->field->name), null, null, $formfield->display_data());
                        $tree->add_node($node);
                    }
                }
            }
        }
    }
    // First access. (Why only for sites ?)
    if (!isset($hiddenfields['firstaccess']) && empty($course)) {
        if ($user->firstaccess) {
            $datestring = userdate($user->firstaccess) . "&nbsp; (" . format_time(time() - $user->firstaccess) . ")";
        } else {
            $datestring = get_string("never");
        }
        $node = new core_user\output\myprofile\node('loginactivity', 'firstaccess', get_string('firstsiteaccess'), null, null, $datestring);
        $tree->add_node($node);
    }
    // Last access.
    if (!isset($hiddenfields['lastaccess'])) {
        if (empty($course)) {
            $string = get_string('lastsiteaccess');
            if ($user->lastaccess) {
                $datestring = userdate($user->lastaccess) . "&nbsp; (" . format_time(time() - $user->lastaccess) . ")";
            } else {
                $datestring = get_string("never");
            }
        } else {
            $string = get_string('lastcourseaccess');
            if ($lastaccess = $DB->get_record('user_lastaccess', array('userid' => $user->id, 'courseid' => $course->id))) {
                $datestring = userdate($lastaccess->timeaccess) . "&nbsp; (" . format_time(time() - $lastaccess->timeaccess) . ")";
            } else {
                $datestring = get_string("never");
            }
        }
        $node = new core_user\output\myprofile\node('loginactivity', 'lastaccess', $string, null, null, $datestring);
        $tree->add_node($node);
    }
    // Last ip.
    if (has_capability('moodle/user:viewlastip', $usercontext) && !isset($hiddenfields['lastip'])) {
        if ($user->lastip) {
            $iplookupurl = new moodle_url('/iplookup/index.php', array('ip' => $user->lastip, 'user' => $USER->id));
            $ipstring = html_writer::link($iplookupurl, $user->lastip);
        } else {
            $ipstring = get_string("none");
        }
        $node = new core_user\output\myprofile\node('loginactivity', 'lastip', get_string('lastip'), null, null, $ipstring);
        $tree->add_node($node);
    }
}
Example #21
0
/**
 * Send an email to a specified user
 *
 * @param stdClass $user  A {@link $USER} object
 * @param stdClass $from A {@link $USER} object
 * @param string $subject plain text subject line of the email
 * @param string $messagetext plain text version of the message
 * @param string $messagehtml complete html version of the message (optional)
 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in $CFG->tempdir
 * @param string $attachname the name of the file (extension indicates MIME)
 * @param bool $usetrueaddress determines whether $from email address should
 *          be sent out. Will be overruled by user profile setting for maildisplay
 * @param string $replyto Email address to reply to
 * @param string $replytoname Name of reply to recipient
 * @param int $wordwrapwidth custom word wrap width, default 79
 * @return bool Returns true if mail was sent OK and false if there was an error.
 */
function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '', $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79)
{
    global $CFG, $PAGE, $SITE;
    if (empty($user) or empty($user->id)) {
        debugging('Can not send email to null user', DEBUG_DEVELOPER);
        return false;
    }
    if (empty($user->email)) {
        debugging('Can not send email to user without email: ' . $user->id, DEBUG_DEVELOPER);
        return false;
    }
    if (!empty($user->deleted)) {
        debugging('Can not send email to deleted user: '******'BEHAT_SITE_RUNNING')) {
        // Fake email sending in behat.
        return true;
    }
    if (!empty($CFG->noemailever)) {
        // Hidden setting for development sites, set in config.php if needed.
        debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
        return true;
    }
    if (email_should_be_diverted($user->email)) {
        $subject = "[DIVERTED {$user->email}] {$subject}";
        $user = clone $user;
        $user->email = $CFG->divertallemailsto;
    }
    // Skip mail to suspended users.
    if (isset($user->auth) && $user->auth == 'nologin' or isset($user->suspended) && $user->suspended) {
        return true;
    }
    if (!validate_email($user->email)) {
        // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
        debugging("email_to_user: User {$user->id} (" . fullname($user) . ") email ({$user->email}) is invalid! Not sending.");
        return false;
    }
    if (over_bounce_threshold($user)) {
        debugging("email_to_user: User {$user->id} (" . fullname($user) . ") is over bounce threshold! Not sending.");
        return false;
    }
    // TLD .invalid  is specifically reserved for invalid domain names.
    // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
    if (substr($user->email, -8) == '.invalid') {
        debugging("email_to_user: User {$user->id} (" . fullname($user) . ") email domain ({$user->email}) is invalid! Not sending.");
        return true;
        // This is not an error.
    }
    // If the user is a remote mnet user, parse the email text for URL to the
    // wwwroot and modify the url to direct the user's browser to login at their
    // home site (identity provider - idp) before hitting the link itself.
    if (is_mnet_remote_user($user)) {
        require_once $CFG->dirroot . '/mnet/lib.php';
        $jumpurl = mnet_get_idp_jump_url($user);
        $callback = partial('mnet_sso_apply_indirection', $jumpurl);
        $messagetext = preg_replace_callback("%({$CFG->wwwroot}[^[:space:]]*)%", $callback, $messagetext);
        $messagehtml = preg_replace_callback("%href=[\"'`]({$CFG->wwwroot}[\\w_:\\?=#&@/;.~-]*)[\"'`]%", $callback, $messagehtml);
    }
    $mail = get_mailer();
    if (!empty($mail->SMTPDebug)) {
        echo '<pre>' . "\n";
    }
    $temprecipients = array();
    $tempreplyto = array();
    // Make sure that we fall back onto some reasonable no-reply address.
    $noreplyaddress = empty($CFG->noreplyaddress) ? 'noreply@' . get_host_from_url($CFG->wwwroot) : $CFG->noreplyaddress;
    // Make up an email address for handling bounces.
    if (!empty($CFG->handlebounces)) {
        $modargs = 'B' . base64_encode(pack('V', $user->id)) . substr(md5($user->email), 0, 16);
        $mail->Sender = generate_email_processing_address(0, $modargs);
    } else {
        $mail->Sender = $noreplyaddress;
    }
    $alloweddomains = null;
    if (!empty($CFG->allowedemaildomains)) {
        $alloweddomains = explode(PHP_EOL, $CFG->allowedemaildomains);
    }
    // Email will be sent using no reply address.
    if (empty($alloweddomains)) {
        $usetrueaddress = false;
    }
    if (is_string($from)) {
        // So we can pass whatever we want if there is need.
        $mail->From = $noreplyaddress;
        $mail->FromName = $from;
        // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
        // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
        // in a course with the sender.
    } else {
        if ($usetrueaddress && can_send_from_real_email_address($from, $user, $alloweddomains)) {
            $mail->From = $from->email;
            $fromdetails = new stdClass();
            $fromdetails->name = fullname($from);
            $fromdetails->url = $CFG->wwwroot;
            $fromstring = $fromdetails->name;
            if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
                $fromstring = get_string('emailvia', 'core', $fromdetails);
            }
            $mail->FromName = $fromstring;
            if (empty($replyto)) {
                $tempreplyto[] = array($from->email, fullname($from));
            }
        } else {
            $mail->From = $noreplyaddress;
            $fromdetails = new stdClass();
            $fromdetails->name = fullname($from);
            $fromdetails->url = $CFG->wwwroot;
            $fromstring = $fromdetails->name;
            if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
                $fromstring = get_string('emailvia', 'core', $fromdetails);
            }
            $mail->FromName = $fromstring;
            if (empty($replyto)) {
                $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
            }
        }
    }
    if (!empty($replyto)) {
        $tempreplyto[] = array($replyto, $replytoname);
    }
    $temprecipients[] = array($user->email, fullname($user));
    // Set word wrap.
    $mail->WordWrap = $wordwrapwidth;
    if (!empty($from->customheaders)) {
        // Add custom headers.
        if (is_array($from->customheaders)) {
            foreach ($from->customheaders as $customheader) {
                $mail->addCustomHeader($customheader);
            }
        } else {
            $mail->addCustomHeader($from->customheaders);
        }
    }
    // If the X-PHP-Originating-Script email header is on then also add an additional
    // header with details of where exactly in moodle the email was triggered from,
    // either a call to message_send() or to email_to_user().
    if (ini_get('mail.add_x_header')) {
        $stack = debug_backtrace(false);
        $origin = $stack[0];
        foreach ($stack as $depth => $call) {
            if ($call['function'] == 'message_send') {
                $origin = $call;
            }
        }
        $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':' . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
        $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
    }
    if (!empty($from->priority)) {
        $mail->Priority = $from->priority;
    }
    $renderer = $PAGE->get_renderer('core');
    $context = array('sitefullname' => $SITE->fullname, 'siteshortname' => $SITE->shortname, 'sitewwwroot' => $CFG->wwwroot, 'subject' => $subject, 'to' => $user->email, 'toname' => fullname($user), 'from' => $mail->From, 'fromname' => $mail->FromName);
    if (!empty($tempreplyto[0])) {
        $context['replyto'] = $tempreplyto[0][0];
        $context['replytoname'] = $tempreplyto[0][1];
    }
    if ($user->id > 0) {
        $context['touserid'] = $user->id;
        $context['tousername'] = $user->username;
    }
    if (!empty($user->mailformat) && $user->mailformat == 1) {
        // Only process html templates if the user preferences allow html email.
        if ($messagehtml) {
            // If html has been given then pass it through the template.
            $context['body'] = $messagehtml;
            $messagehtml = $renderer->render_from_template('core/email_html', $context);
        } else {
            // If no html has been given, BUT there is an html wrapping template then
            // auto convert the text to html and then wrap it.
            $autohtml = trim(text_to_html($messagetext));
            $context['body'] = $autohtml;
            $temphtml = $renderer->render_from_template('core/email_html', $context);
            if ($autohtml != $temphtml) {
                $messagehtml = $temphtml;
            }
        }
    }
    $context['body'] = $messagetext;
    $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
    $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
    $messagetext = $renderer->render_from_template('core/email_text', $context);
    // Autogenerate a MessageID if it's missing.
    if (empty($mail->MessageID)) {
        $mail->MessageID = generate_email_messageid();
    }
    if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
        // Don't ever send HTML to users who don't want it.
        $mail->isHTML(true);
        $mail->Encoding = 'quoted-printable';
        $mail->Body = $messagehtml;
        $mail->AltBody = "\n{$messagetext}\n";
    } else {
        $mail->IsHTML(false);
        $mail->Body = "\n{$messagetext}\n";
    }
    if ($attachment && $attachname) {
        if (preg_match("~\\.\\.~", $attachment)) {
            // Security check for ".." in dir path.
            $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
            $mail->addStringAttachment('Error in attachment.  User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
        } else {
            require_once $CFG->libdir . '/filelib.php';
            $mimetype = mimeinfo('type', $attachname);
            $attachmentpath = $attachment;
            // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
            $attachpath = str_replace('\\', '/', $attachmentpath);
            // Make sure both variables are normalised before comparing.
            $temppath = str_replace('\\', '/', realpath($CFG->tempdir));
            // If the attachment is a full path to a file in the tempdir, use it as is,
            // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
            if (strpos($attachpath, $temppath) !== 0) {
                $attachmentpath = $CFG->dataroot . '/' . $attachmentpath;
            }
            $mail->addAttachment($attachmentpath, $attachname, 'base64', $mimetype);
        }
    }
    // Check if the email should be sent in an other charset then the default UTF-8.
    if (!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset)) {
        // Use the defined site mail charset or eventually the one preferred by the recipient.
        $charset = $CFG->sitemailcharset;
        if (!empty($CFG->allowusermailcharset)) {
            if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
                $charset = $useremailcharset;
            }
        }
        // Convert all the necessary strings if the charset is supported.
        $charsets = get_list_of_charsets();
        unset($charsets['UTF-8']);
        if (in_array($charset, $charsets)) {
            $mail->CharSet = $charset;
            $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
            $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
            $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
            $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
            foreach ($temprecipients as $key => $values) {
                $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
            }
            foreach ($tempreplyto as $key => $values) {
                $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
            }
        }
    }
    foreach ($temprecipients as $values) {
        $mail->addAddress($values[0], $values[1]);
    }
    foreach ($tempreplyto as $values) {
        $mail->addReplyTo($values[0], $values[1]);
    }
    if ($mail->send()) {
        set_send_count($user);
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return true;
    } else {
        // Trigger event for failing to send email.
        $event = \core\event\email_failed::create(array('context' => context_system::instance(), 'userid' => $from->id, 'relateduserid' => $user->id, 'other' => array('subject' => $subject, 'message' => $messagetext, 'errorinfo' => $mail->ErrorInfo)));
        $event->trigger();
        if (CLI_SCRIPT) {
            mtrace('Error: lib/moodlelib.php email_to_user(): ' . $mail->ErrorInfo);
        }
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return false;
    }
}
Example #22
0
/**
 * Send an email to a specified user
 *
 * @global object
 * @global string
 * @global string IdentityProvider(IDP) URL user hits to jump to mnet peer.
 * @uses SITEID
 * @param stdClass $user  A {@link $USER} object
 * @param stdClass $from A {@link $USER} object
 * @param string $subject plain text subject line of the email
 * @param string $messagetext plain text version of the message
 * @param string $messagehtml complete html version of the message (optional)
 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
 * @param string $attachname the name of the file (extension indicates MIME)
 * @param bool $usetrueaddress determines whether $from email address should
 *          be sent out. Will be overruled by user profile setting for maildisplay
 * @param string $replyto Email address to reply to
 * @param string $replytoname Name of reply to recipient
 * @param int $wordwrapwidth custom word wrap width, default 79
 * @return bool Returns true if mail was sent OK and false if there was an error.
 */
function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '', $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79)
{
    global $CFG, $FULLME;
    if (empty($user) || empty($user->email)) {
        mtrace('Error: lib/moodlelib.php email_to_user(): User is null or has no email');
        return false;
    }
    if (!empty($user->deleted)) {
        // do not mail delted users
        mtrace('Error: lib/moodlelib.php email_to_user(): User is deleted');
        return false;
    }
    if (!empty($CFG->noemailever)) {
        // hidden setting for development sites, set in config.php if needed
        mtrace('Error: lib/moodlelib.php email_to_user(): Not sending email due to noemailever config setting');
        return true;
    }
    if (!empty($CFG->divertallemailsto)) {
        $subject = "[DIVERTED {$user->email}] {$subject}";
        $user = clone $user;
        $user->email = $CFG->divertallemailsto;
    }
    // skip mail to suspended users
    if (isset($user->auth) && $user->auth == 'nologin') {
        return true;
    }
    if (over_bounce_threshold($user)) {
        $bouncemsg = "User {$user->id} (" . fullname($user) . ") is over bounce threshold! Not sending.";
        error_log($bouncemsg);
        mtrace('Error: lib/moodlelib.php email_to_user(): ' . $bouncemsg);
        return false;
    }
    // If the user is a remote mnet user, parse the email text for URL to the
    // wwwroot and modify the url to direct the user's browser to login at their
    // home site (identity provider - idp) before hitting the link itself
    if (is_mnet_remote_user($user)) {
        require_once $CFG->dirroot . '/mnet/lib.php';
        $jumpurl = mnet_get_idp_jump_url($user);
        $callback = partial('mnet_sso_apply_indirection', $jumpurl);
        $messagetext = preg_replace_callback("%({$CFG->wwwroot}[^[:space:]]*)%", $callback, $messagetext);
        $messagehtml = preg_replace_callback("%href=[\"'`]({$CFG->wwwroot}[\\w_:\\?=#&@/;.~-]*)[\"'`]%", $callback, $messagehtml);
    }
    $mail = get_mailer();
    if (!empty($mail->SMTPDebug)) {
        echo '<pre>' . "\n";
    }
    $temprecipients = array();
    $tempreplyto = array();
    $supportuser = generate_email_supportuser();
    // make up an email address for handling bounces
    if (!empty($CFG->handlebounces)) {
        $modargs = 'B' . base64_encode(pack('V', $user->id)) . substr(md5($user->email), 0, 16);
        $mail->Sender = generate_email_processing_address(0, $modargs);
    } else {
        $mail->Sender = $supportuser->email;
    }
    if (is_string($from)) {
        // So we can pass whatever we want if there is need
        $mail->From = $CFG->noreplyaddress;
        $mail->FromName = $from;
    } else {
        if ($usetrueaddress and $from->maildisplay) {
            $mail->From = $from->email;
            $mail->FromName = fullname($from);
        } else {
            $mail->From = $CFG->noreplyaddress;
            $mail->FromName = fullname($from);
            if (empty($replyto)) {
                $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
            }
        }
    }
    if (!empty($replyto)) {
        $tempreplyto[] = array($replyto, $replytoname);
    }
    $mail->Subject = substr($subject, 0, 900);
    $temprecipients[] = array($user->email, fullname($user));
    $mail->WordWrap = $wordwrapwidth;
    // set word wrap
    if (!empty($from->customheaders)) {
        // Add custom headers
        if (is_array($from->customheaders)) {
            foreach ($from->customheaders as $customheader) {
                $mail->AddCustomHeader($customheader);
            }
        } else {
            $mail->AddCustomHeader($from->customheaders);
        }
    }
    if (!empty($from->priority)) {
        $mail->Priority = $from->priority;
    }
    if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
        // Don't ever send HTML to users who don't want it
        $mail->IsHTML(true);
        $mail->Encoding = 'quoted-printable';
        // Encoding to use
        $mail->Body = $messagehtml;
        $mail->AltBody = "\n{$messagetext}\n";
    } else {
        $mail->IsHTML(false);
        $mail->Body = "\n{$messagetext}\n";
    }
    if ($attachment && $attachname) {
        if (preg_match("~\\.\\.~", $attachment)) {
            // Security check for ".." in dir path
            $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
            $mail->AddStringAttachment('Error in attachment.  User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
        } else {
            require_once $CFG->libdir . '/filelib.php';
            $mimetype = mimeinfo('type', $attachname);
            $mail->AddAttachment($CFG->dataroot . '/' . $attachment, $attachname, 'base64', $mimetype);
        }
    }
    // Check if the email should be sent in an other charset then the default UTF-8
    if (!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset)) {
        // use the defined site mail charset or eventually the one preferred by the recipient
        $charset = $CFG->sitemailcharset;
        if (!empty($CFG->allowusermailcharset)) {
            if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
                $charset = $useremailcharset;
            }
        }
        // convert all the necessary strings if the charset is supported
        $charsets = get_list_of_charsets();
        unset($charsets['UTF-8']);
        if (in_array($charset, $charsets)) {
            $textlib = textlib_get_instance();
            $mail->CharSet = $charset;
            $mail->FromName = $textlib->convert($mail->FromName, 'utf-8', strtolower($charset));
            $mail->Subject = $textlib->convert($mail->Subject, 'utf-8', strtolower($charset));
            $mail->Body = $textlib->convert($mail->Body, 'utf-8', strtolower($charset));
            $mail->AltBody = $textlib->convert($mail->AltBody, 'utf-8', strtolower($charset));
            foreach ($temprecipients as $key => $values) {
                $temprecipients[$key][1] = $textlib->convert($values[1], 'utf-8', strtolower($charset));
            }
            foreach ($tempreplyto as $key => $values) {
                $tempreplyto[$key][1] = $textlib->convert($values[1], 'utf-8', strtolower($charset));
            }
        }
    }
    foreach ($temprecipients as $values) {
        $mail->AddAddress($values[0], $values[1]);
    }
    foreach ($tempreplyto as $values) {
        $mail->AddReplyTo($values[0], $values[1]);
    }
    if ($mail->Send()) {
        set_send_count($user);
        $mail->IsSMTP();
        // use SMTP directly
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return true;
    } else {
        mtrace('ERROR: ' . $mail->ErrorInfo);
        add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: ' . $mail->ErrorInfo);
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return false;
    }
}
Example #23
0
    /**
     * Return the standard string that says whether you are logged in (and switched
     * roles/logged in as another user).
     * @param bool $withlinks if false, then don't include any links in the HTML produced.
     * If not set, the default is the nologinlinks option from the theme config.php file,
     * and if that is not set, then links are included.
     * @return string HTML fragment.
     */
    public function login_info($withlinks = null) {
        global $USER, $CFG, $DB, $SESSION;

        if (during_initial_install()) {
            return '';
        }

        if (is_null($withlinks)) {
            $withlinks = empty($this->page->layout_options['nologinlinks']);
        }

        $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 = '';
        }

        $loginpage = $this->is_login_page();
        $loginurl = get_login_url();

        if (empty($course->id)) {
            // $course->id is not defined during installation
            return '';
        } else if (isloggedin()) {
            $context = context_course::instance($course->id);

            $fullname = fullname($USER, true);
            // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
            if ($withlinks) {
                $linktitle = get_string('viewprofile');
                $username = "******"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
            } else {
                $username = $fullname;
            }
            if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
                if ($withlinks) {
                    $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
                } else {
                    $username .= " from {$idprovider->name}";
                }
            }
            if (isguestuser()) {
                $loggedinas = $realuserinfo.get_string('loggedinasguest');
                if (!$loginpage && $withlinks) {
                    $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
                }
            } else if (is_role_switched($course->id)) { // Has switched roles
                $rolename = '';
                if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
                    $rolename = ': '.role_get_name($role, $context);
                }
                $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
                if ($withlinks) {
                    $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
                    $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
                }
            } else {
                $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
                if ($withlinks) {
                    $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
                }
            }
        } else {
            $loggedinas = get_string('loggedinnot', 'moodle');
            if (!$loginpage && $withlinks) {
                $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
            }
        }

        $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';

        if (isset($SESSION->justloggedin)) {
            unset($SESSION->justloggedin);
            if (!empty($CFG->displayloginfailures)) {
                if (!isguestuser()) {
                    // Include this file only when required.
                    require_once($CFG->dirroot . '/user/lib.php');
                    if ($count = user_count_login_failures($USER)) {
                        $loggedinas .= '<div class="loginfailures">';
                        $a = new stdClass();
                        $a->attempts = $count;
                        $loggedinas .= get_string('failedloginattempts', '', $a);
                        if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
                            $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
                                    'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
                        }
                        $loggedinas .= '</div>';
                    }
                }
            }
        }

        return $loggedinas;
    }
Example #24
0
    function definition_after_data() {
        global $USER, $CFG, $DB, $OUTPUT;

        $mform =& $this->_form;
        if ($userid = $mform->getElementValue('id')) {
            $user = $DB->get_record('user', array('id'=>$userid));
        } else {
            $user = false;
        }

        // if language does not exist, use site default lang
        if ($langsel = $mform->getElementValue('lang')) {
            $lang = reset($langsel);
            // check lang exists
            if (!get_string_manager()->translation_exists($lang, false)) {
                $lang_el =& $mform->getElement('lang');
                $lang_el->setValue($CFG->lang);
            }
        }

        // user can not change own auth method
        if ($userid == $USER->id) {
            $mform->hardFreeze('auth');
            $mform->hardFreeze('preference_auth_forcepasswordchange');
        }

        // admin must choose some password and supply correct email
        if (!empty($USER->newadminuser)) {
            $mform->addRule('newpassword', get_string('required'), 'required', null, 'client');
            if ($mform->elementExists('suspended')) {
                $mform->removeElement('suspended');
            }
        }

        // require password for new users
        if ($userid == -1) {
            $mform->addRule('newpassword', get_string('required'), 'required', null, 'client');
        }

        if ($user and is_mnet_remote_user($user)) {
            // only local accounts can be suspended
            if ($mform->elementExists('suspended')) {
                $mform->removeElement('suspended');
            }
        }
        if ($user and ($user->id == $USER->id or is_siteadmin($user))) {
            // prevent self and admin mess ups
            if ($mform->elementExists('suspended')) {
                $mform->hardFreeze('suspended');
            }
        }

        // print picture
        if (!empty($CFG->gdversion) and empty($USER->newadminuser)) {
            if ($user) {
                $context = context_user::instance($user->id, MUST_EXIST);
                $fs = get_file_storage();
                $hasuploadedpicture = ($fs->file_exists($context->id, 'user', 'icon', 0, '/', 'f2.png') || $fs->file_exists($context->id, 'user', 'icon', 0, '/', 'f2.jpg'));
                if (!empty($user->picture) && $hasuploadedpicture) {
                    $imagevalue = $OUTPUT->user_picture($user, array('courseid' => SITEID, 'size'=>64));
                } else {
                    $imagevalue = get_string('none');
                }
            } else {
                $imagevalue = get_string('none');
            }
            $imageelement = $mform->getElement('currentpicture');
            $imageelement->setValue($imagevalue);

            if ($user && $mform->elementExists('deletepicture') && !$hasuploadedpicture) {
                $mform->removeElement('deletepicture');
            }
        }

        /// Next the customisable profile fields
        profile_definition_after_data($mform, $userid);
    }
Example #25
0
/**
 * Get a list of essential user navigation items.
 *
 * @param stdclass $user user object.
 * @param moodle_page $page page object.
 * @return stdClass $returnobj navigation information object, where:
 *
 *      $returnobj->navitems    array    array of links where each link is a
 *                                       stdClass with fields url, title, and
 *                                       pix
 *      $returnobj->metadata    array    array of useful user metadata to be
 *                                       used when constructing navigation;
 *                                       fields include:
 *
 *          ROLE FIELDS
 *          asotherrole    bool    whether viewing as another role
 *          rolename       string  name of the role
 *
 *          USER FIELDS
 *          These fields are for the currently-logged in user, or for
 *          the user that the real user is currently logged in as.
 *
 *          userid         int        the id of the user in question
 *          userfullname   string     the user's full name
 *          userprofileurl moodle_url the url of the user's profile
 *          useravatar     string     a HTML fragment - the rendered
 *                                    user_picture for this user
 *          userloginfail  string     an error string denoting the number
 *                                    of login failures since last login
 *
 *          "REAL USER" FIELDS
 *          These fields are for when asotheruser is true, and
 *          correspond to the underlying "real user".
 *
 *          asotheruser        bool    whether viewing as another user
 *          realuserid         int        the id of the user in question
 *          realuserfullname   string     the user's full name
 *          realuserprofileurl moodle_url the url of the user's profile
 *          realuseravatar     string     a HTML fragment - the rendered
 *                                        user_picture for this user
 *
 *          MNET PROVIDER FIELDS
 *          asmnetuser            bool   whether viewing as a user from an
 *                                       MNet provider
 *          mnetidprovidername    string name of the MNet provider
 *          mnetidproviderwwwroot string URL of the MNet provider
 */
function user_get_user_navigation_info($user, $page)
{
    global $OUTPUT, $DB, $SESSION, $CFG;
    $returnobject = new stdClass();
    $returnobject->navitems = array();
    $returnobject->metadata = array();
    $course = $page->course;
    // Query the environment.
    $context = context_course::instance($course->id);
    // Get basic user metadata.
    $returnobject->metadata['userid'] = $user->id;
    $returnobject->metadata['userfullname'] = fullname($user, true);
    $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array('id' => $user->id));
    $returnobject->metadata['useravatar'] = $OUTPUT->user_picture($user, array('link' => false, 'visibletoscreenreaders' => false));
    // Build a list of items for a regular user.
    // Query MNet status.
    if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
        $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
        $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
        $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
    }
    // Did the user just log in?
    if (isset($SESSION->justloggedin)) {
        // Don't unset this flag as login_info still needs it.
        if (!empty($CFG->displayloginfailures)) {
            // We're already in /user/lib.php, so we don't need to include.
            if ($count = user_count_login_failures($user)) {
                // Get login failures string.
                $a = new stdClass();
                $a->attempts = html_writer::tag('span', $count, array('class' => 'value'));
                $returnobject->metadata['userloginfail'] = get_string('failedloginattempts', '', $a);
            }
        }
    }
    // Links: Dashboard.
    $myhome = new stdClass();
    $myhome->itemtype = 'link';
    $myhome->url = new moodle_url('/my/');
    $myhome->title = get_string('mymoodle', 'admin');
    $myhome->pix = "i/course";
    $returnobject->navitems[] = $myhome;
    // Links: My Profile.
    $myprofile = new stdClass();
    $myprofile->itemtype = 'link';
    $myprofile->url = new moodle_url('/user/profile.php', array('id' => $user->id));
    $myprofile->title = get_string('profile');
    $myprofile->pix = "i/user";
    $returnobject->navitems[] = $myprofile;
    // Links: Role-return or logout link.
    $lastobj = null;
    $buildlogout = true;
    $returnobject->metadata['asotherrole'] = false;
    if (is_role_switched($course->id)) {
        if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
            // Build role-return link instead of logout link.
            $rolereturn = new stdClass();
            $rolereturn->itemtype = 'link';
            $rolereturn->url = new moodle_url('/course/switchrole.php', array('id' => $course->id, 'sesskey' => sesskey(), 'switchrole' => 0, 'returnurl' => $page->url->out_as_local_url(false)));
            $rolereturn->pix = "a/logout";
            $rolereturn->title = get_string('switchrolereturn');
            $lastobj = $rolereturn;
            $returnobject->metadata['asotherrole'] = true;
            $returnobject->metadata['rolename'] = role_get_name($role, $context);
            $buildlogout = false;
        }
    }
    if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
        $realuser = \core\session\manager::get_realuser();
        // Save values for the real user, as $user will be full of data for the
        // user the user is disguised as.
        $returnobject->metadata['realuserid'] = $realuser->id;
        $returnobject->metadata['realuserfullname'] = fullname($realuser, true);
        $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', array('id' => $realuser->id));
        $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, array('link' => false, 'visibletoscreenreaders' => false));
        // Build a user-revert link.
        $userrevert = new stdClass();
        $userrevert->itemtype = 'link';
        $userrevert->url = new moodle_url('/course/loginas.php', array('id' => $course->id, 'sesskey' => sesskey()));
        $userrevert->pix = "a/logout";
        $userrevert->title = get_string('logout');
        $lastobj = $userrevert;
        $buildlogout = false;
    }
    if ($buildlogout) {
        // Build a logout link.
        $logout = new stdClass();
        $logout->itemtype = 'link';
        $logout->url = new moodle_url('/login/logout.php', array('sesskey' => sesskey()));
        $logout->pix = "a/logout";
        $logout->title = get_string('logout');
        $lastobj = $logout;
    }
    // Before we add the last item (usually a logout link), add any
    // custom-defined items.
    $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
    foreach ($customitems as $item) {
        $returnobject->navitems[] = $item;
    }
    // Add the last item to the list.
    if (!is_null($lastobj)) {
        $returnobject->navitems[] = $lastobj;
    }
    return $returnobject;
}
Example #26
0
/**
 * Send an email to a specified user
 *
 * @uses $CFG
 * @uses $FULLME
 * @uses $MNETIDPJUMPURL IdentityProvider(IDP) URL user hits to jump to mnet peer.
 * @uses SITEID
 * @param user $user  A {@link $USER} object
 * @param user $from A {@link $USER} object
 * @param string $subject plain text subject line of the email
 * @param string $messagetext plain text version of the message
 * @param string $messagehtml complete html version of the message (optional)
 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
 * @param string $attachname the name of the file (extension indicates MIME)
 * @param bool $usetrueaddress determines whether $from email address should
 *          be sent out. Will be overruled by user profile setting for maildisplay
 * @param int $wordwrapwidth custom word wrap width
 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
 *          was blocked by user and "false" if there was another sort of error.
 */
function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '', $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79)
{
    global $CFG, $FULLME, $MNETIDPJUMPURL;
    static $mnetjumps = array();
    if (empty($user) || empty($user->email)) {
        return false;
    }
    if (!empty($user->deleted)) {
        // do not mail delted users
        return false;
    }
    if (!empty($CFG->noemailever)) {
        // hidden setting for development sites, set in config.php if needed
        return true;
    }
    // skip mail to suspended users
    if (isset($user->auth) && $user->auth == 'nologin') {
        return true;
    }
    if (!empty($user->emailstop)) {
        return 'emailstop';
    }
    if (over_bounce_threshold($user)) {
        error_log("User {$user->id} (" . fullname($user) . ") is over bounce threshold! Not sending.");
        return false;
    }
    // If the user is a remote mnet user, parse the email text for URL to the
    // wwwroot and modify the url to direct the user's browser to login at their
    // home site (identity provider - idp) before hitting the link itself
    if (is_mnet_remote_user($user)) {
        require_once $CFG->dirroot . '/mnet/lib.php';
        // Form the request url to hit the idp's jump.php
        if (isset($mnetjumps[$user->mnethostid])) {
            $MNETIDPJUMPURL = $mnetjumps[$user->mnethostid];
        } else {
            $idp = mnet_get_peer_host($user->mnethostid);
            $idpjumppath = '/auth/mnet/jump.php';
            $MNETIDPJUMPURL = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
            $mnetjumps[$user->mnethostid] = $MNETIDPJUMPURL;
        }
        $messagetext = preg_replace_callback("%({$CFG->wwwroot}[^[:space:]]*)%", 'mnet_sso_apply_indirection', $messagetext);
        $messagehtml = preg_replace_callback("%href=[\"'`]({$CFG->wwwroot}[\\w_:\\?=#&@/;.~-]*)[\"'`]%", 'mnet_sso_apply_indirection', $messagehtml);
    }
    $mail =& get_mailer();
    if (!empty($mail->SMTPDebug)) {
        echo '<pre>' . "\n";
    }
    /// We are going to use textlib services here
    $textlib = textlib_get_instance();
    $supportuser = generate_email_supportuser();
    // make up an email address for handling bounces
    if (!empty($CFG->handlebounces)) {
        $modargs = 'B' . base64_encode(pack('V', $user->id)) . substr(md5($user->email), 0, 16);
        $mail->Sender = generate_email_processing_address(0, $modargs);
    } else {
        $mail->Sender = $supportuser->email;
    }
    if (is_string($from)) {
        // So we can pass whatever we want if there is need
        $mail->From = $CFG->noreplyaddress;
        $mail->FromName = $from;
    } else {
        if ($usetrueaddress and $from->maildisplay) {
            $mail->From = stripslashes($from->email);
            $mail->FromName = fullname($from);
        } else {
            $mail->From = $CFG->noreplyaddress;
            $mail->FromName = fullname($from);
            if (empty($replyto)) {
                $mail->AddReplyTo($CFG->noreplyaddress, get_string('noreplyname'));
            }
        }
    }
    if (!empty($replyto)) {
        $mail->AddReplyTo($replyto, $replytoname);
    }
    $mail->Subject = substr(stripslashes($subject), 0, 900);
    $mail->AddAddress(stripslashes($user->email), fullname($user));
    $mail->WordWrap = $wordwrapwidth;
    // set word wrap
    if (!empty($from->customheaders)) {
        // Add custom headers
        if (is_array($from->customheaders)) {
            foreach ($from->customheaders as $customheader) {
                $mail->AddCustomHeader($customheader);
            }
        } else {
            $mail->AddCustomHeader($from->customheaders);
        }
    }
    if (!empty($from->priority)) {
        $mail->Priority = $from->priority;
    }
    if ($messagehtml && $user->mailformat == 1) {
        // Don't ever send HTML to users who don't want it
        $mail->IsHTML(true);
        $mail->Encoding = 'quoted-printable';
        // Encoding to use
        $mail->Body = $messagehtml;
        $mail->AltBody = "\n{$messagetext}\n";
    } else {
        $mail->IsHTML(false);
        $mail->Body = "\n{$messagetext}\n";
    }
    if ($attachment && $attachname) {
        if (ereg("\\.\\.", $attachment)) {
            // Security check for ".." in dir path
            $mail->AddAddress($supportuser->email, fullname($supportuser, true));
            $mail->AddStringAttachment('Error in attachment.  User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
        } else {
            require_once $CFG->libdir . '/filelib.php';
            $mimetype = mimeinfo('type', $attachname);
            $mail->AddAttachment($CFG->dataroot . '/' . $attachment, $attachname, 'base64', $mimetype);
        }
    }
    /// If we are running under Unicode and sitemailcharset or allowusermailcharset are set, convert the email
    /// encoding to the specified one
    if (!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset)) {
        /// Set it to site mail charset
        $charset = $CFG->sitemailcharset;
        /// Overwrite it with the user mail charset
        if (!empty($CFG->allowusermailcharset)) {
            if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
                $charset = $useremailcharset;
            }
        }
        /// If it has changed, convert all the necessary strings
        $charsets = get_list_of_charsets();
        unset($charsets['UTF-8']);
        if (in_array($charset, $charsets)) {
            /// Save the new mail charset
            $mail->CharSet = $charset;
            /// And convert some strings
            $mail->FromName = $textlib->convert($mail->FromName, 'utf-8', $mail->CharSet);
            //From Name
            foreach ($mail->ReplyTo as $key => $rt) {
                //ReplyTo Names
                $mail->ReplyTo[$key][1] = $textlib->convert($rt[1], 'utf-8', $mail->CharSet);
            }
            $mail->Subject = $textlib->convert($mail->Subject, 'utf-8', $mail->CharSet);
            //Subject
            foreach ($mail->to as $key => $to) {
                $mail->to[$key][1] = $textlib->convert($to[1], 'utf-8', $mail->CharSet);
                //To Names
            }
            $mail->Body = $textlib->convert($mail->Body, 'utf-8', $mail->CharSet);
            //Body
            $mail->AltBody = $textlib->convert($mail->AltBody, 'utf-8', $mail->CharSet);
            //Subject
        }
    }
    if ($mail->Send()) {
        set_send_count($user);
        $mail->IsSMTP();
        // use SMTP directly
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return true;
    } else {
        mtrace('ERROR: ' . $mail->ErrorInfo);
        add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: ' . $mail->ErrorInfo);
        if (!empty($mail->SMTPDebug)) {
            echo '</pre>';
        }
        return false;
    }
}
 /**
  * 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;
 }
Example #28
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>';
}
 /**
  * This function gets called by {@link settings_navigation::load_user_settings()} and actually works out
  * what can be shown/done
  *
  * @param int $courseid The current course' id
  * @param int $userid The user id to load for
  * @param string $gstitle The string to pass to get_string for the branch title
  * @return navigation_node|false
  */
 protected function generate_user_settings($courseid, $userid, $gstitle = 'usercurrentsettings')
 {
     global $DB, $CFG, $USER, $SITE;
     if ($courseid != $SITE->id) {
         if (!empty($this->page->course->id) && $this->page->course->id == $courseid) {
             $course = $this->page->course;
         } else {
             $select = context_helper::get_preload_record_columns_sql('ctx');
             $sql = "SELECT c.*, {$select}\n                          FROM {course} c\n                          JOIN {context} ctx ON c.id = ctx.instanceid\n                         WHERE c.id = :courseid AND ctx.contextlevel = :contextlevel";
             $params = array('courseid' => $courseid, 'contextlevel' => CONTEXT_COURSE);
             $course = $DB->get_record_sql($sql, $params, MUST_EXIST);
             context_helper::preload_from_record($course);
         }
     } else {
         $course = $SITE;
     }
     $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
     // Course context
     $systemcontext = get_system_context();
     $currentuser = $USER->id == $userid;
     if ($currentuser) {
         $user = $USER;
         $usercontext = get_context_instance(CONTEXT_USER, $user->id);
         // User context
     } else {
         $select = context_helper::get_preload_record_columns_sql('ctx');
         $sql = "SELECT u.*, {$select}\n                      FROM {user} u\n                      JOIN {context} ctx ON u.id = ctx.instanceid\n                     WHERE u.id = :userid AND ctx.contextlevel = :contextlevel";
         $params = array('userid' => $userid, 'contextlevel' => CONTEXT_USER);
         $user = $DB->get_record_sql($sql, $params, IGNORE_MISSING);
         if (!$user) {
             return false;
         }
         context_helper::preload_from_record($user);
         // Check that the user can view the profile
         $usercontext = get_context_instance(CONTEXT_USER, $user->id);
         // User context
         $canviewuser = has_capability('moodle/user:viewdetails', $usercontext);
         if ($course->id == $SITE->id) {
             if ($CFG->forceloginforprofiles && !has_coursecontact_role($user->id) && !$canviewuser) {
                 // Reduce possibility of "browsing" userbase at site level
                 // Teachers can browse and be browsed at site level. If not forceloginforprofiles, allow access (bug #4366)
                 return false;
             }
         } else {
             $canviewusercourse = has_capability('moodle/user:viewdetails', $coursecontext);
             $canaccessallgroups = has_capability('moodle/site:accessallgroups', $coursecontext);
             if (!$canviewusercourse && !$canviewuser || !can_access_course($course, $user->id)) {
                 return false;
             }
             if (!$canaccessallgroups && groups_get_course_groupmode($course) == SEPARATEGROUPS) {
                 // If groups are in use, make sure we can see that group
                 return false;
             }
         }
     }
     $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $this->page->context));
     $key = $gstitle;
     if ($gstitle != 'usercurrentsettings') {
         $key .= $userid;
     }
     // Add a user setting branch
     $usersetting = $this->add(get_string($gstitle, 'moodle', $fullname), null, self::TYPE_CONTAINER, null, $key);
     $usersetting->id = 'usersettings';
     if ($this->page->context->contextlevel == CONTEXT_USER && $this->page->context->instanceid == $user->id) {
         // Automatically start by making it active
         $usersetting->make_active();
     }
     // Check if the user has been deleted
     if ($user->deleted) {
         if (!has_capability('moodle/user:update', $coursecontext)) {
             // We can't edit the user so just show the user deleted message
             $usersetting->add(get_string('userdeleted'), null, self::TYPE_SETTING);
         } else {
             // We can edit the user so show the user deleted message and link it to the profile
             if ($course->id == $SITE->id) {
                 $profileurl = new moodle_url('/user/profile.php', array('id' => $user->id));
             } else {
                 $profileurl = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $course->id));
             }
             $usersetting->add(get_string('userdeleted'), $profileurl, self::TYPE_SETTING);
         }
         return true;
     }
     $userauthplugin = false;
     if (!empty($user->auth)) {
         $userauthplugin = get_auth_plugin($user->auth);
     }
     // Add the profile edit link
     if (isloggedin() && !isguestuser($user) && !is_mnet_remote_user($user)) {
         if (($currentuser || is_siteadmin($USER) || !is_siteadmin($user)) && has_capability('moodle/user:update', $systemcontext)) {
             $url = new moodle_url('/user/editadvanced.php', array('id' => $user->id, 'course' => $course->id));
             $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
         } else {
             if (has_capability('moodle/user:editprofile', $usercontext) && !is_siteadmin($user) || $currentuser && has_capability('moodle/user:editownprofile', $systemcontext)) {
                 if ($userauthplugin && $userauthplugin->can_edit_profile()) {
                     $url = $userauthplugin->edit_profile_url();
                     if (empty($url)) {
                         $url = new moodle_url('/user/edit.php', array('id' => $user->id, 'course' => $course->id));
                     }
                     $usersetting->add(get_string('editmyprofile'), $url, self::TYPE_SETTING);
                 }
             }
         }
     }
     // Change password link
     if ($userauthplugin && $currentuser && !session_is_loggedinas() && !isguestuser() && has_capability('moodle/user:changeownpassword', $systemcontext) && $userauthplugin->can_change_password()) {
         $passwordchangeurl = $userauthplugin->change_password_url();
         if (empty($passwordchangeurl)) {
             $passwordchangeurl = new moodle_url('/login/change_password.php', array('id' => $course->id));
         }
         $usersetting->add(get_string("changepassword"), $passwordchangeurl, self::TYPE_SETTING);
     }
     // View the roles settings
     if (has_any_capability(array('moodle/role:assign', 'moodle/role:safeoverride', 'moodle/role:override', 'moodle/role:manage'), $usercontext)) {
         $roles = $usersetting->add(get_string('roles'), null, self::TYPE_SETTING);
         $url = new moodle_url('/admin/roles/usersroles.php', array('userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('thisusersroles', 'role'), $url, self::TYPE_SETTING);
         $assignableroles = get_assignable_roles($usercontext, ROLENAME_BOTH);
         if (!empty($assignableroles)) {
             $url = new moodle_url('/admin/roles/assign.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('assignrolesrelativetothisuser', 'role'), $url, self::TYPE_SETTING);
         }
         if (has_capability('moodle/role:review', $usercontext) || count(get_overridable_roles($usercontext, ROLENAME_BOTH)) > 0) {
             $url = new moodle_url('/admin/roles/permissions.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
             $roles->add(get_string('permissions', 'role'), $url, self::TYPE_SETTING);
         }
         $url = new moodle_url('/admin/roles/check.php', array('contextid' => $usercontext->id, 'userid' => $user->id, 'courseid' => $course->id));
         $roles->add(get_string('checkpermissions', 'role'), $url, self::TYPE_SETTING);
     }
     // Portfolio
     if ($currentuser && !empty($CFG->enableportfolios) && has_capability('moodle/portfolio:export', $systemcontext)) {
         require_once $CFG->libdir . '/portfoliolib.php';
         if (portfolio_instances(true, false)) {
             $portfolio = $usersetting->add(get_string('portfolios', 'portfolio'), null, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfolio.php', array('courseid' => $course->id));
             $portfolio->add(get_string('configure', 'portfolio'), $url, self::TYPE_SETTING);
             $url = new moodle_url('/user/portfoliologs.php', array('courseid' => $course->id));
             $portfolio->add(get_string('logs', 'portfolio'), $url, self::TYPE_SETTING);
         }
     }
     $enablemanagetokens = false;
     if (!empty($CFG->enablerssfeeds)) {
         $enablemanagetokens = true;
     } else {
         if (!is_siteadmin($USER->id) && !empty($CFG->enablewebservices) && has_capability('moodle/webservice:createtoken', get_system_context())) {
             $enablemanagetokens = true;
         }
     }
     // Security keys
     if ($currentuser && $enablemanagetokens) {
         $url = new moodle_url('/user/managetoken.php', array('sesskey' => sesskey()));
         $usersetting->add(get_string('securitykeys', 'webservice'), $url, self::TYPE_SETTING);
     }
     // Repository
     if (!$currentuser && $usercontext->contextlevel == CONTEXT_USER) {
         if (!$this->cache->cached('contexthasrepos' . $usercontext->id)) {
             require_once $CFG->dirroot . '/repository/lib.php';
             $editabletypes = repository::get_editable_types($usercontext);
             $haseditabletypes = !empty($editabletypes);
             unset($editabletypes);
             $this->cache->set('contexthasrepos' . $usercontext->id, $haseditabletypes);
         } else {
             $haseditabletypes = $this->cache->{'contexthasrepos' . $usercontext->id};
         }
         if ($haseditabletypes) {
             $url = new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id));
             $usersetting->add(get_string('repositories', 'repository'), $url, self::TYPE_SETTING);
         }
     }
     // Messaging
     if ($currentuser && has_capability('moodle/user:editownmessageprofile', $systemcontext) || !isguestuser($user) && has_capability('moodle/user:editmessageprofile', $usercontext) && !is_primary_admin($user->id)) {
         $url = new moodle_url('/message/edit.php', array('id' => $user->id));
         $usersetting->add(get_string('editmymessage', 'message'), $url, self::TYPE_SETTING);
     }
     // Blogs
     if ($currentuser && !empty($CFG->bloglevel)) {
         $blog = $usersetting->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER, null, 'blogs');
         $blog->add(get_string('preferences', 'blog'), new moodle_url('/blog/preferences.php'), navigation_node::TYPE_SETTING);
         if (!empty($CFG->useexternalblogs) && $CFG->maxexternalblogsperuser > 0 && has_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM))) {
             $blog->add(get_string('externalblogs', 'blog'), new moodle_url('/blog/external_blogs.php'), navigation_node::TYPE_SETTING);
             $blog->add(get_string('addnewexternalblog', 'blog'), new moodle_url('/blog/external_blog_edit.php'), navigation_node::TYPE_SETTING);
         }
     }
     // Login as ...
     if (!$user->deleted and !$currentuser && !session_is_loggedinas() && has_capability('moodle/user:loginas', $coursecontext) && !is_siteadmin($user->id)) {
         $url = new moodle_url('/course/loginas.php', array('id' => $course->id, 'user' => $user->id, 'sesskey' => sesskey()));
         $usersetting->add(get_string('loginas'), $url, self::TYPE_SETTING);
     }
     return $usersetting;
 }
Example #30
0
// require proper login; guest user can not change password
if (!isloggedin() or isguestuser()) {
    if (empty($SESSION->wantsurl)) {
        $SESSION->wantsurl = $CFG->httpswwwroot . '/login/change_password.php';
    }
    redirect(get_login_url());
}
// do not require change own password cap if change forced
if (!get_user_preferences('auth_forcepasswordchange', false)) {
    require_capability('moodle/user:changeownpassword', $systemcontext);
}
// do not allow "Logged in as" users to change any passwords
if (session_is_loggedinas()) {
    print_error('cannotcallscript');
}
if (is_mnet_remote_user($USER)) {
    $message = get_string('usercannotchangepassword', 'mnet');
    if ($idprovider = $DB->get_record('mnet_host', array('id' => $USER->mnethostid))) {
        $message .= get_string('userchangepasswordlink', 'mnet', $idprovider);
    }
    print_error('userchangepasswordlink', 'mnet', '', $message);
}
// load the appropriate auth plugin
$userauth = get_auth_plugin($USER->auth);
if (!$userauth->can_change_password()) {
    print_error('nopasswordchange', 'auth');
}
if ($changeurl = $userauth->change_password_url()) {
    // this internal scrip not used
    redirect($changeurl);
}