/** * 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; }
/** * 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; }
/** * 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; }
/** * Prints lesson summaries on MyMoodle Page * * Prints lesson name, due date and attempt information on * lessons that have a deadline that has not already passed * and it is available for taking. * * @param array $courses An array of course objects to get lesson instances from * @param array $htmlarray Store overview output array( course ID => 'lesson' => HTML output ) */ function lesson_print_overview($courses, &$htmlarray) { global $USER, $CFG; if (!($lessons = get_all_instances_in_courses('lesson', $courses))) { return; } /// Get Necessary Strings $strlesson = get_string('modulename', 'lesson'); $strnotattempted = get_string('nolessonattempts', 'lesson'); $strattempted = get_string('lessonattempted', 'lesson'); $now = time(); foreach ($lessons as $lesson) { if ($lesson->deadline != 0 and $lesson->deadline >= $now and ($lesson->available == 0 or $lesson->available <= $now)) { // And the lesson is available // Lesson name if (!$lesson->visible) { $class = ' class="dimmed"'; } else { $class = ''; } $str = print_box("{$strlesson}: <a{$class} href=\"{$CFG->wwwroot}/mod/lesson/view.php?id={$lesson->coursemodule}\">" . format_string($lesson->name) . '</a>', 'name', '', true); // Deadline $str .= print_box(get_string('lessoncloseson', 'lesson', userdate($lesson->deadline)), 'info', '', true); // Attempt information if (has_capability('mod/lesson:manage', get_context_instance(CONTEXT_MODULE, $lesson->coursemodule))) { // Number of user attempts $attempts = count_records('lesson_attempts', 'lessonid', $lesson->id); $str .= print_box(get_string('xattempts', 'lesson', $attempts), 'info', '', true); } else { // Determine if the user has attempted the lesson or not if (count_records('lesson_attempts', 'lessonid', $lesson->id, 'userid', $USER->id)) { $str .= print_box($strattempted, 'info', '', true); } else { $str .= print_box($strnotattempted, 'info', '', true); } } $str = print_box($str, 'lesson overview', '', true); if (empty($htmlarray[$lesson->course]['lesson'])) { $htmlarray[$lesson->course]['lesson'] = $str; } else { $htmlarray[$lesson->course]['lesson'] .= $str; } } } }
/** * Returns a list of chats in a provided list of courses, * if no list is provided all chats that the user can view will be returned. * * @param array $courseids the course ids * @return array of chats details * @since Moodle 3.0 */ public static function get_chats_by_courses($courseids = array()) { global $CFG; $returnedchats = array(); $warnings = array(); $params = self::validate_parameters(self::get_chats_by_courses_parameters(), array('courseids' => $courseids)); $courses = array(); if (empty($params['courseids'])) { $courses = enrol_get_my_courses(); $params['courseids'] = array_keys($courses); } // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($courses, $warnings) = external_util::validate_courses($params['courseids'], $courses); // Get the chats in this course, this function checks users visibility permissions. // We can avoid then additional validate_context calls. $chats = get_all_instances_in_courses("chat", $courses); foreach ($chats as $chat) { $chatcontext = context_module::instance($chat->coursemodule); // Entry to return. $chatdetails = array(); // First, we return information that any user can see in the web interface. $chatdetails['id'] = $chat->id; $chatdetails['coursemodule'] = $chat->coursemodule; $chatdetails['course'] = $chat->course; $chatdetails['name'] = external_format_string($chat->name, $chatcontext->id); // Format intro. list($chatdetails['intro'], $chatdetails['introformat']) = external_format_text($chat->intro, $chat->introformat, $chatcontext->id, 'mod_chat', 'intro', null); if (has_capability('mod/chat:chat', $chatcontext)) { $chatdetails['chatmethod'] = $CFG->chat_method; $chatdetails['keepdays'] = $chat->keepdays; $chatdetails['studentlogs'] = $chat->studentlogs; $chatdetails['chattime'] = $chat->chattime; $chatdetails['schedule'] = $chat->schedule; } if (has_capability('moodle/course:manageactivities', $chatcontext)) { $chatdetails['timemodified'] = $chat->timemodified; $chatdetails['section'] = $chat->section; $chatdetails['visible'] = $chat->visible; $chatdetails['groupmode'] = $chat->groupmode; $chatdetails['groupingid'] = $chat->groupingid; } $returnedchats[] = $chatdetails; } } $result = array(); $result['chats'] = $returnedchats; $result['warnings'] = $warnings; return $result; }
/** * Print an overview of all assignments * for the courses. * * @param mixed $courses The list of courses to print the overview for * @param array $htmlarray The array of html to return * * @return true */ function assign_print_overview($courses, &$htmlarray) { global $CFG, $DB; if (empty($courses) || !is_array($courses) || count($courses) == 0) { return true; } if (!($assignments = get_all_instances_in_courses('assign', $courses))) { return true; } $assignmentids = array(); // Do assignment_base::isopen() here without loading the whole thing for speed. foreach ($assignments as $key => $assignment) { $time = time(); $isopen = false; if ($assignment->duedate) { $duedate = false; if ($assignment->cutoffdate) { $duedate = $assignment->cutoffdate; } if ($duedate) { $isopen = $assignment->allowsubmissionsfromdate <= $time && $time <= $duedate; } else { $isopen = $assignment->allowsubmissionsfromdate <= $time; } } if ($isopen) { $assignmentids[] = $assignment->id; } } if (empty($assignmentids)) { // No assignments to look at - we're done. return true; } // Definitely something to print, now include the constants we need. require_once $CFG->dirroot . '/mod/assign/locallib.php'; $strduedate = get_string('duedate', 'assign'); $strcutoffdate = get_string('nosubmissionsacceptedafter', 'assign'); $strnolatesubmissions = get_string('nolatesubmissions', 'assign'); $strduedateno = get_string('duedateno', 'assign'); $strassignment = get_string('modulename', 'assign'); // We do all possible database work here *outside* of the loop to ensure this scales. list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids); $mysubmissions = null; $unmarkedsubmissions = null; foreach ($assignments as $assignment) { // Do not show assignments that are not open. if (!in_array($assignment->id, $assignmentids)) { continue; } $context = context_module::instance($assignment->coursemodule); // Does the submission status of the assignment require notification? if (has_capability('mod/assign:submit', $context)) { // Does the submission status of the assignment require notification? $submitdetails = assign_get_mysubmission_details_for_print_overview($mysubmissions, $sqlassignmentids, $assignmentidparams, $assignment); } else { $submitdetails = false; } if (has_capability('mod/assign:grade', $context)) { // Does the grading status of the assignment require notification ? $gradedetails = assign_get_grade_details_for_print_overview($unmarkedsubmissions, $sqlassignmentids, $assignmentidparams, $assignment, $context); } else { $gradedetails = false; } if (empty($submitdetails) && empty($gradedetails)) { // There is no need to display this assignment as there is nothing to notify. continue; } $dimmedclass = ''; if (!$assignment->visible) { $dimmedclass = ' class="dimmed"'; } $href = $CFG->wwwroot . '/mod/assign/view.php?id=' . $assignment->coursemodule; $basestr = '<div class="assign overview">' . '<div class="name">' . $strassignment . ': ' . '<a ' . $dimmedclass . 'title="' . $strassignment . '" ' . 'href="' . $href . '">' . format_string($assignment->name) . '</a></div>'; if ($assignment->duedate) { $userdate = userdate($assignment->duedate); $basestr .= '<div class="info">' . $strduedate . ': ' . $userdate . '</div>'; } else { $basestr .= '<div class="info">' . $strduedateno . '</div>'; } if ($assignment->cutoffdate) { if ($assignment->cutoffdate == $assignment->duedate) { $basestr .= '<div class="info">' . $strnolatesubmissions . '</div>'; } else { $userdate = userdate($assignment->cutoffdate); $basestr .= '<div class="info">' . $strcutoffdate . ': ' . $userdate . '</div>'; } } // Show only relevant information. if (!empty($submitdetails)) { $basestr .= $submitdetails; } if (!empty($gradedetails)) { $basestr .= $gradedetails; } $basestr .= '</div>'; if (empty($htmlarray[$assignment->course]['assign'])) { $htmlarray[$assignment->course]['assign'] = $basestr; } else { $htmlarray[$assignment->course]['assign'] .= $basestr; } } return true; }
/** * Prints quiz summaries on MyMoodle Page */ function quiz_print_overview($courses, &$htmlarray) { global $USER, $CFG; /// These next 6 Lines are constant in all modules (just change module name) if (empty($courses) || !is_array($courses) || count($courses) == 0) { return array(); } if (!($quizzes = get_all_instances_in_courses('quiz', $courses))) { return; } /// Fetch some language strings outside the main loop. $strquiz = get_string('modulename', 'quiz'); $strnoattempts = get_string('noattempts', 'quiz'); /// We want to list quizzes that are currently available, and which have a close date. /// This is the same as what the lesson does, and the dabate is in MDL-10568. $now = time(); foreach ($quizzes as $quiz) { if ($quiz->timeclose >= $now && $quiz->timeopen < $now) { /// Give a link to the quiz, and the deadline. $str = '<div class="quiz overview">' . '<div class="name">' . $strquiz . ': <a ' . ($quiz->visible ? '' : ' class="dimmed"') . ' href="' . $CFG->wwwroot . '/mod/quiz/view.php?id=' . $quiz->coursemodule . '">' . $quiz->name . '</a></div>'; $str .= '<div class="info">' . get_string('quizcloseson', 'quiz', userdate($quiz->timeclose)) . '</div>'; /// Now provide more information depending on the uers's role. $context = get_context_instance(CONTEXT_MODULE, $quiz->coursemodule); if (has_capability('mod/quiz:viewreports', $context)) { /// For teacher-like people, show a summary of the number of student attempts. // The $quiz objects returned by get_all_instances_in_course have the necessary $cm // fields set to make the following call work. $str .= '<div class="info">' . quiz_num_attempt_summary($quiz, $quiz, true) . '</div>'; } else { if (has_capability('mod/quiz:attempt', $context)) { // Student /// For student-like people, tell them how many attempts they have made. if (isset($USER->id) && ($attempts = quiz_get_user_attempts($quiz->id, $USER->id))) { $numattempts = count($attempts); $str .= '<div class="info">' . get_string('numattemptsmade', 'quiz', $numattempts) . '</div>'; } else { $str .= '<div class="info">' . $strnoattempts . '</div>'; } } else { /// For ayone else, there is no point listing this quiz, so stop processing. continue; } } /// Add the output for this quiz to the rest. $str .= '</div>'; if (empty($htmlarray[$quiz->course]['quiz'])) { $htmlarray[$quiz->course]['quiz'] = $str; } else { $htmlarray[$quiz->course]['quiz'] .= $str; } } } }
/** * Returns a list of books in a provided list of courses, * if no list is provided all books that the user can view will be returned. * * @param array $courseids the course ids * @return array of books details * @since Moodle 3.0 */ public static function get_books_by_courses($courseids = array()) { global $CFG; $returnedbooks = array(); $warnings = array(); $params = self::validate_parameters(self::get_books_by_courses_parameters(), array('courseids' => $courseids)); $courses = array(); if (empty($params['courseids'])) { $courses = enrol_get_my_courses(); $params['courseids'] = array_keys($courses); } // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($courses, $warnings) = external_util::validate_courses($params['courseids'], $courses); // Get the books in this course, this function checks users visibility permissions. // We can avoid then additional validate_context calls. $books = get_all_instances_in_courses("book", $courses); foreach ($books as $book) { $context = context_module::instance($book->coursemodule); // Entry to return. $bookdetails = array(); // First, we return information that any user can see in the web interface. $bookdetails['id'] = $book->id; $bookdetails['coursemodule'] = $book->coursemodule; $bookdetails['course'] = $book->course; $bookdetails['name'] = external_format_string($book->name, $context->id); // Format intro. list($bookdetails['intro'], $bookdetails['introformat']) = external_format_text($book->intro, $book->introformat, $context->id, 'mod_book', 'intro', null); $bookdetails['numbering'] = $book->numbering; $bookdetails['navstyle'] = $book->navstyle; $bookdetails['customtitles'] = $book->customtitles; if (has_capability('moodle/course:manageactivities', $context)) { $bookdetails['revision'] = $book->revision; $bookdetails['timecreated'] = $book->timecreated; $bookdetails['timemodified'] = $book->timemodified; $bookdetails['section'] = $book->section; $bookdetails['visible'] = $book->visible; $bookdetails['groupmode'] = $book->groupmode; $bookdetails['groupingid'] = $book->groupingid; } $returnedbooks[] = $bookdetails; } } $result = array(); $result['books'] = $returnedbooks; $result['warnings'] = $warnings; return $result; }
/** * Prints choice summaries on MyMoodle Page * * Prints choice name, due date and attempt information on * choice activities that have a deadline that has not already passed * and it is available for completing. * @uses CONTEXT_MODULE * @param array $courses An array of course objects to get choice instances from. * @param array $htmlarray Store overview output array( course ID => 'choice' => HTML output ) */ function choice_print_overview($courses, &$htmlarray) { global $USER, $DB, $OUTPUT; if (empty($courses) || !is_array($courses) || count($courses) == 0) { return; } if (!($choices = get_all_instances_in_courses('choice', $courses))) { return; } $now = time(); foreach ($choices as $choice) { if ($choice->timeclose != 0 and $choice->timeclose >= $now and ($choice->timeopen == 0 or $choice->timeopen <= $now)) { // And the choice is available. // Visibility. $class = !$choice->visible ? 'dimmed' : ''; // Link to activity. $url = new moodle_url('/mod/choice/view.php', array('id' => $choice->coursemodule)); $url = html_writer::link($url, format_string($choice->name), array('class' => $class)); $str = $OUTPUT->box(get_string('choiceactivityname', 'choice', $url), 'name'); // Deadline. $str .= $OUTPUT->box(get_string('choicecloseson', 'choice', userdate($choice->timeclose)), 'info'); // Display relevant info based on permissions. if (has_capability('mod/choice:readresponses', context_module::instance($choice->coursemodule))) { $attempts = $DB->count_records('choice_answers', array('choiceid' => $choice->id)); $str .= $OUTPUT->box(get_string('viewallresponses', 'choice', $attempts), 'info'); } else { if (has_capability('mod/choice:choose', context_module::instance($choice->coursemodule))) { // See if the user has submitted anything. $answers = $DB->count_records('choice_answers', array('choiceid' => $choice->id, 'userid' => $USER->id)); if ($answers > 0) { // User has already selected an answer, nothing to show. $str = ''; } else { // User has not made a selection yet. $str .= $OUTPUT->box(get_string('notanswered', 'choice'), 'info'); } } else { // Does not have permission to do anything on this choice activity. $str = ''; } } // Make sure we have something to display. if (!empty($str)) { // Generate the containing div. $str = $OUTPUT->box($str, 'choice overview'); if (empty($htmlarray[$choice->course]['choice'])) { $htmlarray[$choice->course]['choice'] = $str; } else { $htmlarray[$choice->course]['choice'] .= $str; } } } } return; }
/** * Returns a list of scorms in a provided list of courses, * if no list is provided all scorms that the user can view will be returned. * * @param array $courseids the course ids * @return array the scorm details * @since Moodle 3.0 */ public static function get_scorms_by_courses($courseids = array()) { global $CFG; $returnedscorms = array(); $warnings = array(); $params = self::validate_parameters(self::get_scorms_by_courses_parameters(), array('courseids' => $courseids)); $courses = array(); if (empty($params['courseids'])) { $courses = enrol_get_my_courses(); $params['courseids'] = array_keys($courses); } // Ensure there are courseids to loop through. if (!empty($params['courseids'])) { list($courses, $warnings) = external_util::validate_courses($params['courseids'], $courses); // Get the scorms in this course, this function checks users visibility permissions. // We can avoid then additional validate_context calls. $scorms = get_all_instances_in_courses("scorm", $courses); $fs = get_file_storage(); foreach ($scorms as $scorm) { $context = context_module::instance($scorm->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'] = $scorm->id; $module['coursemodule'] = $scorm->coursemodule; $module['course'] = $scorm->course; $module['name'] = external_format_string($scorm->name, $context->id); list($module['intro'], $module['introformat']) = external_format_text($scorm->intro, $scorm->introformat, $context->id, 'mod_scorm', 'intro', $scorm->id); // Check if the SCORM open and return warnings if so. list($open, $openwarnings) = scorm_get_availability_status($scorm, true, $context); if (!$open) { foreach ($openwarnings as $warningkey => $warningdata) { $warnings[] = array('item' => 'scorm', 'itemid' => $scorm->id, 'warningcode' => $warningkey, 'message' => get_string($warningkey, 'scorm', $warningdata)); } } else { $module['packagesize'] = 0; // SCORM size. if ($scorm->scormtype === SCORM_TYPE_LOCAL or $scorm->scormtype === SCORM_TYPE_LOCALSYNC) { if ($packagefile = $fs->get_file($context->id, 'mod_scorm', 'package', 0, '/', $scorm->reference)) { $module['packagesize'] = $packagefile->get_filesize(); // Download URL. $module['packageurl'] = moodle_url::make_webservice_pluginfile_url($context->id, 'mod_scorm', 'package', 0, '/', $scorm->reference)->out(false); } } $module['protectpackagedownloads'] = get_config('scorm', 'protectpackagedownloads'); $viewablefields = array('version', 'maxgrade', 'grademethod', 'whatgrade', 'maxattempt', 'forcecompleted', 'forcenewattempt', 'lastattemptlock', 'displayattemptstatus', 'displaycoursestructure', 'sha1hash', 'md5hash', 'revision', 'launch', 'skipview', 'hidebrowse', 'hidetoc', 'nav', 'navpositionleft', 'navpositiontop', 'auto', 'popup', 'width', 'height', 'timeopen', 'timeclose', 'displayactivityname', 'scormtype', 'reference'); // Check additional permissions for returning optional private settings. if (has_capability('moodle/course:manageactivities', $context)) { $additionalfields = array('updatefreq', 'options', 'completionstatusrequired', 'completionscorerequired', 'autocommit', 'timemodified', 'section', 'visible', 'groupmode', 'groupingid'); $viewablefields = array_merge($viewablefields, $additionalfields); } foreach ($viewablefields as $field) { $module[$field] = $scorm->{$field}; } } $returnedscorms[] = $module; } } $result = array(); $result['scorms'] = $returnedscorms; $result['warnings'] = $warnings; return $result; }
/** * Print an overview of all assignments * for the courses. * * @param mixed $courses The list of courses to print the overview for * @param array $htmlarray The array of html to return */ function assign_print_overview($courses, &$htmlarray) { global $USER, $CFG, $DB; if (empty($courses) || !is_array($courses) || count($courses) == 0) { return array(); } if (!($assignments = get_all_instances_in_courses('assign', $courses))) { return; } $assignmentids = array(); // Do assignment_base::isopen() here without loading the whole thing for speed. foreach ($assignments as $key => $assignment) { $time = time(); $isopen = false; if ($assignment->duedate) { $duedate = false; if ($assignment->cutoffdate) { $duedate = $assignment->cutoffdate; } if ($duedate) { $isopen = $assignment->allowsubmissionsfromdate <= $time && $time <= $duedate; } else { $isopen = $assignment->allowsubmissionsfromdate <= $time; } } if ($isopen) { $assignmentids[] = $assignment->id; } } if (empty($assignmentids)) { // No assignments to look at - we're done. return true; } // Definitely something to print, now include the constants we need. require_once $CFG->dirroot . '/mod/assign/locallib.php'; $strduedate = get_string('duedate', 'assign'); $strcutoffdate = get_string('nosubmissionsacceptedafter', 'assign'); $strnolatesubmissions = get_string('nolatesubmissions', 'assign'); $strduedateno = get_string('duedateno', 'assign'); $strduedateno = get_string('duedateno', 'assign'); $strgraded = get_string('graded', 'assign'); $strnotgradedyet = get_string('notgradedyet', 'assign'); $strnotsubmittedyet = get_string('notsubmittedyet', 'assign'); $strsubmitted = get_string('submitted', 'assign'); $strassignment = get_string('modulename', 'assign'); $strreviewed = get_string('reviewed', 'assign'); // We do all possible database work here *outside* of the loop to ensure this scales. list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids); $mysubmissions = null; $unmarkedsubmissions = null; foreach ($assignments as $assignment) { // Do not show assignments that are not open. if (!in_array($assignment->id, $assignmentids)) { continue; } $dimmedclass = ''; if (!$assignment->visible) { $dimmedclass = ' class="dimmed"'; } $href = $CFG->wwwroot . '/mod/assign/view.php?id=' . $assignment->coursemodule; $str = '<div class="assign overview">' . '<div class="name">' . $strassignment . ': ' . '<a ' . $dimmedclass . 'title="' . $strassignment . '" ' . 'href="' . $href . '">' . format_string($assignment->name) . '</a></div>'; if ($assignment->duedate) { $userdate = userdate($assignment->duedate); $str .= '<div class="info">' . $strduedate . ': ' . $userdate . '</div>'; } else { $str .= '<div class="info">' . $strduedateno . '</div>'; } if ($assignment->cutoffdate) { if ($assignment->cutoffdate == $assignment->duedate) { $str .= '<div class="info">' . $strnolatesubmissions . '</div>'; } else { $userdate = userdate($assignment->cutoffdate); $str .= '<div class="info">' . $strcutoffdate . ': ' . $userdate . '</div>'; } } $context = context_module::instance($assignment->coursemodule); if (has_capability('mod/assign:grade', $context)) { if (!isset($unmarkedsubmissions)) { $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt, mxs.assignment FROM {assign_submission} mxs WHERE mxs.assignment ' . $sqlassignmentids . ' GROUP BY mxs.userid, mxs.assignment'; // Build up and array of unmarked submissions indexed by assignment id/ userid // for use where the user has grading rights on assignment. $dbparams = array_merge($assignmentidparams, array(ASSIGN_SUBMISSION_STATUS_SUBMITTED), $assignmentidparams); $rs = $DB->get_recordset_sql('SELECT s.assignment as assignment, s.userid as userid, s.id as id, s.status as status, g.timemodified as timegraded FROM {assign_submission} s LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON smx.userid = s.userid AND smx.assignment = s.id LEFT JOIN {assign_grades} g ON s.userid = g.userid AND s.assignment = g.assignment AND g.attemptnumber = smx.maxattempt WHERE ( g.timemodified is NULL OR s.timemodified > g.timemodified ) AND s.timemodified IS NOT NULL AND s.status = ? AND s.attemptnumber = smx.maxattempt AND s.assignment ' . $sqlassignmentids, $dbparams); $unmarkedsubmissions = array(); foreach ($rs as $rd) { $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id; } $rs->close(); } // Count how many people can submit. $submissions = 0; if ($students = get_enrolled_users($context, 'mod/assign:view', 0, 'u.id')) { foreach ($students as $student) { if (isset($unmarkedsubmissions[$assignment->id][$student->id])) { $submissions++; } } } if ($submissions) { $urlparams = array('id' => $assignment->coursemodule, 'action' => 'grading'); $url = new moodle_url('/mod/assign/view.php', $urlparams); $str .= '<div class="details">' . '<a href="' . $url . '">' . get_string('submissionsnotgraded', 'assign', $submissions) . '</a></div>'; } } if (has_capability('mod/assign:submit', $context)) { if (!isset($mysubmissions)) { // This is nasty because we only want the last attempt. $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt, mxs.assignment FROM {assign_submission} mxs WHERE mxs.assignment ' . $sqlassignmentids . ' AND mxs.userid = ? GROUP BY mxs.userid, mxs.assignment'; // Get all user submissions, indexed by assignment id. $dbparams = array_merge($assignmentidparams, array($USER->id, $USER->id, $USER->id), $assignmentidparams); $mysubmissions = $DB->get_records_sql('SELECT a.id AS assignment, a.nosubmissions AS nosubmissions, g.timemodified AS timemarked, g.grader AS grader, g.grade AS grade, s.status AS status FROM {assign} a LEFT JOIN ( ' . $submissionmaxattempt . ' ) smx ON smx.assignment = a.id LEFT JOIN {assign_grades} g ON g.assignment = a.id AND g.userid = ? AND g.attemptnumber = smx.maxattempt LEFT JOIN {assign_submission} s ON s.attemptnumber = smx.maxattempt AND s.assignment = a.id AND s.userid = ? WHERE a.id ' . $sqlassignmentids, $dbparams); } $str .= '<div class="details">'; $str .= get_string('mysubmission', 'assign'); $submission = false; if (isset($mysubmissions[$assignment->id])) { $submission = $mysubmissions[$assignment->id]; } if (!$submission || !$submission->status || $submission->status == 'draft') { $str .= $strnotsubmittedyet; } else { if ($submission->nosubmissions) { $str .= get_string('offline', 'assign'); } else { $str .= get_string('submissionstatus_' . $submission->status, 'assign'); } } if (!$submission || !$submission->grade || $submission->grade < 0) { $str .= ', ' . get_string('notgraded', 'assign'); } else { $str .= ', ' . get_string('graded', 'assign'); } $str .= '</div>'; } $str .= '</div>'; if (empty($htmlarray[$assignment->course]['assign'])) { $htmlarray[$assignment->course]['assign'] = $str; } else { $htmlarray[$assignment->course]['assign'] .= $str; } } }
/** * 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(); $modes = 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); $glossary->introfiles = external_util::get_area_files($context->id, 'mod_glossary', 'intro', false, false); // Make sure we have a number of entries per page. if (!$glossary->entbypage) { $glossary->entbypage = $CFG->glossary_entbypage; } // Add the list of browsing modes. if (!isset($modes[$glossary->displayformat])) { $modes[$glossary->displayformat] = self::get_browse_modes_from_display_format($glossary->displayformat); } $glossary->browsemodes = $modes[$glossary->displayformat]; $glossary->canaddentry = has_capability('mod/glossary:write', $context) ? 1 : 0; } } $result = array(); $result['glossaries'] = $glossaries; $result['warnings'] = $warnings; return $result; }
/** * Print an overview of all WebEx Meetings for the courses. * * @param mixed $courses The list of courses to print the overview for * @param array $htmlarray The array of html to return */ function webexactivity_print_overview($courses, &$htmlarray) { global $USER, $CFG, $DB; if (empty($courses) || !is_array($courses) || count($courses) == 0) { return; } if (!($meetings = get_all_instances_in_courses('webexactivity', $courses))) { return; } $displaymeetings = array(); foreach ($meetings as $rec) { $meeting = \mod_webexactivity\meeting::load($rec); if ($meeting->is_available()) { $displaymeetings[] = $meeting; } } if (count($displaymeetings) == 0) { return; } $strmodname = get_string('modulename', 'webexactivity'); $strinprogress = get_string('inprogress', 'webexactivity'); $strstartsoon = get_string('startssoon', 'webexactivity'); $strstarttime = get_string('starttime', 'webexactivity'); $strstatus = get_string('status'); foreach ($displaymeetings as $meeting) { $href = $CFG->wwwroot . '/mod/webexactivity/view.php?id=' . $meeting->coursemodule; $str = '<div class="webexactivity overview"><div class="name">'; $str .= $strmodname . ': <a title="' . $strmodname . '" href="' . $href . '">'; $str .= format_string($meeting->name) . '</a></div>'; $status = $meeting->get_time_status(); if (!isset($meeting->endtime)) { $str .= '<div class="start">' . $strstarttime . ': ' . userdate($meeting->starttime) . '</div>'; } if ($status == \mod_webexactivity\webex::WEBEXACTIVITY_TIME_IN_PROGRESS) { $str .= '<div class="status">' . $strstatus . ': ' . $strinprogress . '</div>'; } else { if ($status == \mod_webexactivity\webex::WEBEXACTIVITY_TIME_AVAILABLE) { $str .= '<div class="status">' . $strstatus . ': ' . $strstartsoon . '</div>'; } } $str .= '</div>'; if (isset($htmlarray[$meeting->course]['webexactivity'])) { $htmlarray[$meeting->course]['webexactivity'] .= $str; } else { $htmlarray[$meeting->course]['webexactivity'] = $str; } } }
/** * Returns a list of databases in a provided list of courses, * if no list is provided all databases that the user can view will be returned. * * @param array $courseids the course ids * @return array the database details * @since Moodle 2.9 */ public static function get_databases_by_courses($courseids = array()) { global $CFG; $params = self::validate_parameters(self::get_databases_by_courses_parameters(), array('courseids' => $courseids)); $warnings = array(); if (!empty($params['courseids'])) { $courses = array(); $courseids = $params['courseids']; } else { $courses = enrol_get_my_courses(); $courseids = array_keys($courses); } // Array to store the databases to return. $arrdatabases = array(); // Ensure there are courseids to loop through. if (!empty($courseids)) { // Array of the courses we are going to retrieve the databases from. $dbcourses = array(); // Go through the courseids. foreach ($courseids as $cid) { // Check the user can function in this context. try { $context = context_course::instance($cid); self::validate_context($context); // Check if this course was already loaded (by enrol_get_my_courses). if (!isset($courses[$cid])) { $courses[$cid] = get_course($cid); } $dbcourses[$cid] = $courses[$cid]; } catch (Exception $e) { $warnings[] = array('item' => 'course', 'itemid' => $cid, 'warningcode' => '1', 'message' => 'No access rights in course context ' . $e->getMessage()); } } // Get the databases in this course, this function checks users visibility permissions. // We can avoid then additional validate_context calls. $databases = get_all_instances_in_courses("data", $dbcourses); foreach ($databases as $database) { $datacontext = context_module::instance($database->coursemodule); // Entry to return. $newdb = array(); // First, we return information that any user can see in the web interface. $newdb['id'] = $database->id; $newdb['coursemodule'] = $database->coursemodule; $newdb['course'] = $database->course; $newdb['name'] = $database->name; // Format intro. list($newdb['intro'], $newdb['introformat']) = external_format_text($database->intro, $database->introformat, $datacontext->id, 'mod_data', 'intro', null); // This information should be only available if the user can see the database entries. if (has_capability('mod/data:viewentry', $datacontext)) { $viewablefields = array('comments', 'timeavailablefrom', 'timeavailableto', 'timeviewfrom', 'timeviewto', 'requiredentries', 'requiredentriestoview'); // This is for avoid a long repetitive list and for // checking that we are retrieving all the required fields. foreach ($viewablefields as $field) { // We do not use isset because it won't work for existing null values. if (!property_exists($database, $field)) { throw new invalid_response_exception('Missing database module required field: ' . $field); } $newdb[$field] = $database->{$field}; } } // Check additional permissions for returning optional private settings. // I avoid intentionally to use can_[add|update]_moduleinfo. if (has_capability('moodle/course:manageactivities', $context)) { $additionalfields = array('maxentries', 'rssarticles', 'singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter', 'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate', 'asearchtemplate', 'approval', 'scale', 'assessed', 'assesstimestart', 'assesstimefinish', 'defaultsort', 'defaultsortdir', 'editany', 'notification'); // This is for avoid a long repetitive list. foreach ($additionalfields as $field) { if (property_exists($database, $field)) { $newdb[$field] = $database->{$field}; } } } $arrdatabases[] = $newdb; } } $result = array(); $result['databases'] = $arrdatabases; $result['warnings'] = $warnings; return $result; }
/** * This function prints the recent activity (since current user's last login) * for specified courses. * @param array $courses Array of courses to print activity for. * @param string by reference $htmlarray Array of html snippets for display some * -where, which this function adds its new html to. */ function questionnaire_print_overview($courses, &$htmlarray) { global $DB, $USER, $CFG; require_once $CFG->dirroot . '/mod/questionnaire/locallib.php'; if (empty($courses) || !is_array($courses) || count($courses) == 0) { return array(); } if (!($questionnaires = get_all_instances_in_courses('questionnaire', $courses))) { return; } // Get all questionnaire logs in ONE query (much better!). $params = array(); $sql = "SELECT instance,cmid,l.course,COUNT(l.id) as count FROM {log} l " . " JOIN {course_modules} cm ON cm.id = cmid " . " JOIN {questionnaire} q ON cm.instance = q.id " . " WHERE ("; foreach ($courses as $course) { $sql .= '(l.course = ? AND l.time > ?) OR '; $params[] = $course->id; $params[] = $course->lastaccess; } $sql = substr($sql, 0, -3); // Take off the last OR. $sql .= ") AND l.module = 'questionnaire' AND action = 'submit' " . " AND userid != ?" . " AND q.resp_view <> ?" . " GROUP BY cmid,l.course,instance"; $params[] = $USER->id; $params[] = QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENANSWERED; if (!($new = $DB->get_records_sql($sql, $params))) { $new = array(); // Avoid warnings. } $strquestionnaires = get_string('modulename', 'questionnaire'); $site = get_site(); if (count($courses) == 1 && isset($courses[$site->id])) { $strnumrespsince1 = get_string('overviewnumresplog1', 'questionnaire'); $strnumrespsince = get_string('overviewnumresplog', 'questionnaire'); } else { $strnumrespsince1 = get_string('overviewnumrespvw1', 'questionnaire'); $strnumrespsince = get_string('overviewnumrespvw', 'questionnaire'); } // Go through the list of all questionnaires build previously, and check whether // they have had any activity. require_once $CFG->dirroot . '/mod/questionnaire/questionnaire.class.php'; foreach ($questionnaires as $questionnaire) { if (array_key_exists($questionnaire->id, $new) && !empty($new[$questionnaire->id])) { $cm = get_coursemodule_from_instance('questionnaire', $questionnaire->id); $context = context_module::instance($cm->id); $qobject = new questionnaire($questionnaire->id, $questionnaire, $questionnaire->course, $cm); $isclosed = $qobject->is_closed(); $answered = !$qobject->user_can_take($USER->id); $count = $new[$questionnaire->id]->count; if ($count > 0 && (has_capability('mod/questionnaire:readallresponseanytime', $context) || has_capability('mod/questionnaire:readallresponses', $context) && ($questionnaire->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_ALWAYS || $questionnaire->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENCLOSED && $isclosed || $questionnaire->resp_view == QUESTIONNAIRE_STUDENTVIEWRESPONSES_WHENANSWERED && $answered))) { if ($count == 1) { $strresp = $strnumrespsince1; } else { $strresp = $strnumrespsince; } $str = '<div class="overview questionnaire"><div class="name">' . $strquestionnaires . ': <a title="' . $strquestionnaires . '" href="' . $CFG->wwwroot . '/mod/questionnaire/view.php?a=' . $questionnaire->id . '">' . $questionnaire->name . '</a></div>'; $str .= '<div class="info">'; $str .= $count . ' ' . $strresp; $str .= '</div></div>'; if (!array_key_exists($questionnaire->course, $htmlarray)) { $htmlarray[$questionnaire->course] = array(); } if (!array_key_exists('questionnaire', $htmlarray[$questionnaire->course])) { $htmlarray[$questionnaire->course]['questionnaire'] = ''; // Initialize, avoid warnings. } $htmlarray[$questionnaire->course]['questionnaire'] .= $str; } } } }
/** * @global object * @global object * @global object * @param array $courses * @param array $htmlarray */ function forum_print_overview($courses,&$htmlarray) { global $USER, $CFG, $DB, $SESSION; if (empty($courses) || !is_array($courses) || count($courses) == 0) { return array(); } if (!$forums = get_all_instances_in_courses('forum',$courses)) { return; } // Courses to search for new posts $coursessqls = array(); $params = array(); foreach ($courses as $course) { // If the user has never entered into the course all posts are pending if ($course->lastaccess == 0) { $coursessqls[] = '(f.course = ?)'; $params[] = $course->id; // Only posts created after the course last access } else { $coursessqls[] = '(f.course = ? AND p.created > ?)'; $params[] = $course->id; $params[] = $course->lastaccess; } } $params[] = $USER->id; $coursessql = implode(' OR ', $coursessqls); $sql = "SELECT f.id, COUNT(*) as count " .'FROM {forum} f ' .'JOIN {forum_discussions} d ON d.forum = f.id ' .'JOIN {forum_posts} p ON p.discussion = d.id ' ."WHERE ($coursessql) " .'AND p.userid != ? ' .'GROUP BY f.id'; if (!$new = $DB->get_records_sql($sql, $params)) { $new = array(); // avoid warnings } // also get all forum tracking stuff ONCE. $trackingforums = array(); foreach ($forums as $forum) { if (forum_tp_can_track_forums($forum)) { $trackingforums[$forum->id] = $forum; } } if (count($trackingforums) > 0) { $cutoffdate = isset($CFG->forum_oldpostdays) ? (time() - ($CFG->forum_oldpostdays*24*60*60)) : 0; $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '. ' FROM {forum_posts} p '. ' JOIN {forum_discussions} d ON p.discussion = d.id '. ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE ('; $params = array($USER->id); foreach ($trackingforums as $track) { $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR '; $params[] = $track->id; if (isset($SESSION->currentgroup[$track->course])) { $groupid = $SESSION->currentgroup[$track->course]; } else { // get first groupid $groupids = groups_get_all_groups($track->course, $USER->id); if ($groupids) { reset($groupids); $groupid = key($groupids); $SESSION->currentgroup[$track->course] = $groupid; } else { $groupid = 0; } unset($groupids); } $params[] = $groupid; } $sql = substr($sql,0,-3); // take off the last OR $sql .= ') AND p.modified >= ? AND r.id is NULL GROUP BY d.forum,d.course'; $params[] = $cutoffdate; if (!$unread = $DB->get_records_sql($sql, $params)) { $unread = array(); } } else { $unread = array(); } if (empty($unread) and empty($new)) { return; } $strforum = get_string('modulename','forum'); foreach ($forums as $forum) { $str = ''; $count = 0; $thisunread = 0; $showunread = false; // either we have something from logs, or trackposts, or nothing. if (array_key_exists($forum->id, $new) && !empty($new[$forum->id])) { $count = $new[$forum->id]->count; } if (array_key_exists($forum->id,$unread)) { $thisunread = $unread[$forum->id]->count; $showunread = true; } if ($count > 0 || $thisunread > 0) { $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'. $forum->name.'</a></div>'; $str .= '<div class="info"><span class="postsincelogin">'; $str .= get_string('overviewnumpostssince', 'forum', $count)."</span>"; if (!empty($showunread)) { $str .= '<div class="unreadposts">'.get_string('overviewnumunread', 'forum', $thisunread).'</div>'; } $str .= '</div></div>'; } if (!empty($str)) { if (!array_key_exists($forum->course,$htmlarray)) { $htmlarray[$forum->course] = array(); } if (!array_key_exists('forum',$htmlarray[$forum->course])) { $htmlarray[$forum->course]['forum'] = ''; // initialize, avoid warnings } $htmlarray[$forum->course]['forum'] .= $str; } } }
function respondusws_print_overview($courses, &$htmlarray) { global $CFG; if (empty($courses) || !is_array($courses) || count($courses) == 0) { return; } $records = get_all_instances_in_courses("respondusws", $courses); if (count($records) == 0) { return; } foreach ($records as $instance) { $summary = '<div class="respondusws overview">' . '<div class="name">' . get_string("modulename", "respondusws") . ': <a ' . ($instance->visible ? '' : ' class="dimmed"') . ' href="' . $CFG->wwwroot . '/mod/respondusws/view.php?id=' . $instance->coursemodule . '">' . format_string($instance->name) . '</a></div></div>'; if (empty($htmlarray[$instance->course]["respondusws"])) { $htmlarray[$instance->course]["respondusws"] = $summary; } else { $htmlarray[$instance->course]["respondusws"] .= $summary; } } }
/** * @global object * @global object * @param array $courses * @param array $htmlarray Passed by reference */ function chat_print_overview($courses, &$htmlarray) { global $USER, $CFG; if (empty($courses) || !is_array($courses) || count($courses) == 0) { return array(); } if (!($chats = get_all_instances_in_courses('chat', $courses))) { return; } $strchat = get_string('modulename', 'chat'); $strnextsession = get_string('nextsession', 'chat'); foreach ($chats as $chat) { if ($chat->chattime and $chat->schedule) { // A chat is scheduled $str = '<div class="chat overview"><div class="name">' . $strchat . ': <a ' . ($chat->visible ? '' : ' class="dimmed"') . ' href="' . $CFG->wwwroot . '/mod/chat/view.php?id=' . $chat->coursemodule . '">' . $chat->name . '</a></div>'; $str .= '<div class="info">' . $strnextsession . ': ' . userdate($chat->chattime) . '</div></div>'; if (empty($htmlarray[$chat->course]['chat'])) { $htmlarray[$chat->course]['chat'] = $str; } else { $htmlarray[$chat->course]['chat'] .= $str; } } } }
function checklist_print_overview($courses, &$htmlarray) { global $USER, $CFG, $DB; $config = get_config('checklist'); if (isset($config->showmymoodle) && !$config->showmymoodle) { return; // Disabled via global config. } if (!isset($config->showcompletemymoodle)) { $config->showcompletemymoodle = 1; } if (empty($courses) || !is_array($courses) || count($courses) == 0) { return; } if (!($checklists = get_all_instances_in_courses('checklist', $courses))) { return; } $strchecklist = get_string('modulename', 'checklist'); foreach ($checklists as $checklist) { $show_all = true; if ($checklist->teacheredit == CHECKLIST_MARKING_STUDENT) { if ($CFG->version < 2011120100) { $context = get_context_instance(CONTEXT_MODULE, $checklist->coursemodule); } else { $context = context_module::instance($checklist->coursemodule); } $show_all = !has_capability('mod/checklist:updateown', $context); } $progressbar = checklist_class::print_user_progressbar($checklist->id, $USER->id, '270px', true, true, !$config->showcompletemymoodle); if (empty($progressbar)) { continue; } // Do not worry about hidden items / groupings as automatic items cannot have dates // (and manual items cannot be hidden / have groupings) if ($show_all) { // Show all items whether or not they are checked off (as this user is unable to check them off) $date_items = $DB->get_records_select('checklist_item', 'checklist = ? AND duetime > 0', array($checklist->id), 'duetime'); } else { // Show only items that have not been checked off $date_items = $DB->get_records_sql('SELECT i.* FROM {checklist_item} i JOIN {checklist_check} c ON c.item = i.id ' . 'WHERE i.checklist = ? AND i.duetime > 0 AND c.userid = ? AND usertimestamp = 0 ' . 'ORDER BY i.duetime', array($checklist->id, $USER->id)); } $str = '<div class="checklist overview"><div class="name">' . $strchecklist . ': ' . '<a title="' . $strchecklist . '" href="' . $CFG->wwwroot . '/mod/checklist/view.php?id=' . $checklist->coursemodule . '">' . $checklist->name . '</a></div>'; $str .= '<div class="info">' . $progressbar . '</div>'; foreach ($date_items as $item) { $str .= '<div class="info">' . $item->displaytext . ': '; if ($item->duetime > time()) { $str .= '<span class="itemdue">'; } else { $str .= '<span class="itemoverdue">'; } $str .= date('j M Y', $item->duetime) . '</span></div>'; } $str .= '</div>'; if (empty($htmlarray[$checklist->course]['checklist'])) { $htmlarray[$checklist->course]['checklist'] = $str; } else { $htmlarray[$checklist->course]['checklist'] .= $str; } } }
function assignment_print_overview($courses, &$htmlarray) { global $USER, $CFG, $DB; if (empty($courses) || !is_array($courses) || count($courses) == 0) { return array(); } if (!$assignments = get_all_instances_in_courses('assignment',$courses)) { return; } $assignmentids = array(); // Do assignment_base::isopen() here without loading the whole thing for speed foreach ($assignments as $key => $assignment) { $time = time(); if ($assignment->timedue) { if ($assignment->preventlate) { $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue); } else { $isopen = ($assignment->timeavailable <= $time); } } if (empty($isopen) || empty($assignment->timedue)) { unset($assignments[$key]); } else { $assignmentids[] = $assignment->id; } } if (empty($assignmentids)){ // no assignments to look at - we're done return true; } $strduedate = get_string('duedate', 'assignment'); $strduedateno = get_string('duedateno', 'assignment'); $strgraded = get_string('graded', 'assignment'); $strnotgradedyet = get_string('notgradedyet', 'assignment'); $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment'); $strsubmitted = get_string('submitted', 'assignment'); $strassignment = get_string('modulename', 'assignment'); $strreviewed = get_string('reviewed','assignment'); // NOTE: we do all possible database work here *outside* of the loop to ensure this scales // list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids); // build up and array of unmarked submissions indexed by assignment id/ userid // for use where the user has grading rights on assignment $rs = $DB->get_recordset_sql("SELECT id, assignment, userid FROM {assignment_submissions} WHERE teacher = 0 AND timemarked = 0 AND assignment $sqlassignmentids", $assignmentidparams); $unmarkedsubmissions = array(); foreach ($rs as $rd) { $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id; } $rs->close(); // get all user submissions, indexed by assignment id $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade FROM {assignment_submissions} WHERE userid = ? AND assignment $sqlassignmentids", array_merge(array($USER->id), $assignmentidparams)); foreach ($assignments as $assignment) { $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '. '<a '.($assignment->visible ? '':' class="dimmed"'). 'title="'.$strassignment.'" href="'.$CFG->wwwroot. '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'. $assignment->name.'</a></div>'; if ($assignment->timedue) { $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>'; } else { $str .= '<div class="info">'.$strduedateno.'</div>'; } $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule); if (has_capability('mod/assignment:grade', $context)) { // count how many people can submit $submissions = 0; // init if ($students = get_enrolled_users($context, 'mod/assignment:view', 0, 'u.id')) { foreach ($students as $student) { if (isset($unmarkedsubmissions[$assignment->id][$student->id])) { $submissions++; } } } if ($submissions) { $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$assignment->coursemodule)); $str .= '<div class="details"><a href="'.$link.'">'.get_string('submissionsnotgraded', 'assignment', $submissions).'</a></div>'; } } else { $str .= '<div class="details">'; if (isset($mysubmissions[$assignment->id])) { $submission = $mysubmissions[$assignment->id]; if ($submission->teacher == 0 && $submission->timemarked == 0) { $str .= $strsubmitted . ', ' . $strnotgradedyet; } else if ($submission->grade <= 0) { $str .= $strsubmitted . ', ' . $strreviewed; } else { $str .= $strsubmitted . ', ' . $strgraded; } } else { $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue); } $str .= '</div>'; } $str .= '</div>'; if (empty($htmlarray[$assignment->course]['assignment'])) { $htmlarray[$assignment->course]['assignment'] = $str; } else { $htmlarray[$assignment->course]['assignment'] .= $str; } } }
/** * Returns an array of all the active instances of a particular module in a given course, * sorted in the order they are defined. * * Returns an array of all the active instances of a particular * module in a given course, sorted in the order they are defined * in the course. Returns an empty array on any errors. * * The returned objects includle the columns cw.section, cm.visible, * cm.groupmode and cm.groupingid, cm.groupmembersonly, and are indexed by cm.id. * * Simply calls {@link all_instances_in_courses()} with a single provided course * * @param string $modulename The name of the module to get instances for * @param object $course The course obect. * @return array of module instance objects, including some extra fields from the course_modules * and course_sections tables, or an empty array if an error occurred. * @param int $userid * @param int $includeinvisible */ function get_all_instances_in_course($modulename, $course, $userid = NULL, $includeinvisible = false) { return get_all_instances_in_courses($modulename, array($course->id => $course), $userid, $includeinvisible); }
function assignment_print_overview($courses, &$htmlarray) { global $USER, $CFG; if (empty($courses) || !is_array($courses) || count($courses) == 0) { return array(); } if (!($assignments = get_all_instances_in_courses('assignment', $courses))) { return; } // Do assignment_base::isopen() here without loading the whole thing for speed foreach ($assignments as $key => $assignment) { $time = time(); if ($assignment->timedue) { if ($assignment->preventlate) { $isopen = $assignment->timeavailable <= $time && $time <= $assignment->timedue; } else { $isopen = $assignment->timeavailable <= $time; } } if (empty($isopen) || empty($assignment->timedue)) { unset($assignments[$key]); } } $strduedate = get_string('duedate', 'assignment'); $strduedateno = get_string('duedateno', 'assignment'); $strgraded = get_string('graded', 'assignment'); $strnotgradedyet = get_string('notgradedyet', 'assignment'); $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment'); $strsubmitted = get_string('submitted', 'assignment'); $strassignment = get_string('modulename', 'assignment'); $strreviewed = get_string('reviewed', 'assignment'); foreach ($assignments as $assignment) { $str = '<div class="assignment overview"><div class="name">' . $strassignment . ': ' . '<a ' . ($assignment->visible ? '' : ' class="dimmed"') . 'title="' . $strassignment . '" href="' . $CFG->wwwroot . '/mod/assignment/view.php?id=' . $assignment->coursemodule . '">' . $assignment->name . '</a></div>'; if ($assignment->timedue) { $str .= '<div class="info">' . $strduedate . ': ' . userdate($assignment->timedue) . '</div>'; } else { $str .= '<div class="info">' . $strduedateno . '</div>'; } $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule); if (has_capability('mod/assignment:grade', $context)) { // count how many people can submit $submissions = 0; // init if ($students = get_users_by_capability($context, 'mod/assignment:submit', '', '', '', '', 0, '', false)) { foreach ($students as $student) { if (get_records_sql("SELECT id,id FROM {$CFG->prefix}assignment_submissions\n WHERE assignment = {$assignment->id} AND\n userid = {$student->id} AND\n teacher = 0 AND\n timemarked = 0")) { $submissions++; } } } if ($submissions) { $str .= get_string('submissionsnotgraded', 'assignment', $submissions); } } else { $sql = "SELECT *\n FROM {$CFG->prefix}assignment_submissions\n WHERE userid = '{$USER->id}'\n AND assignment = '{$assignment->id}'"; if ($submission = get_record_sql($sql)) { if ($submission->teacher == 0 && $submission->timemarked == 0) { $str .= $strsubmitted . ', ' . $strnotgradedyet; } else { if ($submission->grade <= 0) { $str .= $strsubmitted . ', ' . $strreviewed; } else { $str .= $strsubmitted . ', ' . $strgraded; } } } else { $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue); } } $str .= '</div>'; if (empty($htmlarray[$assignment->course]['assignment'])) { $htmlarray[$assignment->course]['assignment'] = $str; } else { $htmlarray[$assignment->course]['assignment'] .= $str; } } }
/** * 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; }
/** * @global object * @global object * @global object * @param array $courses * @param array $htmlarray */ function forum_print_overview($courses,&$htmlarray) { global $USER, $CFG, $DB, $SESSION; if (empty($courses) || !is_array($courses) || count($courses) == 0) { return array(); } if (!$forums = get_all_instances_in_courses('forum',$courses)) { return; } // get all forum logs in ONE query (much better!) $params = array(); $sql = "SELECT instance,cmid,l.course,COUNT(l.id) as count FROM {log} l " ." JOIN {course_modules} cm ON cm.id = cmid " ." WHERE ("; foreach ($courses as $course) { $sql .= '(l.course = ? AND l.time > ?) OR '; $params[] = $course->id; $params[] = $course->lastaccess; } $sql = substr($sql,0,-3); // take off the last OR $sql .= ") AND l.module = 'forum' AND action = 'add post' " ." AND userid != ? GROUP BY cmid,l.course,instance"; $params[] = $USER->id; if (!$new = $DB->get_records_sql($sql, $params)) { $new = array(); // avoid warnings } // also get all forum tracking stuff ONCE. $trackingforums = array(); foreach ($forums as $forum) { if (forum_tp_can_track_forums($forum)) { $trackingforums[$forum->id] = $forum; } } if (count($trackingforums) > 0) { $cutoffdate = isset($CFG->forum_oldpostdays) ? (time() - ($CFG->forum_oldpostdays*24*60*60)) : 0; $sql = 'SELECT d.forum,d.course,COUNT(p.id) AS count '. ' FROM {forum_posts} p '. ' JOIN {forum_discussions} d ON p.discussion = d.id '. ' LEFT JOIN {forum_read} r ON r.postid = p.id AND r.userid = ? WHERE ('; $params = array($USER->id); foreach ($trackingforums as $track) { $sql .= '(d.forum = ? AND (d.groupid = -1 OR d.groupid = 0 OR d.groupid = ?)) OR '; $params[] = $track->id; if (isset($SESSION->currentgroup[$track->course])) { $groupid = $SESSION->currentgroup[$track->course]; } else { $groupid = groups_get_all_groups($track->course, $USER->id); if (is_array($groupid)) { $groupid = array_shift(array_keys($groupid)); $SESSION->currentgroup[$track->course] = $groupid; } else { $groupid = 0; } } $params[] = $groupid; } $sql = substr($sql,0,-3); // take off the last OR $sql .= ') AND p.modified >= ? AND r.id is NULL GROUP BY d.forum,d.course'; $params[] = $cutoffdate; if (!$unread = $DB->get_records_sql($sql, $params)) { $unread = array(); } } else { $unread = array(); } if (empty($unread) and empty($new)) { return; } $strforum = get_string('modulename','forum'); $strnumunread = get_string('overviewnumunread','forum'); $strnumpostssince = get_string('overviewnumpostssince','forum'); foreach ($forums as $forum) { $str = ''; $count = 0; $thisunread = 0; $showunread = false; // either we have something from logs, or trackposts, or nothing. if (array_key_exists($forum->id, $new) && !empty($new[$forum->id])) { $count = $new[$forum->id]->count; } if (array_key_exists($forum->id,$unread)) { $thisunread = $unread[$forum->id]->count; $showunread = true; } if ($count > 0 || $thisunread > 0) { $str .= '<div class="overview forum"><div class="name">'.$strforum.': <a title="'.$strforum.'" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'. $forum->name.'</a></div>'; $str .= '<div class="info"><span class="postsincelogin">'; $str .= $count.' '.$strnumpostssince."</span>"; if (!empty($showunread)) { $str .= '<div class="unreadposts">'.$thisunread .' '.$strnumunread.'</div>'; } $str .= '</div></div>'; } if (!empty($str)) { if (!array_key_exists($forum->course,$htmlarray)) { $htmlarray[$forum->course] = array(); } if (!array_key_exists('forum',$htmlarray[$forum->course])) { $htmlarray[$forum->course]['forum'] = ''; // initialize, avoid warnings } $htmlarray[$forum->course]['forum'] .= $str; } } }
/** * Print an overview of all assignments * for the courses. * * @param mixed $courses The list of courses to print the overview for * @param array $htmlarray The array of html to return */ function assign_print_overview($courses, &$htmlarray) { global $USER, $CFG, $DB; if (empty($courses) || !is_array($courses) || count($courses) == 0) { return array(); } if (!($assignments = get_all_instances_in_courses('assign', $courses))) { return; } $assignmentids = array(); // Do assignment_base::isopen() here without loading the whole thing for speed foreach ($assignments as $key => $assignment) { $time = time(); $isopen = false; if ($assignment->duedate) { $duedate = false; if ($assignment->cutoffdate) { $duedate = $assignment->cutoffdate; } if ($duedate) { $isopen = $assignment->allowsubmissionsfromdate <= $time && $time <= $duedate; } else { $isopen = $assignment->allowsubmissionsfromdate <= $time; } } if ($isopen) { $assignmentids[] = $assignment->id; } } if (empty($assignmentids)) { // no assignments to look at - we're done return true; } $strduedate = get_string('duedate', 'assign'); $strcutoffdate = get_string('nosubmissionsacceptedafter', 'assign'); $strnolatesubmissions = get_string('nolatesubmissions', 'assign'); $strduedateno = get_string('duedateno', 'assign'); $strduedateno = get_string('duedateno', 'assign'); $strgraded = get_string('graded', 'assign'); $strnotgradedyet = get_string('notgradedyet', 'assign'); $strnotsubmittedyet = get_string('notsubmittedyet', 'assign'); $strsubmitted = get_string('submitted', 'assign'); $strassignment = get_string('modulename', 'assign'); $strreviewed = get_string('reviewed', 'assign'); // NOTE: we do all possible database work here *outside* of the loop to ensure this scales // list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids); // build up and array of unmarked submissions indexed by assignment id/ userid // for use where the user has grading rights on assignment $rs = $DB->get_recordset_sql("SELECT s.assignment as assignment, s.userid as userid, s.id as id, s.status as status, g.timemodified as timegraded\n FROM {assign_submission} s LEFT JOIN {assign_grades} g ON s.userid = g.userid and s.assignment = g.assignment\n WHERE g.timemodified = 0 OR s.timemodified > g.timemodified\n AND s.assignment {$sqlassignmentids}", $assignmentidparams); $unmarkedsubmissions = array(); foreach ($rs as $rd) { $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id; } $rs->close(); // get all user submissions, indexed by assignment id $mysubmissions = $DB->get_records_sql("SELECT a.id AS assignment, a.nosubmissions AS nosubmissions, g.timemodified AS timemarked, g.grader AS grader, g.grade AS grade, s.status AS status\n FROM {assign} a LEFT JOIN {assign_grades} g ON g.assignment = a.id AND g.userid = ? LEFT JOIN {assign_submission} s ON s.assignment = a.id AND s.userid = ?\n AND a.id {$sqlassignmentids}", array_merge(array($USER->id, $USER->id), $assignmentidparams)); foreach ($assignments as $assignment) { // Do not show assignments that are not open if (!in_array($assignment->id, $assignmentids)) { continue; } $str = '<div class="assign overview"><div class="name">' . $strassignment . ': ' . '<a ' . ($assignment->visible ? '' : ' class="dimmed"') . 'title="' . $strassignment . '" href="' . $CFG->wwwroot . '/mod/assign/view.php?id=' . $assignment->coursemodule . '">' . format_string($assignment->name) . '</a></div>'; if ($assignment->duedate) { $str .= '<div class="info">' . $strduedate . ': ' . userdate($assignment->duedate) . '</div>'; } else { $str .= '<div class="info">' . $strduedateno . '</div>'; } if ($assignment->cutoffdate) { if ($assignment->cutoffdate == $assignment->duedate) { $str .= '<div class="info">' . $strnolatesubmissions . '</div>'; } else { $str .= '<div class="info">' . $strcutoffdate . ': ' . userdate($assignment->cutoffdate) . '</div>'; } } $context = context_module::instance($assignment->coursemodule); if (has_capability('mod/assign:grade', $context)) { // count how many people can submit $submissions = 0; // init if ($students = get_enrolled_users($context, 'mod/assign:view', 0, 'u.id')) { foreach ($students as $student) { if (isset($unmarkedsubmissions[$assignment->id][$student->id])) { $submissions++; } } } if ($submissions) { $link = new moodle_url('/mod/assign/view.php', array('id' => $assignment->coursemodule, 'action' => 'grading')); $str .= '<div class="details"><a href="' . $link . '">' . get_string('submissionsnotgraded', 'assign', $submissions) . '</a></div>'; } } if (has_capability('mod/assign:submit', $context)) { $str .= '<div class="details">'; $str .= get_string('mysubmission', 'assign'); $submission = $mysubmissions[$assignment->id]; if ($submission->nosubmissions) { $str .= get_string('offline', 'assign'); } else { if (!$submission->status || $submission->status == 'draft') { $str .= $strnotsubmittedyet; } else { $str .= get_string('submissionstatus_' . $submission->status, 'assign'); } } if (!$submission->grade || $submission->grade < 0) { $str .= ', ' . get_string('notgraded', 'assign'); } else { $str .= ', ' . get_string('graded', 'assign'); } $str .= '</div>'; } $str .= '</div>'; if (empty($htmlarray[$assignment->course]['assign'])) { $htmlarray[$assignment->course]['assign'] = $str; } else { $htmlarray[$assignment->course]['assign'] .= $str; } } }
public function test_get_all_instances_in_courses() { global $CFG; $this->resetAfterTest(); $this->setAdminUser(); // Some generators have bogus access control. $this->assertFileExists("{$CFG->dirroot}/mod/folder/lib.php"); $this->assertFileExists("{$CFG->dirroot}/mod/glossary/lib.php"); $course1 = $this->getDataGenerator()->create_course(); $course2 = $this->getDataGenerator()->create_course(); $course3 = $this->getDataGenerator()->create_course(); $folder1a = $this->getDataGenerator()->create_module('folder', array('course' => $course1, 'section' => 3)); $folder1b = $this->getDataGenerator()->create_module('folder', array('course' => $course1)); $glossary1 = $this->getDataGenerator()->create_module('glossary', array('course' => $course1)); $folder2 = $this->getDataGenerator()->create_module('folder', array('course' => $course2)); $glossary2a = $this->getDataGenerator()->create_module('glossary', array('course' => $course2)); $glossary2b = $this->getDataGenerator()->create_module('glossary', array('course' => $course2)); $folder3 = $this->getDataGenerator()->create_module('folder', array('course' => $course3)); $modules = get_all_instances_in_courses('folder', array($course1->id => $course1, $course2->id => $course2)); $this->assertCount(3, $modules); foreach ($modules as $cm) { if ($folder1a->cmid == $cm->coursemodule) { $folder = $folder1a; } else { if ($folder1b->cmid == $cm->coursemodule) { $folder = $folder1b; } else { if ($folder2->cmid == $cm->coursemodule) { $folder = $folder2; } else { $this->fail('Unexpected cm' . $cm->coursemodule); } } } $this->assertSame($folder->name, $cm->name); $this->assertSame($folder->course, $cm->course); } try { get_all_instances_in_courses('a b', array($course1->id => $course1, $course2->id => $course2)); $this->fail('coding_exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } try { get_all_instances_in_courses('', array($course1->id => $course1, $course2->id => $course2)); $this->fail('coding_exception expected'); } catch (moodle_exception $e) { $this->assertInstanceOf('coding_exception', $e); } }
/** * This is a standard Moodle module that prints out a summary of all activities * of this kind in the My Moodle page for a user * * @param object $courses * @param object $htmlarray * @return bool success */ function turnitintool_print_overview($courses, &$htmlarray) { global $USER, $CFG, $DB; if (empty($courses) || !is_array($courses) || count($courses) == 0) { return array(); } if (!($turnitintools = get_all_instances_in_courses('turnitintool', $courses))) { return; } $ids = array(); $tiidata = array(); foreach ($turnitintools as $key => $turnitintool) { $now = time(); $parts = turnitintool_get_records_select('turnitintool_parts', 'turnitintoolid=' . $turnitintool->id . ' AND deleted=0', NULL, 'id'); $context = turnitintool_get_context('MODULE', $turnitintool->coursemodule); // Get Early and Late Date Boundries for each part of this assignment $earlydate = 0; $latedate = 0; $partsarray = array(); foreach ($parts as $part) { $earlydate = ($part->dtstart < $earlydate or $earlydate == 0) ? $part->dtstart : $earlydate; $latedate = $part->dtpost > $latedate ? $part->dtpost : $latedate; $partsarray[$part->id]['name'] = $part->partname; $partsarray[$part->id]['dtdue'] = $part->dtdue; if (has_capability('mod/turnitintool:grade', $context)) { // If user is a grader $subquery = turnitintool_get_records_select('turnitintool_submissions', 'turnitintoolid=' . $turnitintool->id . ' AND submission_part=' . $part->id . ' AND submission_objectid IS NOT NULL AND userid!=0', NULL, '', 'count(userid)'); $numsubmissions = key($subquery); $gradequery = turnitintool_get_records_select('turnitintool_submissions', 'turnitintoolid=' . $turnitintool->id . ' AND submission_part=' . $part->id . ' AND userid!=0 AND submission_grade IS NOT NULL', NULL, '', 'count(userid)'); $numgrades = key($gradequery); $allusers = get_users_by_capability($context, 'mod/turnitintool:submit', 'u.id', '', '', '', 0, '', false); $input = new stdClass(); $input->submitted = $numsubmissions; $input->graded = $numgrades; $input->total = count($allusers); $input->gplural = $numgrades != 1 ? 's' : ''; $partsarray[$part->id]['status'] = get_string('tutorstatus', 'turnitintool', $input); } else { // If user is a student if ($submission = turnitintool_get_record_select('turnitintool_submissions', 'turnitintoolid=' . $turnitintool->id . ' AND submission_part=' . $part->id . ' AND userid=' . $USER->id . ' AND submission_objectid IS NOT NULL')) { $input = new stdClass(); $input->modified = userdate($submission->submission_modified, get_string('strftimedatetimeshort', 'langconfig')); $input->objectid = $submission->submission_objectid; $partsarray[$part->id]['status'] = get_string('studentstatus', 'turnitintool', $input); } else { $partsarray[$part->id]['status'] = get_string('nosubmissions', 'turnitintool'); } } } if ($earlydate <= $now and $latedate >= $now) { // Turnitin Assignment Is Active for this user $str = '<div class="turnitintool overview"><div class="name">' . get_string('modulename', 'turnitintool') . ': ' . '<a ' . ($turnitintool->visible ? '' : ' class="dimmed"') . 'title="' . get_string('modulename', 'turnitintool') . '" href="' . $CFG->wwwroot . '/mod/turnitintool/view.php?id=' . $turnitintool->coursemodule . '">' . $turnitintool->name . '</a></div>'; foreach ($partsarray as $thispart) { $str .= '<div class="info"><b>' . $thispart['name'] . ' - ' . get_string('dtdue', 'turnitintool') . ': ' . userdate($thispart['dtdue'], get_string('strftimedatetimeshort', 'langconfig'), $USER->timezone) . '</b><br /> <i>' . $thispart['status'] . '</i></div>'; } $str .= '</div>'; if (empty($htmlarray[$turnitintool->course]['turnitintool'])) { $htmlarray[$turnitintool->course]['turnitintool'] = $str; } else { $htmlarray[$turnitintool->course]['turnitintool'] .= $str; } } } }
/** * writes overview info for course_overview block - displays upcoming scorm objects that have a due date * * @param object $type - type of log(aicc,scorm12,scorm13) used as prefix for filename * @param array $htmlarray * @return mixed */ function scorm_print_overview($courses, &$htmlarray) { global $USER, $CFG; if (empty($courses) || !is_array($courses) || count($courses) == 0) { return array(); } if (!$scorms = get_all_instances_in_courses('scorm', $courses)) { return; } $strscorm = get_string('modulename', 'scorm'); $strduedate = get_string('duedate', 'scorm'); foreach ($scorms as $scorm) { $time = time(); $showattemptstatus = false; if ($scorm->timeopen) { $isopen = ($scorm->timeopen <= $time && $time <= $scorm->timeclose); } if ($scorm->displayattemptstatus == SCORM_DISPLAY_ATTEMPTSTATUS_ALL || $scorm->displayattemptstatus == SCORM_DISPLAY_ATTEMPTSTATUS_MY) { $showattemptstatus = true; } if ($showattemptstatus || !empty($isopen) || !empty($scorm->timeclose)) { $str = html_writer::start_div('scorm overview').html_writer::div($strscorm. ': '. html_writer::link($CFG->wwwroot.'/mod/scorm/view.php?id='.$scorm->coursemodule, $scorm->name, array('title' => $strscorm, 'class' => $scorm->visible ? '' : 'dimmed')), 'name'); if ($scorm->timeclose) { $str .= html_writer::div($strduedate.': '.userdate($scorm->timeclose), 'info'); } if ($showattemptstatus) { require_once($CFG->dirroot.'/mod/scorm/locallib.php'); $str .= html_writer::div(scorm_get_attempt_status($USER, $scorm), 'details'); } $str .= html_writer::end_div(); if (empty($htmlarray[$scorm->course]['scorm'])) { $htmlarray[$scorm->course]['scorm'] = $str; } else { $htmlarray[$scorm->course]['scorm'] .= $str; } } } }