MDL-76866 editor_atto: Remove old install script
[moodle.git] / course / renderer.php
blobf01d069f05cac52cbb0d87838c23bdc08b8cf9ce
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Renderer for use with the course section and all the goodness that falls
20 * within it.
22 * This renderer should contain methods useful to courses, and categories.
24 * @package moodlecore
25 * @copyright 2010 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 /**
30 * The core course renderer
32 * Can be retrieved with the following:
33 * $renderer = $PAGE->get_renderer('core','course');
35 class core_course_renderer extends plugin_renderer_base {
36 const COURSECAT_SHOW_COURSES_NONE = 0; /* do not show courses at all */
37 const COURSECAT_SHOW_COURSES_COUNT = 5; /* do not show courses but show number of courses next to category name */
38 const COURSECAT_SHOW_COURSES_COLLAPSED = 10;
39 const COURSECAT_SHOW_COURSES_AUTO = 15; /* will choose between collapsed and expanded automatically */
40 const COURSECAT_SHOW_COURSES_EXPANDED = 20;
41 const COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT = 30;
43 const COURSECAT_TYPE_CATEGORY = 0;
44 const COURSECAT_TYPE_COURSE = 1;
46 /**
47 * A cache of strings
48 * @var stdClass
50 protected $strings;
52 /**
53 * Whether a category content is being initially rendered with children. This is mainly used by the
54 * core_course_renderer::corsecat_tree() to render the appropriate action for the Expand/Collapse all link on
55 * page load.
56 * @var bool
58 protected $categoryexpandedonload = false;
60 /**
61 * Override the constructor so that we can initialise the string cache
63 * @param moodle_page $page
64 * @param string $target
66 public function __construct(moodle_page $page, $target) {
67 $this->strings = new stdClass;
68 $courseid = $page->course->id;
69 parent::__construct($page, $target);
72 /**
73 * @deprecated since 3.2
75 protected function add_modchoosertoggle() {
76 throw new coding_exception('core_course_renderer::add_modchoosertoggle() can not be used anymore.');
79 /**
80 * Renders course info box.
82 * @param stdClass $course
83 * @return string
85 public function course_info_box(stdClass $course) {
86 $content = '';
87 $content .= $this->output->box_start('generalbox info');
88 $chelper = new coursecat_helper();
89 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
90 $content .= $this->coursecat_coursebox($chelper, $course);
91 $content .= $this->output->box_end();
92 return $content;
95 /**
96 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
98 * @deprecated since 2.5
100 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
102 * @param array $ignored argument ignored
103 * @return string
105 public final function course_category_tree(array $ignored) {
106 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
107 return $this->frontpage_combo_list();
111 * Renderers a category for use with course_category_tree
113 * @deprecated since 2.5
115 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
117 * @param array $category
118 * @param int $depth
119 * @return string
121 protected final function course_category_tree_category(stdClass $category, $depth=1) {
122 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
123 return '';
127 * Render a modchooser.
129 * @param renderable $modchooser The chooser.
130 * @return string
132 public function render_modchooser(renderable $modchooser) {
133 return $this->render_from_template('core_course/modchooser', $modchooser->export_for_template($this));
137 * @deprecated since 3.9
139 public function course_modchooser() {
140 throw new coding_exception('course_modchooser() can not be used anymore, please use course_activitychooser() instead.');
144 * Build the HTML for the module chooser javascript popup.
146 * @param int $courseid The course id to fetch modules for.
147 * @return string
149 public function course_activitychooser($courseid) {
151 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchooser')) {
152 return '';
155 // Build an object of config settings that we can then hook into in the Activity Chooser.
156 $chooserconfig = (object) [
157 'tabmode' => get_config('core', 'activitychoosertabmode'),
159 $this->page->requires->js_call_amd('core_course/activitychooser', 'init', [$courseid, $chooserconfig]);
161 return '';
165 * Build the HTML for a specified set of modules
167 * @param array $modules A set of modules as used by the
168 * course_modchooser_module function
169 * @return string The composed HTML for the module
171 protected function course_modchooser_module_types($modules) {
172 debugging('Method core_course_renderer::course_modchooser_module_types() is deprecated, ' .
173 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
174 return '';
178 * Return the HTML for the specified module adding any required classes
180 * @param object $module An object containing the title, and link. An
181 * icon, and help text may optionally be specified. If the module
182 * contains subtypes in the types option, then these will also be
183 * displayed.
184 * @param array $classes Additional classes to add to the encompassing
185 * div element
186 * @return string The composed HTML for the module
188 protected function course_modchooser_module($module, $classes = array('option')) {
189 debugging('Method core_course_renderer::course_modchooser_module() is deprecated, ' .
190 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
191 return '';
194 protected function course_modchooser_title($title, $identifier = null) {
195 debugging('Method core_course_renderer::course_modchooser_title() is deprecated, ' .
196 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
197 return '';
201 * Renders HTML for displaying the sequence of course module editing buttons
203 * @deprecated since Moodle 4.0 MDL-72656 - please do not use this function any more.
205 * @see course_get_cm_edit_actions()
207 * @param action_link[] $actions Array of action_link objects
208 * @param cm_info $mod The module we are displaying actions for.
209 * @param array $displayoptions additional display options:
210 * ownerselector => A JS/CSS selector that can be used to find an cm node.
211 * If specified the owning node will be given the class 'action-menu-shown' when the action
212 * menu is being displayed.
213 * constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
214 * the action menu to when it is being displayed.
215 * donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
216 * @return string
218 public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
219 global $CFG;
221 debugging(
222 'course_section_cm_edit_actions is deprecated. Use core_courseformat\\output\\local\\content\\cm\\controlmenu instead.',
223 DEBUG_DEVELOPER
226 if (empty($actions)) {
227 return '';
230 if (isset($displayoptions['ownerselector'])) {
231 $ownerselector = $displayoptions['ownerselector'];
232 } else if ($mod) {
233 $ownerselector = '#module-'.$mod->id;
234 } else {
235 debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
236 $ownerselector = 'li.activity';
239 if (isset($displayoptions['constraintselector'])) {
240 $constraint = $displayoptions['constraintselector'];
241 } else {
242 $constraint = '.course-content';
245 $menu = new action_menu();
246 $menu->set_owner_selector($ownerselector);
247 $menu->set_constraint($constraint);
248 $menu->set_menu_trigger(get_string('edit'));
250 foreach ($actions as $action) {
251 if ($action instanceof action_menu_link) {
252 $action->add_class('cm-edit-action');
254 $menu->add($action);
256 $menu->attributes['class'] .= ' section-cm-edit-actions commands';
258 // Prioritise the menu ahead of all other actions.
259 $menu->prioritise = true;
261 return $this->render($menu);
265 * Renders HTML for the menus to add activities and resources to the current course
267 * Renders the ajax control (the link which when clicked produces the activity chooser modal). No noscript fallback.
269 * @param stdClass $course
270 * @param int $section relative section number (field course_sections.section)
271 * @param int $sectionreturn The section to link back to
272 * @param array $displayoptions additional display options, for example blocks add
273 * option 'inblock' => true, suggesting to display controls vertically
274 * @return string
276 function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
277 // Check to see if user can add menus.
278 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
279 || !$this->page->user_is_editing()) {
280 return '';
283 $data = [
284 'sectionid' => $section,
285 'sectionreturn' => $sectionreturn
287 $ajaxcontrol = $this->render_from_template('course/activitychooserbutton', $data);
289 // Load the JS for the modal.
290 $this->course_activitychooser($course->id);
292 return $ajaxcontrol;
296 * Render the deprecated nonajax activity chooser.
298 * @deprecated since Moodle 3.11
300 * @todo MDL-71331 deprecate this function
301 * @param stdClass $course the course object
302 * @param int $section relative section number (field course_sections.section)
303 * @param int $sectionreturn The section to link back to
304 * @param array $displayoptions additional display options, for example blocks add
305 * option 'inblock' => true, suggesting to display controls vertically
306 * @return string
308 private function course_section_add_cm_control_nonajax($course, $section, $sectionreturn = null,
309 $displayoptions = array()): string {
310 global $USER;
312 $vertical = !empty($displayoptions['inblock']);
314 // Check to see if user can add menus.
315 if (
316 !has_capability('moodle/course:manageactivities', context_course::instance($course->id))
317 || !$this->page->user_is_editing()
319 return '';
322 debugging('non-js dropdowns are deprecated.', DEBUG_DEVELOPER);
323 // Retrieve all modules with associated metadata.
324 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
325 $urlparams = ['section' => $section];
326 if (!is_null($sectionreturn)) {
327 $urlparams['sr'] = $sectionreturn;
329 $modules = $contentitemservice->get_content_items_for_user_in_course($USER, $course, $urlparams);
331 // Return if there are no content items to add.
332 if (empty($modules)) {
333 return '';
336 // We'll sort resources and activities into two lists.
337 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
339 foreach ($modules as $module) {
340 $activityclass = MOD_CLASS_ACTIVITY;
341 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
342 $activityclass = MOD_CLASS_RESOURCE;
343 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
344 // System modules cannot be added by user, do not add to dropdown.
345 continue;
347 $link = $module->link;
348 $activities[$activityclass][$link] = $module->title;
351 $straddactivity = get_string('addactivity');
352 $straddresource = get_string('addresource');
353 $sectionname = get_section_name($course, $section);
354 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
355 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
357 $nonajaxcontrol = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-'
358 . $section));
360 if (!$vertical) {
361 $nonajaxcontrol .= html_writer::start_tag('div', array('class' => 'horizontal'));
364 if (!empty($activities[MOD_CLASS_RESOURCE])) {
365 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array('' => $straddresource), "ressection$section");
366 $select->set_help_icon('resources');
367 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
368 $nonajaxcontrol .= $this->output->render($select);
371 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
372 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array('' => $straddactivity), "section$section");
373 $select->set_help_icon('activities');
374 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
375 $nonajaxcontrol .= $this->output->render($select);
378 if (!$vertical) {
379 $nonajaxcontrol .= html_writer::end_tag('div');
382 $nonajaxcontrol .= html_writer::end_tag('div');
384 return $nonajaxcontrol;
388 * Renders html to display a course search form
390 * @param string $value default value to populate the search field
391 * @return string
393 public function course_search_form($value = '') {
395 $data = [
396 'action' => \core_search\manager::get_course_search_url(),
397 'btnclass' => 'btn-primary',
398 'inputname' => 'q',
399 'searchstring' => get_string('searchcourses'),
400 'hiddenfields' => (object) ['name' => 'areaids', 'value' => 'core_course-course'],
401 'query' => $value
403 return $this->render_from_template('core/search_input', $data);
407 * Renders html for completion box on course page
409 * If completion is disabled, returns empty string
410 * If completion is automatic, returns an icon of the current completion state
411 * If completion is manual, returns a form (with an icon inside) that allows user to
412 * toggle completion
414 * @deprecated since Moodle 3.11
415 * @todo MDL-71183 Final deprecation in Moodle 4.3.
416 * @see \core_renderer::activity_information
418 * @param stdClass $course course object
419 * @param completion_info $completioninfo completion info for the course, it is recommended
420 * to fetch once for all modules in course/section for performance
421 * @param cm_info $mod module to show completion for
422 * @param array $displayoptions display options, not used in core
423 * @return string
425 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
426 global $CFG, $DB, $USER;
428 debugging(__FUNCTION__ . ' is deprecated and is being replaced by the activity_information output component.',
429 DEBUG_DEVELOPER);
431 $output = '';
433 $istrackeduser = $completioninfo->is_tracked_user($USER->id);
434 $isediting = $this->page->user_is_editing();
436 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
437 return $output;
439 if ($completioninfo === null) {
440 $completioninfo = new completion_info($course);
442 $completion = $completioninfo->is_enabled($mod);
444 if ($completion == COMPLETION_TRACKING_NONE) {
445 if ($isediting) {
446 $output .= html_writer::span('&nbsp;', 'filler');
448 return $output;
451 $completionicon = '';
453 if ($isediting || !$istrackeduser) {
454 switch ($completion) {
455 case COMPLETION_TRACKING_MANUAL :
456 $completionicon = 'manual-enabled'; break;
457 case COMPLETION_TRACKING_AUTOMATIC :
458 $completionicon = 'auto-enabled'; break;
460 } else {
461 $completiondata = $completioninfo->get_data($mod, true);
462 if ($completion == COMPLETION_TRACKING_MANUAL) {
463 switch($completiondata->completionstate) {
464 case COMPLETION_INCOMPLETE:
465 $completionicon = 'manual-n' . ($completiondata->overrideby ? '-override' : '');
466 break;
467 case COMPLETION_COMPLETE:
468 $completionicon = 'manual-y' . ($completiondata->overrideby ? '-override' : '');
469 break;
471 } else { // Automatic
472 switch($completiondata->completionstate) {
473 case COMPLETION_INCOMPLETE:
474 $completionicon = 'auto-n' . ($completiondata->overrideby ? '-override' : '');
475 break;
476 case COMPLETION_COMPLETE:
477 $completionicon = 'auto-y' . ($completiondata->overrideby ? '-override' : '');
478 break;
479 case COMPLETION_COMPLETE_PASS:
480 $completionicon = 'auto-pass'; break;
481 case COMPLETION_COMPLETE_FAIL:
482 $completionicon = 'auto-fail'; break;
486 if ($completionicon) {
487 $formattedname = html_entity_decode($mod->get_formatted_name(), ENT_QUOTES, 'UTF-8');
488 if (!$isediting && $istrackeduser && $completiondata->overrideby) {
489 $args = new stdClass();
490 $args->modname = $formattedname;
491 $overridebyuser = \core_user::get_user($completiondata->overrideby, '*', MUST_EXIST);
492 $args->overrideuser = fullname($overridebyuser);
493 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $args);
494 } else {
495 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
498 if ($isediting || !$istrackeduser || !has_capability('moodle/course:togglecompletion', $mod->context)) {
499 // When editing, the icon is just an image.
500 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
501 array('title' => $imgalt, 'class' => 'iconsmall'));
502 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
503 array('class' => 'autocompletion'));
504 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
505 $newstate =
506 $completiondata->completionstate == COMPLETION_COMPLETE
507 ? COMPLETION_INCOMPLETE
508 : COMPLETION_COMPLETE;
509 // In manual mode the icon is a toggle form...
511 // If this completion state is used by the
512 // conditional activities system, we need to turn
513 // off the JS.
514 $extraclass = '';
515 if (!empty($CFG->enableavailability) &&
516 core_availability\info::completion_value_used($course, $mod->id)) {
517 $extraclass = ' preventjs';
519 $output .= html_writer::start_tag('form', array('method' => 'post',
520 'action' => new moodle_url('/course/togglecompletion.php'),
521 'class' => 'togglecompletion'. $extraclass));
522 $output .= html_writer::start_tag('div');
523 $output .= html_writer::empty_tag('input', array(
524 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
525 $output .= html_writer::empty_tag('input', array(
526 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
527 $output .= html_writer::empty_tag('input', array(
528 'type' => 'hidden', 'name' => 'modulename', 'value' => $formattedname));
529 $output .= html_writer::empty_tag('input', array(
530 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
531 $output .= html_writer::tag('button',
532 $this->output->pix_icon('i/completion-' . $completionicon, $imgalt),
533 array('class' => 'btn btn-link', 'aria-live' => 'assertive'));
534 $output .= html_writer::end_tag('div');
535 $output .= html_writer::end_tag('form');
536 } else {
537 // In auto mode, the icon is just an image.
538 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
539 array('title' => $imgalt));
540 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
541 array('class' => 'autocompletion'));
544 return $output;
548 * Checks if course module has any conditions that may make it unavailable for
549 * all or some of the students
551 * @deprecated since Moodle 4.0 MDL-72656 - please do not use this function any more.
553 * @param cm_info $mod
554 * @return bool
556 public function is_cm_conditionally_hidden(cm_info $mod) {
557 global $CFG;
559 debugging(
560 'is_cm_conditionally_hidden is deprecated. Use \core_availability\info_module::is_available_for_all instead',
561 DEBUG_DEVELOPER
564 $conditionalhidden = false;
565 if (!empty($CFG->enableavailability)) {
566 $info = new \core_availability\info_module($mod);
567 $conditionalhidden = !$info->is_available_for_all();
569 return $conditionalhidden;
573 * Renders html to display a name with the link to the course module on a course page
575 * If module is unavailable for user but still needs to be displayed
576 * in the list, just the name is returned without a link
578 * Note, that for course modules that never have separate pages (i.e. labels)
579 * this function return an empty string
581 * @deprecated since Moodle 4.0 MDL-72656 - please do not use this function any more.
583 * @param cm_info $mod
584 * @param array $displayoptions
585 * @return string
587 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
588 debugging(
589 'course_section_cm_name is deprecated. Use core_courseformat\\output\\local\\content\\cm\\cmname class instead.',
590 DEBUG_DEVELOPER
593 if (!$mod->is_visible_on_course_page() || !$mod->url) {
594 // Nothing to be displayed to the user.
595 return '';
598 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
599 $groupinglabel = $mod->get_grouping_label($textclasses);
601 // Render element that allows to edit activity name inline.
602 $format = course_get_format($mod->course);
603 $cmnameclass = $format->get_output_classname('content\\cm\\cmname');
604 // Mod inplace name editable.
605 $cmname = new $cmnameclass(
606 $format,
607 $mod->get_section_info(),
608 $mod,
609 null,
610 $displayoptions
613 $renderer = $format->get_renderer($this->page);
614 return $renderer->render($cmname) . $groupinglabel;
618 * Returns the CSS classes for the activity name/content
620 * @deprecated since Moodle 4.0 MDL-72656 - please do not use this function any more.
622 * For items which are hidden, unavailable or stealth but should be displayed
623 * to current user ($mod->is_visible_on_course_page()), we show those as dimmed.
624 * Students will also see as dimmed activities names that are not yet available
625 * but should still be displayed (without link) with availability info.
627 * @param cm_info $mod
628 * @return array array of two elements ($linkclasses, $textclasses)
630 protected function course_section_cm_classes(cm_info $mod) {
632 debugging(
633 'course_section_cm_classes is deprecated. Now it is part of core_courseformat\\output\\local\\content\\cm ',
634 DEBUG_DEVELOPER
637 $format = course_get_format($mod->course);
639 $cmclass = $format->get_output_classname('content\\cm');
640 $cmoutput = new $cmclass(
641 $format,
642 $mod->get_section_info(),
643 $mod,
645 return [
646 $cmoutput->get_link_classes(),
647 $cmoutput->get_text_classes(),
652 * Renders html to display a name with the link to the course module on a course page
654 * If module is unavailable for user but still needs to be displayed
655 * in the list, just the name is returned without a link
657 * Note, that for course modules that never have separate pages (i.e. labels)
658 * this function return an empty string
660 * @deprecated since Moodle 4.0 MDL-72656 - please do not use this function any more.
662 * @param cm_info $mod
663 * @param array $displayoptions
664 * @return string
666 public function course_section_cm_name_title(cm_info $mod, $displayoptions = array()) {
668 debugging(
669 'course_section_cm_name_title is deprecated. Use core_courseformat\\output\\local\\cm\\title class instead.',
670 DEBUG_DEVELOPER
673 $output = '';
674 $url = $mod->url;
675 if (!$mod->is_visible_on_course_page() || !$url) {
676 // Nothing to be displayed to the user.
677 return $output;
680 //Accessibility: for files get description via icon, this is very ugly hack!
681 $instancename = $mod->get_formatted_name();
682 $altname = $mod->modfullname;
683 // Avoid unnecessary duplication: if e.g. a forum name already
684 // includes the word forum (or Forum, etc) then it is unhelpful
685 // to include that in the accessible description that is added.
686 if (false !== strpos(core_text::strtolower($instancename),
687 core_text::strtolower($altname))) {
688 $altname = '';
690 // File type after name, for alphabetic lists (screen reader).
691 if ($altname) {
692 $altname = get_accesshide(' '.$altname);
695 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
697 // Get on-click attribute value if specified and decode the onclick - it
698 // has already been encoded for display (puke).
699 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
701 // Display link itself.
702 $instancename = html_writer::tag('span', $instancename . $altname, ['class' => 'instancename ml-1']);
704 $imageicon = html_writer::empty_tag('img', ['src' => $mod->get_icon_url(),
705 'class' => 'activityicon', 'alt' => '', 'role' => 'presentation', 'aria-hidden' => 'true']);
706 $imageicon = html_writer::tag('span', $imageicon, ['class' => 'activityiconcontainer courseicon']);
707 $activitylink = $imageicon . $instancename;
709 if ($mod->uservisible) {
710 $output .= html_writer::link($url, $activitylink, array('class' => 'aalink' . $linkclasses, 'onclick' => $onclick));
711 } else {
712 // We may be displaying this just in order to show information
713 // about visibility, without the actual link ($mod->is_visible_on_course_page()).
714 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses));
716 return $output;
720 * Renders html to display the module content on the course page (i.e. text of the labels)
722 * @deprecated since Moodle 4.0 MDL-72656 - please do not use this function any more.
724 * @param cm_info $mod
725 * @param array $displayoptions
726 * @return string
728 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
730 debugging(
731 'course_section_cm_text is deprecated. Now it is part of core_courseformat\\output\\local\\content\\cm ',
732 DEBUG_DEVELOPER
735 $output = '';
736 if (!$mod->is_visible_on_course_page()) {
737 // nothing to be displayed to the user
738 return $output;
740 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
741 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
742 if ($mod->url && $mod->uservisible) {
743 if ($content) {
744 // If specified, display extra content after link.
745 $output = html_writer::tag('div', $content, array('class' =>
746 trim('contentafterlink ' . $textclasses)));
748 } else {
749 $groupinglabel = $mod->get_grouping_label($textclasses);
751 // No link, so display only content.
752 $output = html_writer::tag('div', $content . $groupinglabel,
753 array('class' => 'contentwithoutlink ' . $textclasses));
755 return $output;
759 * Displays availability info for a course section or course module
761 * @deprecated since Moodle 4.0 MDL-72656 - please do not use this function any more.
762 * @param string $text
763 * @param string $additionalclasses
764 * @return string
766 public function availability_info($text, $additionalclasses = '') {
768 debugging(
769 'availability_info is deprecated. Use core_courseformat\\output\\local\\content\\section\\availability instead',
770 DEBUG_DEVELOPER
773 $data = ['text' => $text, 'classes' => $additionalclasses];
774 $additionalclasses = array_filter(explode(' ', $additionalclasses));
776 if (in_array('ishidden', $additionalclasses)) {
777 $data['ishidden'] = 1;
779 } else if (in_array('isstealth', $additionalclasses)) {
780 $data['isstealth'] = 1;
782 } else if (in_array('isrestricted', $additionalclasses)) {
783 $data['isrestricted'] = 1;
785 if (in_array('isfullinfo', $additionalclasses)) {
786 $data['isfullinfo'] = 1;
790 return $this->render_from_template('core/availability_info', $data);
794 * Renders HTML to show course module availability information (for someone who isn't allowed
795 * to see the activity itself, or for staff)
797 * @deprecated since Moodle 4.0 MDL-72656 - please do not use this function any more.
798 * @param cm_info $mod
799 * @param array $displayoptions
800 * @return string
802 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
804 debugging(
805 'course_section_cm_availability is deprecated. Use core_courseformat\\output\\local\\content\\cm\\availability instead',
806 DEBUG_DEVELOPER
809 $format = course_get_format($mod->course);
811 $availabilityclass = $format->get_output_classname('content\\cm\\availability');
812 $availability = new $availabilityclass(
813 $format,
814 $mod->get_section_info(),
815 $mod,
817 $renderer = $format->get_renderer($this->page);
818 return $renderer->render($availability);
822 * Renders HTML to display one course module for display within a section.
824 * @deprecated since 4.0 - use core_course output components or course_format::course_section_updated_cm_item instead.
826 * This function calls:
827 * {@link core_course_renderer::course_section_cm()}
829 * @param stdClass $course
830 * @param completion_info $completioninfo
831 * @param cm_info $mod
832 * @param int|null $sectionreturn
833 * @param array $displayoptions
834 * @return String
836 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = []) {
838 debugging(
839 'course_section_cm_list_item is deprecated. Use renderer course_section_updated_cm_item instead',
840 DEBUG_DEVELOPER
843 $output = '';
844 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
845 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
846 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
848 return $output;
852 * Renders HTML to display one course module in a course section
854 * This includes link, content, availability, completion info and additional information
855 * that module type wants to display (i.e. number of unread forum posts)
857 * @deprecated since 4.0 MDL-72656 - use core_course output components instead.
859 * @param stdClass $course
860 * @param completion_info $completioninfo
861 * @param cm_info $mod
862 * @param int|null $sectionreturn
863 * @param array $displayoptions
864 * @return string
866 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = []) {
868 debugging(
869 'course_section_cm is deprecated. Use core_courseformat\\output\\content\\cm output class instead.',
870 DEBUG_DEVELOPER
873 if (!$mod->is_visible_on_course_page()) {
874 return '';
877 $format = course_get_format($course);
878 $modinfo = $format->get_modinfo();
879 // Output renderers works only with real section_info objects.
880 if ($sectionreturn) {
881 $format->set_section_number($sectionreturn);
883 $section = $modinfo->get_section_info($format->get_section_number());
885 $cmclass = $format->get_output_classname('content\\cm');
886 $cm = new $cmclass($format, $section, $mod, $displayoptions);
887 // The course outputs works with format renderers, not with course renderers.
888 $renderer = $format->get_renderer($this->page);
889 $data = $cm->export_for_template($renderer);
890 return $this->output->render_from_template('core_courseformat/local/content/cm', $data);
894 * Message displayed to the user when they try to access unavailable activity following URL
896 * This method is a very simplified version of {@link course_section_cm()} to be part of the error
897 * notification only. It also does not check if module is visible on course page or not.
899 * The message will be displayed inside notification!
901 * @param cm_info $cm
902 * @return string
904 public function course_section_cm_unavailable_error_message(cm_info $cm) {
905 if ($cm->uservisible) {
906 return null;
908 if (!$cm->availableinfo) {
909 return get_string('activityiscurrentlyhidden');
912 $altname = get_accesshide(' ' . $cm->modfullname);
913 $name = html_writer::empty_tag('img', array('src' => $cm->get_icon_url(),
914 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
915 html_writer::tag('span', ' '.$cm->get_formatted_name() . $altname, array('class' => 'instancename'));
916 $formattedinfo = \core_availability\info::format_info($cm->availableinfo, $cm->get_course());
917 return html_writer::div($name, 'activityinstance-error') .
918 html_writer::div($formattedinfo, 'availabilityinfo-error');
922 * Renders HTML to display a list of course modules in a course section
923 * Also displays "move here" controls in Javascript-disabled mode.
925 * @deprecated since 4.0 MDL-72656 - use core_course output components instead.
927 * This function calls {@link core_course_renderer::course_section_cm()}
929 * @param stdClass $course course object
930 * @param int|stdClass|section_info $section relative section number or section object
931 * @param int $sectionreturn section number to return to
932 * @param int $displayoptions
933 * @return void
935 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = []) {
936 global $USER;
938 debugging('course_section_cm_list is deprecated. Use core_courseformat\\output\\local\\content\\section\\cmlist '.
939 'classes instead.', DEBUG_DEVELOPER);
941 $output = '';
943 $format = course_get_format($course);
944 $modinfo = $format->get_modinfo();
946 if (is_object($section)) {
947 $section = $modinfo->get_section_info($section->section);
948 } else {
949 $section = $modinfo->get_section_info($section);
951 $completioninfo = new completion_info($course);
953 // check if we are currently in the process of moving a module with JavaScript disabled
954 $ismoving = $format->show_editor() && ismoving($course->id);
956 if ($ismoving) {
957 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
960 // Get the list of modules visible to user (excluding the module being moved if there is one)
961 $moduleshtml = [];
962 if (!empty($modinfo->sections[$section->section])) {
963 foreach ($modinfo->sections[$section->section] as $modnumber) {
964 $mod = $modinfo->cms[$modnumber];
966 if ($ismoving and $mod->id == $USER->activitycopy) {
967 // do not display moving mod
968 continue;
971 if ($modulehtml = $this->course_section_cm_list_item($course,
972 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
973 $moduleshtml[$modnumber] = $modulehtml;
978 $sectionoutput = '';
979 if (!empty($moduleshtml) || $ismoving) {
980 foreach ($moduleshtml as $modnumber => $modulehtml) {
981 if ($ismoving) {
982 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
983 $sectionoutput .= html_writer::tag('li',
984 html_writer::link($movingurl, '', array('title' => $strmovefull, 'class' => 'movehere')),
985 array('class' => 'movehere'));
988 $sectionoutput .= $modulehtml;
991 if ($ismoving) {
992 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
993 $sectionoutput .= html_writer::tag('li',
994 html_writer::link($movingurl, '', array('title' => $strmovefull, 'class' => 'movehere')),
995 array('class' => 'movehere'));
999 // Always output the section module list.
1000 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1002 return $output;
1006 * Displays a custom list of courses with paging bar if necessary
1008 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1009 * appears under the list.
1011 * If both $paginationurl and $totalcount are specified, and $totalcount is
1012 * bigger than count($courses), a paging bar is displayed above and under the
1013 * courses list.
1015 * @param array $courses array of course records (or instances of core_course_list_element) to show on this page
1016 * @param bool $showcategoryname whether to add category name to the course description
1017 * @param string $additionalclasses additional CSS classes to add to the div.courses
1018 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1019 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1020 * @param int $page current page number (defaults to 0 referring to the first page)
1021 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1022 * @return string
1024 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1025 global $CFG;
1026 // create instance of coursecat_helper to pass display options to function rendering courses list
1027 $chelper = new coursecat_helper();
1028 if ($showcategoryname) {
1029 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1030 } else {
1031 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1033 if ($totalcount !== null && $paginationurl !== null) {
1034 // add options to display pagination
1035 if ($perpage === null) {
1036 $perpage = $CFG->coursesperpage;
1038 $chelper->set_courses_display_options(array(
1039 'limit' => $perpage,
1040 'offset' => ((int)$page) * $perpage,
1041 'paginationurl' => $paginationurl,
1043 } else if ($paginationurl !== null) {
1044 // add options to display 'View more' link
1045 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1046 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1048 $chelper->set_attributes(array('class' => $additionalclasses));
1049 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1050 return $content;
1054 * Returns HTML to display course name.
1056 * @param coursecat_helper $chelper
1057 * @param core_course_list_element $course
1058 * @return string
1060 protected function course_name(coursecat_helper $chelper, core_course_list_element $course): string {
1061 $content = '';
1062 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1063 $nametag = 'h3';
1064 } else {
1065 $nametag = 'div';
1067 $coursename = $chelper->get_course_formatted_name($course);
1068 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', ['id' => $course->id]),
1069 $coursename, ['class' => $course->visible ? 'aalink' : 'aalink dimmed']);
1070 $content .= html_writer::tag($nametag, $coursenamelink, ['class' => 'coursename']);
1071 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1072 $content .= html_writer::start_tag('div', ['class' => 'moreinfo']);
1073 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1074 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()
1075 || $course->has_custom_fields()) {
1076 $url = new moodle_url('/course/info.php', ['id' => $course->id]);
1077 $image = $this->output->pix_icon('i/info', $this->strings->summary);
1078 $content .= html_writer::link($url, $image, ['title' => $this->strings->summary]);
1079 // Make sure JS file to expand course content is included.
1080 $this->coursecat_include_js();
1083 $content .= html_writer::end_tag('div');
1084 return $content;
1088 * Returns HTML to display course enrolment icons.
1090 * @param core_course_list_element $course
1091 * @return string
1093 protected function course_enrolment_icons(core_course_list_element $course): string {
1094 $content = '';
1095 if ($icons = enrol_get_course_info_icons($course)) {
1096 $content .= html_writer::start_tag('div', ['class' => 'enrolmenticons']);
1097 foreach ($icons as $icon) {
1098 $content .= $this->render($icon);
1100 $content .= html_writer::end_tag('div');
1102 return $content;
1106 * Displays one course in the list of courses.
1108 * This is an internal function, to display an information about just one course
1109 * please use {@link core_course_renderer::course_info_box()}
1111 * @param coursecat_helper $chelper various display options
1112 * @param core_course_list_element|stdClass $course
1113 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1114 * depend on the course position in list - first/last/even/odd)
1115 * @return string
1117 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1118 if (!isset($this->strings->summary)) {
1119 $this->strings->summary = get_string('summary');
1121 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1122 return '';
1124 if ($course instanceof stdClass) {
1125 $course = new core_course_list_element($course);
1127 $content = '';
1128 $classes = trim('coursebox clearfix '. $additionalclasses);
1129 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1130 $classes .= ' collapsed';
1133 // .coursebox
1134 $content .= html_writer::start_tag('div', array(
1135 'class' => $classes,
1136 'data-courseid' => $course->id,
1137 'data-type' => self::COURSECAT_TYPE_COURSE,
1140 $content .= html_writer::start_tag('div', array('class' => 'info'));
1141 $content .= $this->course_name($chelper, $course);
1142 $content .= $this->course_enrolment_icons($course);
1143 $content .= html_writer::end_tag('div');
1145 $content .= html_writer::start_tag('div', array('class' => 'content'));
1146 $content .= $this->coursecat_coursebox_content($chelper, $course);
1147 $content .= html_writer::end_tag('div');
1149 $content .= html_writer::end_tag('div'); // .coursebox
1150 return $content;
1154 * Returns HTML to display course summary.
1156 * @param coursecat_helper $chelper
1157 * @param core_course_list_element $course
1158 * @return string
1160 protected function course_summary(coursecat_helper $chelper, core_course_list_element $course): string {
1161 $content = '';
1162 if ($course->has_summary()) {
1163 $content .= html_writer::start_tag('div', ['class' => 'summary']);
1164 $content .= $chelper->get_course_formatted_summary($course,
1165 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1166 $content .= html_writer::end_tag('div');
1168 return $content;
1172 * Returns HTML to display course contacts.
1174 * @param core_course_list_element $course
1175 * @return string
1177 protected function course_contacts(core_course_list_element $course) {
1178 $content = '';
1179 if ($course->has_course_contacts()) {
1180 $content .= html_writer::start_tag('ul', ['class' => 'teachers']);
1181 foreach ($course->get_course_contacts() as $coursecontact) {
1182 $rolenames = array_map(function ($role) {
1183 return $role->displayname;
1184 }, $coursecontact['roles']);
1185 $name = html_writer::tag('span', implode(", ", $rolenames).': ', ['class' => 'font-weight-bold']);
1186 $name .= html_writer::link(new moodle_url('/user/view.php',
1187 ['id' => $coursecontact['user']->id, 'course' => SITEID]),
1188 $coursecontact['username']);
1189 $content .= html_writer::tag('li', $name);
1191 $content .= html_writer::end_tag('ul');
1193 return $content;
1197 * Returns HTML to display course overview files.
1199 * @param core_course_list_element $course
1200 * @return string
1202 protected function course_overview_files(core_course_list_element $course): string {
1203 global $CFG;
1205 $contentimages = $contentfiles = '';
1206 foreach ($course->get_course_overviewfiles() as $file) {
1207 $isimage = $file->is_valid_image();
1208 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php",
1209 '/' . $file->get_contextid() . '/' . $file->get_component() . '/' .
1210 $file->get_filearea() . $file->get_filepath() . $file->get_filename(), !$isimage);
1211 if ($isimage) {
1212 $contentimages .= html_writer::tag('div',
1213 html_writer::empty_tag('img', ['src' => $url]),
1214 ['class' => 'courseimage']);
1215 } else {
1216 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1217 $filename = html_writer::tag('span', $image, ['class' => 'fp-icon']).
1218 html_writer::tag('span', $file->get_filename(), ['class' => 'fp-filename']);
1219 $contentfiles .= html_writer::tag('span',
1220 html_writer::link($url, $filename),
1221 ['class' => 'coursefile fp-filename-icon']);
1224 return $contentimages . $contentfiles;
1228 * Returns HTML to display course category name.
1230 * @param coursecat_helper $chelper
1231 * @param core_course_list_element $course
1232 * @return string
1234 protected function course_category_name(coursecat_helper $chelper, core_course_list_element $course): string {
1235 $content = '';
1236 // Display course category if necessary (for example in search results).
1237 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1238 if ($cat = core_course_category::get($course->category, IGNORE_MISSING)) {
1239 $content .= html_writer::start_tag('div', ['class' => 'coursecat']);
1240 $content .= html_writer::tag('span', get_string('category').': ', ['class' => 'font-weight-bold']);
1241 $content .= html_writer::link(new moodle_url('/course/index.php', ['categoryid' => $cat->id]),
1242 $cat->get_formatted_name(), ['class' => $cat->visible ? '' : 'dimmed']);
1243 $content .= html_writer::end_tag('div');
1246 return $content;
1250 * Returns HTML to display course custom fields.
1252 * @param core_course_list_element $course
1253 * @return string
1255 protected function course_custom_fields(core_course_list_element $course): string {
1256 $content = '';
1257 if ($course->has_custom_fields()) {
1258 $handler = core_course\customfield\course_handler::create();
1259 $customfields = $handler->display_custom_fields_data($course->get_custom_fields());
1260 $content .= \html_writer::tag('div', $customfields, ['class' => 'customfields-container']);
1262 return $content;
1266 * Returns HTML to display course content (summary, course contacts and optionally category name)
1268 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1270 * @param coursecat_helper $chelper various display options
1271 * @param stdClass|core_course_list_element $course
1272 * @return string
1274 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1275 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1276 return '';
1278 if ($course instanceof stdClass) {
1279 $course = new core_course_list_element($course);
1281 $content = \html_writer::start_tag('div', ['class' => 'd-flex']);
1282 $content .= $this->course_overview_files($course);
1283 $content .= \html_writer::start_tag('div', ['class' => 'flex-grow-1']);
1284 $content .= $this->course_summary($chelper, $course);
1285 $content .= $this->course_contacts($course);
1286 $content .= $this->course_category_name($chelper, $course);
1287 $content .= $this->course_custom_fields($course);
1288 $content .= \html_writer::end_tag('div');
1289 $content .= \html_writer::end_tag('div');
1290 return $content;
1294 * Renders the list of courses
1296 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1297 * method from outside of the class
1299 * If list of courses is specified in $courses; the argument $chelper is only used
1300 * to retrieve display options and attributes, only methods get_show_courses(),
1301 * get_courses_display_option() and get_and_erase_attributes() are called.
1303 * @param coursecat_helper $chelper various display options
1304 * @param array $courses the list of courses to display
1305 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1306 * defaulted to count($courses)
1307 * @return string
1309 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1310 global $CFG;
1311 if ($totalcount === null) {
1312 $totalcount = count($courses);
1314 if (!$totalcount) {
1315 // Courses count is cached during courses retrieval.
1316 return '';
1319 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1320 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1321 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1322 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1323 } else {
1324 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1328 // prepare content of paging bar if it is needed
1329 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1330 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1331 if ($totalcount > count($courses)) {
1332 // there are more results that can fit on one page
1333 if ($paginationurl) {
1334 // the option paginationurl was specified, display pagingbar
1335 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1336 $page = $chelper->get_courses_display_option('offset') / $perpage;
1337 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1338 $paginationurl->out(false, array('perpage' => $perpage)));
1339 if ($paginationallowall) {
1340 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1341 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1343 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1344 // the option for 'View more' link was specified, display more link
1345 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1346 $morelink = html_writer::tag(
1347 'div',
1348 html_writer::link($viewmoreurl, $viewmoretext, ['class' => 'btn btn-secondary']),
1349 ['class' => 'paging paging-morelink']
1352 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1353 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1354 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1355 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1358 // display list of courses
1359 $attributes = $chelper->get_and_erase_attributes('courses');
1360 $content = html_writer::start_tag('div', $attributes);
1362 if (!empty($pagingbar)) {
1363 $content .= $pagingbar;
1366 $coursecount = 0;
1367 foreach ($courses as $course) {
1368 $coursecount ++;
1369 $classes = ($coursecount%2) ? 'odd' : 'even';
1370 if ($coursecount == 1) {
1371 $classes .= ' first';
1373 if ($coursecount >= count($courses)) {
1374 $classes .= ' last';
1376 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1379 if (!empty($pagingbar)) {
1380 $content .= $pagingbar;
1382 if (!empty($morelink)) {
1383 $content .= $morelink;
1386 $content .= html_writer::end_tag('div'); // .courses
1387 return $content;
1391 * Renders the list of subcategories in a category
1393 * @param coursecat_helper $chelper various display options
1394 * @param core_course_category $coursecat
1395 * @param int $depth depth of the category in the current tree
1396 * @return string
1398 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1399 global $CFG;
1400 $subcategories = array();
1401 if (!$chelper->get_categories_display_option('nodisplay')) {
1402 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1404 $totalcount = $coursecat->get_children_count();
1405 if (!$totalcount) {
1406 // Note that we call core_course_category::get_children_count() AFTER core_course_category::get_children()
1407 // to avoid extra DB requests.
1408 // Categories count is cached during children categories retrieval.
1409 return '';
1412 // prepare content of paging bar or more link if it is needed
1413 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1414 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1415 if ($totalcount > count($subcategories)) {
1416 if ($paginationurl) {
1417 // the option 'paginationurl was specified, display pagingbar
1418 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1419 $page = $chelper->get_categories_display_option('offset') / $perpage;
1420 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1421 $paginationurl->out(false, array('perpage' => $perpage)));
1422 if ($paginationallowall) {
1423 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1424 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1426 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1427 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1428 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1429 $viewmoreurl->param('categoryid', $coursecat->id);
1431 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1432 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1433 array('class' => 'paging paging-morelink'));
1435 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1436 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1437 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1438 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1441 // display list of subcategories
1442 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1444 if (!empty($pagingbar)) {
1445 $content .= $pagingbar;
1448 foreach ($subcategories as $subcategory) {
1449 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1452 if (!empty($pagingbar)) {
1453 $content .= $pagingbar;
1455 if (!empty($morelink)) {
1456 $content .= $morelink;
1459 $content .= html_writer::end_tag('div');
1460 return $content;
1464 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1466 protected function coursecat_include_js() {
1467 if (!$this->page->requires->should_create_one_time_item_now('core_course_categoryexpanderjsinit')) {
1468 return;
1471 // We must only load this module once.
1472 $this->page->requires->yui_module('moodle-course-categoryexpander',
1473 'Y.Moodle.course.categoryexpander.init');
1477 * Returns HTML to display the subcategories and courses in the given category
1479 * This method is re-used by AJAX to expand content of not loaded category
1481 * @param coursecat_helper $chelper various display options
1482 * @param core_course_category $coursecat
1483 * @param int $depth depth of the category in the current tree
1484 * @return string
1486 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1487 $content = '';
1488 // Subcategories
1489 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1491 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1492 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1493 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1494 if ($showcoursesauto && $depth) {
1495 // this is definitely collapsed mode
1496 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1499 // Courses
1500 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1501 $courses = array();
1502 if (!$chelper->get_courses_display_option('nodisplay')) {
1503 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1505 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1506 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1507 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1508 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1511 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1514 if ($showcoursesauto) {
1515 // restore the show_courses back to AUTO
1516 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1519 return $content;
1523 * Returns HTML to display a course category as a part of a tree
1525 * This is an internal function, to display a particular category and all its contents
1526 * use {@link core_course_renderer::course_category()}
1528 * @param coursecat_helper $chelper various display options
1529 * @param core_course_category $coursecat
1530 * @param int $depth depth of this category in the current tree
1531 * @return string
1533 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1534 // open category tag
1535 $classes = array('category');
1536 if (empty($coursecat->visible)) {
1537 $classes[] = 'dimmed_category';
1539 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1540 // do not load content
1541 $categorycontent = '';
1542 $classes[] = 'notloaded';
1543 if ($coursecat->get_children_count() ||
1544 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1545 $classes[] = 'with_children';
1546 $classes[] = 'collapsed';
1548 } else {
1549 // load category content
1550 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1551 $classes[] = 'loaded';
1552 if (!empty($categorycontent)) {
1553 $classes[] = 'with_children';
1554 // Category content loaded with children.
1555 $this->categoryexpandedonload = true;
1559 // Make sure JS file to expand category content is included.
1560 $this->coursecat_include_js();
1562 $content = html_writer::start_tag('div', array(
1563 'class' => join(' ', $classes),
1564 'data-categoryid' => $coursecat->id,
1565 'data-depth' => $depth,
1566 'data-showcourses' => $chelper->get_show_courses(),
1567 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1570 // category name
1571 $categoryname = $coursecat->get_formatted_name();
1572 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1573 array('categoryid' => $coursecat->id)),
1574 $categoryname);
1575 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1576 && ($coursescount = $coursecat->get_courses_count())) {
1577 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1578 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1580 $content .= html_writer::start_tag('div', array('class' => 'info'));
1582 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname aabtn'));
1583 $content .= html_writer::end_tag('div'); // .info
1585 // add category content to the output
1586 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1588 $content .= html_writer::end_tag('div'); // .category
1590 // Return the course category tree HTML
1591 return $content;
1595 * Returns HTML to display a tree of subcategories and courses in the given category
1597 * @param coursecat_helper $chelper various display options
1598 * @param core_course_category $coursecat top category (this category's name and description will NOT be added to the tree)
1599 * @return string
1601 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1602 // Reset the category expanded flag for this course category tree first.
1603 $this->categoryexpandedonload = false;
1604 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1605 if (empty($categorycontent)) {
1606 return '';
1609 // Start content generation
1610 $content = '';
1611 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1612 $content .= html_writer::start_tag('div', $attributes);
1614 if ($coursecat->get_children_count()) {
1615 $classes = array(
1616 'collapseexpand', 'aabtn'
1619 // Check if the category content contains subcategories with children's content loaded.
1620 if ($this->categoryexpandedonload) {
1621 $classes[] = 'collapse-all';
1622 $linkname = get_string('collapseall');
1623 } else {
1624 $linkname = get_string('expandall');
1627 // Only show the collapse/expand if there are children to expand.
1628 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1629 $content .= html_writer::link('#', $linkname, array('class' => implode(' ', $classes)));
1630 $content .= html_writer::end_tag('div');
1631 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1634 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1636 $content .= html_writer::end_tag('div'); // .course_category_tree
1638 return $content;
1642 * Renders HTML to display particular course category - list of it's subcategories and courses
1644 * Invoked from /course/index.php
1646 * @param int|stdClass|core_course_category $category
1648 public function course_category($category) {
1649 global $CFG;
1650 $usertop = core_course_category::user_top();
1651 if (empty($category)) {
1652 $coursecat = $usertop;
1653 } else if (is_object($category) && $category instanceof core_course_category) {
1654 $coursecat = $category;
1655 } else {
1656 $coursecat = core_course_category::get(is_object($category) ? $category->id : $category);
1658 $site = get_site();
1659 $actionbar = new \core_course\output\category_action_bar($this->page, $coursecat);
1660 $output = $this->render_from_template('core_course/category_actionbar', $actionbar->export_for_template($this));
1662 if (core_course_category::is_simple_site()) {
1663 // There is only one category in the system, do not display link to it.
1664 $strfulllistofcourses = get_string('fulllistofcourses');
1665 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1666 } else if (!$coursecat->id || !$coursecat->is_uservisible()) {
1667 $strcategories = get_string('categories');
1668 $this->page->set_title("$site->shortname: $strcategories");
1669 } else {
1670 $strfulllistofcourses = get_string('fulllistofcourses');
1671 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1674 // Print current category description
1675 $chelper = new coursecat_helper();
1676 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1677 $output .= $this->box($description, array('class' => 'generalbox info'));
1680 // Prepare parameters for courses and categories lists in the tree
1681 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1682 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1684 $coursedisplayoptions = array();
1685 $catdisplayoptions = array();
1686 $browse = optional_param('browse', null, PARAM_ALPHA);
1687 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1688 $page = optional_param('page', 0, PARAM_INT);
1689 $baseurl = new moodle_url('/course/index.php');
1690 if ($coursecat->id) {
1691 $baseurl->param('categoryid', $coursecat->id);
1693 if ($perpage != $CFG->coursesperpage) {
1694 $baseurl->param('perpage', $perpage);
1696 $coursedisplayoptions['limit'] = $perpage;
1697 $catdisplayoptions['limit'] = $perpage;
1698 if ($browse === 'courses' || !$coursecat->get_children_count()) {
1699 $coursedisplayoptions['offset'] = $page * $perpage;
1700 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1701 $catdisplayoptions['nodisplay'] = true;
1702 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1703 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1704 } else if ($browse === 'categories' || !$coursecat->get_courses_count()) {
1705 $coursedisplayoptions['nodisplay'] = true;
1706 $catdisplayoptions['offset'] = $page * $perpage;
1707 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1708 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1709 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1710 } else {
1711 // we have a category that has both subcategories and courses, display pagination separately
1712 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1713 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1715 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1717 // Display course category tree.
1718 $output .= $this->coursecat_tree($chelper, $coursecat);
1720 return $output;
1724 * Serves requests to /course/category.ajax.php
1726 * In this renderer implementation it may expand the category content or
1727 * course content.
1729 * @return string
1730 * @throws coding_exception
1732 public function coursecat_ajax() {
1733 global $DB, $CFG;
1735 $type = required_param('type', PARAM_INT);
1737 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1738 // This is a request for a category list of some kind.
1739 $categoryid = required_param('categoryid', PARAM_INT);
1740 $showcourses = required_param('showcourses', PARAM_INT);
1741 $depth = required_param('depth', PARAM_INT);
1743 $category = core_course_category::get($categoryid);
1745 $chelper = new coursecat_helper();
1746 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1747 $coursedisplayoptions = array(
1748 'limit' => $CFG->coursesperpage,
1749 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1751 $catdisplayoptions = array(
1752 'limit' => $CFG->coursesperpage,
1753 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1755 $chelper->set_show_courses($showcourses)->
1756 set_courses_display_options($coursedisplayoptions)->
1757 set_categories_display_options($catdisplayoptions);
1759 return $this->coursecat_category_content($chelper, $category, $depth);
1760 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1761 // This is a request for the course information.
1762 $courseid = required_param('courseid', PARAM_INT);
1764 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1766 $chelper = new coursecat_helper();
1767 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1768 return $this->coursecat_coursebox_content($chelper, $course);
1769 } else {
1770 throw new coding_exception('Invalid request type');
1775 * Renders html to display search result page
1777 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1778 * @return string
1780 public function search_courses($searchcriteria) {
1781 global $CFG;
1782 $content = '';
1784 $search = '';
1785 if (!empty($searchcriteria['search'])) {
1786 $search = $searchcriteria['search'];
1788 $content .= $this->course_search_form($search);
1790 if (!empty($searchcriteria)) {
1791 // print search results
1793 $displayoptions = array('sort' => array('displayname' => 1));
1794 // take the current page and number of results per page from query
1795 $perpage = optional_param('perpage', 0, PARAM_RAW);
1796 if ($perpage !== 'all') {
1797 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1798 $page = optional_param('page', 0, PARAM_INT);
1799 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1801 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1802 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1803 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1805 $class = 'course-search-result';
1806 foreach ($searchcriteria as $key => $value) {
1807 if (!empty($value)) {
1808 $class .= ' course-search-result-'. $key;
1811 $chelper = new coursecat_helper();
1812 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1813 set_courses_display_options($displayoptions)->
1814 set_search_criteria($searchcriteria)->
1815 set_attributes(array('class' => $class));
1817 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1818 $totalcount = core_course_category::search_courses_count($searchcriteria);
1819 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1821 if (!$totalcount) {
1822 if (!empty($searchcriteria['search'])) {
1823 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1824 } else {
1825 $content .= $this->heading(get_string('novalidcourses'));
1827 } else {
1828 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1829 $content .= $courseslist;
1832 return $content;
1836 * Renders html to print list of courses tagged with particular tag
1838 * @param int $tagid id of the tag
1839 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1840 * are displayed on the page and the per-page limit may be bigger
1841 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1842 * to display items in the same context first
1843 * @param int $ctx context id where to search for records
1844 * @param bool $rec search in subcontexts as well
1845 * @param array $displayoptions
1846 * @return string empty string if no courses are marked with this tag or rendered list of courses
1848 public function tagged_courses($tagid, $exclusivemode = true, $ctx = 0, $rec = true, $displayoptions = null) {
1849 global $CFG;
1850 if (empty($displayoptions)) {
1851 $displayoptions = array();
1853 $showcategories = !core_course_category::is_simple_site();
1854 $displayoptions += array('limit' => $CFG->coursesperpage, 'offset' => 0);
1855 $chelper = new coursecat_helper();
1856 $searchcriteria = array('tagid' => $tagid, 'ctx' => $ctx, 'rec' => $rec);
1857 $chelper->set_show_courses($showcategories ? self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT :
1858 self::COURSECAT_SHOW_COURSES_EXPANDED)->
1859 set_search_criteria($searchcriteria)->
1860 set_courses_display_options($displayoptions)->
1861 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1862 // (we set the same css class as in search results by tagid)
1863 if ($totalcount = core_course_category::search_courses_count($searchcriteria)) {
1864 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1865 if ($exclusivemode) {
1866 return $this->coursecat_courses($chelper, $courses, $totalcount);
1867 } else {
1868 $tagfeed = new core_tag\output\tagfeed();
1869 $img = $this->output->pix_icon('i/course', '');
1870 foreach ($courses as $course) {
1871 $url = course_get_url($course);
1872 $imgwithlink = html_writer::link($url, $img);
1873 $coursename = html_writer::link($url, $course->get_formatted_name());
1874 $details = '';
1875 if ($showcategories && ($cat = core_course_category::get($course->category, IGNORE_MISSING))) {
1876 $details = get_string('category').': '.
1877 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1878 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1880 $tagfeed->add($imgwithlink, $coursename, $details);
1882 return $this->output->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($this->output));
1885 return '';
1889 * Returns HTML to display one remote course
1891 * @param stdClass $course remote course information, contains properties:
1892 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1893 * @return string
1895 protected function frontpage_remote_course(stdClass $course) {
1896 $url = new moodle_url('/auth/mnet/jump.php', array(
1897 'hostid' => $course->hostid,
1898 'wantsurl' => '/course/view.php?id='. $course->remoteid
1901 $output = '';
1902 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1903 $output .= html_writer::start_tag('div', array('class' => 'info'));
1904 $output .= html_writer::start_tag('h3', array('class' => 'coursename'));
1905 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1906 $output .= html_writer::end_tag('h3'); // .name
1907 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1908 $output .= html_writer::end_tag('div'); // .info
1909 $output .= html_writer::start_tag('div', array('class' => 'content'));
1910 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1911 $options = new stdClass();
1912 $options->noclean = true;
1913 $options->para = false;
1914 $options->overflowdiv = true;
1915 $output .= format_text($course->summary, $course->summaryformat, $options);
1916 $output .= html_writer::end_tag('div'); // .summary
1917 $addinfo = format_string($course->hostname) . ' : '
1918 . format_string($course->cat_name) . ' : '
1919 . format_string($course->shortname);
1920 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1921 $output .= html_writer::end_tag('div'); // .content
1922 $output .= html_writer::end_tag('div'); // .coursebox
1923 return $output;
1927 * Returns HTML to display one remote host
1929 * @param array $host host information, contains properties: name, url, count
1930 * @return string
1932 protected function frontpage_remote_host($host) {
1933 $output = '';
1934 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1935 $output .= html_writer::start_tag('div', array('class' => 'info'));
1936 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1937 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1938 $output .= html_writer::end_tag('h3'); // .name
1939 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1940 $output .= html_writer::end_tag('div'); // .info
1941 $output .= html_writer::start_tag('div', array('class' => 'content'));
1942 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1943 $output .= $host['count'] . ' ' . get_string('courses');
1944 $output .= html_writer::end_tag('div'); // .content
1945 $output .= html_writer::end_tag('div'); // .coursebox
1946 return $output;
1950 * Returns HTML to print list of courses user is enrolled to for the frontpage
1952 * Also lists remote courses or remote hosts if MNET authorisation is used
1954 * @return string
1956 public function frontpage_my_courses() {
1957 global $USER, $CFG, $DB;
1959 if (!isloggedin() or isguestuser()) {
1960 return '';
1963 $output = '';
1964 $courses = enrol_get_my_courses('summary, summaryformat');
1965 $rhosts = array();
1966 $rcourses = array();
1967 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1968 $rcourses = get_my_remotecourses($USER->id);
1969 $rhosts = get_my_remotehosts();
1972 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1974 $chelper = new coursecat_helper();
1975 $totalcount = count($courses);
1976 if (count($courses) > $CFG->frontpagecourselimit) {
1977 // There are more enrolled courses than we can display, display link to 'My courses'.
1978 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
1979 $chelper->set_courses_display_options(array(
1980 'viewmoreurl' => new moodle_url('/my/courses.php'),
1981 'viewmoretext' => new lang_string('mycourses')
1983 } else if (core_course_category::top()->is_uservisible()) {
1984 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
1985 $chelper->set_courses_display_options(array(
1986 'viewmoreurl' => new moodle_url('/course/index.php'),
1987 'viewmoretext' => new lang_string('fulllistofcourses')
1989 $totalcount = $DB->count_records('course') - 1;
1991 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
1992 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
1993 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
1995 // MNET
1996 if (!empty($rcourses)) {
1997 // at the IDP, we know of all the remote courses
1998 $output .= html_writer::start_tag('div', array('class' => 'courses'));
1999 foreach ($rcourses as $course) {
2000 $output .= $this->frontpage_remote_course($course);
2002 $output .= html_writer::end_tag('div'); // .courses
2003 } elseif (!empty($rhosts)) {
2004 // non-IDP, we know of all the remote servers, but not courses
2005 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2006 foreach ($rhosts as $host) {
2007 $output .= $this->frontpage_remote_host($host);
2009 $output .= html_writer::end_tag('div'); // .courses
2012 return $output;
2016 * Returns HTML to print list of available courses for the frontpage
2018 * @return string
2020 public function frontpage_available_courses() {
2021 global $CFG;
2023 $chelper = new coursecat_helper();
2024 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2025 set_courses_display_options(array(
2026 'recursive' => true,
2027 'limit' => $CFG->frontpagecourselimit,
2028 'viewmoreurl' => new moodle_url('/course/index.php'),
2029 'viewmoretext' => new lang_string('fulllistofcourses')));
2031 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
2032 $courses = core_course_category::top()->get_courses($chelper->get_courses_display_options());
2033 $totalcount = core_course_category::top()->get_courses_count($chelper->get_courses_display_options());
2034 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
2035 // Print link to create a new course, for the 1st available category.
2036 return $this->add_new_course_button();
2038 return $this->coursecat_courses($chelper, $courses, $totalcount);
2042 * Returns HTML to the "add new course" button for the page
2044 * @return string
2046 public function add_new_course_button() {
2047 global $CFG;
2048 // Print link to create a new course, for the 1st available category.
2049 $output = $this->container_start('buttons');
2050 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2051 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2052 $output .= $this->container_end('buttons');
2053 return $output;
2057 * Returns HTML to print tree with course categories and courses for the frontpage
2059 * @return string
2061 public function frontpage_combo_list() {
2062 global $CFG;
2063 // TODO MDL-10965 improve.
2064 $tree = core_course_category::top();
2065 if (!$tree->get_children_count()) {
2066 return '';
2068 $chelper = new coursecat_helper();
2069 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2070 set_categories_display_options(array(
2071 'limit' => $CFG->coursesperpage,
2072 'viewmoreurl' => new moodle_url('/course/index.php',
2073 array('browse' => 'categories', 'page' => 1))
2074 ))->
2075 set_courses_display_options(array(
2076 'limit' => $CFG->coursesperpage,
2077 'viewmoreurl' => new moodle_url('/course/index.php',
2078 array('browse' => 'courses', 'page' => 1))
2079 ))->
2080 set_attributes(array('class' => 'frontpage-category-combo'));
2081 return $this->coursecat_tree($chelper, $tree);
2085 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2087 * @return string
2089 public function frontpage_categories_list() {
2090 global $CFG;
2091 // TODO MDL-10965 improve.
2092 $tree = core_course_category::top();
2093 if (!$tree->get_children_count()) {
2094 return '';
2096 $chelper = new coursecat_helper();
2097 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2098 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2099 set_categories_display_options(array(
2100 'limit' => $CFG->coursesperpage,
2101 'viewmoreurl' => new moodle_url('/course/index.php',
2102 array('browse' => 'categories', 'page' => 1))
2103 ))->
2104 set_attributes(array('class' => 'frontpage-category-names'));
2105 return $this->coursecat_tree($chelper, $tree);
2109 * Renders the activity information.
2111 * Defer to template.
2113 * @param \core_course\output\activity_information $page
2114 * @return string html for the page
2116 public function render_activity_information(\core_course\output\activity_information $page) {
2117 $data = $page->export_for_template($this->output);
2118 return $this->output->render_from_template('core_course/activity_info', $data);
2122 * Renders the activity navigation.
2124 * Defer to template.
2126 * @param \core_course\output\activity_navigation $page
2127 * @return string html for the page
2129 public function render_activity_navigation(\core_course\output\activity_navigation $page) {
2130 $data = $page->export_for_template($this->output);
2131 return $this->output->render_from_template('core_course/activity_navigation', $data);
2135 * Display waiting information about backup size during uploading backup process
2136 * @param object $backupfile the backup stored_file
2137 * @return $html string
2139 public function sendingbackupinfo($backupfile) {
2140 $sizeinfo = new stdClass();
2141 $sizeinfo->total = number_format($backupfile->get_filesize() / 1000000, 2);
2142 $html = html_writer::tag('div', get_string('sendingsize', 'hub', $sizeinfo),
2143 array('class' => 'courseuploadtextinfo'));
2144 return $html;
2148 * Hub information (logo - name - description - link)
2149 * @param object $hubinfo
2150 * @return string html code
2152 public function hubinfo($hubinfo) {
2153 $screenshothtml = html_writer::empty_tag('img',
2154 array('src' => $hubinfo['imgurl'], 'alt' => $hubinfo['name']));
2155 $hubdescription = html_writer::tag('div', $screenshothtml,
2156 array('class' => 'hubscreenshot'));
2158 $hubdescription .= html_writer::tag('a', $hubinfo['name'],
2159 array('class' => 'hublink', 'href' => $hubinfo['url'],
2160 'onclick' => 'this.target="_blank"'));
2162 $hubdescription .= html_writer::tag('div', format_text($hubinfo['description'], FORMAT_PLAIN),
2163 array('class' => 'hubdescription'));
2164 $hubdescription = html_writer::tag('div', $hubdescription, array('class' => 'hubinfo clearfix'));
2166 return $hubdescription;
2170 * Output frontpage summary text and frontpage modules (stored as section 1 in site course)
2172 * This may be disabled in settings
2174 * @return string
2176 public function frontpage_section1() {
2177 global $SITE, $USER;
2179 $output = '';
2180 $editing = $this->page->user_is_editing();
2182 if ($editing) {
2183 // Make sure section with number 1 exists.
2184 course_create_sections_if_missing($SITE, 1);
2187 $modinfo = get_fast_modinfo($SITE);
2188 $section = $modinfo->get_section_info(1);
2191 if (($section && (!empty($modinfo->sections[1]) or !empty($section->summary))) or $editing) {
2193 $format = course_get_format($SITE);
2194 $frontpageclass = $format->get_output_classname('content\\frontpagesection');
2195 $frontpagesection = new $frontpageclass($format, $section);
2197 // The course outputs works with format renderers, not with course renderers.
2198 $renderer = $format->get_renderer($this->page);
2199 $output .= $renderer->render($frontpagesection);
2202 return $output;
2206 * Output news for the frontpage (extract from site-wide news forum)
2208 * @param stdClass $forum record from db table 'forum' that represents the site news forum
2209 * @return string
2211 protected function frontpage_news($forum) {
2212 global $CFG, $SITE, $SESSION, $USER;
2213 require_once($CFG->dirroot .'/mod/forum/lib.php');
2215 $output = '';
2217 if (isloggedin()) {
2218 $SESSION->fromdiscussion = $CFG->wwwroot;
2219 $subtext = '';
2220 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forum)) {
2221 if (!\mod_forum\subscriptions::is_forcesubscribed($forum)) {
2222 $subtext = get_string('unsubscribe', 'forum');
2224 } else {
2225 $subtext = get_string('subscribe', 'forum');
2227 $suburl = new moodle_url('/mod/forum/subscribe.php', array('id' => $forum->id, 'sesskey' => sesskey()));
2228 $output .= html_writer::tag('div', html_writer::link($suburl, $subtext), array('class' => 'subscribelink'));
2231 $coursemodule = get_coursemodule_from_instance('forum', $forum->id);
2232 $context = context_module::instance($coursemodule->id);
2234 $entityfactory = mod_forum\local\container::get_entity_factory();
2235 $forumentity = $entityfactory->get_forum_from_stdclass($forum, $context, $coursemodule, $SITE);
2237 $rendererfactory = mod_forum\local\container::get_renderer_factory();
2238 $discussionsrenderer = $rendererfactory->get_frontpage_news_discussion_list_renderer($forumentity);
2239 $cm = \cm_info::create($coursemodule);
2240 return $output . $discussionsrenderer->render($USER, $cm, null, null, 0, $SITE->newsitems);
2244 * Renders part of frontpage with a skip link (i.e. "My courses", "Site news", etc.)
2246 * @param string $skipdivid
2247 * @param string $contentsdivid
2248 * @param string $header Header of the part
2249 * @param string $contents Contents of the part
2250 * @return string
2252 protected function frontpage_part($skipdivid, $contentsdivid, $header, $contents) {
2253 if (strval($contents) === '') {
2254 return '';
2256 $output = html_writer::link('#' . $skipdivid,
2257 get_string('skipa', 'access', core_text::strtolower(strip_tags($header))),
2258 array('class' => 'skip-block skip aabtn'));
2260 // Wrap frontpage part in div container.
2261 $output .= html_writer::start_tag('div', array('id' => $contentsdivid));
2262 $output .= $this->heading($header);
2264 $output .= $contents;
2266 // End frontpage part div container.
2267 $output .= html_writer::end_tag('div');
2269 $output .= html_writer::tag('span', '', array('class' => 'skip-block-to', 'id' => $skipdivid));
2270 return $output;
2274 * Outputs contents for frontpage as configured in $CFG->frontpage or $CFG->frontpageloggedin
2276 * @return string
2278 public function frontpage() {
2279 global $CFG, $SITE;
2281 $output = '';
2283 if (isloggedin() and !isguestuser() and isset($CFG->frontpageloggedin)) {
2284 $frontpagelayout = $CFG->frontpageloggedin;
2285 } else {
2286 $frontpagelayout = $CFG->frontpage;
2289 foreach (explode(',', $frontpagelayout) as $v) {
2290 switch ($v) {
2291 // Display the main part of the front page.
2292 case FRONTPAGENEWS:
2293 if ($SITE->newsitems) {
2294 // Print forums only when needed.
2295 require_once($CFG->dirroot .'/mod/forum/lib.php');
2296 if (($newsforum = forum_get_course_forum($SITE->id, 'news')) &&
2297 ($forumcontents = $this->frontpage_news($newsforum))) {
2298 $newsforumcm = get_fast_modinfo($SITE)->instances['forum'][$newsforum->id];
2299 $output .= $this->frontpage_part('skipsitenews', 'site-news-forum',
2300 $newsforumcm->get_formatted_name(), $forumcontents);
2303 break;
2305 case FRONTPAGEENROLLEDCOURSELIST:
2306 $mycourseshtml = $this->frontpage_my_courses();
2307 if (!empty($mycourseshtml)) {
2308 $output .= $this->frontpage_part('skipmycourses', 'frontpage-course-list',
2309 get_string('mycourses'), $mycourseshtml);
2311 break;
2313 case FRONTPAGEALLCOURSELIST:
2314 $availablecourseshtml = $this->frontpage_available_courses();
2315 $output .= $this->frontpage_part('skipavailablecourses', 'frontpage-available-course-list',
2316 get_string('availablecourses'), $availablecourseshtml);
2317 break;
2319 case FRONTPAGECATEGORYNAMES:
2320 $output .= $this->frontpage_part('skipcategories', 'frontpage-category-names',
2321 get_string('categories'), $this->frontpage_categories_list());
2322 break;
2324 case FRONTPAGECATEGORYCOMBO:
2325 $output .= $this->frontpage_part('skipcourses', 'frontpage-category-combo',
2326 get_string('courses'), $this->frontpage_combo_list());
2327 break;
2329 case FRONTPAGECOURSESEARCH:
2330 $output .= $this->box($this->course_search_form(''), 'd-flex justify-content-center');
2331 break;
2334 $output .= '<br />';
2337 return $output;
2342 * Class storing display options and functions to help display course category and/or courses lists
2344 * This is a wrapper for core_course_category objects that also stores display options
2345 * and functions to retrieve sorted and paginated lists of categories/courses.
2347 * If theme overrides methods in core_course_renderers that access this class
2348 * it may as well not use this class at all or extend it.
2350 * @package core
2351 * @copyright 2013 Marina Glancy
2352 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2354 class coursecat_helper {
2355 /** @var string [none, collapsed, expanded] how (if) display courses list */
2356 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2357 /** @var int depth to expand subcategories in the tree (deeper subcategories will be loaded by AJAX or proceed to category page by clicking on category name) */
2358 protected $subcatdepth = 1;
2359 /** @var array options to display courses list */
2360 protected $coursesdisplayoptions = array();
2361 /** @var array options to display subcategories list */
2362 protected $categoriesdisplayoptions = array();
2363 /** @var array additional HTML attributes */
2364 protected $attributes = array();
2365 /** @var array search criteria if the list is a search result */
2366 protected $searchcriteria = null;
2369 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2371 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2372 * @return coursecat_helper
2374 public function set_show_courses($showcourses) {
2375 $this->showcourses = $showcourses;
2376 // Automatically set the options to preload summary and coursecontacts for core_course_category::get_courses()
2377 // and core_course_category::search_courses().
2378 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2379 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2380 $this->coursesdisplayoptions['customfields'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED;
2381 return $this;
2385 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2387 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2389 public function get_show_courses() {
2390 return $this->showcourses;
2394 * Sets the maximum depth to expand subcategories in the tree
2396 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2398 * @param int $subcatdepth
2399 * @return coursecat_helper
2401 public function set_subcat_depth($subcatdepth) {
2402 $this->subcatdepth = $subcatdepth;
2403 return $this;
2407 * Returns the maximum depth to expand subcategories in the tree
2409 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2411 * @return int
2413 public function get_subcat_depth() {
2414 return $this->subcatdepth;
2418 * Sets options to display list of courses
2420 * Options are later submitted as argument to core_course_category::get_courses() and/or core_course_category::search_courses()
2422 * Options that core_course_category::get_courses() accept:
2423 * - recursive - return courses from subcategories as well. Use with care,
2424 * this may be a huge list!
2425 * - summary - preloads fields 'summary' and 'summaryformat'
2426 * - coursecontacts - preloads course contacts
2427 * - customfields - preloads custom fields data
2428 * - isenrolled - preloads indication whether this user is enrolled in the course
2429 * - sort - list of fields to sort. Example
2430 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2431 * will sort by idnumber asc, shortname asc and id desc.
2432 * Default: array('sortorder' => 1)
2433 * Only cached fields may be used for sorting!
2434 * - offset
2435 * - limit - maximum number of children to return, 0 or null for no limit
2437 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2439 * Also renderer can set here any additional options it wants to pass between renderer functions.
2441 * @param array $options
2442 * @return coursecat_helper
2444 public function set_courses_display_options($options) {
2445 $this->coursesdisplayoptions = $options;
2446 $this->set_show_courses($this->showcourses); // this will calculate special display options
2447 return $this;
2451 * Sets one option to display list of courses
2453 * @see coursecat_helper::set_courses_display_options()
2455 * @param string $key
2456 * @param mixed $value
2457 * @return coursecat_helper
2459 public function set_courses_display_option($key, $value) {
2460 $this->coursesdisplayoptions[$key] = $value;
2461 return $this;
2465 * Return the specified option to display list of courses
2467 * @param string $optionname option name
2468 * @param mixed $defaultvalue default value for option if it is not specified
2469 * @return mixed
2471 public function get_courses_display_option($optionname, $defaultvalue = null) {
2472 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2473 return $this->coursesdisplayoptions[$optionname];
2474 } else {
2475 return $defaultvalue;
2480 * Returns all options to display the courses
2482 * This array is usually passed to {@link core_course_category::get_courses()} or
2483 * {@link core_course_category::search_courses()}
2485 * @return array
2487 public function get_courses_display_options() {
2488 return $this->coursesdisplayoptions;
2492 * Sets options to display list of subcategories
2494 * Options 'sort', 'offset' and 'limit' are passed to core_course_category::get_children().
2495 * Any other options may be used by renderer functions
2497 * @param array $options
2498 * @return coursecat_helper
2500 public function set_categories_display_options($options) {
2501 $this->categoriesdisplayoptions = $options;
2502 return $this;
2506 * Return the specified option to display list of subcategories
2508 * @param string $optionname option name
2509 * @param mixed $defaultvalue default value for option if it is not specified
2510 * @return mixed
2512 public function get_categories_display_option($optionname, $defaultvalue = null) {
2513 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2514 return $this->categoriesdisplayoptions[$optionname];
2515 } else {
2516 return $defaultvalue;
2521 * Returns all options to display list of subcategories
2523 * This array is usually passed to {@link core_course_category::get_children()}
2525 * @return array
2527 public function get_categories_display_options() {
2528 return $this->categoriesdisplayoptions;
2532 * Sets additional general options to pass between renderer functions, usually HTML attributes
2534 * @param array $attributes
2535 * @return coursecat_helper
2537 public function set_attributes($attributes) {
2538 $this->attributes = $attributes;
2539 return $this;
2543 * Return all attributes and erases them so they are not applied again
2545 * @param string $classname adds additional class name to the beginning of $attributes['class']
2546 * @return array
2548 public function get_and_erase_attributes($classname) {
2549 $attributes = $this->attributes;
2550 $this->attributes = array();
2551 if (empty($attributes['class'])) {
2552 $attributes['class'] = '';
2554 $attributes['class'] = $classname . ' '. $attributes['class'];
2555 return $attributes;
2559 * Sets the search criteria if the course is a search result
2561 * Search string will be used to highlight terms in course name and description
2563 * @param array $searchcriteria
2564 * @return coursecat_helper
2566 public function set_search_criteria($searchcriteria) {
2567 $this->searchcriteria = $searchcriteria;
2568 return $this;
2572 * Returns formatted and filtered description of the given category
2574 * @param core_course_category $coursecat category
2575 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2576 * if context is not specified it will be added automatically
2577 * @return string|null
2579 public function get_category_formatted_description($coursecat, $options = null) {
2580 if ($coursecat->id && $coursecat->is_uservisible() && !empty($coursecat->description)) {
2581 if (!isset($coursecat->descriptionformat)) {
2582 $descriptionformat = FORMAT_MOODLE;
2583 } else {
2584 $descriptionformat = $coursecat->descriptionformat;
2586 if ($options === null) {
2587 $options = array('noclean' => true, 'overflowdiv' => true);
2588 } else {
2589 $options = (array)$options;
2591 $context = context_coursecat::instance($coursecat->id);
2592 if (!isset($options['context'])) {
2593 $options['context'] = $context;
2595 $text = file_rewrite_pluginfile_urls($coursecat->description,
2596 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2597 return format_text($text, $descriptionformat, $options);
2599 return null;
2603 * Returns given course's summary with proper embedded files urls and formatted
2605 * @param core_course_list_element $course
2606 * @param array|stdClass $options additional formatting options
2607 * @return string
2609 public function get_course_formatted_summary($course, $options = array()) {
2610 global $CFG;
2611 require_once($CFG->libdir. '/filelib.php');
2612 if (!$course->has_summary()) {
2613 return '';
2615 $options = (array)$options;
2616 $context = context_course::instance($course->id);
2617 if (!isset($options['context'])) {
2618 // TODO see MDL-38521
2619 // option 1 (current), page context - no code required
2620 // option 2, system context
2621 // $options['context'] = context_system::instance();
2622 // option 3, course context:
2623 // $options['context'] = $context;
2624 // option 4, course category context:
2625 // $options['context'] = $context->get_parent_context();
2627 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2628 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2629 if (!empty($this->searchcriteria['search'])) {
2630 $summary = highlight($this->searchcriteria['search'], $summary);
2632 return $summary;
2636 * Returns course name as it is configured to appear in courses lists formatted to course context
2638 * @param core_course_list_element $course
2639 * @param array|stdClass $options additional formatting options
2640 * @return string
2642 public function get_course_formatted_name($course, $options = array()) {
2643 $options = (array)$options;
2644 if (!isset($options['context'])) {
2645 $options['context'] = context_course::instance($course->id);
2647 $name = format_string(get_course_display_name_for_list($course), true, $options);
2648 if (!empty($this->searchcriteria['search'])) {
2649 $name = highlight($this->searchcriteria['search'], $name);
2651 return $name;