public function get_all_notes() { echo \html_writer::tag('p', get_string('viewallnote', 'local_note'), ['class' => 'lead']); $courses = enrol_get_my_courses('id'); $courselist = []; foreach ($courses as $key => $nouse) { $courselist[] = $key; } if (empty($courselist)) { return \html_writer::div(get_string("nonotesavailable", "local_note"), 'alert alert-warning'); } $sql = 'select * from {cli_note} where courseid in(' . implode(',', $courselist) . ') and status = 1 order by id DESC'; $record = $this->db->get_records_sql($sql); if (!empty($record) && $record != null) { $table = new \html_table(); $table->head = (array) get_strings(['serial', 'author', 'date', 'course', 'title', 'content', 'attachment', 'label', 'active', 'action'], 'local_note'); $count = 1; foreach ($record as $key => $row) { $status = $row->status == true ? '<span class="label label-success">' . get_string('active', 'local_note') . '</span>' : '<span class="label label-warning">' . get_string('inactive', 'local_note') . '</span>'; $action = '<i class="fa fa-lock" title="Access denied"></i>'; $user = $this->db->get_record('user', ['id' => $row->publisherid], 'firstname, lastname'); $author = $user->firstname . ' ' . $user->lastname; if ($this->userid == $row->publisherid) { $action = \html_writer::link(new \moodle_url($this->cfg->wwwroot . '/local/note/edit_note.php?id=' . $row->id), '<i class="fa fa-edit"></i> ', ['title' => 'Edit note']); $action .= \html_writer::link(new \moodle_url($this->cfg->wwwroot . '/local/note/delete_note.php?id=' . $row->id), ' <i class="fa fa-trash"></i>', ['title' => 'Delete note']); } $course = $this->db->get_record('course', array('id' => $row->courseid), 'fullname'); $table->data[] = array($count++, $author, date('j M Y', $row->createdtime), \html_writer::link(new \moodle_url($this->cfg->wwwroot . '/course/view.php', ['id' => $row->courseid]), $course->fullname), '<a href="view_note.php?id=' . $row->id . '">' . $row->title . '</a>', strip_tags(substr($row->content, 0, 20)) . ' <a href="view_note.php?id=' . $row->id . '">' . get_string('more', 'local_note') . '</a>', \html_writer::link(new \moodle_url($this->get_attachment($row->attachment)['url']), $this->get_attachment($row->attachment)['filename'], ['download' => 'download']), $row->label, $status, $action); } return \html_writer::table($table); } else { return \html_writer::div(get_string("nonotesavailable", "local_note"), 'alert alert-warning'); } }
/** * Create basic setup for test cases * @return bool */ public function setup() { global $CFG; $this->resetAfterTest(true); // Read settings from config.json. $configdata = file_get_contents($CFG->dirroot . '/local/onenote/tests/phpu_config_data.json'); if (!$configdata) { echo 'Please provide PHPUnit testing configs in a config.json file'; return false; } $this->config = json_decode($configdata, false); $this->user = $this->getDataGenerator()->create_user(); $this->user1 = $this->getDataGenerator()->create_user(); $this->course1 = $this->getDataGenerator()->create_course(); $this->course2 = $this->getDataGenerator()->create_course(); // Setting user and enrolling to the courses created with teacher role. $this->setUser($this->user->id); $c1ctx = context_course::instance($this->course1->id); $c2ctx = context_course::instance($this->course2->id); $this->getDataGenerator()->enrol_user($this->user->id, $this->course1->id, 3); $this->getDataGenerator()->enrol_user($this->user->id, $this->course2->id, 3); $this->assertCount(2, enrol_get_my_courses()); $courses = enrol_get_my_courses(); // Student enrollment. $this->setUser($this->user1->id); $this->getDataGenerator()->enrol_user($this->user1->id, $this->course1->id, 5); $this->getDataGenerator()->enrol_user($this->user1->id, $this->course2->id, 5); $this->assertCount(2, get_enrolled_users($c1ctx)); }
/** * Returns a list of glossaries in a provided list of courses. * * If no list is provided all glossaries that the user can view will be returned. * * @param array $courseids the course IDs. * @return array of glossaries * @since Moodle 3.1 */ public static function get_glossaries_by_courses($courseids = array()) { $params = self::validate_parameters(self::get_glossaries_by_courses_parameters(), array('courseids' => $courseids)); $warnings = array(); $courses = array(); $courseids = $params['courseids']; if (empty($courseids)) { $courses = enrol_get_my_courses(); $courseids = array_keys($courses); } // Array to store the glossaries to return. $glossaries = array(); // Ensure there are courseids to loop through. if (!empty($courseids)) { list($courses, $warnings) = external_util::validate_courses($courseids, $courses); // Get the glossaries in these courses, this function checks users visibility permissions. $glossaries = get_all_instances_in_courses('glossary', $courses); foreach ($glossaries as $glossary) { $context = context_module::instance($glossary->coursemodule); $glossary->name = external_format_string($glossary->name, $context->id); list($glossary->intro, $glossary->introformat) = external_format_text($glossary->intro, $glossary->introformat, $context->id, 'mod_glossary', 'intro', null); } } $result = array(); $result['glossaries'] = $glossaries; $result['warnings'] = $warnings; return $result; }
protected function render_custom_menu(custom_menu $menu) { global $CFG; require_once $CFG->dirroot . '/course/lib.php'; //navigation mycourses is no supported since 2.4 if (isloggedin() && !isguestuser() && ($mycourses = enrol_get_my_courses(NULL, 'visible DESC, fullname ASC'))) { $branchlabel = get_string('mycourses'); $branchurl = new moodle_url('/course/index.php'); $branchtitle = $branchlabel; $branchsort = 8000; $branch = $menu->add($branchlabel, $branchurl, $branchtitle, $branchsort); foreach ($mycourses as $mycourse) { $branch->add($mycourse->shortname, new moodle_url('/course/view.php', array('id' => $mycourse->id)), $mycourse->fullname); } } $course_id = $this->page->course->id; if (isloggedin() && $course_id > 1) { $branchlabel = get_string('grades'); $branchurl = new moodle_url('/grade/report/index.php?id=' . $this->page->course->id); $branchtitle = $branchlabel; $branchsort = 10000; $branch = $menu->add($branchlabel, $branchurl, $branchtitle, $branchsort); } return parent::render_custom_menu($menu); }
protected function render_custom_menu(custom_menu $menu) { /* * This code replaces adds the current enrolled * courses to the custommenu. */ $hasdisplaymycourses = empty($this->page->theme->settings->displaymycourses) ? false : $this->page->theme->settings->displaymycourses; if (isloggedin() && !isguestuser() && $hasdisplaymycourses) { $mycoursetitle = $this->page->theme->settings->mycoursetitle; if ($mycoursetitle == 'module') { $branchtitle = get_string('mymodules', 'theme_evolved'); } else { if ($mycoursetitle == 'unit') { $branchtitle = get_string('myunits', 'theme_evolved'); } else { if ($mycoursetitle == 'class') { $branchtitle = get_string('myclasses', 'theme_evolved'); } else { $branchtitle = get_string('mycourses', 'theme_evolved'); } } } $branchlabel = '<i class="fa fa-briefcase"></i>' . $branchtitle; $branchurl = new moodle_url('/my/index.php'); $branchsort = 10000; $branch = $menu->add($branchlabel, $branchurl, $branchtitle, $branchsort); if ($courses = enrol_get_my_courses(NULL, 'fullname ASC')) { foreach ($courses as $course) { if ($course->visible) { $branch->add(format_string($course->fullname), new moodle_url('/course/view.php?id=' . $course->id), format_string($course->shortname)); } } } else { $noenrolments = get_string('noenrolments', 'theme_evolved'); $branch->add('<em>' . $noenrolments . '</em>', new moodle_url('/'), $noenrolments); } } /* * This code replaces adds the My Dashboard * functionality to the custommenu. */ $hasdisplaymydashboard = empty($this->page->theme->settings->displaymydashboard) ? false : $this->page->theme->settings->displaymydashboard; if (isloggedin() && !isguestuser() && $hasdisplaymydashboard) { $branchlabel = '<i class="fa fa-dashboard"></i>' . get_string('mydashboard', 'theme_evolved'); $branchurl = new moodle_url('/my/index.php'); $branchtitle = get_string('mydashboard', 'theme_evolved'); $branchsort = 10000; $branch = $menu->add($branchlabel, $branchurl, $branchtitle, $branchsort); $branch->add(get_string('profile') . '</em>', new moodle_url('/user/profile.php'), get_string('profile')); $branch->add(get_string('pluginname', 'block_calendar_month') . '</em>', new moodle_url('/calendar/view.php'), get_string('pluginname', 'block_calendar_month')); $branch->add(get_string('pluginname', 'block_messages') . '</em>', new moodle_url('/message/index.php'), get_string('pluginname', 'block_messages')); $branch->add(get_string('badges') . '</em>', new moodle_url('/badges/mybadges.php'), get_string('badges')); $branch->add(get_string('privatefiles', 'block_private_files') . '</em>', new moodle_url('/user/files.php'), get_string('privatefiles', 'block_private_files')); $branch->add(get_string('logout') . '</em>', new moodle_url('/login/logout.php'), get_string('logout')); } return parent::render_custom_menu($menu); }
/** * Returns a list of forums in a provided list of courses, * if no list is provided all forums that the user can view * will be returned. * * @param array $courseids the course ids * @return array the forum details * @since Moodle 2.5 */ public static function get_forums_by_courses($courseids = array()) { global $CFG, $DB, $USER; require_once($CFG->dirroot . "/mod/forum/lib.php"); $params = self::validate_parameters(self::get_forums_by_courses_parameters(), array('courseids' => $courseids)); if (empty($params['courseids'])) { // Get all the courses the user can view. $courseids = array_keys(enrol_get_my_courses()); } else { $courseids = $params['courseids']; } // Array to store the forums to return. $arrforums = array(); // Ensure there are courseids to loop through. if (!empty($courseids)) { // Go through the courseids and return the forums. foreach ($courseids as $cid) { // Get the course context. $context = context_course::instance($cid); // Check the user can function in this context. self::validate_context($context); // Get the forums in this course. if ($forums = $DB->get_records('forum', array('course' => $cid))) { // Get the modinfo for the course. $modinfo = get_fast_modinfo($cid); // Get the forum instances. $foruminstances = $modinfo->get_instances_of('forum'); // Loop through the forums returned by modinfo. foreach ($foruminstances as $forumid => $cm) { // If it is not visible or present in the forums get_records call, continue. if (!$cm->uservisible || !isset($forums[$forumid])) { continue; } // Set the forum object. $forum = $forums[$forumid]; // Get the module context. $context = context_module::instance($cm->id); // Check they have the view forum capability. require_capability('mod/forum:viewdiscussion', $context); // Format the intro before being returning using the format setting. list($forum->intro, $forum->introformat) = external_format_text($forum->intro, $forum->introformat, $context->id, 'mod_forum', 'intro', 0); // Add the course module id to the object, this information is useful. $forum->cmid = $cm->id; // Add the forum to the array to return. $arrforums[$forum->id] = (array) $forum; } } } } return $arrforums; }
/** * Returns a list of surveys in a provided list of courses, * if no list is provided all surveys that the user can view will be returned. * * @param array $courseids the course ids * @return array of surveys details * @since Moodle 3.0 */ public static function get_surveys_by_courses($courseids = array()) { global $CFG, $USER, $DB; $returnedsurveys = array(); $warnings = array(); $params = self::validate_parameters(self::get_surveys_by_courses_parameters(), array('courseids' => $courseids)); $mycourses = array(); if (empty($params['courseids'])) { $mycourses = enrol_get_my_courses(); $params['courseids'] = array_keys($mycourses); } // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($courses, $warnings) = external_util::validate_courses($params['courseids'], $mycourses); // Get the surveys in this course, this function checks users visibility permissions. // We can avoid then additional validate_context calls. $surveys = get_all_instances_in_courses("survey", $courses); foreach ($surveys as $survey) { $context = context_module::instance($survey->coursemodule); // Entry to return. $surveydetails = array(); // First, we return information that any user can see in the web interface. $surveydetails['id'] = $survey->id; $surveydetails['coursemodule'] = $survey->coursemodule; $surveydetails['course'] = $survey->course; $surveydetails['name'] = external_format_string($survey->name, $context->id); if (has_capability('mod/survey:participate', $context)) { $trimmedintro = trim($survey->intro); if (empty($trimmedintro)) { $tempo = $DB->get_field("survey", "intro", array("id" => $survey->template)); $survey->intro = get_string($tempo, "survey"); } // Format intro. list($surveydetails['intro'], $surveydetails['introformat']) = external_format_text($survey->intro, $survey->introformat, $context->id, 'mod_survey', 'intro', null); $surveydetails['introfiles'] = external_util::get_area_files($context->id, 'mod_survey', 'intro', false, false); $surveydetails['template'] = $survey->template; $surveydetails['days'] = $survey->days; $surveydetails['questions'] = $survey->questions; $surveydetails['surveydone'] = survey_already_done($survey->id, $USER->id) ? 1 : 0; } if (has_capability('moodle/course:manageactivities', $context)) { $surveydetails['timecreated'] = $survey->timecreated; $surveydetails['timemodified'] = $survey->timemodified; $surveydetails['section'] = $survey->section; $surveydetails['visible'] = $survey->visible; $surveydetails['groupmode'] = $survey->groupmode; $surveydetails['groupingid'] = $survey->groupingid; } $returnedsurveys[] = $surveydetails; } } $result = array(); $result['surveys'] = $returnedsurveys; $result['warnings'] = $warnings; return $result; }
/** * Returns a list of forums in a provided list of courses, * if no list is provided all forums that the user can view * will be returned. * * @param array $courseids the course ids * @return array the forum details * @since Moodle 2.5 */ public static function get_forums_by_courses($courseids = array()) { global $CFG; require_once $CFG->dirroot . "/mod/forum/lib.php"; $params = self::validate_parameters(self::get_forums_by_courses_parameters(), array('courseids' => $courseids)); if (empty($params['courseids'])) { // Get all the courses the user can view. $courseids = array_keys(enrol_get_my_courses()); } else { $courseids = $params['courseids']; } // Array to store the forums to return. $arrforums = array(); // Ensure there are courseids to loop through. if (!empty($courseids)) { // Array of the courses we are going to retrieve the forums from. $dbcourses = array(); // Mod info for courses. $modinfocourses = array(); // Go through the courseids and return the forums. foreach ($courseids as $courseid) { // Check the user can function in this context. try { $context = context_course::instance($courseid); self::validate_context($context); // Get the modinfo for the course. $modinfocourses[$courseid] = get_fast_modinfo($courseid); $dbcourses[$courseid] = $modinfocourses[$courseid]->get_course(); } catch (Exception $e) { continue; } } // Get the forums in this course. This function checks users visibility permissions. if ($forums = get_all_instances_in_courses("forum", $dbcourses)) { foreach ($forums as $forum) { $course = $dbcourses[$forum->course]; $cm = $modinfocourses[$course->id]->get_cm($forum->coursemodule); $context = context_module::instance($cm->id); // Skip forums we are not allowed to see discussions. if (!has_capability('mod/forum:viewdiscussion', $context)) { continue; } // Format the intro before being returning using the format setting. list($forum->intro, $forum->introformat) = external_format_text($forum->intro, $forum->introformat, $context->id, 'mod_forum', 'intro', 0); // Discussions count. This function does static request cache. $forum->numdiscussions = forum_count_discussions($forum, $cm, $course); $forum->cmid = $forum->coursemodule; // Add the forum to the array to return. $arrforums[$forum->id] = $forum; } } } return $arrforums; }
/** * Returns a list of wikis in a provided list of courses, * if no list is provided all wikis that the user can view will be returned. * * @param array $courseids The courses IDs. * @return array Containing a list of warnings and a list of wikis. * @since Moodle 3.1 */ public static function get_wikis_by_courses($courseids = array()) { $returnedwikis = array(); $warnings = array(); $params = self::validate_parameters(self::get_wikis_by_courses_parameters(), array('courseids' => $courseids)); $mycourses = array(); if (empty($params['courseids'])) { $mycourses = enrol_get_my_courses(); $params['courseids'] = array_keys($mycourses); } // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($courses, $warnings) = external_util::validate_courses($params['courseids'], $mycourses); // Get the wikis in this course, this function checks users visibility permissions. // We can avoid then additional validate_context calls. $wikis = get_all_instances_in_courses('wiki', $courses); foreach ($wikis as $wiki) { $context = context_module::instance($wiki->coursemodule); // Entry to return. $module = array(); // First, we return information that any user can see in (or can deduce from) the web interface. $module['id'] = $wiki->id; $module['coursemodule'] = $wiki->coursemodule; $module['course'] = $wiki->course; $module['name'] = external_format_string($wiki->name, $context->id); $viewablefields = []; if (has_capability('mod/wiki:viewpage', $context)) { list($module['intro'], $module['introformat']) = external_format_text($wiki->intro, $wiki->introformat, $context->id, 'mod_wiki', 'intro', $wiki->id); $module['introfiles'] = external_util::get_area_files($context->id, 'mod_wiki', 'intro', false, false); $viewablefields = array('firstpagetitle', 'wikimode', 'defaultformat', 'forceformat', 'editbegin', 'editend', 'section', 'visible', 'groupmode', 'groupingid'); } // Check additional permissions for returning optional private settings. if (has_capability('moodle/course:manageactivities', $context)) { $additionalfields = array('timecreated', 'timemodified'); $viewablefields = array_merge($viewablefields, $additionalfields); } foreach ($viewablefields as $field) { $module[$field] = $wiki->{$field}; } // Check if user can add new pages. $module['cancreatepages'] = wiki_can_create_pages($context); $returnedwikis[] = $module; } } $result = array(); $result['wikis'] = $returnedwikis; $result['warnings'] = $warnings; return $result; }
function get_content() { global $CFG, $OUTPUT, $USER, $DB; //global $CFG, $SESSION, $USER, $COURSE, $SITE, $PAGE, $DB; if ($this->content !== null) { return $this->content; } if (empty($this->instance)) { $this->content = ''; return $this->content; } $this->content = new stdClass(); $this->content->text = ''; $this->content->footer = ''; //show my incomplete courses //$completion = get_completion($USER->id); //print_object($completion); //complete courses //show the courses the user is enrolled. $this->content->text .= '<h2>Enrolled Courses</h2>'; $mycourses = enrol_get_my_courses(); /** TODO: - Count how many courses the user is enrolled to - Count how many courses are complete (if timecompleted is not null) - */ //total courses $totalcourses = $DB->count_records('course_completions', array('userid' => $USER->id)); //incomplete courses //$incompletecourses = $DB->count_records('course_completions', array('userid'=>$USER->id,'timecompleted'=>NULL)); //inprogress courses $sql = "SELECT * FROM {course_completions} WHERE userid = :userid AND timestarted <> :timestarted AND timecompleted IS NULL"; $inprogress_records = $DB->get_records_sql($sql, array('userid' => $USER->id, 'timestarted' => '0')); $inprogress_count = count($inprogress_records); //complete courses $sql = "SELECT * FROM {course_completions} WHERE userid = :userid AND timecompleted IS NOT :timecompleted"; $complete_records = $DB->get_records_sql($sql, array('userid' => $USER->id, 'timecompleted' => NULL)); $completecourses = count($complete_records); //print_object($inprogress_count); foreach ($mycourses as $course) { $this->content->text .= '<p><a href="">' . $course->shortname . '</a></p>'; } //$this->content->text .= "Incomplete: " . $incompletecourses." / ".$totalcourses."<br>"; $this->content->text .= "Inprogress: " . $inprogress_count . "<br>"; $this->content->text .= "Complete: " . $completecourses . "<br>"; $this->content->text .= "Total Courses: " . $totalcourses . "<br>"; return $this->content; }
/** * Returns a list of forums in a provided list of courses, * if no list is provided all forums that the user can view * will be returned. * * @param array $courseids the course ids * @return array the forum details * @since Moodle 2.5 */ public static function get_forums_by_courses($courseids = array()) { global $CFG; require_once($CFG->dirroot . "/mod/forum/lib.php"); $params = self::validate_parameters(self::get_forums_by_courses_parameters(), array('courseids' => $courseids)); if (empty($params['courseids'])) { $params['courseids'] = array_keys(enrol_get_my_courses()); } // Array to store the forums to return. $arrforums = array(); $warnings = array(); // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($courses, $warnings) = external_util::validate_courses($params['courseids']); // Get the forums in this course. This function checks users visibility permissions. $forums = get_all_instances_in_courses("forum", $courses); foreach ($forums as $forum) { $course = $courses[$forum->course]; $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id); $context = context_module::instance($cm->id); // Skip forums we are not allowed to see discussions. if (!has_capability('mod/forum:viewdiscussion', $context)) { continue; } // Format the intro before being returning using the format setting. list($forum->intro, $forum->introformat) = external_format_text($forum->intro, $forum->introformat, $context->id, 'mod_forum', 'intro', 0); // Discussions count. This function does static request cache. $forum->numdiscussions = forum_count_discussions($forum, $cm, $course); $forum->cmid = $forum->coursemodule; $forum->cancreatediscussions = forum_user_can_post_discussion($forum, null, -1, $cm, $context); // Add the forum to the array to return. $arrforums[$forum->id] = $forum; } } return $arrforums; }
/** * Return sorted list of user courses * * @return array courses */ function block_my_course_progress_get_sorted_courses() { global $USER; $courses = enrol_get_my_courses(); if (array_key_exists($site->id, $courses)) { unset($courses[$site->id]); } foreach ($courses as $c) { if (isset($USER->lastcourseaccess[$c->id])) { $courses[$c->id]->lastaccess = $USER->lastcourseaccess[$c->id]; } else { $courses[$c->id]->lastaccess = 0; } } return $courses; }
protected function render_custom_menu(custom_menu $menu) { global $CFG; $hasdisplaymycourses = theme_lambda_get_setting('mycourses_dropdown'); if (isloggedin() && !isguestuser() && $hasdisplaymycourses) { $branchlabel = get_string('mycourses'); $branchurl = new moodle_url('#'); $branchtitle = $branchlabel; $branchsort = 10000; $branch = $menu->add($branchlabel, $branchurl, $branchtitle, $branchsort); if ($mycourses = enrol_get_my_courses(NULL, 'visible DESC, fullname ASC')) { foreach ($mycourses as $mycourse) { $branch->add($mycourse->shortname, new moodle_url('/course/view.php', array('id' => $mycourse->id)), $mycourse->fullname); } } else { $hometext = get_string('myhome'); $homelabel = $hometext; $branch->add($homelabel, new moodle_url('/my/index.php'), $hometext); } } return parent::render_custom_menu($menu); }
/** * get all resources! * */ function block_resources_get_all_resources() { global $DB; // get courses list in wich logged user was enrolled $courses = enrol_get_my_courses(); if (empty($courses)) { return false; } $ids = implode(',', array_keys($courses)); // --------- cycle by courses foreach ($courses as $key => $course) { if (!isset($courses[$key]->resources)) { $courses[$key]->resources = array(); } // get videoresources list from courses and then render it // * link to videoresource = link to course modules $courses[$key]->videoresources = get_coursemodules_in_course('videoresource', $course->id); } // get resources list from all courses with AVG rating $resources = $DB->get_records_sql(' SELECT DISTINCT rl.course * 10000 + si.id as id, si.id as section_id, rl.course, r.id as resource_id, r.url, r.title, r.internal_title, r.description, r.author, r.source , (SELECT AVG(t.rating) FROM mdl_rating t LEFT JOIN mdl_resource_section_items si ON si.id = t.itemid WHERE si.resource_item_id = r.id) as avgrate FROM mdl_resourcelib rl RIGHT JOIN mdl_resourcelib_content rc ON rl.id = rc.resourcelib_id RIGHT JOIN mdl_resource_lists l ON rc.instance_id = l.id RIGHT JOIN mdl_resource_list_sections ls ON l.id = ls.resource_list_id RIGHT JOIN mdl_resource_section_items si ON ls.resource_section_id = si.resource_section_id RIGHT JOIN mdl_resource_items r ON r.id = si.resource_item_id WHERE rl.course IN (' . $ids . ') ORDER BY ls.sort_order, si.sort_order'); foreach ($resources as $key => $resource) { if (!isset($courses[$resource->course]->resources[$resource->resource_id])) { $courses[$resource->course]->resources[$resource->resource_id] = $resource; } } return $courses; }
/** * Create basic setup for test cases * @return bool */ public function setup() { global $CFG; return true; // Need to update tests to not contact external services. $this->resetAfterTest(true); $this->user = $this->getDataGenerator()->create_user(); $this->user1 = $this->getDataGenerator()->create_user(); $this->course1 = $this->getDataGenerator()->create_course(); $this->course2 = $this->getDataGenerator()->create_course(); // Setting user and enrolling to the courses created with teacher role. $this->setUser($this->user->id); $c1ctx = context_course::instance($this->course1->id); $c2ctx = context_course::instance($this->course2->id); $this->getDataGenerator()->enrol_user($this->user->id, $this->course1->id, 3); $this->getDataGenerator()->enrol_user($this->user->id, $this->course2->id, 3); $this->assertCount(2, enrol_get_my_courses()); $courses = enrol_get_my_courses(); // Student enrollment. $this->setUser($this->user1->id); $this->getDataGenerator()->enrol_user($this->user1->id, $this->course1->id, 5); $this->getDataGenerator()->enrol_user($this->user1->id, $this->course2->id, 5); $this->assertCount(2, get_enrolled_users($c1ctx)); }
/** * Is used to fetch all user courses he is a teacher in and he can request a label for */ function block_elabel_get_my_courses() { global $DB, $USER; $courses = enrol_get_my_courses(); $data = array(); foreach ($courses as $course) { //skip course if the is not a teacher if (!has_capability('block/elabel:audit', context_course::instance($course->id), $USER)) { unset($course); continue; } $request = $DB->get_record('block_elabel_request', array('courseid' => $course->id)); if (!$request) { $course->status = STATUS_NEW; $course->requestid = 0; } else { $course->status = $request->state; $course->requestid = $request->id; } list($faculty, $department, $center) = block_elabel_get_coursecat_infos($course->id); $data[] = array('title' => $course->fullname, 'faculty' => $faculty, 'user' => fullname($USER), 'status' => $course->status, 'requestid' => $course->requestid, 'courseid' => $course->id, 'timecreated' => isset($request->timecreated) ? date("d.m.Y", $request->timecreated) : '', 'timegranted' => isset($request->timegranted) ? date("d.m.Y", $request->timegranted) : ''); } return $data; }
public function getCourseList() { $fieldMap = ["id" => "course_id", "shortname" => "short_name", "fullname" => "display_name"]; $retval = []; $sortorder = 'visible DESC, sortorder ASC'; if ($courses = enrol_get_my_courses(NULL, $sortorder)) { foreach ($courses as $k => $course) { $this->mark($course->id . " " . $course->visible); if ($course->visible < 1) { next; } $c = []; foreach ($fieldMap as $k => $v) { if (property_exists($course, $k)) { $c[$v] = $course->{$k}; } } // ignore course files/images // FIXME: add references to icons and images. $retval[] = $c; } } return $retval; }
/** * Returns an array of forums that the current user is subscribed to and is allowed to unsubscribe from * * @return array An array of unsubscribable forums */ function forum_get_optional_subscribed_forums() { global $USER, $DB; // Get courses that $USER is enrolled in and can see $courses = enrol_get_my_courses(); if (empty($courses)) { return array(); } $courseids = array(); foreach($courses as $course) { $courseids[] = $course->id; } list($coursesql, $courseparams) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED, 'c'); // get all forums from the user's courses that they are subscribed to and which are not set to forced $sql = "SELECT f.id, cm.id as cm, cm.visible FROM {forum} f JOIN {course_modules} cm ON cm.instance = f.id JOIN {modules} m ON m.name = :modulename AND m.id = cm.module LEFT JOIN {forum_subscriptions} fs ON (fs.forum = f.id AND fs.userid = :userid) WHERE f.forcesubscribe <> :forcesubscribe AND fs.id IS NOT NULL AND cm.course $coursesql"; $params = array_merge($courseparams, array('modulename'=>'forum', 'userid'=>$USER->id, 'forcesubscribe'=>FORUM_FORCESUBSCRIBE)); if (!$forums = $DB->get_records_sql($sql, $params)) { return array(); } $unsubscribableforums = array(); // Array to return foreach($forums as $forum) { if (empty($forum->visible)) { // the forum is hidden $context = context_module::instance($forum->cm); if (!has_capability('moodle/course:viewhiddenactivities', $context)) { // the user can't see the hidden forum continue; } } // subscribe.php only requires 'mod/forum:managesubscriptions' when // unsubscribing a user other than yourself so we don't require it here either // A check for whether the forum has subscription set to forced is built into the SQL above $unsubscribableforums[] = $forum; } return $unsubscribableforums; }
protected function render_custom_menu(custom_menu $menu) { global $CFG; require_once $CFG->dirroot . '/course/lib.php'; // TODO: eliminate this duplicated logic, it belongs in core, not // here. See MDL-39565. $addlangmenu = true; $langs = get_string_manager()->get_list_of_translations(); if (count($langs) < 2 or empty($CFG->langmenu) or $this->page->course != SITEID and !empty($this->page->course->lang)) { $addlangmenu = false; } if (!$menu->has_children() && $addlangmenu === false) { return ''; } if ($addlangmenu) { $strlang = get_string('language'); $currentlang = current_language(); if (isset($langs[$currentlang])) { $currentlang = $langs[$currentlang]; } else { $currentlang = $strlang; } $this->language = $menu->add($currentlang, new moodle_url('#'), $strlang, 10000); foreach ($langs as $langtype => $langname) { $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname); } } // Add a login or logout link // if (isloggedin()) { // $branchlabel = get_string('logout'); // $branchurl = new moodle_url('/login/logout.php'); // } else { // $branchlabel = get_string('login'); // $branchurl = new moodle_url('/login/index.php'); // } // $branch = $menu->add($branchlabel, $branchurl, $branchlabel, -1); // // Add My Courses to the menu form http://docs.moodle.org/dev/Adding_courses_and_categories_to_the_custom_menu if (isloggedin() && !isguestuser() && ($mycourses = enrol_get_my_courses(NULL, 'visible DESC, fullname ASC'))) { //which does work $branchlabel = get_string('mycourses'); $branchurl = new moodle_url('/course/index.php'); $branchtitle = $branchlabel; $branchsort = 8000; // lower numbers = higher priority e.g. move this item to the left on the Custom Menu $branch = $menu->add($branchlabel, $branchurl, $branchtitle, $branchsort); foreach ($mycourses as $mycourse) { $branch->add($mycourse->shortname, new moodle_url('/course/view.php', array('id' => $mycourse->id)), $mycourse->fullname); } } //****************************https://moodle.org/mod/forum/discuss.php?d=219352*************************************** //global $CFG; //require_once($CFG->dirroot.'/course/lib.php'); // //$branch = $menu->add(get_string('courses', 'theme_warwickclean'), null, null, 1); // //$categorytree = get_course_category_tree(); //foreach ($categorytree as $category) { //$this->add_category_to_custommenu($branch, $category); //} // //$this->render_mycourses_custom_menu($menu, 0.5) ; //return parent::render_custom_menu($menu); //} // //protected function add_category_to_custommenu(custom_menu_item $parent, stdClass $category) { //$branch = $parent->add($category->name, new moodle_url('/course/category.php', array('id' => $category->id))); //if (!empty($category->categories)) { //foreach ($category->categories as $subcategory) { //$this->add_category_to_custommenu($branch, $subcategory); //} //} //if (!empty($category->courses)) { //foreach ($category->courses as $course) { //$branch->add($course->shortname, new moodle_url('/course/view.php', array('id' => $course->id)), $course->fullname); //} //} //} // //protected function render_mycourses_custom_menu(custom_menu_item $menu, $position) { //this function adds the mycourses branch to the navbar. // // //if (isloggedin() && !isguestuser() && $mycourses = enrol_get_my_courses(NULL, 'visible DESC, fullname ASC')) { // //$branchlabel = get_string('mycourses') ; //$branchurl = new moodle_url('/course/index.php'); //$branchtitle = $branchlabel; //$branch = $menu->add($branchlabel, $branchurl, $branchtitle); // //foreach ($mycourses as $mycourse) { //$branch->add($mycourse->shortname, new moodle_url('/course/view.php', array('id' => $mycourse->id)), $mycourse->fullname); //} //} // //******************************************************************* // Add a custom link to top navigation $branchlabel = "Navigation"; $branchurl = new moodle_url('/courses.php'); $branch = $menu->add($branchlabel, $branchurl); $branch->add("Nothing Here Yet", new moodle_url('/'), "Nothing Here Yet"); // Add a custom link to top navigation $branchlabel = "Categories"; $branchurl = new moodle_url('/course'); $branch = $menu->add($branchlabel, $branchurl); $branch->add('All Categories', new moodle_url('/course')); $branch->add('Helix', new moodle_url('/course/index.php?categoryid=10')); $branch->add('Miscellaneous', new moodle_url('/course/index.php?categoryid=1')); $branch->add(' Medicine MBChB', new moodle_url('/course/index.php?categoryid=6')); $branch->add('Richard', new moodle_url('/course/index.php?categoryid=4')); $branch->add('Templates', new moodle_url('/course/index.php?categoryid=3')); // Add a custom link to top navigation $branchlabel = "Links"; $branchurl = new moodle_url('/courses.php'); $branch = $menu->add($branchlabel, $branchurl); $branch->add("Insite", new moodle_url('/'), "Insite"); $branch->add("Mahara", new moodle_url('/'), "Mahara"); $branch->add("Start.Warwick", new moodle_url('/'), "Tabula"); $branch->add("Tabula", new moodle_url('/'), "Tabula"); // Add a custom link to top navigation $branchlabel = "Help"; $branchurl = new moodle_url('/course/'); $branch = $menu->add($branchlabel, $branchurl); $branch->add("Help1", new moodle_url('/'), "Insite"); $branch->add("Help2", new moodle_url('/'), "Mahara"); // Add a custom link to top navigation $branchlabel = "Help Dept"; $branchurl = new moodle_url('/course/'); $branchtitle = "Chemistry"; $branchsort = 10000; $branch = $menu->add($branchlabel, $branchurl); $branch->add("Chem Help1", new moodle_url('/'), "Chem Help1"); $branch->add("Chem Help2", new moodle_url('/'), "Chem Help2"); // Add a custom link to top navigation $branchlabel = '<i class="fa fa-cog fa-lg"></i>'; $branchurl = new moodle_url('/course/'); $branchtitle = "settings"; $branch = $menu->add($branchlabel, $branchurl, $branchtitle); $branch->add('<i class="icon-user"></i>' . get_string('profile') . ' ', new moodle_url('/user/profile.php'), get_string('profile')); $branch->add('<i class="icon-calendar"></i>' . get_string('pluginname', 'block_calendar_month') . ' ', new moodle_url('/calendar/view.php'), get_string('pluginname', 'block_calendar_month')); $branch->add('<i class="icon-envelope"></i>' . get_string('pluginname', 'block_messages') . ' ', new moodle_url('/message/index.php'), get_string('pluginname', 'block_messages')); $branch->add('<i class="icon-certificate"></i>' . get_string('badges') . ' ', new moodle_url('/badges/mybadges.php'), get_string('badges')); $branch->add('<i class="icon-file"></i>' . get_string('privatefiles', 'block_private_files') . ' ', new moodle_url('/user/files.php'), get_string('privatefiles', 'block_private_files')); $branch->add('<i class="icon-signout"></i>' . get_string('logout') . ' ', new moodle_url('/login/logout.php'), get_string('logout')); // Add a custom settings icon link to top navigation $branchlabel = '<i class="fa fa-arrows-h fa-lg"></i>'; $branchurl = new moodle_url('/course/'); $branchtitle = "maximise"; $branch = $menu->add($branchlabel, $branchurl, $branchtitle); //$branch = $menu->add('<div id="icondiv">'.$branchlabel.'</div>', $branchurl, $branchtitle) ; $content = '<ul class="nav">'; foreach ($menu->get_children() as $item) { $content .= $this->render_custom_menu_item($item, 1); } return $content . '</ul>'; }
/** * Initialises the navigation object. * * This causes the navigation object to look at the current state of the page * that it is associated with and then load the appropriate content. * * This should only occur the first time that the navigation structure is utilised * which will normally be either when the navbar is called to be displayed or * when a block makes use of it. * * @return bool */ public function initialise() { global $CFG, $SITE, $USER, $DB; // Check if it has alread been initialised if ($this->initialised || during_initial_install()) { return true; } $this->initialised = true; // Set up the five base root nodes. These are nodes where we will put our // content and are as follows: // site: Navigation for the front page. // myprofile: User profile information goes here. // mycourses: The users courses get added here. // courses: Additional courses are added here. // users: Other users information loaded here. $this->rootnodes = array(); if (get_home_page() == HOMEPAGE_SITE) { // The home element should be my moodle because the root element is the site if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home'); } } else { // The home element should be the site because the root node is my moodle $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home'); if ($CFG->defaulthomepage == HOMEPAGE_MY) { // We need to stop automatic redirection $this->rootnodes['home']->action->param('redirect', '0'); } } $this->rootnodes['site'] = $this->add_course($SITE); $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile'); $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses'); $this->rootnodes['courses'] = $this->add(get_string('courses'), null, self::TYPE_ROOTNODE, null, 'courses'); $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users'); // Fetch all of the users courses. $limit = 20; if (!empty($CFG->navcourselimit)) { $limit = $CFG->navcourselimit; } $mycourses = enrol_get_my_courses(NULL, 'visible DESC,sortorder ASC', $limit); $showallcourses = count($mycourses) == 0 || !empty($CFG->navshowallcourses); $showcategories = $showallcourses && $this->show_categories(); $issite = $this->page->course->id != SITEID; $ismycourse = array_key_exists($this->page->course->id, $mycourses); // Check if any courses were returned. if (count($mycourses) > 0) { // Add all of the users courses to the navigation foreach ($mycourses as $course) { $course->coursenode = $this->add_course($course, false, true); } } if ($showallcourses) { // Load all courses $this->load_all_courses(); } // We always load the frontpage course to ensure it is available without // JavaScript enabled. $frontpagecourse = $this->load_course($SITE); $this->add_front_page_course_essentials($frontpagecourse, $SITE); $canviewcourseprofile = true; // Next load context specific content into the navigation switch ($this->page->context->contextlevel) { case CONTEXT_SYSTEM: // This has already been loaded we just need to map the variable $coursenode = $frontpagecourse; $this->load_all_categories(null, $showcategories); break; case CONTEXT_COURSECAT: // This has already been loaded we just need to map the variable $coursenode = $frontpagecourse; $this->load_all_categories($this->page->context->instanceid, $showcategories); break; case CONTEXT_BLOCK: case CONTEXT_COURSE: // Load the course associated with the page into the navigation $course = $this->page->course; if ($showcategories && !$issite && !$ismycourse) { $this->load_all_categories($course->category, $showcategories); } $coursenode = $this->load_course($course); // If the course wasn't added then don't try going any further. if (!$coursenode) { $canviewcourseprofile = false; break; } // If the user is not enrolled then we only want to show the // course node and not populate it. $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); // Not enrolled, can't view, and hasn't switched roles if (!can_access_course($coursecontext)) { // TODO: very ugly hack - do not force "parents" to enrol into course their child is enrolled in, // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805) $isparent = false; if ($this->useridtouseforparentchecks) { if ($this->useridtouseforparentchecks != $USER->id) { $usercontext = get_context_instance(CONTEXT_USER, $this->useridtouseforparentchecks, MUST_EXIST); if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id)) and has_capability('moodle/user:viewdetails', $usercontext)) { $isparent = true; } } } if (!$isparent) { $coursenode->make_active(); $canviewcourseprofile = false; break; } } // Add the essentials such as reports etc... $this->add_course_essentials($coursenode, $course); if ($this->format_display_course_content($course->format)) { // Load the course sections $sections = $this->load_course_sections($course, $coursenode); } if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) { $coursenode->make_active(); } break; case CONTEXT_MODULE: $course = $this->page->course; $cm = $this->page->cm; if ($showcategories && !$issite && !$ismycourse) { $this->load_all_categories($course->category, $showcategories); } // Load the course associated with the page into the navigation $coursenode = $this->load_course($course); // If the course wasn't added then don't try going any further. if (!$coursenode) { $canviewcourseprofile = false; break; } // If the user is not enrolled then we only want to show the // course node and not populate it. $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); if (!can_access_course($coursecontext)) { $coursenode->make_active(); $canviewcourseprofile = false; break; } $this->add_course_essentials($coursenode, $course); // Load the course sections into the page $sections = $this->load_course_sections($course, $coursenode); if ($course->id != SITEID) { // Find the section for the $CM associated with the page and collect // its section number. if (isset($cm->sectionnum)) { $cm->sectionnumber = $cm->sectionnum; } else { foreach ($sections as $section) { if ($section->id == $cm->section) { $cm->sectionnumber = $section->section; break; } } } // Load all of the section activities for the section the cm belongs to. if (isset($cm->sectionnumber) and !empty($sections[$cm->sectionnumber])) { list($sectionarray, $activityarray) = $this->generate_sections_and_activities($course); $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, $activityarray); } else { $activities = array(); if ($activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course))) { // "stealth" activity from unavailable section $activities[$cm->id] = $activity; } } } else { $activities = array(); $activities[$cm->id] = $coursenode->get($cm->id, navigation_node::TYPE_ACTIVITY); } if (!empty($activities[$cm->id])) { // Finally load the cm specific navigaton information $this->load_activity($cm, $course, $activities[$cm->id]); // Check if we have an active ndoe if (!$activities[$cm->id]->contains_active_node() && !$activities[$cm->id]->search_for_active_node()) { // And make the activity node active. $activities[$cm->id]->make_active(); } } else { //TODO: something is wrong, what to do? (Skodak) } break; case CONTEXT_USER: $course = $this->page->course; if ($course->id != SITEID) { if ($showcategories && !$issite && !$ismycourse) { $this->load_all_categories($course->category, $showcategories); } // Load the course associated with the user into the navigation $coursenode = $this->load_course($course); // If the course wasn't added then don't try going any further. if (!$coursenode) { $canviewcourseprofile = false; break; } // If the user is not enrolled then we only want to show the // course node and not populate it. $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); if (!can_access_course($coursecontext)) { $coursenode->make_active(); $canviewcourseprofile = false; break; } $this->add_course_essentials($coursenode, $course); $sections = $this->load_course_sections($course, $coursenode); } break; } $limit = 20; if (!empty($CFG->navcourselimit)) { $limit = $CFG->navcourselimit; } if ($showcategories) { $categories = $this->find_all_of_type(self::TYPE_CATEGORY); foreach ($categories as &$category) { if ($category->children->count() >= $limit) { $url = new moodle_url('/course/category.php', array('id' => $category->key)); $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING); } } } else { if ($this->rootnodes['courses']->children->count() >= $limit) { $this->rootnodes['courses']->add(get_string('viewallcoursescategories'), new moodle_url('/course/index.php'), self::TYPE_SETTING); } } // Load for the current user $this->load_for_user(); if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != SITEID && $canviewcourseprofile) { $this->load_for_user(null, true); } // Load each extending user into the navigation. foreach ($this->extendforuser as $user) { if ($user->id != $USER->id) { $this->load_for_user($user); } } // Give the local plugins a chance to include some navigation if they want. foreach (get_list_of_plugins('local') as $plugin) { if (!file_exists($CFG->dirroot . '/local/' . $plugin . '/lib.php')) { continue; } require_once $CFG->dirroot . '/local/' . $plugin . '/lib.php'; $function = $plugin . '_extends_navigation'; if (function_exists($function)) { $function($this); } } // Remove any empty root nodes foreach ($this->rootnodes as $node) { // Dont remove the home node if ($node->key !== 'home' && !$node->has_children()) { $node->remove(); } } if (!$this->contains_active_node()) { $this->search_for_active_node(); } // If the user is not logged in modify the navigation structure as detailed // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure} if (!isloggedin()) { $activities = clone $this->rootnodes['site']->children; $this->rootnodes['site']->remove(); $children = clone $this->children; $this->children = new navigation_node_collection(); foreach ($activities as $child) { $this->children->add($child); } foreach ($children as $child) { $this->children->add($child); } } return true; }
/** * Loads a single category into the AJAX navigation. * * This function is special in that it doesn't concern itself with the parent of * the requested category or its siblings. * This is because with the AJAX navigation we know exactly what is wanted and only need to * request that. * * @global moodle_database $DB * @param int $categoryid id of category to load in navigation. * @param int $nodetype type of node, if category is under MyHome then it's TYPE_MY_CATEGORY * @return void. */ protected function load_category($categoryid, $nodetype = self::TYPE_CATEGORY) { global $CFG, $DB; $limit = 20; if (!empty($CFG->navcourselimit)) { $limit = (int) $CFG->navcourselimit; } $catcontextsql = context_helper::get_preload_record_columns_sql('ctx'); $sql = "SELECT cc.*, {$catcontextsql}\n FROM {course_categories} cc\n JOIN {context} ctx ON cc.id = ctx.instanceid\n WHERE ctx.contextlevel = " . CONTEXT_COURSECAT . " AND\n (cc.id = :categoryid1 OR cc.parent = :categoryid2)\n ORDER BY cc.depth ASC, cc.sortorder ASC, cc.id ASC"; $params = array('categoryid1' => $categoryid, 'categoryid2' => $categoryid); $categories = $DB->get_recordset_sql($sql, $params, 0, $limit); $categorylist = array(); $subcategories = array(); $basecategory = null; foreach ($categories as $category) { $categorylist[] = $category->id; context_helper::preload_from_record($category); if ($category->id == $categoryid) { $this->add_category($category, $this, $nodetype); $basecategory = $this->addedcategories[$category->id]; } else { $subcategories[$category->id] = $category; } } $categories->close(); // If category is shown in MyHome then only show enrolled courses and hide empty subcategories, // else show all courses. if ($nodetype === self::TYPE_MY_CATEGORY) { $courses = enrol_get_my_courses(); $categoryids = array(); // Only search for categories if basecategory was found. if (!is_null($basecategory)) { // Get course parent category ids. foreach ($courses as $course) { $categoryids[] = $course->category; } // Get a unique list of category ids which a part of the path // to user's courses. $coursesubcategories = array(); $addedsubcategories = array(); list($sql, $params) = $DB->get_in_or_equal($categoryids); $categories = $DB->get_recordset_select('course_categories', 'id ' . $sql, $params, 'sortorder, id', 'id, path'); foreach ($categories as $category) { $coursesubcategories = array_merge($coursesubcategories, explode('/', trim($category->path, "/"))); } $coursesubcategories = array_unique($coursesubcategories); // Only add a subcategory if it is part of the path to user's course and // wasn't already added. foreach ($subcategories as $subid => $subcategory) { if (in_array($subid, $coursesubcategories) && !in_array($subid, $addedsubcategories)) { $this->add_category($subcategory, $basecategory, $nodetype); $addedsubcategories[] = $subid; } } } foreach ($courses as $course) { // Add course if it's in category. if (in_array($course->category, $categorylist)) { $this->add_course($course, true, self::COURSE_MY); } } } else { if (!is_null($basecategory)) { foreach ($subcategories as $key => $category) { $this->add_category($category, $basecategory, $nodetype); } } $courses = $DB->get_recordset('course', array('category' => $categoryid), 'sortorder', '*', 0, $limit); foreach ($courses as $course) { $this->add_course($course); } $courses->close(); } }
/** * Returns a list of quizzes in a provided list of courses, * if no list is provided all quizzes that the user can view will be returned. * * @param array $courseids Array of course ids * @return array of quizzes details * @since Moodle 3.1 */ public static function get_quizzes_by_courses($courseids = array()) { global $USER; $warnings = array(); $returnedquizzes = array(); $params = array('courseids' => $courseids); $params = self::validate_parameters(self::get_quizzes_by_courses_parameters(), $params); $mycourses = array(); if (empty($params['courseids'])) { $mycourses = enrol_get_my_courses(); $params['courseids'] = array_keys($mycourses); } // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($courses, $warnings) = external_util::validate_courses($params['courseids'], $mycourses); // Get the quizzes in this course, this function checks users visibility permissions. // We can avoid then additional validate_context calls. $quizzes = get_all_instances_in_courses("quiz", $courses); foreach ($quizzes as $quiz) { $context = context_module::instance($quiz->coursemodule); // Update quiz with override information. $quiz = quiz_update_effective_access($quiz, $USER->id); // Entry to return. $quizdetails = array(); // First, we return information that any user can see in the web interface. $quizdetails['id'] = $quiz->id; $quizdetails['coursemodule'] = $quiz->coursemodule; $quizdetails['course'] = $quiz->course; $quizdetails['name'] = external_format_string($quiz->name, $context->id); if (has_capability('mod/quiz:view', $context)) { // Format intro. list($quizdetails['intro'], $quizdetails['introformat']) = external_format_text($quiz->intro, $quiz->introformat, $context->id, 'mod_quiz', 'intro', null); $viewablefields = array('timeopen', 'timeclose', 'grademethod', 'section', 'visible', 'groupmode', 'groupingid'); $timenow = time(); $quizobj = quiz::create($quiz->id, $USER->id); $accessmanager = new quiz_access_manager($quizobj, $timenow, has_capability('mod/quiz:ignoretimelimits', $context, null, false)); // Fields the user could see if have access to the quiz. if (!$accessmanager->prevent_access()) { // Some times this function returns just empty. $hasfeedback = quiz_has_feedback($quiz); $quizdetails['hasfeedback'] = !empty($hasfeedback) ? 1 : 0; $quizdetails['hasquestions'] = (int) $quizobj->has_questions(); $quizdetails['autosaveperiod'] = get_config('quiz', 'autosaveperiod'); $additionalfields = array('timelimit', 'attempts', 'attemptonlast', 'grademethod', 'decimalpoints', 'questiondecimalpoints', 'reviewattempt', 'reviewcorrectness', 'reviewmarks', 'reviewspecificfeedback', 'reviewgeneralfeedback', 'reviewrightanswer', 'reviewoverallfeedback', 'questionsperpage', 'navmethod', 'sumgrades', 'grade', 'browsersecurity', 'delay1', 'delay2', 'showuserpicture', 'showblocks', 'completionattemptsexhausted', 'completionpass', 'overduehandling', 'graceperiod', 'preferredbehaviour', 'canredoquestions'); $viewablefields = array_merge($viewablefields, $additionalfields); } // Fields only for managers. if (has_capability('moodle/course:manageactivities', $context)) { $additionalfields = array('shuffleanswers', 'timecreated', 'timemodified', 'password', 'subnet'); $viewablefields = array_merge($viewablefields, $additionalfields); } foreach ($viewablefields as $field) { $quizdetails[$field] = $quiz->{$field}; } } $returnedquizzes[] = $quizdetails; } } $result = array(); $result['quizzes'] = $returnedquizzes; $result['warnings'] = $warnings; return $result; }
/** * Search contacts. * * @param string $searchtext query string. * @param bool $onlymycourses limit the search to the user's courses only. * @return external_description * @since Moodle 2.5 */ public static function search_contacts($searchtext, $onlymycourses = false) { global $CFG, $USER, $PAGE; require_once $CFG->dirroot . '/user/lib.php'; // Check if messaging is enabled. if (!$CFG->messaging) { throw new moodle_exception('disabled', 'message'); } require_once $CFG->libdir . '/enrollib.php'; $params = array('searchtext' => $searchtext, 'onlymycourses' => $onlymycourses); $params = self::validate_parameters(self::search_contacts_parameters(), $params); // Extra validation, we do not allow empty queries. if ($params['searchtext'] === '') { throw new moodle_exception('querystringcannotbeempty'); } $courseids = array(); if ($params['onlymycourses']) { $mycourses = enrol_get_my_courses(array('id')); foreach ($mycourses as $mycourse) { $courseids[] = $mycourse->id; } } else { $courseids[] = SITEID; } // Retrieving the users matching the query. $users = message_search_users($courseids, $params['searchtext']); $results = array(); foreach ($users as $user) { $results[$user->id] = $user; } // Reorganising information. foreach ($results as &$user) { $newuser = array('id' => $user->id, 'fullname' => fullname($user)); // Avoid undefined property notice as phone not specified. $user->phone1 = null; $user->phone2 = null; $userpicture = new user_picture($user); $userpicture->size = 1; // Size f1. $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false); $userpicture->size = 0; // Size f2. $newuser['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false); $user = $newuser; } return $results; }
function get_content() { global $CFG, $USER, $DB, $OUTPUT; if ($this->content !== NULL) { return $this->content; } $this->content = new stdClass(); $this->content->items = array(); $this->content->icons = array(); $this->content->footer = ''; $icon = '<img src="' . $OUTPUT->pix_url('i/course') . '" class="icon" alt="" />'; $adminseesall = true; if (isset($CFG->block_course_list_adminview)) { if ($CFG->block_course_list_adminview == 'own') { $adminseesall = false; } } if (empty($CFG->disablemycourses) and isloggedin() and !isguestuser() and !(has_capability('moodle/course:update', context_system::instance()) and $adminseesall)) { // Just print My Courses if ($courses = enrol_get_my_courses(NULL, 'visible DESC, fullname ASC')) { foreach ($courses as $course) { $coursecontext = context_course::instance($course->id); $linkcss = $course->visible ? "" : " class=\"dimmed\" "; $this->content->items[] = "<a {$linkcss} title=\"" . format_string($course->shortname, true, array('context' => $coursecontext)) . "\" " . "href=\"{$CFG->wwwroot}/course/view.php?id={$course->id}\">" . $icon . format_string(get_course_display_name_for_list($course)) . "</a>"; } $this->title = get_string('mycourses'); /// If we can update any course of the view all isn't hidden, show the view all courses link if (has_capability('moodle/course:update', context_system::instance()) || empty($CFG->block_course_list_hideallcourseslink)) { $this->content->footer = "<a href=\"{$CFG->wwwroot}/course/index.php\">" . get_string("fulllistofcourses") . "</a> ..."; } } $this->get_remote_courses(); if ($this->content->items) { // make sure we don't return an empty list return $this->content; } } $categories = coursecat::get(0)->get_children(); // Parent = 0 ie top-level categories only if ($categories) { //Check we have categories if (count($categories) > 1 || count($categories) == 1 && $DB->count_records('course') > 200) { // Just print top level category links foreach ($categories as $category) { $categoryname = $category->get_formatted_name(); $linkcss = $category->visible ? "" : " class=\"dimmed\" "; $this->content->items[] = "<a {$linkcss} href=\"{$CFG->wwwroot}/course/index.php?categoryid={$category->id}\">" . $icon . $categoryname . "</a>"; } /// If we can update any course of the view all isn't hidden, show the view all courses link if (has_capability('moodle/course:update', context_system::instance()) || empty($CFG->block_course_list_hideallcourseslink)) { $this->content->footer .= "<a href=\"{$CFG->wwwroot}/course/index.php\">" . get_string('fulllistofcourses') . '</a> ...'; } $this->title = get_string('categories'); } else { // Just print course names of single category $category = array_shift($categories); $courses = get_courses($category->id); if ($courses) { foreach ($courses as $course) { $coursecontext = context_course::instance($course->id); $linkcss = $course->visible ? "" : " class=\"dimmed\" "; $this->content->items[] = "<a {$linkcss} title=\"" . format_string($course->shortname, true, array('context' => $coursecontext)) . "\" " . "href=\"{$CFG->wwwroot}/course/view.php?id={$course->id}\">" . $icon . format_string(get_course_display_name_for_list($course), true, array('context' => context_course::instance($course->id))) . "</a>"; } /// If we can update any course of the view all isn't hidden, show the view all courses link if (has_capability('moodle/course:update', context_system::instance()) || empty($CFG->block_course_list_hideallcourseslink)) { $this->content->footer .= "<a href=\"{$CFG->wwwroot}/course/index.php\">" . get_string('fulllistofcourses') . '</a> ...'; } $this->get_remote_courses(); } else { $this->content->icons[] = ''; $this->content->items[] = get_string('nocoursesyet'); if (has_capability('moodle/course:create', context_coursecat::instance($category->id))) { $this->content->footer = '<a href="' . $CFG->wwwroot . '/course/edit.php?category=' . $category->id . '">' . get_string("addnewcourse") . '</a> ...'; } $this->get_remote_courses(); } $this->title = get_string('courses'); } } return $this->content; }
/** * Creates the blocks main content * * @return string */ public function get_content() { global $USER, $COURSE, $CFG, $OUTPUT, $DB; // If content has already been generated, don't waste time generating it again. if ($this->content !== null) { return $this->content; } $this->content = new stdClass(); $this->content->text = ''; $this->content->footer = ''; $blockinstancesonpage = array(); // Guests do not have any progress. Don't show them the block. if (!isloggedin() or isguestuser()) { return $this->content; } // Draw the multi-bar content for the Dashboard and Front page. if (block_progress_on_site_page()) { $courses = enrol_get_my_courses(); $coursenametoshow = get_config('block_progress', 'coursenametoshow') ?: 'shortname'; $sql = "SELECT bi.id,\n bp.id AS blockpositionid,\n COALESCE(bp.region, bi.defaultregion) AS region,\n COALESCE(bp.weight, bi.defaultweight) AS weight,\n COALESCE(bp.visible, 1) AS visible,\n bi.configdata\n FROM {block_instances} bi\n LEFT JOIN {block_positions} bp ON bp.blockinstanceid = bi.id\n AND " . $DB->sql_like('bp.pagetype', ':pagetype', false) . "\n WHERE bi.blockname = 'progress'\n AND bi.parentcontextid = :contextid\n ORDER BY region, weight, bi.id"; foreach ($courses as $courseid => $course) { // Get specific block config and context. $modules = block_progress_modules_in_use($course->id); if ($course->visible && !empty($modules)) { $context = block_progress_get_course_context($course->id); $params = array('contextid' => $context->id, 'pagetype' => 'course-view-%'); $blockinstances = $DB->get_records_sql($sql, $params); $blockinstancesonpage = array_merge($blockinstancesonpage, array_keys($blockinstances)); foreach ($blockinstances as $blockid => $blockinstance) { $blockinstance->config = unserialize(base64_decode($blockinstance->configdata)); if (!empty($blockinstance->config)) { $blockinstance->events = block_progress_event_information($blockinstance->config, $modules, $course->id); $blockinstance->events = block_progress_filter_visibility($blockinstance->events, $USER->id, $context, $course); } if ($blockinstance->visible == 0 || empty($blockinstance->config) || $blockinstance->events == 0 || !empty($blockinstance->config->group) && !has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($blockinstance->config->group, $USER->id)) { unset($blockinstances[$blockid]); } } // Output the Progress Bar. if (!empty($blockinstances)) { $courselink = new moodle_url('/course/view.php', array('id' => $course->id)); $linktext = HTML_WRITER::tag('h3', s($course->{$coursenametoshow})); $this->content->text .= HTML_WRITER::link($courselink, $linktext); } foreach ($blockinstances as $blockid => $blockinstance) { if ($blockinstance->config->progressTitle != '') { $this->content->text .= HTML_WRITER::tag('p', s(format_string($blockinstance->config->progressTitle))); } $attempts = block_progress_attempts($modules, $blockinstance->config, $blockinstance->events, $USER->id, $course->id); $this->content->text .= block_progress_bar($modules, $blockinstance->config, $blockinstance->events, $USER->id, $blockinstance->id, $attempts, $course->id); } } } // Show a message explaining lack of bars, but only while editing is on. if ($this->page->user_is_editing() && $this->content->text == '') { $this->content->text = get_string('no_blocks', 'block_progress'); } } else { // Check if user is in group for block. if (!empty($this->config->group) && !has_capability('moodle/site:accessallgroups', $this->context) && !groups_is_member($this->config->group, $USER->id)) { return $this->content; } // Check if any activities/resources have been created. $modules = block_progress_modules_in_use($COURSE->id); if (empty($modules)) { if (has_capability('moodle/block:edit', $this->context)) { $this->content->text .= get_string('no_events_config_message', 'block_progress'); } return $this->content; } // Check if activities/resources have been selected in config. $events = block_progress_event_information($this->config, $modules, $COURSE->id); $context = block_progress_get_course_context($COURSE->id); $events = block_progress_filter_visibility($events, $USER->id, $context); if ($events === null || $events === 0) { if (has_capability('moodle/block:edit', $this->context)) { $this->content->text .= get_string('no_events_message', 'block_progress'); if ($USER->editing) { $parameters = array('id' => $COURSE->id, 'sesskey' => sesskey(), 'bui_editid' => $this->instance->id); $url = new moodle_url('/course/view.php', $parameters); $label = get_string('selectitemstobeadded', 'block_progress'); $this->content->text .= $OUTPUT->single_button($url, $label); if ($events === 0) { $url->param('turnallon', '1'); $label = get_string('addallcurrentitems', 'block_progress'); $this->content->text .= $OUTPUT->single_button($url, $label); } } } return $this->content; } else { if (empty($events)) { if (has_capability('moodle/block:edit', $this->context)) { $this->content->text .= get_string('no_visible_events_message', 'block_progress'); } return $this->content; } } // Display progress bar. $attempts = block_progress_attempts($modules, $this->config, $events, $USER->id, $COURSE->id); $this->content->text = block_progress_bar($modules, $this->config, $events, $USER->id, $this->instance->id, $attempts, $COURSE->id); $blockinstancesonpage = array($this->instance->id); // Allow teachers to access the overview page. if (has_capability('block/progress:overview', $this->context)) { $parameters = array('progressbarid' => $this->instance->id, 'courseid' => $COURSE->id); $url = new moodle_url('/blocks/progress/overview.php', $parameters); $label = get_string('overview', 'block_progress'); $options = array('class' => 'overviewButton'); $this->content->text .= $OUTPUT->single_button($url, $label, 'post', $options); } } // Organise access to JS. $jsmodule = array('name' => 'block_progress', 'fullpath' => '/blocks/progress/module.js', 'requires' => array(), 'strings' => array()); $arguments = array($blockinstancesonpage, array($USER->id)); $this->page->requires->js_init_call('M.block_progress.init', $arguments, false, $jsmodule); return $this->content; }
/** * Prints custom user information on the home page. * Over time this can include all sorts of information */ function print_my_moodle() { global $USER, $CFG, $DB, $OUTPUT; if (!isloggedin() or isguestuser()) { print_error('nopermissions', '', '', 'See My Moodle'); } $courses = enrol_get_my_courses('summary', 'visible DESC,sortorder ASC'); $rhosts = array(); $rcourses = array(); if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode === 'strict') { $rcourses = get_my_remotecourses($USER->id); $rhosts = get_my_remotehosts(); } if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) { if (!empty($courses)) { echo '<ul class="unlist">'; foreach ($courses as $course) { if ($course->id == SITEID) { continue; } echo '<li>'; print_course($course); echo "</li>\n"; } echo "</ul>\n"; } // MNET if (!empty($rcourses)) { // at the IDP, we know of all the remote courses foreach ($rcourses as $course) { print_remote_course($course, "100%"); } } elseif (!empty($rhosts)) { // non-IDP, we know of all the remote servers, but not courses foreach ($rhosts as $host) { print_remote_host($host, "100%"); } } unset($course); unset($host); if ($DB->count_records("course") > count($courses) + 1) { // Some courses not being displayed echo "<table width=\"100%\"><tr><td align=\"center\">"; print_course_search("", false, "short"); echo "</td><td align=\"center\">"; echo $OUTPUT->single_button("{$CFG->wwwroot}/course/index.php", get_string("fulllistofcourses"), "get"); echo "</td></tr></table>\n"; } } else { if ($DB->count_records("course_categories") > 1) { echo $OUTPUT->box_start("categorybox"); print_whole_category_list(); echo $OUTPUT->box_end(); } else { print_courses(0); } } }
/** * Displays a course filter selector * * @param moodle_url $returnurl The URL that the user should be taken too upon selecting a course. * @param string $label The label to use for the course select. * @return string */ protected function course_filter_selector(moodle_url $returnurl, $label = null) { global $USER, $SESSION, $CFG; if (!isloggedin() or isguestuser()) { return ''; } if (has_capability('moodle/calendar:manageentries', context_system::instance()) && !empty($CFG->calendar_adminseesall)) { $courses = get_courses('all', 'c.shortname', 'c.id,c.shortname'); } else { $courses = enrol_get_my_courses(); } unset($courses[SITEID]); $courseoptions = array(); $courseoptions[SITEID] = get_string('fulllistofcourses'); foreach ($courses as $course) { $coursecontext = context_course::instance($course->id); $courseoptions[$course->id] = format_string($course->shortname, true, array('context' => $coursecontext)); } if ($this->page->course->id !== SITEID) { $selected = $this->page->course->id; } else { $selected = ''; } $courseurl = new moodle_url($returnurl); $courseurl->remove_params('course'); $select = new single_select($courseurl, 'course', $courseoptions, $selected, null); $select->class = 'cal_courses_flt'; if ($label !== null) { $select->set_label($label); } else { $select->set_label(get_string('listofcourses'), array('class' => 'accesshide')); } return $this->output->render($select); }
$hiddenfields = array(); // Teachers and admins are allowed to see everything. } else { $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields)); } if (isset($hiddenfields['lastaccess'])) { // Do not allow access since filtering. $accesssince = 0; } // Print settings and things in a table across the top. $controlstable = new html_table(); $controlstable->attributes['class'] = 'controls'; $controlstable->cellspacing = 0; $controlstable->data[] = new html_table_row(); // Print my course menus. if ($mycourses = enrol_get_my_courses()) { $courselist = array(); $popupurl = new moodle_url('/user/index.php?roleid=' . $roleid . '&sifirst=&silast='); foreach ($mycourses as $mycourse) { $coursecontext = context_course::instance($mycourse->id); $courselist[$mycourse->id] = format_string($mycourse->shortname, true, array('context' => $coursecontext)); } if (has_capability('moodle/site:viewparticipants', $systemcontext)) { unset($courselist[SITEID]); $courselist = array(SITEID => format_string($SITE->shortname, true, array('context' => $systemcontext))) + $courselist; } $select = new single_select($popupurl, 'id', $courselist, $course->id, null, 'courseform'); $select->set_label(get_string('mycourses')); $controlstable->data[0]->cells[] = $OUTPUT->render($select); } $controlstable->data[0]->cells[] = groups_print_course_menu($course, $baseurl->out(), true);
/** * Initialises the navigation object. * * This causes the navigation object to look at the current state of the page * that it is associated with and then load the appropriate content. * * This should only occur the first time that the navigation structure is utilised * which will normally be either when the navbar is called to be displayed or * when a block makes use of it. * * @return bool */ public function initialise() { global $CFG, $SITE, $USER, $DB; // Check if it has alread been initialised if ($this->initialised || during_initial_install()) { return true; } $this->initialised = true; // Set up the five base root nodes. These are nodes where we will put our // content and are as follows: // site: Navigation for the front page. // myprofile: User profile information goes here. // mycourses: The users courses get added here. // courses: Additional courses are added here. // users: Other users information loaded here. $this->rootnodes = array(); if (get_home_page() == HOMEPAGE_SITE) { // The home element should be my moodle because the root element is the site if (isloggedin() && !isguestuser()) { // Makes no sense if you aren't logged in $this->rootnodes['home'] = $this->add(get_string('myhome'), new moodle_url('/my/'), self::TYPE_SETTING, null, 'home'); } } else { // The home element should be the site because the root node is my moodle $this->rootnodes['home'] = $this->add(get_string('sitehome'), new moodle_url('/'), self::TYPE_SETTING, null, 'home'); if (!empty($CFG->defaulthomepage) && $CFG->defaulthomepage == HOMEPAGE_MY) { // We need to stop automatic redirection $this->rootnodes['home']->action->param('redirect', '0'); } } $this->rootnodes['site'] = $this->add_course($SITE); $this->rootnodes['myprofile'] = $this->add(get_string('myprofile'), null, self::TYPE_USER, null, 'myprofile'); $this->rootnodes['mycourses'] = $this->add(get_string('mycourses'), null, self::TYPE_ROOTNODE, null, 'mycourses'); $this->rootnodes['courses'] = $this->add(get_string('courses'), new moodle_url('/course/index.php'), self::TYPE_ROOTNODE, null, 'courses'); $this->rootnodes['users'] = $this->add(get_string('users'), null, self::TYPE_ROOTNODE, null, 'users'); // We always load the frontpage course to ensure it is available without // JavaScript enabled. $this->add_front_page_course_essentials($this->rootnodes['site'], $SITE); $this->load_course_sections($SITE, $this->rootnodes['site']); // Fetch all of the users courses. $mycourses = enrol_get_my_courses(); // We need to show categories if we can show categories and the user isn't enrolled in any courses or we're not showing all courses $showcategories = $this->show_categories() && (count($mycourses) == 0 || !empty($CFG->navshowallcourses)); // $issite gets set to true if the current pages course is the sites frontpage course $issite = $this->page->course->id == $SITE->id; // $ismycourse gets set to true if the user is enrolled in the current pages course. $ismycourse = !$issite && array_key_exists($this->page->course->id, $mycourses); // Check if any courses were returned. if (count($mycourses) > 0) { // Check if categories should be displayed within the my courses branch if (!empty($CFG->navshowmycoursecategories)) { // Find the category of each mycourse $categories = array(); foreach ($mycourses as $course) { $categories[] = $course->category; } // Do a single DB query to get the categories immediately associated with // courses the user is enrolled in. $categories = $DB->get_records_list('course_categories', 'id', array_unique($categories), 'depth ASC, sortorder ASC'); // Work out the parent categories that we need to load that we havn't // already got. $categoryids = array(); foreach ($categories as $category) { $categoryids = array_merge($categoryids, explode('/', trim($category->path, '/'))); } $categoryids = array_unique($categoryids); $categoryids = array_diff($categoryids, array_keys($categories)); if (count($categoryids)) { // Fetch any other categories we need. $allcategories = $DB->get_records_list('course_categories', 'id', $categoryids, 'depth ASC, sortorder ASC'); if (is_array($allcategories) && count($allcategories) > 0) { $categories = array_merge($categories, $allcategories); } } // We ONLY want the categories, we need to get rid of the keys $categories = array_values($categories); $addedcategories = array(); while (($category = array_shift($categories)) !== null) { if ($category->parent == '0') { $categoryparent = $this->rootnodes['mycourses']; } else { if (array_key_exists($category->parent, $addedcategories)) { $categoryparent = $addedcategories[$category->parent]; } else { // Prepare to count iterations. We don't want to loop forever // accidentally if for some reason a category can't be placed. if (!isset($category->loopcount)) { $category->loopcount = 0; } $category->loopcount++; if ($category->loopcount > 5) { // This is a pretty serious problem and this should never happen. // If it does then for some reason a category has been loaded but // its parents have now. It could be data corruption. debugging('Category ' . $category->id . ' could not be placed within the navigation', DEBUG_DEVELOPER); } else { // Add it back to the end of the categories array array_push($categories, $category); } continue; } } $url = new moodle_url('/course/category.php', array('id' => $category->id)); $addedcategories[$category->id] = $categoryparent->add($category->name, $url, self::TYPE_CATEGORY, $category->name, $category->id); if (!$category->visible) { // Let's decide the context where viewhidden cap checks will happen. if ($category->parent == '0') { $contexttocheck = context_system::instance(); } else { $contexttocheck = context_coursecat::instance($category->parent); } if (!has_capability('moodle/category:viewhiddencategories', $contexttocheck)) { $addedcategories[$category->id]->display = false; } else { $addedcategories[$category->id]->hidden = true; } } } } // Add all of the users courses to the navigation. // First up we need to add to the mycourses section. foreach ($mycourses as $course) { $course->coursenode = $this->add_course($course, false, true); } if (!empty($CFG->navshowallcourses)) { // Load all courses $this->load_all_courses(); } // Next if nasvshowallcourses is enabled then we need to add courses // to the courses branch as well. if (!empty($CFG->navshowallcourses)) { foreach ($mycourses as $course) { if (!empty($course->category) && !$this->can_add_more_courses_to_category($course->category)) { continue; } $genericcoursenode = $this->add_course($course, true); if ($genericcoursenode->isactive) { // We don't want this node to be active because we want the // node in the mycourses branch to be active. $genericcoursenode->make_inactive(); $genericcoursenode->collapse = true; if ($genericcoursenode->parent && $genericcoursenode->parent->type == self::TYPE_CATEGORY) { $parent = $genericcoursenode->parent; while ($parent && $parent->type == self::TYPE_CATEGORY) { $parent->collapse = true; $parent = $parent->parent; } } } } } } else { if (!empty($CFG->navshowallcourses) || !$this->show_categories()) { // Load all courses $this->load_all_courses(); } } $canviewcourseprofile = true; // Next load context specific content into the navigation switch ($this->page->context->contextlevel) { case CONTEXT_SYSTEM: // This has already been loaded we just need to map the variable if ($showcategories) { $this->load_all_categories(self::LOAD_ROOT_CATEGORIES, true); } break; case CONTEXT_COURSECAT: // This has already been loaded we just need to map the variable if ($this->show_categories()) { $this->load_all_categories($this->page->context->instanceid, true); } break; case CONTEXT_BLOCK: case CONTEXT_COURSE: if ($issite) { // If it is the front page course, or a block on it then // all we need to do is load the root categories if required if ($showcategories) { $this->load_all_categories(self::LOAD_ROOT_CATEGORIES, true); } break; } // Load the course associated with the page into the navigation $course = $this->page->course; if ($this->show_categories() && !$ismycourse) { // The user isn't enrolled in the course and we need to show categories in which case we need // to load the category relating to the course and depending up $showcategories all of the root categories as well. $this->load_all_categories($course->category, $showcategories); } $coursenode = $this->load_course($course); // If the course wasn't added then don't try going any further. if (!$coursenode) { $canviewcourseprofile = false; break; } // If the user is not enrolled then we only want to show the // course node and not populate it. // Not enrolled, can't view, and hasn't switched roles if (!can_access_course($course)) { // TODO: very ugly hack - do not force "parents" to enrol into course their child is enrolled in, // this hack has been propagated from user/view.php to display the navigation node. (MDL-25805) $isparent = false; if ($this->useridtouseforparentchecks) { if ($this->useridtouseforparentchecks != $USER->id) { $usercontext = get_context_instance(CONTEXT_USER, $this->useridtouseforparentchecks, MUST_EXIST); if ($DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id)) and has_capability('moodle/user:viewdetails', $usercontext)) { $isparent = true; } } } if (!$isparent) { $coursenode->make_active(); $canviewcourseprofile = false; break; } } // Add the essentials such as reports etc... $this->add_course_essentials($coursenode, $course); if ($this->format_display_course_content($course->format)) { // Load the course sections $sections = $this->load_course_sections($course, $coursenode); } if (!$coursenode->contains_active_node() && !$coursenode->search_for_active_node()) { $coursenode->make_active(); } break; case CONTEXT_MODULE: if ($issite) { // If this is the site course then most information will have // already been loaded. // However we need to check if there is more content that can // yet be loaded for the specific module instance. $activitynode = $this->rootnodes['site']->get($this->page->cm->id, navigation_node::TYPE_ACTIVITY); if ($activitynode) { $this->load_activity($this->page->cm, $this->page->course, $activitynode); } break; } $course = $this->page->course; $cm = $this->page->cm; if ($this->show_categories() && !$ismycourse) { $this->load_all_categories($course->category, $showcategories); } // Load the course associated with the page into the navigation $coursenode = $this->load_course($course); // If the course wasn't added then don't try going any further. if (!$coursenode) { $canviewcourseprofile = false; break; } // If the user is not enrolled then we only want to show the // course node and not populate it. if (!can_access_course($course)) { $coursenode->make_active(); $canviewcourseprofile = false; break; } $this->add_course_essentials($coursenode, $course); // Get section number from $cm (if provided) - we need this // before loading sections in order to tell it to load this section // even if it would not normally display (=> it contains only // a label, which we are now editing) $sectionnum = isset($cm->sectionnum) ? $cm->sectionnum : 0; if ($sectionnum) { // This value has to be stored in a member variable because // otherwise we would have to pass it through a public API // to course formats and they would need to change their // functions to pass it along again... $this->includesectionnum = $sectionnum; } else { $this->includesectionnum = false; } // Load the course sections into the page $sections = $this->load_course_sections($course, $coursenode); if ($course->id != $SITE->id) { // Find the section for the $CM associated with the page and collect // its section number. if ($sectionnum) { $cm->sectionnumber = $sectionnum; } else { foreach ($sections as $section) { if ($section->id == $cm->section) { $cm->sectionnumber = $section->section; break; } } } // Load all of the section activities for the section the cm belongs to. if (isset($cm->sectionnumber) and !empty($sections[$cm->sectionnumber])) { list($sectionarray, $activityarray) = $this->generate_sections_and_activities($course); $activities = $this->load_section_activities($sections[$cm->sectionnumber]->sectionnode, $cm->sectionnumber, $activityarray); } else { $activities = array(); if ($activity = $this->load_stealth_activity($coursenode, get_fast_modinfo($course))) { // "stealth" activity from unavailable section $activities[$cm->id] = $activity; } } } else { $activities = array(); $activities[$cm->id] = $coursenode->get($cm->id, navigation_node::TYPE_ACTIVITY); } if (!empty($activities[$cm->id])) { // Finally load the cm specific navigaton information $this->load_activity($cm, $course, $activities[$cm->id]); // Check if we have an active ndoe if (!$activities[$cm->id]->contains_active_node() && !$activities[$cm->id]->search_for_active_node()) { // And make the activity node active. $activities[$cm->id]->make_active(); } } else { //TODO: something is wrong, what to do? (Skodak) } break; case CONTEXT_USER: if ($issite) { // The users profile information etc is already loaded // for the front page. break; } $course = $this->page->course; if ($this->show_categories() && !$ismycourse) { $this->load_all_categories($course->category, $showcategories); } // Load the course associated with the user into the navigation $coursenode = $this->load_course($course); // If the course wasn't added then don't try going any further. if (!$coursenode) { $canviewcourseprofile = false; break; } // If the user is not enrolled then we only want to show the // course node and not populate it. if (!can_access_course($course)) { $coursenode->make_active(); $canviewcourseprofile = false; break; } $this->add_course_essentials($coursenode, $course); $sections = $this->load_course_sections($course, $coursenode); break; } // Look for all categories which have been loaded if ($showcategories) { $categories = $this->find_all_of_type(self::TYPE_CATEGORY); if (count($categories) !== 0) { $categoryids = array(); foreach ($categories as $category) { $categoryids[] = $category->key; } list($categoriessql, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED); $params['limit'] = !empty($CFG->navcourselimit) ? $CFG->navcourselimit : 20; $sql = "SELECT cc.id, COUNT(c.id) AS coursecount\n FROM {course_categories} cc\n JOIN {course} c ON c.category = cc.id\n WHERE cc.id {$categoriessql}\n GROUP BY cc.id\n HAVING COUNT(c.id) > :limit"; $excessivecategories = $DB->get_records_sql($sql, $params); foreach ($categories as &$category) { if (array_key_exists($category->key, $excessivecategories) && !$this->can_add_more_courses_to_category($category)) { $url = new moodle_url('/course/category.php', array('id' => $category->key)); $category->add(get_string('viewallcourses'), $url, self::TYPE_SETTING); } } } } else { if ((!empty($CFG->navshowallcourses) || empty($mycourses)) && !$this->can_add_more_courses_to_category($this->rootnodes['courses'])) { $this->rootnodes['courses']->add(get_string('viewallcoursescategories'), new moodle_url('/course/index.php'), self::TYPE_SETTING); } } // Load for the current user $this->load_for_user(); if ($this->page->context->contextlevel >= CONTEXT_COURSE && $this->page->context->instanceid != $SITE->id && $canviewcourseprofile) { $this->load_for_user(null, true); } // Load each extending user into the navigation. foreach ($this->extendforuser as $user) { if ($user->id != $USER->id) { $this->load_for_user($user); } } // Give the local plugins a chance to include some navigation if they want. foreach (get_plugin_list_with_file('local', 'lib.php', true) as $plugin => $file) { $function = "local_{$plugin}_extends_navigation"; $oldfunction = "{$plugin}_extends_navigation"; if (function_exists($function)) { // This is the preferred function name as there is less chance of conflicts $function($this); } else { if (function_exists($oldfunction)) { // We continue to support the old function name to ensure backwards compatability $oldfunction($this); } } } // Remove any empty root nodes foreach ($this->rootnodes as $node) { // Dont remove the home node if ($node->key !== 'home' && !$node->has_children()) { $node->remove(); } } if (!$this->contains_active_node()) { $this->search_for_active_node(); } // If the user is not logged in modify the navigation structure as detailed // in {@link http://docs.moodle.org/dev/Navigation_2.0_structure} if (!isloggedin()) { $activities = clone $this->rootnodes['site']->children; $this->rootnodes['site']->remove(); $children = clone $this->children; $this->children = new navigation_node_collection(); foreach ($activities as $child) { $this->children->add($child); } foreach ($children as $child) { $this->children->add($child); } } return true; }
/** * Get Calendar events * * @param array $events A list of events * @param array $options various options * @return array Array of event details * @since Moodle 2.5 */ public static function get_calendar_events($events = array(), $options = array()) { global $SITE, $DB, $USER, $CFG; require_once $CFG->dirroot . "/calendar/lib.php"; // Parameter validation. $params = self::validate_parameters(self::get_calendar_events_parameters(), array('events' => $events, 'options' => $options)); $funcparam = array('courses' => array(), 'groups' => array()); $hassystemcap = has_capability('moodle/calendar:manageentries', context_system::instance()); $warnings = array(); // Let us findout courses that we can return events from. if (!$hassystemcap) { $courses = enrol_get_my_courses(); $courses = array_keys($courses); foreach ($params['events']['courseids'] as $id) { if (in_array($id, $courses)) { $funcparam['courses'][] = $id; } else { $warnings[] = array('item' => $id, 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to access this course'); } } } else { $courses = $params['events']['courseids']; $funcparam['courses'] = $courses; } // Let us findout groups that we can return events from. if (!$hassystemcap) { $groups = groups_get_my_groups(); $groups = array_keys($groups); foreach ($params['events']['groupids'] as $id) { if (in_array($id, $groups)) { $funcparam['groups'][] = $id; } else { $warnings[] = array('item' => $id, 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to access this group'); } } } else { $groups = $params['events']['groupids']; $funcparam['groups'] = $groups; } // Do we need user events? if (!empty($params['options']['userevents'])) { $funcparam['users'] = array($USER->id); } else { $funcparam['users'] = false; } // Do we need site events? if (!empty($params['options']['siteevents'])) { $funcparam['courses'][] = $SITE->id; } // We treat 0 and null as no end. if (empty($params['options']['timeend'])) { $params['options']['timeend'] = PHP_INT_MAX; } $eventlist = calendar_get_events($params['options']['timestart'], $params['options']['timeend'], $funcparam['users'], $funcparam['groups'], $funcparam['courses'], true, $params['options']['ignorehidden']); // WS expects arrays. $events = array(); foreach ($eventlist as $id => $event) { $events[$id] = (array) $event; } // We need to get events asked for eventids. $eventsbyid = calendar_get_events_by_id($params['events']['eventids']); foreach ($eventsbyid as $eventid => $eventobj) { $event = (array) $eventobj; if (isset($events[$eventid])) { continue; } if ($hassystemcap) { // User can see everything, no further check is needed. $events[$eventid] = $event; } else { if (!empty($eventobj->modulename)) { $cm = get_coursemodule_from_instance($eventobj->modulename, $eventobj->instance); if (\core_availability\info_module::is_user_visible($cm, 0, false)) { $events[$eventid] = $event; } } else { // Can the user actually see this event? $eventobj = calendar_event::load($eventobj); if ($eventobj->courseid == $SITE->id || !empty($eventobj->groupid) && in_array($eventobj->groupid, $groups) || !empty($eventobj->courseid) && in_array($eventobj->courseid, $courses) || $USER->id == $eventobj->userid || calendar_edit_event_allowed($eventid)) { $events[$eventid] = $event; } else { $warnings[] = array('item' => $eventid, 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to view this event'); } } } } return array('events' => $events, 'warnings' => $warnings); }