protected function mycourses($CFG, $sidebar) { $mycourses = enrol_get_users_courses($_SESSION['USER']->id); $courselist = array(); foreach ($mycourses as $key => $val) { $courselist[] = $val->id; } $content = ''; for ($x = 1; $x <= sizeof($courselist); $x++) { $course = get_course($courselist[$x - 1]); $title = $course->fullname; if ($course instanceof stdClass) { require_once $CFG->libdir . '/coursecatlib.php'; $course = new course_in_list($course); } $url = $CFG->wwwroot . "/theme/keats/pix/coursenoimage.jpg"; foreach ($course->get_course_overviewfiles() as $file) { $isimage = $file->is_valid_image(); $url = file_encode_url("{$CFG->wwwroot}/pluginfile.php", '/' . $file->get_contextid() . '/' . $file->get_component() . '/' . $file->get_filearea() . $file->get_filepath() . $file->get_filename(), !$isimage); if (!$isimage) { $url = $CFG->wwwroot . "/theme/keats/pix/coursenoimage.jpg"; } } $content .= '<div class="view view-second view-mycourse ' . ($x % 3 == 0 ? 'view-nomargin' : '') . '"> <img src="' . $url . '" /> <div class="mask"> <h2>' . $title . '</h2> <a href="' . $CFG->wwwroot . '/course/view.php?id=' . $courselist[$x - 1] . '" class="info">Enter</a> </div> </div>'; } return $content; }
/** * Function to display a teacher's available exams. This uses all the * courses that a teacher is enrolled in and checks which course has * exams related to it. Shows the exam, the date and adds a */ function display_exams_list() { global $DB, $CFG, $USER; $IP_Address = $tableName = 'Exams'; $user_table = 'user'; $table = new html_table(); $table->head = array('Course', 'Date', 'Navigation'); $table->tablealign = 'center'; $table->width = '100%'; $user_courses = enrol_get_users_courses($USER->id, true, '*', 'visible DESC,sortorder ASC'); /** * Checks the teachers courses with available tests and if exists add to the main page. */ foreach ($user_courses as $uc) { $rec = $DB->get_records_sql('SELECT booklet_id, year_semester_origin FROM {mem_booklet_data} WHERE course_id=?', array(intval($uc->id))); $row_info = array(); if (count($rec) > 0) { $row = new html_table_row(array($uc->fullname, current($rec)->year_semester_origin, '<div style="text-align: center"><a href=' . $CFG->wwwroot . '/local/memplugin/grid.php?course_id=' . intval($uc->id) . '>' . get_string('startmarking', 'local_memplugin') . '</a></div>')); $table->data[] = $row; } } echo html_writer::table($table); }
/** * Constructor. Sets local copies of user preferences and initialises grade_tree. * @param int $userid * @param object $gpr grade plugin return tracking object * @param string $context */ public function __construct($userid, $gpr, $context) { global $CFG, $COURSE, $DB; parent::__construct($COURSE->id, $gpr, $context); // Get the user (for full name). $this->user = $DB->get_record('user', array('id' => $userid)); // Load the user's courses. $this->courses = enrol_get_users_courses($this->user->id, false, 'id, shortname, showgrades'); $this->showrank = array(); $this->showrank['any'] = false; $this->showtotalsifcontainhidden = array(); if ($this->courses) { foreach ($this->courses as $course) { $this->showrank[$course->id] = grade_get_setting($course->id, 'report_overview_showrank', !empty($CFG->grade_report_overview_showrank)); if ($this->showrank[$course->id]) { $this->showrank['any'] = true; } $this->showtotalsifcontainhidden[$course->id] = grade_get_setting($course->id, 'report_overview_showtotalsifcontainhidden', $CFG->grade_report_overview_showtotalsifcontainhidden); } } // base url for sorting by first/last name $this->baseurl = $CFG->wwwroot . '/grade/overview/index.php?id=' . $userid; $this->pbarurl = $this->baseurl; $this->setup_table(); }
public function get_content() { global $DB; if ($this->content !== null) { return $this->content; } global $CFG, $USER, $PAGE; $this->content = new stdClass(); require_once($CFG->dirroot.'/blocks/queries/lib.php'); require_once($CFG->dirroot.'/blocks/queries/commentform.php'); require_once($CFG->dirroot.'/blocks/queries/queries_form.php'); //query to enrol users courses particulars $courses = enrol_get_users_courses($USER->id); //calling function for if login user instructor or not $instructorlogin = block_queries_getrole_user($courses,'instructor'); //calling function for if login user registrar or not $registrarlogin = block_queries_getrole_user($courses,'registrar'); //calling function for if login user student or not $studentlogin = block_queries_getrole_user($courses,'student'); /************calling function for getting data to the logged in user*************/ $this->content->text = block_queries_display_view($USER,$instructorlogin,$registrarlogin,$studentlogin); $this->content->footer = ''; $this->page->requires->js('/blocks/queries/js/commentform_popup.js'); // Return the content object return $this->content; }
/** * Get list of courses user is enrolled in (only active enrolments are returned). * Please note the current user must be able to access the course, otherwise the course is not included. * * @param int $userid * @return array of courses */ public static function get_users_courses($userid) { global $USER, $DB; // Do basic automatic PARAM checks on incoming data, using params description // If any problems are found then exceptions are thrown with helpful error messages $params = self::validate_parameters(self::get_users_courses_parameters(), array('userid' => $userid)); $courses = enrol_get_users_courses($params['userid'], true, 'id, shortname, fullname, idnumber, visible'); $result = array(); foreach ($courses as $course) { $context = context_course::instance($course->id, IGNORE_MISSING); try { self::validate_context($context); } catch (Exception $e) { // current user can not access this course, sorry we can not disclose who is enrolled in this course! continue; } if ($userid != $USER->id and !has_capability('moodle/course:viewparticipants', $context)) { // we need capability to view participants continue; } list($enrolledsqlselect, $enrolledparams) = get_enrolled_sql($context); $enrolledsql = "SELECT COUNT(*) FROM ({$enrolledsqlselect}) AS enrolleduserids"; $enrolledusercount = $DB->count_records_sql($enrolledsql, $enrolledparams); $result[] = array('id' => $course->id, 'shortname' => $course->shortname, 'fullname' => $course->fullname, 'idnumber' => $course->idnumber, 'visible' => $course->visible, 'enrolledusercount' => $enrolledusercount); } return $result; }
function message_print_contact_selector($countunreadtotal, $usergroup, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showcontactactionlinks, $page = 0) { global $PAGE; echo html_writer::start_tag('div', array('class' => 'contactselector mdl-align')); //if 0 unread messages and they've requested unread messages then show contacts if ($countunreadtotal == 0 && $usergroup == VIEW_UNREAD_MESSAGES) { $usergroup = VIEW_CONTACTS; } //if they have no blocked users and they've requested blocked users switch them over to contacts if (count($blockedusers) == 0 && $usergroup == VIEW_BLOCKED) { $usergroup = VIEW_CONTACTS; } $onlyactivecourses = true; $courses = enrol_get_users_courses($user1->id, $onlyactivecourses); $coursecontexts = message_get_course_contexts($courses); //we need one of these again so holding on to them $strunreadmessages = null; if ($countunreadtotal > 0) { //if there are unread messages $strunreadmessages = get_string('unreadmessages', 'message', $countunreadtotal); } message_print_usergroup_selector($usergroup, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages); $refreshpage = false; if ($usergroup == VIEW_UNREAD_MESSAGES) { message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $refreshpage, $PAGE->url, 1, $showcontactactionlinks, $strunreadmessages, $user2); } else { if ($usergroup == VIEW_CONTACTS || $usergroup == VIEW_SEARCH) { message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $refreshpage, $PAGE->url, 0, $showcontactactionlinks, $strunreadmessages, $user2); } else { if ($usergroup == VIEW_BLOCKED) { message_print_blocked_users($blockedusers, $PAGE->url, $showcontactactionlinks, null, $user2); } else { if (substr($usergroup, 0, 7) == VIEW_COURSE) { $courseidtoshow = intval(substr($usergroup, 7)); if (!empty($courseidtoshow) && array_key_exists($courseidtoshow, $coursecontexts) && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) { message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showcontactactionlinks, null, $page, $user2); } else { //shouldn't get here. User trying to access a course they're not in perhaps. add_to_log(SITEID, 'message', 'view', 'index.php', $usergroup); } } } } } echo html_writer::start_tag('form', array('action' => 'index.php', 'method' => 'GET')); echo html_writer::start_tag('fieldset'); $managebuttonclass = 'visible'; if ($usergroup == VIEW_SEARCH) { $managebuttonclass = 'hiddenelement'; } $strmanagecontacts = get_string('search', 'message'); echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'usergroup', 'value' => VIEW_SEARCH)); echo html_writer::empty_tag('input', array('type' => 'submit', 'value' => $strmanagecontacts, 'class' => $managebuttonclass)); echo html_writer::end_tag('fieldset'); echo html_writer::end_tag('form'); echo html_writer::end_tag('div'); }
function execute($data, $user, $courseid) { global $DB, $CFG; require_once $CFG->libdir . '/enrollib.php'; $finalcourses = array(); $mycourses = enrol_get_users_courses($user->id); if (!empty($mycourses)) { $finalcourses = array_keys($mycourses); } return $finalcourses; }
public function definition() { global $CFG, $USER, $DB; $mform = $this->_form; $mform->addElement('header', 'general', get_string('askaquestion', 'block_queries')); $courses = enrol_get_users_courses($USER->id); foreach ($courses as $course) { // to get instructors in course level $sql = "SELECT u.id, u.email, u.firstname, u.lastname\n FROM {context} AS cxt\n JOIN {role_assignments} AS ra\n ON cxt.id = ra.contextid \n JOIN {user} AS u\n ON ra.userid = u.id\n WHERE cxt.instanceid = {$course->id} AND ra.roleid = 10 AND cxt.contextlevel = 50"; $instructors = $DB->get_records_sql($sql); $instructors12 = array(); foreach ($instructors as $instructor) { $fullname = fullname($instructor); $instructors12[$instructor->id . ',instructor'] = $fullname; } } $registraroptions = array(); foreach ($courses as $course) { // to get registrars in course level $sql = "SELECT u.id, u.email, u.firstname, u.lastname\n FROM {context} AS cxt\n JOIN {role_assignments} AS ra\n ON cxt.id = ra.contextid \n JOIN {user} AS u\n ON ra.userid = u.id\n WHERE cxt.instanceid = {$course->id} AND ra.roleid = 9 AND cxt.contextlevel = 50"; $registrars = $DB->get_records_sql($sql); foreach ($registrars as $registrar) { $registrarfullname = fullname($registrar); $registraroptions[$registrar->id . ',registrar'] = $registrarfullname; } } $record = $DB->get_record_sql("SELECT * FROM {user} where id = 2"); $adminoption = array(); $adminoption[$record->id . ',admin'] = $record->firstname; $options = array(get_string('instructor', 'block_queries') => $instructors12, get_string('registrar', 'block_queries') => $registraroptions, get_string('admin', 'block_queries') => $adminoption); $mform->addElement('selectgroups', 'usertype', get_string('usertype', 'block_queries'), $options); $mform->addRule('usertype', get_string('required'), 'required', null, 'client'); $adminoption[$record->id] = $record->firstname; $mform->addElement('text', 'subject', get_string('subject', 'block_queries')); $mform->setType('subject', PARAM_RAW); $mform->addRule('subject', get_string('required'), 'required', null, 'client'); $mform->addElement('textarea', 'description', get_string('description', 'block_queries'), 'wrap="virtual" rows="3" cols="25"'); $mform->addRule('description', get_string('required'), 'required', null, 'client'); $this->add_action_buttons(FALSE, get_string('postquery', 'block_queries')); $mform->addElement('html', html_writer::tag('a', get_string('mypreviewqueries', 'block_queries'), array('href' => $CFG->wwwroot . '/blocks/queries/display_queries.php?studentid=' . $USER->id, 'class' => 'mypreviewqueries'))); }
function definition() { global $CFG, $DB, $USER; $mform = $this->_form; $attributes_heading = 'size="24"'; $attributes_radio_text = 'size="11"'; //General Section. $mform->addElement('header', 'general', get_string('genheader', 'local_memplugin')); //Get list of logged in user's enrolled courses and display as checkboxes. $user_courses = enrol_get_users_courses($USER->id, true, '*', 'visible DESC,sortorder ASC'); $select_course_array = array(); $select_course_array[0] = ''; // Add a blank space to the select box. $selectgroup = array(); //TODO Remove below Select code for checkboxes instead of dropdown foreach ($user_courses as $uc) { $select_course_array[$uc->id] = $uc->fullname; } $selectgroup[] = $mform->createElement('select', 'coursechoices', get_string('sectionheader', 'local_memplugin'), $select_course_array); $mform->addElement('group', 'courseselect', get_string('courses', 'local_memplugin'), $selectgroup, array('<br>'), false); //TODO For now we can only handle one course section but uncomment the following and get rid of the above //Selection items to make it checkboxes again. /* foreach ($user_courses as $uc){ $courses_group[] =& $mform->createElement('advcheckbox', 'courseboxes['.$uc->id.']', null, $uc->fullname, array('group'=>0),array(0,1)); } $mform->addElement('group', 'courseselect', get_string('courses', 'local_memplugin'), $courses_group, array('<br>'), false); */ $mform->addElement('header', 'fileheader', get_string('file', 'local_memplugin')); //Switch to a filepicker for now until we figure out how it works. //$mform->addElement('filemanager', 'files', get_string('exambatch', 'local_memplugin'), null, array('accepted_types' => 'image/png')); $mform->addElement('filepicker', 'userfile', get_string('exambatch', 'local_memplugin'), null, array('accepted_types' => 'application/zip')); $mform->closeHeaderBefore('buttonar'); $buttonarray = array(); //$buttonarray[] =& $mform->createElement('submit','savebutton', get_string('savebutton', 'local_memplugin')); $buttonarray[] =& $mform->createElement('submit', 'markbutton', get_string('markbutton', 'local_memplugin')); $buttonarray[] =& $mform->createElement('cancel'); $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false); }
/** * Constructor. Sets local copies of user preferences and initialises grade_tree. * @param int $userid * @param object $gpr grade plugin return tracking object * @param string $context */ public function __construct($userid, $gpr, $context) { global $CFG, $COURSE, $DB; parent::__construct($COURSE->id, $gpr, $context); // Get the user (for full name). $this->user = $DB->get_record('user', array('id' => $userid)); // Load the user's courses. $this->courses = enrol_get_users_courses($this->user->id, false, 'id, shortname, showgrades'); $this->showrank = array(); $this->showrank['any'] = false; $this->showtotalsifcontainhidden = array(); $this->studentcourseids = array(); $this->teachercourses = array(); $roleids = explode(',', get_config('moodle', 'gradebookroles')); if ($this->courses) { foreach ($this->courses as $course) { $this->showrank[$course->id] = grade_get_setting($course->id, 'report_overview_showrank', !empty($CFG->grade_report_overview_showrank)); if ($this->showrank[$course->id]) { $this->showrank['any'] = true; } $this->showtotalsifcontainhidden[$course->id] = grade_get_setting($course->id, 'report_overview_showtotalsifcontainhidden', $CFG->grade_report_overview_showtotalsifcontainhidden); $coursecontext = context_course::instance($course->id); foreach ($roleids as $roleid) { if (user_has_role_assignment($userid, $roleid, $coursecontext->id)) { $this->studentcourseids[$course->id] = $course->id; // We only need to check if one of the roleids has been assigned. break; } } if (has_capability('moodle/grade:viewall', $coursecontext, $userid)) { $this->teachercourses[$course->id] = $course; } } } // base url for sorting by first/last name $this->baseurl = $CFG->wwwroot . '/grade/overview/index.php?id=' . $userid; $this->pbarurl = $this->baseurl; $this->setup_table(); }
/** * Returns unread messages count and courses * @return array */ public static function count_unread_and_courses_messages($userid = '0') { global $DB, $USER; //Parameter validation //REQUIRED $params = self::validate_parameters(self::count_unread_messages_parameters(), array('userid' => $userid)); //Context validation //OPTIONAL but in most web service it should present $context = get_context_instance(CONTEXT_USER, $USER->id); self::validate_context($context); //Capability checking //OPTIONAL but in most web service it should present if (!has_capability('moodle/user:viewdetails', $context)) { throw new moodle_exception('cannotviewprofile'); } $messagecount = $DB->count_records_select('message', 'useridto=' . (int) $userid); $courses = enrol_get_users_courses($params['userid'], true, 'id, shortname, fullname, idnumber, visible'); $result = array('messagecount' => $messagecount, 'courses' => array()); foreach ($courses as $course) { $context = context_course::instance($course->id, IGNORE_MISSING); try { self::validate_context($context); } catch (Exception $e) { // current user can not access this course, sorry we can not disclose who is enrolled in this course! continue; } if ($userid != $USER->id and !has_capability('moodle/course:viewparticipants', $context)) { // we need capability to view participants continue; } list($enrolledsqlselect, $enrolledparams) = get_enrolled_sql($context); $enrolledsql = "SELECT COUNT('x') FROM ({$enrolledsqlselect}) enrolleduserids"; $enrolledusercount = $DB->count_records_sql($enrolledsql, $enrolledparams); $result['courses'][] = array('id' => $course->id, 'shortname' => $course->shortname, 'fullname' => $course->fullname, 'idnumber' => $course->idnumber, 'visible' => $course->visible, 'enrolledusercount' => $enrolledusercount); } return $result; }
function block_mystats_mycourses() { global $USER; $mycourses = array(); $count = 0; $enrolledcourses = enrol_get_users_courses($USER->id); foreach ($enrolledcourses as $course) { if (isset($USER->lastcourseaccess[$course->id])) { $course->lastaccess = $USER->lastcourseaccess[$course->id]; } else { $course->lastaccess = 0; } $mycourses[$course->id] = $course; $count++; } if (is_enabled_auth('mnet')) { $remotecourses = get_my_remotecourses(); foreach ($remotecourses as $course) { $mycourses[$course->id] = $course; $count++; } } return $mycourses; }
/** * Get list of courses user is enrolled in (only active enrolments are returned). * * Please note the current user must be able to access the course, otherwise the course is not included. * * @param int $userid * @return array of courses */ public static function get_users_courses($userid) { global $USER; // Do basic automatic PARAM checks on incoming data, using params description // If any problems are found then exceptions are thrown with helpful error messages $params = self::validate_parameters(self::get_users_courses_parameters(), array('userid' => $userid)); $courses = enrol_get_users_courses($params['userid'], true, 'id, shortname, fullname, idnumber, visible'); $result = array(); foreach ($courses as $course) { $context = get_context_instance(CONTEXT_COURSE, $course->id); try { self::validate_context($context); } catch (Exception $e) { // current user can not access this course, sorry we can not disclose who is enrolled in this course! continue; } if ($userid != $USER->id and !has_capability('moodle/course:viewparticipants', $context)) { // we need capability to view participants continue; } $result[] = array('id' => $course->id, 'shortname' => $course->shortname, 'fullname' => $course->fullname, 'idnumber' => $course->idnumber, 'visible' => $course->visible); } return $result; }
function block_mycourses_users() { global $CFG, $DB, $USER, $OUTPUT; $courses = enrol_get_users_courses($USER->id); //print_object($courses); $output = ''; foreach ($courses as $course) { $summary = $DB->get_record_sql("SELECT * FROM {course} WHERE id = {$course->id}"); //print_object($summary); $output .= "<div>"; $output .= html_writer::tag('b', $course->fullname, array()); $output .= html_writer::tag('p', $summary->summary, array()); $output .= html_writer::tag('a', get_string('launch', 'block_mycourses'), array()); $data = array(); $line = array(); $user = $DB->get_record_sql("SELECT firstname FROM {user} WHERE id = {$USER->id}"); $line[] = $user->firstname; $date1 = date('d/m/Y', $course->startdate); $line[] = $date1; $completed_date = $DB->get_record_sql("SELECT * FROM {course_completions} WHERE course = {$course->id}"); $date2 = date('d/m/Y', $completed_date->timecompleted); if (!empty($date2)) { $line[] = "--"; } else { $line[] = $date2; } $data[] = $line; $table = new html_table(); $table->head = array(get_string('training_name', 'block_mycourses'), get_string('training_code', 'block_mycourses'), get_string('launch', 'block_mycourses')); $table->data = $data; $output .= html_writer::table($table); $output .= html_writer::tag('a', get_string('launch', 'block_mycourses'), array()); $output .= "</div>"; } return $output; }
/** * Loads user specific information into the navigation in the appropriate place. * * If no user is provided the current user is assumed. * * @param stdClass $user * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means) * @return bool */ protected function load_for_user($user = null, $forceforcontext = false) { global $DB, $CFG, $USER, $SITE; if ($user === null) { // We can't require login here but if the user isn't logged in we don't // want to show anything if (!isloggedin() || isguestuser()) { return false; } $user = $USER; } else { if (!is_object($user)) { // If the user is not an object then get them from the database $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\n ctx.contextlevel = :contextlevel"; $user = $DB->get_record_sql($sql, array('userid' => (int) $user, 'contextlevel' => CONTEXT_USER), MUST_EXIST); context_helper::preload_from_record($user); } } $iscurrentuser = $user->id == $USER->id; $usercontext = context_user::instance($user->id); // Get the course set against the page, by default this will be the site $course = $this->page->course; $baseargs = array('id' => $user->id); if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) { $coursenode = $this->add_course($course, false, self::COURSE_CURRENT); $baseargs['course'] = $course->id; $coursecontext = context_course::instance($course->id); $issitecourse = false; } else { // Load all categories and get the context for the system $coursecontext = context_system::instance(); $issitecourse = true; } // Create a node to add user information under. $usersnode = null; if (!$issitecourse) { // Not the current user so add it to the participants node for the current course. $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER); $userviewurl = new moodle_url('/user/view.php', $baseargs); } else { if ($USER->id != $user->id) { // This is the site so add a users node to the root branch. $usersnode = $this->rootnodes['users']; if (has_capability('moodle/course:viewparticipants', $coursecontext)) { $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id)); } $userviewurl = new moodle_url('/user/profile.php', $baseargs); } } if (!$usersnode) { // We should NEVER get here, if the course hasn't been populated // with a participants node then the navigaiton either wasn't generated // for it (you are missing a require_login or set_context call) or // you don't have access.... in the interests of no leaking informatin // we simply quit... return false; } // Add a branch for the current user. $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext); $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, 'user' . $user->id); if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) { $usernode->make_active(); } // Add user information to the participants or user node. if ($issitecourse) { // If the user is the current user or has permission to view the details of the requested // user than add a view profile link. if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) { if ($issitecourse || $iscurrentuser && !$forceforcontext) { $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs)); } else { $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs)); } } 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 = $usernode->add(get_string('forumposts', 'forum')); $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs)); $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode' => 'discussions')))); } // 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 = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER); foreach ($options as $type => $option) { if ($type == "rss") { $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', '')); } else { $blogs->add($option['string'], $option['link']); } } } } // 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); $usernode->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'); $usernode->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); } $usernode->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)); } if ($USER->id != $user->id) { $usernode->add(get_string('grades', 'grades'), $url, self::TYPE_SETTING, null, 'usergrades'); } else { $usernode->add(get_string('grades', 'grades'), $url); } } // If the user is the current user add the repositories for the current user. $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields)); if (!$iscurrentuser && $course->id == $SITE->id && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) { // Add view grade report is permitted. $reports = core_component::get_plugin_list('gradereport'); arsort($reports); // User is last, we want to test it first. $userscourses = enrol_get_users_courses($user->id); $userscoursesnode = $usernode->add(get_string('courses')); $count = 0; foreach ($userscourses as $usercourse) { if ($count === (int) $CFG->navcourselimit) { $url = new moodle_url('/user/profile.php', array('id' => $user->id, 'showallcourses' => 1)); $userscoursesnode->add(get_string('showallcourses'), $url); break; } $count++; $usercoursecontext = context_course::instance($usercourse->id); $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext)); $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER); $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext); if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) { foreach ($reports as $plugin => $plugindir) { if (has_capability('gradereport/' . $plugin . ':view', $usercoursecontext)) { // Stop when the first visible plugin is found. $gradeavailable = true; break; } } } if ($gradeavailable) { $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id)); $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', '')); } // Add a node to view the users notes if permitted. if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) { $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id)); $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING); } if (can_access_course($usercourse, $user->id, '', true)) { $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php', array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', '')); } $reporttab = $usercoursenode->add(get_string('activityreports')); $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php'); foreach ($reports as $reportfunction) { $reportfunction($reporttab, $user, $usercourse); } $reporttab->trim_if_empty(); } } // 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($usernode, $user, $usercontext, $course, $coursecontext); } } } } return true; }
function att_get_user_courses_attendances($userid) { global $DB; $usercourses = enrol_get_users_courses($userid); list($usql, $uparams) = $DB->get_in_or_equal(array_keys($usercourses), SQL_PARAMS_NAMED, 'cid0'); $sql = "SELECT att.id as attid, att.course as courseid, course.fullname as coursefullname,\n course.startdate as coursestartdate, att.name as attname, att.grade as attgrade\n FROM {attendance} att\n JOIN {course} course\n ON att.course = course.id\n WHERE att.course {$usql}\n ORDER BY coursefullname ASC, attname ASC"; $params = array_merge($uparams, array('uid' => $userid)); return $DB->get_records_sql($sql, $params); }
$PAGE->requires->js('/teacher/html-table-search.js',true); $PAGE->requires->css('/teacher/bootstrap-select.css',true); $PAGE->requires->js('/teacher/bootstrap-select.js',true); echo "<input id='baseurl' type='hidden' value=".$CFG->wwwroot ."/>"; require_once($CFG->dirroot.'/teacher/customlib.php'); $PAGE->requires->js('/teacher/custom.js',true); $PAGE->requires->css('/teacher/styles.css',true); if(user_has_role_assignment($USER->id,3)) { $context = context_user::instance($USER->id); $PAGE->set_context($context); $enrolledcourses = block_course_overview_get_sorted_courses(); $cours = enrol_get_users_courses($USER->id); echo $OUTPUT->header(); ?> <div id="demo"> <div id="watchlist"> <a href="<?php echo $CFG->wwwroot?>/teacher/dashboard.php" class='link'>Courses</a> <a href="<?php echo $CFG->wwwroot?>/teacher/reports.php" class='link'>Reports</a> <a href="<?php echo $CFG->wwwroot?>/teacher/watchlist.php" class='current link' >Watchlist</a> <div class="yui3-skin-sam"> <div id="course-sel"> <?php $html = html_writer::start_tag('form', array('action' => new moodle_url('/teacher/inx.php'),
/** * Tries to obtain user details, either recurring directly to the user's system profile * or through one of the user's course enrollments (course profile). * * @param object $user The user. * @return array if unsuccessful or the allowed user details. */ function user_get_user_details_courses($user) { global $USER; $userdetails = null; // Get the courses that the user is enrolled in (only active). $courses = enrol_get_users_courses($user->id, true); $systemprofile = false; if (can_view_user_details_cap($user) || $user->id == $USER->id || has_coursecontact_role($user->id)) { $systemprofile = true; } // Try using system profile. if ($systemprofile) { $userdetails = user_get_user_details($user, null); } else { // Try through course profile. foreach ($courses as $course) { if (can_view_user_details_cap($user, $course) || $user->id == $USER->id || has_coursecontact_role($user->id)) { $userdetails = user_get_user_details($user, $course); } } } return $userdetails; }
} if ($course->groupmode != NOGROUPS) { $groupstr .= ' <a href="' . $CFG->wwwroot . '/user/index.php?id=' . $course->id . '&group=' . $group->id . '">' . format_string($group->name) . '</a>,'; } else { $groupstr .= ' ' . format_string($group->name); // the user/index.php shows groups only when course in group mode } } if ($groupstr !== '') { print_row(get_string("group") . ":", rtrim($groupstr, ', ')); } } } // Show other courses they may be in if (!isset($hiddenfields['mycourses'])) { if ($mycourses = enrol_get_users_courses($user->id, true, NULL, 'visible DESC,sortorder ASC')) { $shown = 0; $courselisting = ''; foreach ($mycourses as $mycourse) { if ($mycourse->category) { if ($mycourse->id != $course->id) { $class = ''; if ($mycourse->visible == 0) { $ccontext = get_context_instance(CONTEXT_COURSE, $mycourse->id); if (!has_capability('moodle/course:viewhiddencourses', $ccontext)) { continue; } $class = 'class="dimmed"'; } $courselisting .= "<a href=\"{$CFG->wwwroot}/user/view.php?id={$user->id}&course={$mycourse->id}\" {$class} >" . format_string($mycourse->fullname) . "</a>, "; } else {
/** * Print the selector that allows the user to view their contacts, course participants, their recent * conversations etc * * @param int $countunreadtotal how many unread messages does the user have? * @param int $viewing What is the user viewing? ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_SEARCH etc * @param object $user1 the user whose messages are being viewed * @param object $user2 the user $user1 is talking to * @param array $blockedusers an array of users blocked by $user1 * @param array $onlinecontacts an array of $user1's online contacts * @param array $offlinecontacts an array of $user1's offline contacts * @param array $strangers an array of users who have messaged $user1 who aren't contacts * @param bool $showactionlinks show action links (add/remove contact etc) * @param int $page if there are so many users listed that they have to be split into pages what page are we viewing * @return void */ function message_print_contact_selector($countunreadtotal, $viewing, $user1, $user2, $blockedusers, $onlinecontacts, $offlinecontacts, $strangers, $showactionlinks, $page=0) { global $PAGE; echo html_writer::start_tag('div', array('class' => 'contactselector mdl-align')); //if 0 unread messages and they've requested unread messages then show contacts if ($countunreadtotal == 0 && $viewing == MESSAGE_VIEW_UNREAD_MESSAGES) { $viewing = MESSAGE_VIEW_CONTACTS; } //if they have no blocked users and they've requested blocked users switch them over to contacts if (count($blockedusers) == 0 && $viewing == MESSAGE_VIEW_BLOCKED) { $viewing = MESSAGE_VIEW_CONTACTS; } $onlyactivecourses = true; $courses = enrol_get_users_courses($user1->id, $onlyactivecourses); $coursecontexts = message_get_course_contexts($courses);//we need one of these again so holding on to them $strunreadmessages = null; if ($countunreadtotal>0) { //if there are unread messages $strunreadmessages = get_string('unreadmessages','message', $countunreadtotal); } message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, count($blockedusers), $strunreadmessages, $user1); if ($viewing == MESSAGE_VIEW_UNREAD_MESSAGES) { message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 1, $showactionlinks,$strunreadmessages, $user2); } else if ($viewing == MESSAGE_VIEW_CONTACTS || $viewing == MESSAGE_VIEW_SEARCH || $viewing == MESSAGE_VIEW_RECENT_CONVERSATIONS || $viewing == MESSAGE_VIEW_RECENT_NOTIFICATIONS) { message_print_contacts($onlinecontacts, $offlinecontacts, $strangers, $PAGE->url, 0, $showactionlinks, $strunreadmessages, $user2); } else if ($viewing == MESSAGE_VIEW_BLOCKED) { message_print_blocked_users($blockedusers, $PAGE->url, $showactionlinks, null, $user2); } else if (substr($viewing, 0, 7) == MESSAGE_VIEW_COURSE) { $courseidtoshow = intval(substr($viewing, 7)); if (!empty($courseidtoshow) && array_key_exists($courseidtoshow, $coursecontexts) && has_capability('moodle/course:viewparticipants', $coursecontexts[$courseidtoshow])) { message_print_participants($coursecontexts[$courseidtoshow], $courseidtoshow, $PAGE->url, $showactionlinks, null, $page, $user2); } } // Only show the search button if we're viewing our own contacts. if ($viewing == MESSAGE_VIEW_CONTACTS && $user2 == null) { echo html_writer::start_tag('form', array('action' => 'index.php','method' => 'GET')); echo html_writer::start_tag('fieldset'); $managebuttonclass = 'visible'; $strmanagecontacts = get_string('search','message'); echo html_writer::empty_tag('input', array('type' => 'hidden','name' => 'viewing','value' => MESSAGE_VIEW_SEARCH)); echo html_writer::empty_tag('input', array('type' => 'submit','value' => $strmanagecontacts,'class' => $managebuttonclass)); echo html_writer::end_tag('fieldset'); echo html_writer::end_tag('form'); } echo html_writer::end_tag('div'); }
/** * Returns an array of courses the user is enrolled in, and for each course all of the seplments that the user can * view within that course. * * @param array $courseids An optional array of course ids. If provided only seplments within the given course * will be returned. If the user is not enrolled in a given course a warning will be generated and returned. * @param array $capabilities An array of additional capability checks you wish to be made on the course context. * @return An array of courses and warnings. * @since Moodle 2.4 */ public static function get_seplments($courseids = array(), $capabilities = array()) { global $USER, $DB, $CFG; require_once "{$CFG->dirroot}/mod/sepl/locallib.php"; $params = self::validate_parameters(self::get_seplments_parameters(), array('courseids' => $courseids, 'capabilities' => $capabilities)); $warnings = array(); $fields = 'sortorder,shortname,fullname,timemodified'; $courses = enrol_get_users_courses($USER->id, true, $fields); // Used to test for ids that have been requested but can't be returned. if (count($params['courseids']) > 0) { foreach ($params['courseids'] as $courseid) { if (!in_array($courseid, array_keys($courses))) { unset($courses[$courseid]); $warnings[] = array('item' => 'course', 'itemid' => $courseid, 'warningcode' => '2', 'message' => 'User is not enrolled or does not have requested capability'); } } } foreach ($courses as $id => $course) { if (count($params['courseids']) > 0 && !in_array($id, $params['courseids'])) { unset($courses[$id]); } $context = context_course::instance($id); try { self::validate_context($context); } catch (Exception $e) { unset($courses[$id]); $warnings[] = array('item' => 'course', 'itemid' => $id, 'warningcode' => '1', 'message' => 'No access rights in course context ' . $e->getMessage() . $e->getTraceAsString()); continue; } if (count($params['capabilities']) > 0 && !has_all_capabilities($params['capabilities'], $context)) { unset($courses[$id]); } } $extrafields = 'm.id as seplmentid, ' . 'm.course, ' . 'm.nosubmissions, ' . 'm.submissiondrafts, ' . 'm.sendnotifications, ' . 'm.sendlatenotifications, ' . 'm.sendstudentnotifications, ' . 'm.duedate, ' . 'm.allowsubmissionsfromdate, ' . 'm.grade, ' . 'm.timemodified, ' . 'm.completionsubmit, ' . 'm.cutoffdate, ' . 'm.teamsubmission, ' . 'm.requireallteammemberssubmit, ' . 'm.teamsubmissiongroupingid, ' . 'm.blindmarking, ' . 'm.revealidentities, ' . 'm.attemptreopenmethod, ' . 'm.maxattempts, ' . 'm.markingworkflow, ' . 'm.markingallocation, ' . 'm.requiresubmissionstatement, ' . 'm.intro, ' . 'm.introformat'; $coursearray = array(); foreach ($courses as $id => $course) { $seplmentarray = array(); // Get a list of seplments for the course. if ($modules = get_coursemodules_in_course('sepl', $courses[$id]->id, $extrafields)) { foreach ($modules as $module) { $context = context_module::instance($module->id); try { self::validate_context($context); require_capability('mod/sepl:view', $context); } catch (Exception $e) { $warnings[] = array('item' => 'module', 'itemid' => $module->id, 'warningcode' => '1', 'message' => 'No access rights in module context'); continue; } $configrecords = $DB->get_recordset('sepl_plugin_config', array('seplment' => $module->seplmentid)); $configarray = array(); foreach ($configrecords as $configrecord) { $configarray[] = array('id' => $configrecord->id, 'seplment' => $configrecord->seplment, 'plugin' => $configrecord->plugin, 'subtype' => $configrecord->subtype, 'name' => $configrecord->name, 'value' => $configrecord->value); } $configrecords->close(); $seplment = array('id' => $module->seplmentid, 'cmid' => $module->id, 'course' => $module->course, 'name' => $module->name, 'nosubmissions' => $module->nosubmissions, 'submissiondrafts' => $module->submissiondrafts, 'sendnotifications' => $module->sendnotifications, 'sendlatenotifications' => $module->sendlatenotifications, 'sendstudentnotifications' => $module->sendstudentnotifications, 'duedate' => $module->duedate, 'allowsubmissionsfromdate' => $module->allowsubmissionsfromdate, 'grade' => $module->grade, 'timemodified' => $module->timemodified, 'completionsubmit' => $module->completionsubmit, 'cutoffdate' => $module->cutoffdate, 'teamsubmission' => $module->teamsubmission, 'requireallteammemberssubmit' => $module->requireallteammemberssubmit, 'teamsubmissiongroupingid' => $module->teamsubmissiongroupingid, 'blindmarking' => $module->blindmarking, 'revealidentities' => $module->revealidentities, 'attemptreopenmethod' => $module->attemptreopenmethod, 'maxattempts' => $module->maxattempts, 'markingworkflow' => $module->markingworkflow, 'markingallocation' => $module->markingallocation, 'requiresubmissionstatement' => $module->requiresubmissionstatement, 'configs' => $configarray); // Return or not intro and file attachments depending on the plugin settings. $sepl = new sepl($context, null, null); if ($sepl->show_intro()) { list($seplment['intro'], $seplment['introformat']) = external_format_text($module->intro, $module->introformat, $context->id, 'mod_sepl', ASSIGN_INTROATTACHMENT_FILEAREA, 0); $fs = get_file_storage(); if ($files = $fs->get_area_files($context->id, 'mod_sepl', ASSIGN_INTROATTACHMENT_FILEAREA, 0, 'timemodified', false)) { $seplment['introattachments'] = array(); foreach ($files as $file) { $filename = $file->get_filename(); $seplment['introattachments'][] = array('filename' => $filename, 'mimetype' => $file->get_mimetype(), 'fileurl' => moodle_url::make_webservice_pluginfile_url($context->id, 'mod_sepl', ASSIGN_INTROATTACHMENT_FILEAREA, 0, '/', $filename)->out(false)); } } } $seplmentarray[] = $seplment; } } $coursearray[] = array('id' => $courses[$id]->id, 'fullname' => $courses[$id]->fullname, 'shortname' => $courses[$id]->shortname, 'timemodified' => $courses[$id]->timemodified, 'seplments' => $seplmentarray); } $result = array('courses' => $coursearray, 'warnings' => $warnings); return $result; }
/** * Returns the aggregated or calculated course grade for the given user(s). * @public * @param int $userid * @param int $courseid optional id of course or array of ids, empty means all uses courses (returns array if not present) * @return mixed grade info or grades array including item info, false if error */ function grade_get_course_grade($userid, $courseid_or_ids = null) { if (!is_array($courseid_or_ids)) { if (empty($courseid_or_ids)) { if (!($courses = enrol_get_users_courses($userid))) { return false; } $courseids = array_keys($courses); return grade_get_course_grade($userid, $courseids); } if (!is_numeric($courseid_or_ids)) { return false; } if (!($grades = grade_get_course_grade($userid, array($courseid_or_ids)))) { return false; } else { // only one grade - not array $grade = reset($grades); return $grade; } } foreach ($courseid_or_ids as $courseid) { $grade_item = grade_item::fetch_course_item($courseid); $course_items[$grade_item->courseid] = $grade_item; } $grades = array(); foreach ($course_items as $grade_item) { if ($grade_item->needsupdate) { grade_regrade_final_grades($courseid); } $item = new stdClass(); $item->scaleid = $grade_item->scaleid; $item->name = $grade_item->get_name(); $item->grademin = $grade_item->grademin; $item->grademax = $grade_item->grademax; $item->gradepass = $grade_item->gradepass; $item->locked = $grade_item->is_locked(); $item->hidden = $grade_item->is_hidden(); switch ($grade_item->gradetype) { case GRADE_TYPE_NONE: continue; case GRADE_TYPE_VALUE: $item->scaleid = 0; break; case GRADE_TYPE_TEXT: $item->scaleid = 0; $item->grademin = 0; $item->grademax = 0; $item->gradepass = 0; break; } $grade_grade = new grade_grade(array('userid' => $userid, 'itemid' => $grade_item->id)); $grade_grade->grade_item =& $grade_item; $grade = new stdClass(); $grade->grade = $grade_grade->finalgrade; $grade->locked = $grade_grade->is_locked(); $grade->hidden = $grade_grade->is_hidden(); $grade->overridden = $grade_grade->overridden; $grade->feedback = $grade_grade->feedback; $grade->feedbackformat = $grade_grade->feedbackformat; $grade->usermodified = $grade_grade->usermodified; $grade->dategraded = $grade_grade->get_dategraded(); $grade->item = $item; // create text representation of grade if ($grade_item->needsupdate) { $grade->grade = false; $grade->str_grade = get_string('error'); $grade->str_long_grade = $grade->str_grade; } else { if (is_null($grade->grade)) { $grade->str_grade = '-'; $grade->str_long_grade = $grade->str_grade; } else { $grade->str_grade = grade_format_gradevalue($grade->grade, $grade_item); if ($grade_item->gradetype == GRADE_TYPE_SCALE or $grade_item->get_displaytype() != GRADE_DISPLAY_TYPE_REAL) { $grade->str_long_grade = $grade->str_grade; } else { $a = new stdClass(); $a->grade = $grade->str_grade; $a->max = grade_format_gradevalue($grade_item->grademax, $grade_item); $grade->str_long_grade = get_string('gradelong', 'grades', $a); } } } // create html representation of feedback if (is_null($grade->feedback)) { $grade->str_feedback = ''; } else { $grade->str_feedback = format_text($grade->feedback, $grade->feedbackformat); } $grades[$grade_item->courseid] = $grade; } return $grades; }
/** * This function confirms the remote (ID provider) host's mnet session * by communicating the token and UA over the XMLRPC transport layer, and * returns the local user record on success. * * @param string $token The random session token. * @param mnet_peer $remotepeer The ID provider mnet_peer object. * @return array The local user record. */ function confirm_mnet_session($token, $remotepeer) { global $CFG, $DB; require_once $CFG->dirroot . '/mnet/xmlrpc/client.php'; require_once $CFG->libdir . '/gdlib.php'; // verify the remote host is configured locally before attempting RPC call if (!($remotehost = $DB->get_record('mnet_host', array('wwwroot' => $remotepeer->wwwroot, 'deleted' => 0)))) { print_error('notpermittedtoland', 'mnet'); } // set up the RPC request $mnetrequest = new mnet_xmlrpc_client(); $mnetrequest->set_method('auth/mnet/auth.php/user_authorise'); // set $token and $useragent parameters $mnetrequest->add_param($token); $mnetrequest->add_param(sha1($_SERVER['HTTP_USER_AGENT'])); // Thunderbirds are go! Do RPC call and store response if ($mnetrequest->send($remotepeer) === true) { $remoteuser = (object) $mnetrequest->response; } else { foreach ($mnetrequest->error as $errormessage) { list($code, $message) = array_map('trim', explode(':', $errormessage, 2)); if ($code == 702) { $site = get_site(); print_error('mnet_session_prohibited', 'mnet', $remotepeer->wwwroot, format_string($site->fullname)); exit; } $message .= "ERROR {$code}:<br/>{$errormessage}<br/>"; } print_error("rpcerror", '', '', $message); } unset($mnetrequest); if (empty($remoteuser) or empty($remoteuser->username)) { print_error('unknownerror', 'mnet'); exit; } if (user_not_fully_set_up($remoteuser)) { print_error('notenoughidpinfo', 'mnet'); exit; } $remoteuser = mnet_strip_user($remoteuser, mnet_fields_to_import($remotepeer)); $remoteuser->auth = 'mnet'; $remoteuser->wwwroot = $remotepeer->wwwroot; // the user may roam from Moodle 1.x where lang has _utf8 suffix // also, make sure that the lang is actually installed, otherwise set site default if (isset($remoteuser->lang)) { $remoteuser->lang = clean_param(str_replace('_utf8', '', $remoteuser->lang), PARAM_LANG); } if (empty($remoteuser->lang)) { if (!empty($CFG->lang)) { $remoteuser->lang = $CFG->lang; } else { $remoteuser->lang = 'en'; } } $firsttime = false; // get the local record for the remote user $localuser = $DB->get_record('user', array('username' => $remoteuser->username, 'mnethostid' => $remotehost->id)); // add the remote user to the database if necessary, and if allowed // TODO: refactor into a separate function if (empty($localuser) || !$localuser->id) { /* if (empty($this->config->auto_add_remote_users)) { print_error('nolocaluser', 'mnet'); } See MDL-21327 for why this is commented out */ $remoteuser->mnethostid = $remotehost->id; $remoteuser->firstaccess = time(); // First time user in this server, grab it here $remoteuser->id = $DB->insert_record('user', $remoteuser); $firsttime = true; $localuser = $remoteuser; } // check sso access control list for permission first if (!$this->can_login_remotely($localuser->username, $remotehost->id)) { print_error('sso_mnet_login_refused', 'mnet', '', array('user' => $localuser->username, 'host' => $remotehost->name)); } $fs = get_file_storage(); // update the local user record with remote user data foreach ((array) $remoteuser as $key => $val) { if ($key == '_mnet_userpicture_timemodified' and empty($CFG->disableuserimages) and isset($remoteuser->picture)) { // update the user picture if there is a newer verion at the identity provider $usercontext = get_context_instance(CONTEXT_USER, $localuser->id, MUST_EXIST); if ($usericonfile = $fs->get_file($usercontext->id, 'user', 'icon', 0, '/', 'f1.png')) { $localtimemodified = $usericonfile->get_timemodified(); } else { if ($usericonfile = $fs->get_file($usercontext->id, 'user', 'icon', 0, '/', 'f1.jpg')) { $localtimemodified = $usericonfile->get_timemodified(); } else { $localtimemodified = 0; } } if (!empty($val) and $localtimemodified < $val) { mnet_debug('refetching the user picture from the identity provider host'); $fetchrequest = new mnet_xmlrpc_client(); $fetchrequest->set_method('auth/mnet/auth.php/fetch_user_image'); $fetchrequest->add_param($localuser->username); if ($fetchrequest->send($remotepeer) === true) { if (strlen($fetchrequest->response['f1']) > 0) { $imagefilename = $CFG->dataroot . '/temp/mnet-usericon-' . $localuser->id; $imagecontents = base64_decode($fetchrequest->response['f1']); file_put_contents($imagefilename, $imagecontents); if (process_new_icon($usercontext, 'user', 'icon', 0, $imagefilename)) { $localuser->picture = 1; } unlink($imagefilename); } // note that since Moodle 2.0 we ignore $fetchrequest->response['f2'] // the mimetype information provided is ignored and the type of the file is detected // by process_new_icon() } } } if ($key == 'myhosts') { $localuser->mnet_foreign_host_array = array(); foreach ($val as $rhost) { $name = clean_param($rhost['name'], PARAM_ALPHANUM); $url = clean_param($rhost['url'], PARAM_URL); $count = clean_param($rhost['count'], PARAM_INT); $url_is_local = stristr($url, $CFG->wwwroot); if (!empty($name) && !empty($count) && empty($url_is_local)) { $localuser->mnet_foreign_host_array[] = array('name' => $name, 'url' => $url, 'count' => $count); } } } $localuser->{$key} = $val; } $localuser->mnethostid = $remotepeer->id; if (empty($localuser->firstaccess)) { // Now firstaccess, grab it here $localuser->firstaccess = time(); } $DB->update_record('user', $localuser); if (!$firsttime) { // repeat customer! let the IDP know about enrolments // we have for this user. // set up the RPC request $mnetrequest = new mnet_xmlrpc_client(); $mnetrequest->set_method('auth/mnet/auth.php/update_enrolments'); // pass username and an assoc array of "my courses" // with info so that the IDP can maintain mnetservice_enrol_enrolments $mnetrequest->add_param($remoteuser->username); $fields = 'id, category, sortorder, fullname, shortname, idnumber, summary, startdate, visible'; $courses = enrol_get_users_courses($localuser->id, false, $fields, 'visible DESC,sortorder ASC'); if (is_array($courses) && !empty($courses)) { // Second request to do the JOINs that we'd have done // inside enrol_get_users_courses() if we had been allowed $sql = "SELECT c.id,\n cc.name AS cat_name, cc.description AS cat_description\n FROM {course} c\n JOIN {course_categories} cc ON c.category = cc.id\n WHERE c.id IN (" . join(',', array_keys($courses)) . ')'; $extra = $DB->get_records_sql($sql); $keys = array_keys($courses); $defaultrole = reset(get_archetype_roles('student')); //$defaultrole = get_default_course_role($ccache[$shortname]); //TODO: rewrite this completely, there is no default course role any more!!! foreach ($keys as $id) { if ($courses[$id]->visible == 0) { unset($courses[$id]); continue; } $courses[$id]->cat_id = $courses[$id]->category; $courses[$id]->defaultroleid = $defaultrole->id; unset($courses[$id]->category); unset($courses[$id]->visible); $courses[$id]->cat_name = $extra[$id]->cat_name; $courses[$id]->cat_description = $extra[$id]->cat_description; $courses[$id]->defaultrolename = $defaultrole->name; // coerce to array $courses[$id] = (array) $courses[$id]; } } else { // if the array is empty, send it anyway // we may be clearing out stale entries $courses = array(); } $mnetrequest->add_param($courses); // Call 0800-RPC Now! -- we don't care too much if it fails // as it's just informational. if ($mnetrequest->send($remotepeer) === false) { // error_log(print_r($mnetrequest->error,1)); } } return $localuser; }
/** * Returns an array of courses the user is enrolled, and for each course all of the assignments that the user can * view within that course. * * @param array $courseids An optional array of course ids. If provided only assignments within the given course * will be returned. If the user is not enrolled in or can't view a given course a warning will be generated and returned. * @param array $capabilities An array of additional capability checks you wish to be made on the course context. * @param bool $includenotenrolledcourses Wheter to return courses that the user can see even if is not enroled in. * This requires the parameter $courseids to not be empty. * @return An array of courses and warnings. * @since Moodle 2.4 */ public static function get_assignments($courseids = array(), $capabilities = array(), $includenotenrolledcourses = false) { global $USER, $DB, $CFG; $params = self::validate_parameters(self::get_assignments_parameters(), array('courseids' => $courseids, 'capabilities' => $capabilities, 'includenotenrolledcourses' => $includenotenrolledcourses)); $warnings = array(); $courses = array(); $fields = 'sortorder,shortname,fullname,timemodified'; // If the courseids list is empty, we return only the courses where the user is enrolled in. if (empty($params['courseids'])) { $courses = enrol_get_users_courses($USER->id, true, $fields); $courseids = array_keys($courses); } else { if ($includenotenrolledcourses) { // In this case, we don't have to check here for enrolmnents. Maybe the user can see the course even if is not enrolled. $courseids = $params['courseids']; } else { // We need to check for enrolments. $mycourses = enrol_get_users_courses($USER->id, true, $fields); $mycourseids = array_keys($mycourses); foreach ($params['courseids'] as $courseid) { if (!in_array($courseid, $mycourseids)) { unset($courses[$courseid]); $warnings[] = array('item' => 'course', 'itemid' => $courseid, 'warningcode' => '2', 'message' => 'User is not enrolled or does not have requested capability'); } else { $courses[$courseid] = $mycourses[$courseid]; } } $courseids = array_keys($courses); } } foreach ($courseids as $cid) { try { $context = context_course::instance($cid); self::validate_context($context); // Check if this course was already loaded (by enrol_get_users_courses). if (!isset($courses[$cid])) { $courses[$cid] = get_course($cid); } $courses[$cid]->contextid = $context->id; } catch (Exception $e) { unset($courses[$cid]); $warnings[] = array('item' => 'course', 'itemid' => $cid, 'warningcode' => '1', 'message' => 'No access rights in course context ' . $e->getMessage()); continue; } if (count($params['capabilities']) > 0 && !has_all_capabilities($params['capabilities'], $context)) { unset($courses[$cid]); } } $extrafields = 'm.id as assignmentid, ' . 'm.course, ' . 'm.nosubmissions, ' . 'm.submissiondrafts, ' . 'm.sendnotifications, ' . 'm.sendlatenotifications, ' . 'm.sendstudentnotifications, ' . 'm.duedate, ' . 'm.allowsubmissionsfromdate, ' . 'm.grade, ' . 'm.timemodified, ' . 'm.completionsubmit, ' . 'm.cutoffdate, ' . 'm.teamsubmission, ' . 'm.requireallteammemberssubmit, ' . 'm.teamsubmissiongroupingid, ' . 'm.blindmarking, ' . 'm.revealidentities, ' . 'm.attemptreopenmethod, ' . 'm.maxattempts, ' . 'm.markingworkflow, ' . 'm.markingallocation, ' . 'm.requiresubmissionstatement, ' . 'm.preventsubmissionnotingroup, ' . 'm.intro, ' . 'm.introformat'; $coursearray = array(); foreach ($courses as $id => $course) { $assignmentarray = array(); // Get a list of assignments for the course. if ($modules = get_coursemodules_in_course('assign', $courses[$id]->id, $extrafields)) { foreach ($modules as $module) { $context = context_module::instance($module->id); try { self::validate_context($context); require_capability('mod/assign:view', $context); } catch (Exception $e) { $warnings[] = array('item' => 'module', 'itemid' => $module->id, 'warningcode' => '1', 'message' => 'No access rights in module context'); continue; } $assign = new assign($context, null, null); // Get configurations for only enabled plugins. $plugins = $assign->get_submission_plugins(); $plugins = array_merge($plugins, $assign->get_feedback_plugins()); $configarray = array(); foreach ($plugins as $plugin) { if ($plugin->is_enabled() && $plugin->is_visible()) { $configrecords = $plugin->get_config_for_external(); foreach ($configrecords as $name => $value) { $configarray[] = array('plugin' => $plugin->get_type(), 'subtype' => $plugin->get_subtype(), 'name' => $name, 'value' => $value); } } } $assignment = array('id' => $module->assignmentid, 'cmid' => $module->id, 'course' => $module->course, 'name' => $module->name, 'nosubmissions' => $module->nosubmissions, 'submissiondrafts' => $module->submissiondrafts, 'sendnotifications' => $module->sendnotifications, 'sendlatenotifications' => $module->sendlatenotifications, 'sendstudentnotifications' => $module->sendstudentnotifications, 'duedate' => $module->duedate, 'allowsubmissionsfromdate' => $module->allowsubmissionsfromdate, 'grade' => $module->grade, 'timemodified' => $module->timemodified, 'completionsubmit' => $module->completionsubmit, 'cutoffdate' => $module->cutoffdate, 'teamsubmission' => $module->teamsubmission, 'requireallteammemberssubmit' => $module->requireallteammemberssubmit, 'teamsubmissiongroupingid' => $module->teamsubmissiongroupingid, 'blindmarking' => $module->blindmarking, 'revealidentities' => $module->revealidentities, 'attemptreopenmethod' => $module->attemptreopenmethod, 'maxattempts' => $module->maxattempts, 'markingworkflow' => $module->markingworkflow, 'markingallocation' => $module->markingallocation, 'requiresubmissionstatement' => $module->requiresubmissionstatement, 'preventsubmissionnotingroup' => $module->preventsubmissionnotingroup, 'configs' => $configarray); // Return or not intro and file attachments depending on the plugin settings. if ($assign->show_intro()) { list($assignment['intro'], $assignment['introformat']) = external_format_text($module->intro, $module->introformat, $context->id, 'mod_assign', 'intro', null); $assignment['introfiles'] = external_util::get_area_files($context->id, 'mod_assign', 'intro', false, false); $assignment['introattachments'] = external_util::get_area_files($context->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA, 0); } if ($module->requiresubmissionstatement) { // Submission statement is required, return the submission statement value. $adminconfig = get_config('assign'); list($assignment['submissionstatement'], $assignment['submissionstatementformat']) = external_format_text($adminconfig->submissionstatement, FORMAT_MOODLE, $context->id, 'mod_assign', '', 0); } $assignmentarray[] = $assignment; } } $coursearray[] = array('id' => $courses[$id]->id, 'fullname' => external_format_string($courses[$id]->fullname, $course->contextid), 'shortname' => external_format_string($courses[$id]->shortname, $course->contextid), 'timemodified' => $courses[$id]->timemodified, 'assignments' => $assignmentarray); } $result = array('courses' => $coursearray, 'warnings' => $warnings); return $result; }
/** * Get an array of courses where cap requested is available * and user is enrolled, this can be relatively slow. * * @deprecated since 2.2, use enrol_get_users_courses() instead * @param int $userid A user id. By default (null) checks the permissions of the current user. * @param string $cap - name of the capability * @param array $accessdata_ignored * @param bool $doanything_ignored * @param string $sort - sorting fields - prefix each fieldname with "c." * @param array $fields - additional fields you are interested in... * @param int $limit_ignored * @return array $courses - ordered array of course objects - see notes above */ function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) { $courses = enrol_get_users_courses($userid, true, $fields, $sort); foreach ($courses as $id => $course) { $context = context_course::instance($id); if (!has_capability($cap, $context, $userid)) { unset($courses[$id]); } } return $courses; }
$session = $DB->get_record_sql('SELECT s.id,c.fullname FROM {user} u INNER JOIN {user_enrolments} ue ON (ue.userid = u.id) INNER JOIN {enrol} e ON (e.id = ue.enrolid) INNER JOIN {course} c ON (e.courseid = c.id) INNER JOIN {local_attendance_session} s ON (c.id=s.courseid) WHERE ue.userid = ' . $user->id . ' AND s.open=1 AND c.id=' . $courseid); $attendanceExists = $DB->record_exists("local_attendance_attendance", array('sessionid' => $session->id, 'userid' => $user->id)); if (!$attendanceExists) { $DB->insert_record('local_attendance_attendance', array('sessionid' => $session->id, 'userid' => $user->id, 'ip' => $ip)); } else { echo get_string('alreadyregistered', 'local_attendance'); } } if ($action == "teacherLogin") { $username = required_param('user', PARAM_ALPHANUMEXT); $password = required_param('pass', PARAM_RAW_TRIMMED); if (!($username && $password)) { echo get_string('allfields', 'local_attendance'); } elseif (!($user = authenticate_user_login($username, $password))) { echo get_string('invalidlogin', 'local_attendance'); } else { $userCourses = enrol_get_users_courses($user->id); $n = 0; foreach ($userCourses as $course) { $courseContext = context_course::instance($course->id); if (has_capability('local/attendance:teacherview', $courseContext, $user->id)) { $n++; } } if ($n > 0) { $_SESSION['teacher_webapp'] = $user; } else { echo 'No eres profesor de ningun ramo'; } } }
/** * An array of forum objects that the user is allowed to read/search through. * * @global object * @global object * @global object * @param int $userid * @param int $courseid if 0, we look for forums throughout the whole site. * @return array of forum objects, or false if no matches * Forum objects have the following attributes: * id, type, course, cmid, cmvisible, cmgroupmode, accessallgroups, * viewhiddentimedposts */ function forum_get_readable_forums($userid, $courseid=0) { global $CFG, $DB, $USER; require_once($CFG->dirroot.'/course/lib.php'); if (!$forummod = $DB->get_record('modules', array('name' => 'forum'))) { print_error('notinstalled', 'forum'); } if ($courseid) { $courses = $DB->get_records('course', array('id' => $courseid)); } else { // If no course is specified, then the user can see SITE + his courses. $courses1 = $DB->get_records('course', array('id' => SITEID)); $courses2 = enrol_get_users_courses($userid, true, array('modinfo')); $courses = array_merge($courses1, $courses2); } if (!$courses) { return array(); } $readableforums = array(); foreach ($courses as $course) { $modinfo = get_fast_modinfo($course); if (is_null($modinfo->groups)) { $modinfo->groups = groups_get_user_groups($course->id, $userid); } if (empty($modinfo->instances['forum'])) { // hmm, no forums? continue; } $courseforums = $DB->get_records('forum', array('course' => $course->id)); foreach ($modinfo->instances['forum'] as $forumid => $cm) { if (!$cm->uservisible or !isset($courseforums[$forumid])) { continue; } $context = context_module::instance($cm->id); $forum = $courseforums[$forumid]; $forum->context = $context; $forum->cm = $cm; if (!has_capability('mod/forum:viewdiscussion', $context)) { continue; } /// group access if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) { if (is_null($modinfo->groups)) { $modinfo->groups = groups_get_user_groups($course->id, $USER->id); } if (isset($modinfo->groups[$cm->groupingid])) { $forum->onlygroups = $modinfo->groups[$cm->groupingid]; $forum->onlygroups[] = -1; } else { $forum->onlygroups = array(-1); } } /// hidden timed discussions $forum->viewhiddentimedposts = true; if (!empty($CFG->forum_enabletimedposts)) { if (!has_capability('mod/forum:viewhiddentimedposts', $context)) { $forum->viewhiddentimedposts = false; } } /// qanda access if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $context)) { // We need to check whether the user has posted in the qanda forum. $forum->onlydiscussions = array(); // Holds discussion ids for the discussions // the user is allowed to see in this forum. if ($discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $USER->id)) { foreach ($discussionspostedin as $d) { $forum->onlydiscussions[] = $d->id; } } } $readableforums[$forum->id] = $forum; } unset($modinfo); } // End foreach $courses return $readableforums; }
/** * * Give user record from mdl_user, build an array conntains * all user details * @param stdClass $user user record from mdl_user * @param stdClass $context context object * @param stdClass $course moodle course * @param array $userfields required fields * @return array */ function user_get_user_details($user, $course = null, array $userfields = array()) { global $USER, $DB, $CFG; require_once $CFG->dirroot . "/user/profile/lib.php"; //custom field library require_once $CFG->dirroot . "/lib/filelib.php"; // file handling on description and friends $defaultfields = array('id', 'username', 'fullname', 'firstname', 'lastname', 'email', 'address', 'phone1', 'phone2', 'icq', 'skype', 'yahoo', 'aim', 'msn', 'department', 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed', 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat', 'city', 'url', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields', 'groups', 'roles', 'preferences', 'enrolledcourses'); if (empty($userfields)) { $userfields = $defaultfields; } foreach ($userfields as $thefield) { if (!in_array($thefield, $defaultfields)) { throw new moodle_exception('invaliduserfield', 'error', '', $thefield); } } // Make sure id and fullname are included if (!in_array('id', $userfields)) { $userfields[] = 'id'; } if (!in_array('fullname', $userfields)) { $userfields[] = 'fullname'; } if (!empty($course)) { $context = get_context_instance(CONTEXT_COURSE, $course->id); $usercontext = get_context_instance(CONTEXT_USER, $user->id); $canviewdetailscap = has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext); } else { $context = get_context_instance(CONTEXT_USER, $user->id); $usercontext = $context; $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext); } $currentuser = $user->id == $USER->id; $isadmin = is_siteadmin($USER); if (!empty($course)) { $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context); } else { $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context); } $canviewfullnames = has_capability('moodle/site:viewfullnames', $context); if (!empty($course)) { $canviewuseremail = has_capability('moodle/course:useremail', $context); } else { $canviewuseremail = false; } $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id)); if (!empty($course)) { $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context); } else { $canaccessallgroups = false; } if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) { // skip this user details return null; } $userdetails = array(); $userdetails['id'] = $user->id; if (($isadmin or $currentuser) and in_array('username', $userfields)) { $userdetails['username'] = $user->username; } if ($isadmin or $canviewfullnames) { if (in_array('firstname', $userfields)) { $userdetails['firstname'] = $user->firstname; } if (in_array('lastname', $userfields)) { $userdetails['lastname'] = $user->lastname; } } $userdetails['fullname'] = fullname($user); if (in_array('customfields', $userfields)) { $fields = $DB->get_recordset_sql("SELECT f.*\n FROM {user_info_field} f\n JOIN {user_info_category} c\n ON f.categoryid=c.id\n ORDER BY c.sortorder ASC, f.sortorder ASC"); $userdetails['customfields'] = array(); 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()) { $userdetails['customfields'][] = array('name' => $formfield->field->name, 'value' => $formfield->data, 'type' => $field->datatype, 'shortname' => $formfield->field->shortname); } } $fields->close(); // unset customfields if it's empty if (empty($userdetails['customfields'])) { unset($userdetails['customfields']); } } // profile image if (in_array('profileimageurl', $userfields)) { $profileimageurl = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', NULL, '/', 'f1'); $userdetails['profileimageurl'] = $profileimageurl->out(false); } if (in_array('profileimageurlsmall', $userfields)) { $profileimageurlsmall = moodle_url::make_pluginfile_url($usercontext->id, 'user', 'icon', NULL, '/', 'f2'); $userdetails['profileimageurlsmall'] = $profileimageurlsmall->out(false); } //hidden user field if ($canviewhiddenuserfields) { $hiddenfields = array(); // address, phone1 and phone2 not appears in hidden fields list // but require viewhiddenfields capability // according to user/profile.php if ($user->address && in_array('address', $userfields)) { $userdetails['address'] = $user->address; } if ($user->phone1 && in_array('phone1', $userfields)) { $userdetails['phone1'] = $user->phone1; } if ($user->phone2 && in_array('phone2', $userfields)) { $userdetails['phone2'] = $user->phone2; } } else { $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields)); } if (isset($user->description) && (!isset($hiddenfields['description']) or $isadmin)) { if (!$cannotviewdescription) { if (in_array('description', $userfields)) { $user->description = file_rewrite_pluginfile_urls($user->description, 'pluginfile.php', $usercontext->id, 'user', 'profile', null); $userdetails['description'] = $user->description; } if (in_array('descriptionformat', $userfields)) { $userdetails['descriptionformat'] = $user->descriptionformat; } } } if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) { $userdetails['country'] = $user->country; } if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) { $userdetails['city'] = $user->city; } if (in_array('url', $userfields) && $user->url && (!isset($hiddenfields['webpage']) or $isadmin)) { $url = $user->url; if (strpos($user->url, '://') === false) { $url = 'http://' . $url; } $user->url = clean_param($user->url, PARAM_URL); $userdetails['url'] = $user->url; } if (in_array('icq', $userfields) && $user->icq && (!isset($hiddenfields['icqnumber']) or $isadmin)) { $userdetails['icq'] = $user->icq; } if (in_array('skype', $userfields) && $user->skype && (!isset($hiddenfields['skypeid']) or $isadmin)) { $userdetails['skype'] = $user->skype; } if (in_array('yahoo', $userfields) && $user->yahoo && (!isset($hiddenfields['yahooid']) or $isadmin)) { $userdetails['yahoo'] = $user->yahoo; } if (in_array('aim', $userfields) && $user->aim && (!isset($hiddenfields['aimid']) or $isadmin)) { $userdetails['aim'] = $user->aim; } if (in_array('msn', $userfields) && $user->msn && (!isset($hiddenfields['msnid']) or $isadmin)) { $userdetails['msn'] = $user->msn; } if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) { if ($user->firstaccess) { $userdetails['firstaccess'] = $user->firstaccess; } else { $userdetails['firstaccess'] = 0; } } if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) { if ($user->lastaccess) { $userdetails['lastaccess'] = $user->lastaccess; } else { $userdetails['lastaccess'] = 0; } } if (in_array('email', $userfields) && ($currentuser or $canviewuseremail or $user->maildisplay == 1 or $user->maildisplay == 2 and enrol_sharing_course($user, $USER))) { $userdetails['email'] = $user->email; } if (in_array('interests', $userfields) && !empty($CFG->usetags)) { require_once $CFG->dirroot . '/tag/lib.php'; if ($interests = tag_get_tags_csv('user', $user->id, TAG_RETURN_TEXT)) { $userdetails['interests'] = $interests; } } //Departement/Institution are not displayed on any profile, however you can get them from editing profile. if ($isadmin or $currentuser) { if (in_array('institution', $userfields) && $user->institution) { $userdetails['institution'] = $user->institution; } if (in_array('department', $userfields) && isset($user->department)) { //isset because it's ok to have department 0 $userdetails['department'] = $user->department; } } if (in_array('roles', $userfields) && !empty($course)) { // not a big secret $roles = get_user_roles($context, $user->id, false); $userdetails['roles'] = array(); foreach ($roles as $role) { $userdetails['roles'][] = array('roleid' => $role->roleid, 'name' => $role->name, 'shortname' => $role->shortname, 'sortorder' => $role->sortorder); } } // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) { $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name,g.description'); $userdetails['groups'] = array(); foreach ($usergroups as $group) { $group->description = file_rewrite_pluginfile_urls($group->description, 'pluginfile.php', $context->id, 'group', 'description', $group->id); $userdetails['groups'][] = array('id' => $group->id, 'name' => $group->name, 'description' => $group->description); } } //list of courses where the user is enrolled if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) { $enrolledcourses = array(); if ($mycourses = enrol_get_users_courses($user->id, true)) { foreach ($mycourses as $mycourse) { if ($mycourse->category) { $coursecontext = get_context_instance(CONTEXT_COURSE, $mycourse->id); $enrolledcourse = array(); $enrolledcourse['id'] = $mycourse->id; $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $mycourse->id))); $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext)); $enrolledcourses[] = $enrolledcourse; } } $userdetails['enrolledcourses'] = $enrolledcourses; } } //user preferences if (in_array('preferences', $userfields) && $currentuser) { $preferences = array(); $userpreferences = get_user_preferences(); foreach ($userpreferences as $prefname => $prefvalue) { $preferences[] = array('name' => $prefname, 'value' => $prefvalue); } $userdetails['preferences'] = $preferences; } return $userdetails; }
/** * Loads user specific information into the navigation in the appropriate place. * * If no user is provided the current user is assumed. * * @param stdClass $user * @param bool $forceforcontext probably force something to be loaded somewhere (ask SamH if not sure what this means) * @return bool */ protected function load_for_user($user = null, $forceforcontext = false) { global $DB, $CFG, $USER, $SITE; if ($user === null) { // We can't require login here but if the user isn't logged in we don't // want to show anything if (!isloggedin() || isguestuser()) { return false; } $user = $USER; } else { if (!is_object($user)) { // If the user is not an object then get them from the database $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\n ctx.contextlevel = :contextlevel"; $user = $DB->get_record_sql($sql, array('userid' => (int) $user, 'contextlevel' => CONTEXT_USER), MUST_EXIST); context_helper::preload_from_record($user); } } $iscurrentuser = $user->id == $USER->id; $usercontext = get_context_instance(CONTEXT_USER, $user->id); // Get the course set against the page, by default this will be the site $course = $this->page->course; $baseargs = array('id' => $user->id); if ($course->id != $SITE->id && (!$iscurrentuser || $forceforcontext)) { $coursenode = $this->load_course($course); $baseargs['course'] = $course->id; $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); $issitecourse = false; } else { // Load all categories and get the context for the system $coursecontext = get_context_instance(CONTEXT_SYSTEM); $issitecourse = true; } // Create a node to add user information under. if ($iscurrentuser && !$forceforcontext) { // If it's the current user the information will go under the profile root node $usernode = $this->rootnodes['myprofile']; $course = get_site(); $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); $issitecourse = true; } else { if (!$issitecourse) { // Not the current user so add it to the participants node for the current course $usersnode = $coursenode->get('participants', navigation_node::TYPE_CONTAINER); $userviewurl = new moodle_url('/user/view.php', $baseargs); } else { // This is the site so add a users node to the root branch $usersnode = $this->rootnodes['users']; if (has_capability('moodle/course:viewparticipants', $coursecontext)) { $usersnode->action = new moodle_url('/user/index.php', array('id' => $course->id)); } $userviewurl = new moodle_url('/user/profile.php', $baseargs); } if (!$usersnode) { // We should NEVER get here, if the course hasn't been populated // with a participants node then the navigaiton either wasn't generated // for it (you are missing a require_login or set_context call) or // you don't have access.... in the interests of no leaking informatin // we simply quit... return false; } // Add a branch for the current user $canseefullname = has_capability('moodle/site:viewfullnames', $coursecontext); $usernode = $usersnode->add(fullname($user, $canseefullname), $userviewurl, self::TYPE_USER, null, $user->id); if ($this->page->context->contextlevel == CONTEXT_USER && $user->id == $this->page->context->instanceid) { $usernode->make_active(); } } // If the user is the current user or has permission to view the details of the requested // user than add a view profile link. if ($iscurrentuser || has_capability('moodle/user:viewdetails', $coursecontext) || has_capability('moodle/user:viewdetails', $usercontext)) { if ($issitecourse || $iscurrentuser && !$forceforcontext) { $usernode->add(get_string('viewprofile'), new moodle_url('/user/profile.php', $baseargs)); } else { $usernode->add(get_string('viewprofile'), new moodle_url('/user/view.php', $baseargs)); } } 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 = $usernode->add(get_string('forumposts', 'forum')); $forumtab->add(get_string('posts', 'forum'), new moodle_url('/mod/forum/user.php', $baseargs)); $forumtab->add(get_string('discussions', 'forum'), new moodle_url('/mod/forum/user.php', array_merge($baseargs, array('mode' => 'discussions')))); } // Add blog nodes if (!empty($CFG->bloglevel)) { 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 = $usernode->add(get_string('blogs', 'blog'), null, navigation_node::TYPE_CONTAINER); foreach ($options as $type => $option) { if ($type == "rss") { $blogs->add($option['string'], $option['link'], settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', '')); } else { $blogs->add($option['string'], $option['link']); } } } } if (!empty($CFG->messaging)) { $messageargs = null; if ($USER->id != $user->id) { $messageargs = array('id' => $user->id); } $url = new moodle_url('/message/index.php', $messageargs); $usernode->add(get_string('messages', 'message'), $url, self::TYPE_SETTING, null, 'messages'); } $context = get_context_instance(CONTEXT_USER, $USER->id); if ($iscurrentuser && has_capability('moodle/user:manageownfiles', $context)) { $url = new moodle_url('/user/files.php'); $usernode->add(get_string('myfiles'), $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) { $url->param('course', $coursecontext->instanceid); } $usernode->add(get_string('notes', 'notes'), $url); } // Add reports node $reporttab = $usernode->add(get_string('activityreports')); $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php'); foreach ($reports as $reportfunction) { $reportfunction($reporttab, $user, $course); } $anyreport = has_capability('moodle/user:viewuseractivitiesreport', $usercontext); if ($anyreport || $course->showreports && $iscurrentuser && $forceforcontext) { // Add grade hardcoded grade report if necessary $gradeaccess = false; if (has_capability('moodle/grade:viewall', $coursecontext)) { //ok - can view all course grades $gradeaccess = true; } else { if ($course->showgrades) { if ($iscurrentuser && has_capability('moodle/grade:view', $coursecontext)) { //ok - can view own grades $gradeaccess = true; } else { if (has_capability('moodle/grade:viewall', $usercontext)) { // ok - can view grades of this user - parent most probably $gradeaccess = true; } else { if ($anyreport) { // ok - can view grades of this user - parent most probably $gradeaccess = true; } } } } } if ($gradeaccess) { $reporttab->add(get_string('grade'), new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id, 'user' => $usercontext->instanceid))); } } // Check the number of nodes in the report node... if there are none remove the node $reporttab->trim_if_empty(); // If the user is the current user add the repositories for the current user $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields)); if ($iscurrentuser) { 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) { $usernode->add(get_string('repositories', 'repository'), new moodle_url('/repository/manage_instances.php', array('contextid' => $usercontext->id))); } } else { if ($course->id == $SITE->id && has_capability('moodle/user:viewdetails', $usercontext) && (!in_array('mycourses', $hiddenfields) || has_capability('moodle/user:viewhiddendetails', $coursecontext))) { // Add view grade report is permitted $reports = get_plugin_list('gradereport'); arsort($reports); // user is last, we want to test it first $userscourses = enrol_get_users_courses($user->id); $userscoursesnode = $usernode->add(get_string('courses')); foreach ($userscourses as $usercourse) { $usercoursecontext = get_context_instance(CONTEXT_COURSE, $usercourse->id); $usercourseshortname = format_string($usercourse->shortname, true, array('context' => $usercoursecontext)); $usercoursenode = $userscoursesnode->add($usercourseshortname, new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $usercourse->id)), self::TYPE_CONTAINER); $gradeavailable = has_capability('moodle/grade:viewall', $usercoursecontext); if (!$gradeavailable && !empty($usercourse->showgrades) && is_array($reports) && !empty($reports)) { foreach ($reports as $plugin => $plugindir) { if (has_capability('gradereport/' . $plugin . ':view', $usercoursecontext)) { //stop when the first visible plugin is found $gradeavailable = true; break; } } } if ($gradeavailable) { $url = new moodle_url('/grade/report/index.php', array('id' => $usercourse->id)); $usercoursenode->add(get_string('grades'), $url, self::TYPE_SETTING, null, null, new pix_icon('i/grades', '')); } // Add a node to view the users notes if permitted if (!empty($CFG->enablenotes) && has_any_capability(array('moodle/notes:manage', 'moodle/notes:view'), $usercoursecontext)) { $url = new moodle_url('/notes/index.php', array('user' => $user->id, 'course' => $usercourse->id)); $usercoursenode->add(get_string('notes', 'notes'), $url, self::TYPE_SETTING); } if (can_access_course($usercourse, $user->id)) { $usercoursenode->add(get_string('entercourse'), new moodle_url('/course/view.php', array('id' => $usercourse->id)), self::TYPE_SETTING, null, null, new pix_icon('i/course', '')); } $reporttab = $usercoursenode->add(get_string('activityreports')); $reports = get_plugin_list_with_function('report', 'extend_navigation_user', 'lib.php'); foreach ($reports as $reportfunction) { $reportfunction($reporttab, $user, $usercourse); } $reporttab->trim_if_empty(); } } } return true; }
/** * Get an array of courses where cap requested is available * and user is enrolled, this can be relatively slow. * * @deprecated since 2.2 * @see enrol_get_users_courses() * @param int $userid A user id. By default (null) checks the permissions of the current user. * @param string $cap - name of the capability * @param array $accessdata_ignored * @param bool $doanything_ignored * @param string $sort - sorting fields - prefix each fieldname with "c." * @param array $fields - additional fields you are interested in... * @param int $limit_ignored * @return array $courses - ordered array of course objects - see notes above */ function get_user_courses_bycap($userid, $cap, $accessdata_ignored, $doanything_ignored, $sort = 'c.sortorder ASC', $fields = null, $limit_ignored = 0) { debugging('get_user_courses_bycap() is deprecated, please use enrol_get_users_courses() instead.', DEBUG_DEVELOPER); $courses = enrol_get_users_courses($userid, true, $fields, $sort); foreach ($courses as $id => $course) { $context = context_course::instance($id); if (!has_capability($cap, $context, $userid)) { unset($courses[$id]); } } return $courses; }