MDL-72094 report_log: Modify the styling of the selector form elements
[moodle.git] / course / renderer.php
blob3d8d78e805a052fc7d424bd7bacff04235b4113e
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 parent::__construct($page, $target);
71 /**
72 * @deprecated since 3.2
74 protected function add_modchoosertoggle() {
75 throw new coding_exception('core_course_renderer::add_modchoosertoggle() can not be used anymore.');
78 /**
79 * Renders course info box.
81 * @param stdClass $course
82 * @return string
84 public function course_info_box(stdClass $course) {
85 $content = '';
86 $content .= $this->output->box_start('generalbox info');
87 $chelper = new coursecat_helper();
88 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
89 $content .= $this->coursecat_coursebox($chelper, $course);
90 $content .= $this->output->box_end();
91 return $content;
94 /**
95 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
97 * @deprecated since 2.5
99 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
101 * @param array $ignored argument ignored
102 * @return string
104 public final function course_category_tree(array $ignored) {
105 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
106 return $this->frontpage_combo_list();
110 * Renderers a category for use with course_category_tree
112 * @deprecated since 2.5
114 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
116 * @param array $category
117 * @param int $depth
118 * @return string
120 protected final function course_category_tree_category(stdClass $category, $depth=1) {
121 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
122 return '';
126 * Render a modchooser.
128 * @param renderable $modchooser The chooser.
129 * @return string
131 public function render_modchooser(renderable $modchooser) {
132 return $this->render_from_template('core_course/modchooser', $modchooser->export_for_template($this));
136 * Build the HTML for the module chooser javascript popup
138 * @param array $modules A set of modules as returned form @see
139 * get_module_metadata
140 * @param object $course The course that will be displayed
141 * @return string The composed HTML for the module
143 public function course_modchooser($modules, $course) {
144 debugging('course_modchooser() is deprecated. Please use course_activitychooser() instead.', DEBUG_DEVELOPER);
146 return $this->course_activitychooser($course->id);
150 * Build the HTML for the module chooser javascript popup.
152 * @param int $courseid The course id to fetch modules for.
153 * @return string
155 public function course_activitychooser($courseid) {
157 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchooser')) {
158 return '';
161 // Build an object of config settings that we can then hook into in the Activity Chooser.
162 $chooserconfig = (object) [
163 'tabmode' => get_config('core', 'activitychoosertabmode'),
165 $this->page->requires->js_call_amd('core_course/activitychooser', 'init', [$courseid, $chooserconfig]);
167 return '';
171 * Build the HTML for a specified set of modules
173 * @param array $modules A set of modules as used by the
174 * course_modchooser_module function
175 * @return string The composed HTML for the module
177 protected function course_modchooser_module_types($modules) {
178 debugging('Method core_course_renderer::course_modchooser_module_types() is deprecated, ' .
179 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
180 return '';
184 * Return the HTML for the specified module adding any required classes
186 * @param object $module An object containing the title, and link. An
187 * icon, and help text may optionally be specified. If the module
188 * contains subtypes in the types option, then these will also be
189 * displayed.
190 * @param array $classes Additional classes to add to the encompassing
191 * div element
192 * @return string The composed HTML for the module
194 protected function course_modchooser_module($module, $classes = array('option')) {
195 debugging('Method core_course_renderer::course_modchooser_module() is deprecated, ' .
196 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
197 return '';
200 protected function course_modchooser_title($title, $identifier = null) {
201 debugging('Method core_course_renderer::course_modchooser_title() is deprecated, ' .
202 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
203 return '';
207 * Renders HTML for displaying the sequence of course module editing buttons
209 * @see course_get_cm_edit_actions()
211 * @param action_link[] $actions Array of action_link objects
212 * @param cm_info $mod The module we are displaying actions for.
213 * @param array $displayoptions additional display options:
214 * ownerselector => A JS/CSS selector that can be used to find an cm node.
215 * If specified the owning node will be given the class 'action-menu-shown' when the action
216 * menu is being displayed.
217 * constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
218 * the action menu to when it is being displayed.
219 * donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
220 * @return string
222 public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
223 global $CFG;
225 if (empty($actions)) {
226 return '';
229 if (isset($displayoptions['ownerselector'])) {
230 $ownerselector = $displayoptions['ownerselector'];
231 } else if ($mod) {
232 $ownerselector = '#module-'.$mod->id;
233 } else {
234 debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
235 $ownerselector = 'li.activity';
238 if (isset($displayoptions['constraintselector'])) {
239 $constraint = $displayoptions['constraintselector'];
240 } else {
241 $constraint = '.course-content';
244 $menu = new action_menu();
245 $menu->set_owner_selector($ownerselector);
246 $menu->set_constraint($constraint);
247 $menu->set_alignment(action_menu::TR, action_menu::BR);
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 $straddeither = get_string('addresourceoractivity');
285 $ajaxcontrol = html_writer::start_tag('div', array('class' => 'mdl-right'));
286 $ajaxcontrol .= html_writer::start_tag('div', array('class' => 'section-modchooser'));
288 $icon = $this->output->pix_icon('t/add', '');
289 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
291 $ajaxcontrol .= html_writer::tag('button', $icon . $span, [
292 'class' => 'section-modchooser-link btn btn-link',
293 'data-action' => 'open-chooser',
294 'data-sectionid' => $section,
295 'data-sectionreturnid' => $sectionreturn,
298 $ajaxcontrol .= html_writer::end_tag('div');
299 $ajaxcontrol .= html_writer::end_tag('div');
301 // Load the JS for the modal.
302 $this->course_activitychooser($course->id);
304 return $ajaxcontrol;
308 * Render the deprecated nonajax activity chooser.
310 * @deprecated since Moodle 3.11
312 * @todo MDL-71331 deprecate this function
313 * @param stdClass $course the course object
314 * @param int $section relative section number (field course_sections.section)
315 * @param int $sectionreturn The section to link back to
316 * @param array $displayoptions additional display options, for example blocks add
317 * option 'inblock' => true, suggesting to display controls vertically
318 * @return string
320 private function course_section_add_cm_control_nonajax($course, $section, $sectionreturn = null,
321 $displayoptions = array()): string {
322 global $USER;
324 $vertical = !empty($displayoptions['inblock']);
326 // Check to see if user can add menus.
327 if (
328 !has_capability('moodle/course:manageactivities', context_course::instance($course->id))
329 || !$this->page->user_is_editing()
331 return '';
334 debugging('non-js dropdowns are deprecated.', DEBUG_DEVELOPER);
335 // Retrieve all modules with associated metadata.
336 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
337 $urlparams = ['section' => $section];
338 if (!is_null($sectionreturn)) {
339 $urlparams['sr'] = $sectionreturn;
341 $modules = $contentitemservice->get_content_items_for_user_in_course($USER, $course, $urlparams);
343 // Return if there are no content items to add.
344 if (empty($modules)) {
345 return '';
348 // We'll sort resources and activities into two lists.
349 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
351 foreach ($modules as $module) {
352 $activityclass = MOD_CLASS_ACTIVITY;
353 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
354 $activityclass = MOD_CLASS_RESOURCE;
355 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
356 // System modules cannot be added by user, do not add to dropdown.
357 continue;
359 $link = $module->link;
360 $activities[$activityclass][$link] = $module->title;
363 $straddactivity = get_string('addactivity');
364 $straddresource = get_string('addresource');
365 $sectionname = get_section_name($course, $section);
366 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
367 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
369 $nonajaxcontrol = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-'
370 . $section));
372 if (!$vertical) {
373 $nonajaxcontrol .= html_writer::start_tag('div', array('class' => 'horizontal'));
376 if (!empty($activities[MOD_CLASS_RESOURCE])) {
377 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array('' => $straddresource), "ressection$section");
378 $select->set_help_icon('resources');
379 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
380 $nonajaxcontrol .= $this->output->render($select);
383 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
384 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array('' => $straddactivity), "section$section");
385 $select->set_help_icon('activities');
386 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
387 $nonajaxcontrol .= $this->output->render($select);
390 if (!$vertical) {
391 $nonajaxcontrol .= html_writer::end_tag('div');
394 $nonajaxcontrol .= html_writer::end_tag('div');
396 return $nonajaxcontrol;
400 * Renders html to display a course search form
402 * @param string $value default value to populate the search field
403 * @return string
405 public function course_search_form($value = '') {
407 $data = [
408 'action' => \core_search\manager::get_course_search_url(),
409 'btnclass' => 'btn-primary',
410 'inputname' => 'q',
411 'searchstring' => get_string('searchcourses'),
412 'hiddenfields' => (object) ['name' => 'areaids', 'value' => 'core_course-course'],
413 'query' => $value
415 return $this->render_from_template('core/search_input', $data);
419 * Renders html for completion box on course page
421 * If completion is disabled, returns empty string
422 * If completion is automatic, returns an icon of the current completion state
423 * If completion is manual, returns a form (with an icon inside) that allows user to
424 * toggle completion
426 * @deprecated since Moodle 3.11
427 * @todo MDL-71183 Final deprecation in Moodle 4.3.
428 * @see \core_renderer::activity_information
430 * @param stdClass $course course object
431 * @param completion_info $completioninfo completion info for the course, it is recommended
432 * to fetch once for all modules in course/section for performance
433 * @param cm_info $mod module to show completion for
434 * @param array $displayoptions display options, not used in core
435 * @return string
437 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
438 global $CFG, $DB, $USER;
440 debugging(__FUNCTION__ . ' is deprecated and is being replaced by the activity_information output component.',
441 DEBUG_DEVELOPER);
443 $output = '';
445 $istrackeduser = $completioninfo->is_tracked_user($USER->id);
446 $isediting = $this->page->user_is_editing();
448 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
449 return $output;
451 if ($completioninfo === null) {
452 $completioninfo = new completion_info($course);
454 $completion = $completioninfo->is_enabled($mod);
456 if ($completion == COMPLETION_TRACKING_NONE) {
457 if ($isediting) {
458 $output .= html_writer::span('&nbsp;', 'filler');
460 return $output;
463 $completionicon = '';
465 if ($isediting || !$istrackeduser) {
466 switch ($completion) {
467 case COMPLETION_TRACKING_MANUAL :
468 $completionicon = 'manual-enabled'; break;
469 case COMPLETION_TRACKING_AUTOMATIC :
470 $completionicon = 'auto-enabled'; break;
472 } else {
473 $completiondata = $completioninfo->get_data($mod, true);
474 if ($completion == COMPLETION_TRACKING_MANUAL) {
475 switch($completiondata->completionstate) {
476 case COMPLETION_INCOMPLETE:
477 $completionicon = 'manual-n' . ($completiondata->overrideby ? '-override' : '');
478 break;
479 case COMPLETION_COMPLETE:
480 $completionicon = 'manual-y' . ($completiondata->overrideby ? '-override' : '');
481 break;
483 } else { // Automatic
484 switch($completiondata->completionstate) {
485 case COMPLETION_INCOMPLETE:
486 $completionicon = 'auto-n' . ($completiondata->overrideby ? '-override' : '');
487 break;
488 case COMPLETION_COMPLETE:
489 $completionicon = 'auto-y' . ($completiondata->overrideby ? '-override' : '');
490 break;
491 case COMPLETION_COMPLETE_PASS:
492 $completionicon = 'auto-pass'; break;
493 case COMPLETION_COMPLETE_FAIL:
494 $completionicon = 'auto-fail'; break;
498 if ($completionicon) {
499 $formattedname = html_entity_decode($mod->get_formatted_name(), ENT_QUOTES, 'UTF-8');
500 if (!$isediting && $istrackeduser && $completiondata->overrideby) {
501 $args = new stdClass();
502 $args->modname = $formattedname;
503 $overridebyuser = \core_user::get_user($completiondata->overrideby, '*', MUST_EXIST);
504 $args->overrideuser = fullname($overridebyuser);
505 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $args);
506 } else {
507 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
510 if ($isediting || !$istrackeduser || !has_capability('moodle/course:togglecompletion', $mod->context)) {
511 // When editing, the icon is just an image.
512 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
513 array('title' => $imgalt, 'class' => 'iconsmall'));
514 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
515 array('class' => 'autocompletion'));
516 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
517 $newstate =
518 $completiondata->completionstate == COMPLETION_COMPLETE
519 ? COMPLETION_INCOMPLETE
520 : COMPLETION_COMPLETE;
521 // In manual mode the icon is a toggle form...
523 // If this completion state is used by the
524 // conditional activities system, we need to turn
525 // off the JS.
526 $extraclass = '';
527 if (!empty($CFG->enableavailability) &&
528 core_availability\info::completion_value_used($course, $mod->id)) {
529 $extraclass = ' preventjs';
531 $output .= html_writer::start_tag('form', array('method' => 'post',
532 'action' => new moodle_url('/course/togglecompletion.php'),
533 'class' => 'togglecompletion'. $extraclass));
534 $output .= html_writer::start_tag('div');
535 $output .= html_writer::empty_tag('input', array(
536 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
537 $output .= html_writer::empty_tag('input', array(
538 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
539 $output .= html_writer::empty_tag('input', array(
540 'type' => 'hidden', 'name' => 'modulename', 'value' => $formattedname));
541 $output .= html_writer::empty_tag('input', array(
542 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
543 $output .= html_writer::tag('button',
544 $this->output->pix_icon('i/completion-' . $completionicon, $imgalt),
545 array('class' => 'btn btn-link', 'aria-live' => 'assertive'));
546 $output .= html_writer::end_tag('div');
547 $output .= html_writer::end_tag('form');
548 } else {
549 // In auto mode, the icon is just an image.
550 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
551 array('title' => $imgalt));
552 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
553 array('class' => 'autocompletion'));
556 return $output;
560 * Checks if course module has any conditions that may make it unavailable for
561 * all or some of the students
563 * @param cm_info $mod
564 * @return bool
566 public function is_cm_conditionally_hidden(cm_info $mod) {
567 global $CFG;
568 $conditionalhidden = false;
569 if (!empty($CFG->enableavailability)) {
570 $info = new \core_availability\info_module($mod);
571 $conditionalhidden = !$info->is_available_for_all();
573 return $conditionalhidden;
577 * Renders html to display a name with the link to the course module on a course page
579 * If module is unavailable for user but still needs to be displayed
580 * in the list, just the name is returned without a link
582 * Note, that for course modules that never have separate pages (i.e. labels)
583 * this function return an empty string
585 * @param cm_info $mod
586 * @param array $displayoptions
587 * @return string
589 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
590 if (!$mod->is_visible_on_course_page() || !$mod->url) {
591 // Nothing to be displayed to the user.
592 return '';
595 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
596 $groupinglabel = $mod->get_grouping_label($textclasses);
598 // Render element that allows to edit activity name inline. It calls {@link course_section_cm_name_title()}
599 // to get the display title of the activity.
600 $tmpl = new \core_course\output\course_module_name($mod, $this->page->user_is_editing(), $displayoptions);
601 return $this->output->render_from_template('core/inplace_editable', $tmpl->export_for_template($this->output)) .
602 $groupinglabel;
606 * Returns the CSS classes for the activity name/content
608 * For items which are hidden, unavailable or stealth but should be displayed
609 * to current user ($mod->is_visible_on_course_page()), we show those as dimmed.
610 * Students will also see as dimmed activities names that are not yet available
611 * but should still be displayed (without link) with availability info.
613 * @param cm_info $mod
614 * @return array array of two elements ($linkclasses, $textclasses)
616 protected function course_section_cm_classes(cm_info $mod) {
617 $linkclasses = '';
618 $textclasses = '';
619 if ($mod->uservisible) {
620 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
621 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
622 has_capability('moodle/course:viewhiddenactivities', $mod->context);
623 if ($accessiblebutdim) {
624 $linkclasses .= ' dimmed';
625 $textclasses .= ' dimmed_text';
626 if ($conditionalhidden) {
627 $linkclasses .= ' conditionalhidden';
628 $textclasses .= ' conditionalhidden';
631 if ($mod->is_stealth()) {
632 // Stealth activity is the one that is not visible on course page.
633 // It still may be displayed to the users who can manage it.
634 $linkclasses .= ' stealth';
635 $textclasses .= ' stealth';
637 } else {
638 $linkclasses .= ' dimmed';
639 $textclasses .= ' dimmed dimmed_text';
641 return array($linkclasses, $textclasses);
645 * Renders html to display a name with the link to the course module on a course page
647 * If module is unavailable for user but still needs to be displayed
648 * in the list, just the name is returned without a link
650 * Note, that for course modules that never have separate pages (i.e. labels)
651 * this function return an empty string
653 * @param cm_info $mod
654 * @param array $displayoptions
655 * @return string
657 public function course_section_cm_name_title(cm_info $mod, $displayoptions = array()) {
658 $output = '';
659 $url = $mod->url;
660 if (!$mod->is_visible_on_course_page() || !$url) {
661 // Nothing to be displayed to the user.
662 return $output;
665 //Accessibility: for files get description via icon, this is very ugly hack!
666 $instancename = $mod->get_formatted_name();
667 $altname = $mod->modfullname;
668 // Avoid unnecessary duplication: if e.g. a forum name already
669 // includes the word forum (or Forum, etc) then it is unhelpful
670 // to include that in the accessible description that is added.
671 if (false !== strpos(core_text::strtolower($instancename),
672 core_text::strtolower($altname))) {
673 $altname = '';
675 // File type after name, for alphabetic lists (screen reader).
676 if ($altname) {
677 $altname = get_accesshide(' '.$altname);
680 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
682 // Get on-click attribute value if specified and decode the onclick - it
683 // has already been encoded for display (puke).
684 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
686 // Display link itself.
687 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
688 'class' => 'iconlarge activityicon', 'alt' => '', 'role' => 'presentation', 'aria-hidden' => 'true')) .
689 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
690 if ($mod->uservisible) {
691 $output .= html_writer::link($url, $activitylink, array('class' => 'aalink' . $linkclasses, 'onclick' => $onclick));
692 } else {
693 // We may be displaying this just in order to show information
694 // about visibility, without the actual link ($mod->is_visible_on_course_page()).
695 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses));
697 return $output;
701 * Renders html to display the module content on the course page (i.e. text of the labels)
703 * @param cm_info $mod
704 * @param array $displayoptions
705 * @return string
707 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
708 $output = '';
709 if (!$mod->is_visible_on_course_page()) {
710 // nothing to be displayed to the user
711 return $output;
713 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
714 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
715 if ($mod->url && $mod->uservisible) {
716 if ($content) {
717 // If specified, display extra content after link.
718 $output = html_writer::tag('div', $content, array('class' =>
719 trim('contentafterlink ' . $textclasses)));
721 } else {
722 $groupinglabel = $mod->get_grouping_label($textclasses);
724 // No link, so display only content.
725 $output = html_writer::tag('div', $content . $groupinglabel,
726 array('class' => 'contentwithoutlink ' . $textclasses));
728 return $output;
732 * Displays availability info for a course section or course module
734 * @param string $text
735 * @param string $additionalclasses
736 * @return string
738 public function availability_info($text, $additionalclasses = '') {
740 $data = ['text' => $text, 'classes' => $additionalclasses];
741 $additionalclasses = array_filter(explode(' ', $additionalclasses));
743 if (in_array('ishidden', $additionalclasses)) {
744 $data['ishidden'] = 1;
746 } else if (in_array('isstealth', $additionalclasses)) {
747 $data['isstealth'] = 1;
749 } else if (in_array('isrestricted', $additionalclasses)) {
750 $data['isrestricted'] = 1;
752 if (in_array('isfullinfo', $additionalclasses)) {
753 $data['isfullinfo'] = 1;
757 return $this->render_from_template('core/availability_info', $data);
761 * Renders HTML to show course module availability information (for someone who isn't allowed
762 * to see the activity itself, or for staff)
764 * @param cm_info $mod
765 * @param array $displayoptions
766 * @return string
768 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
769 global $CFG;
770 $output = '';
771 if (!$mod->is_visible_on_course_page()) {
772 return $output;
774 if (!$mod->uservisible) {
775 // this is a student who is not allowed to see the module but might be allowed
776 // to see availability info (i.e. "Available from ...")
777 if (!empty($mod->availableinfo)) {
778 $formattedinfo = \core_availability\info::format_info(
779 $mod->availableinfo, $mod->get_course());
780 $output = $this->availability_info($formattedinfo, 'isrestricted');
782 return $output;
784 // this is a teacher who is allowed to see module but still should see the
785 // information that module is not available to all/some students
786 $modcontext = context_module::instance($mod->id);
787 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
788 if ($canviewhidden && !$mod->visible) {
789 // This module is hidden but current user has capability to see it.
790 // Do not display the availability info if the whole section is hidden.
791 if ($mod->get_section_info()->visible) {
792 $output .= $this->availability_info(get_string('hiddenfromstudents'), 'ishidden');
794 } else if ($mod->is_stealth()) {
795 // This module is available but is normally not displayed on the course page
796 // (this user can see it because they can manage it).
797 $output .= $this->availability_info(get_string('hiddenoncoursepage'), 'isstealth');
799 if ($canviewhidden && !empty($CFG->enableavailability)) {
800 // Display information about conditional availability.
801 // Don't add availability information if user is not editing and activity is hidden.
802 if ($mod->visible || $this->page->user_is_editing()) {
803 $hidinfoclass = 'isrestricted isfullinfo';
804 if (!$mod->visible) {
805 $hidinfoclass .= ' hide';
807 $ci = new \core_availability\info_module($mod);
808 $fullinfo = $ci->get_full_information();
809 if ($fullinfo) {
810 $formattedinfo = \core_availability\info::format_info(
811 $fullinfo, $mod->get_course());
812 $output .= $this->availability_info($formattedinfo, $hidinfoclass);
816 return $output;
820 * Renders HTML to display one course module for display within a section.
822 * @deprecated since 4.0 - use core_course output components or course_format::course_section_updated_cm_item instead.
824 * This function calls:
825 * {@link core_course_renderer::course_section_cm()}
827 * @param stdClass $course
828 * @param completion_info $completioninfo
829 * @param cm_info $mod
830 * @param int|null $sectionreturn
831 * @param array $displayoptions
832 * @return String
834 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = []) {
836 debugging(
837 'course_section_cm_list_item is deprecated. Use renderer course_section_updated_cm_item instead',
838 DEBUG_DEVELOPER
841 $output = '';
842 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
843 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
844 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
846 return $output;
850 * Renders HTML to display one course module in a course section
852 * This includes link, content, availability, completion info and additional information
853 * that module type wants to display (i.e. number of unread forum posts)
855 * @deprecated since 4.0 - use core_course output components instead.
857 * @param stdClass $course
858 * @param completion_info $completioninfo
859 * @param cm_info $mod
860 * @param int|null $sectionreturn
861 * @param array $displayoptions
862 * @return string
864 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = []) {
866 debugging(
867 'course_section_cm is deprecated. Use core_courseformat\output\content\cm output classes instead.',
868 DEBUG_DEVELOPER
871 if (!$mod->is_visible_on_course_page()) {
872 return '';
875 $format = course_get_format($course);
876 $modinfo = $format->get_modinfo();
877 // Output renderers works only with real section_info objects.
878 if ($sectionreturn) {
879 $format->set_section_number($sectionreturn);
881 $section = $modinfo->get_section_info($format->get_section_number());
883 $cmclass = $format->get_output_classname('content\\section\\cm');
884 $cm = new $cmclass($format, $section, $mod, $displayoptions);
885 // The course outputs works with format renderers, not with course renderers.
886 $renderer = $format->get_renderer($this->page);
887 $data = $cm->export_for_template($renderer);
888 return $this->output->render_from_template('core_courseformat/local/content/cm', $data);
892 * Message displayed to the user when they try to access unavailable activity following URL
894 * This method is a very simplified version of {@link course_section_cm()} to be part of the error
895 * notification only. It also does not check if module is visible on course page or not.
897 * The message will be displayed inside notification!
899 * @param cm_info $cm
900 * @return string
902 public function course_section_cm_unavailable_error_message(cm_info $cm) {
903 if ($cm->uservisible) {
904 return null;
906 if (!$cm->availableinfo) {
907 return get_string('activityiscurrentlyhidden');
910 $altname = get_accesshide(' ' . $cm->modfullname);
911 $name = html_writer::empty_tag('img', array('src' => $cm->get_icon_url(),
912 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
913 html_writer::tag('span', ' '.$cm->get_formatted_name() . $altname, array('class' => 'instancename'));
914 $formattedinfo = \core_availability\info::format_info($cm->availableinfo, $cm->get_course());
915 return html_writer::div($name, 'activityinstance-error') .
916 html_writer::div($formattedinfo, 'availabilityinfo-error');
920 * Renders HTML to display a list of course modules in a course section
921 * Also displays "move here" controls in Javascript-disabled mode.
923 * @deprecated since 4.0 - use core_course output components instead.
925 * This function calls {@link core_course_renderer::course_section_cm()}
927 * @param stdClass $course course object
928 * @param int|stdClass|section_info $section relative section number or section object
929 * @param int $sectionreturn section number to return to
930 * @param int $displayoptions
931 * @return void
933 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = []) {
934 global $USER;
936 debugging('course_section_cm_list is deprecated. Use core_course\\output\\section_format\\cmlist '.
937 'classes instead.', DEBUG_DEVELOPER);
939 $output = '';
941 $format = course_get_format($course);
942 $modinfo = $format->get_modinfo();
944 if (is_object($section)) {
945 $section = $modinfo->get_section_info($section->section);
946 } else {
947 $section = $modinfo->get_section_info($section);
949 $completioninfo = new completion_info($course);
951 // check if we are currently in the process of moving a module with JavaScript disabled
952 $ismoving = $format->show_editor() && ismoving($course->id);
954 if ($ismoving) {
955 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
958 // Get the list of modules visible to user (excluding the module being moved if there is one)
959 $moduleshtml = [];
960 if (!empty($modinfo->sections[$section->section])) {
961 foreach ($modinfo->sections[$section->section] as $modnumber) {
962 $mod = $modinfo->cms[$modnumber];
964 if ($ismoving and $mod->id == $USER->activitycopy) {
965 // do not display moving mod
966 continue;
969 if ($modulehtml = $this->course_section_cm_list_item($course,
970 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
971 $moduleshtml[$modnumber] = $modulehtml;
976 $sectionoutput = '';
977 if (!empty($moduleshtml) || $ismoving) {
978 foreach ($moduleshtml as $modnumber => $modulehtml) {
979 if ($ismoving) {
980 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
981 $sectionoutput .= html_writer::tag('li',
982 html_writer::link($movingurl, '', array('title' => $strmovefull, 'class' => 'movehere')),
983 array('class' => 'movehere'));
986 $sectionoutput .= $modulehtml;
989 if ($ismoving) {
990 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
991 $sectionoutput .= html_writer::tag('li',
992 html_writer::link($movingurl, '', array('title' => $strmovefull, 'class' => 'movehere')),
993 array('class' => 'movehere'));
997 // Always output the section module list.
998 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1000 return $output;
1004 * Displays a custom list of courses with paging bar if necessary
1006 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1007 * appears under the list.
1009 * If both $paginationurl and $totalcount are specified, and $totalcount is
1010 * bigger than count($courses), a paging bar is displayed above and under the
1011 * courses list.
1013 * @param array $courses array of course records (or instances of core_course_list_element) to show on this page
1014 * @param bool $showcategoryname whether to add category name to the course description
1015 * @param string $additionalclasses additional CSS classes to add to the div.courses
1016 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1017 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1018 * @param int $page current page number (defaults to 0 referring to the first page)
1019 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1020 * @return string
1022 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1023 global $CFG;
1024 // create instance of coursecat_helper to pass display options to function rendering courses list
1025 $chelper = new coursecat_helper();
1026 if ($showcategoryname) {
1027 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1028 } else {
1029 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1031 if ($totalcount !== null && $paginationurl !== null) {
1032 // add options to display pagination
1033 if ($perpage === null) {
1034 $perpage = $CFG->coursesperpage;
1036 $chelper->set_courses_display_options(array(
1037 'limit' => $perpage,
1038 'offset' => ((int)$page) * $perpage,
1039 'paginationurl' => $paginationurl,
1041 } else if ($paginationurl !== null) {
1042 // add options to display 'View more' link
1043 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1044 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1046 $chelper->set_attributes(array('class' => $additionalclasses));
1047 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1048 return $content;
1052 * Returns HTML to display course name.
1054 * @param coursecat_helper $chelper
1055 * @param core_course_list_element $course
1056 * @return string
1058 protected function course_name(coursecat_helper $chelper, core_course_list_element $course): string {
1059 $content = '';
1060 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1061 $nametag = 'h3';
1062 } else {
1063 $nametag = 'div';
1065 $coursename = $chelper->get_course_formatted_name($course);
1066 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', ['id' => $course->id]),
1067 $coursename, ['class' => $course->visible ? 'aalink' : 'aalink dimmed']);
1068 $content .= html_writer::tag($nametag, $coursenamelink, ['class' => 'coursename']);
1069 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1070 $content .= html_writer::start_tag('div', ['class' => 'moreinfo']);
1071 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1072 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()
1073 || $course->has_custom_fields()) {
1074 $url = new moodle_url('/course/info.php', ['id' => $course->id]);
1075 $image = $this->output->pix_icon('i/info', $this->strings->summary);
1076 $content .= html_writer::link($url, $image, ['title' => $this->strings->summary]);
1077 // Make sure JS file to expand course content is included.
1078 $this->coursecat_include_js();
1081 $content .= html_writer::end_tag('div');
1082 return $content;
1086 * Returns HTML to display course enrolment icons.
1088 * @param core_course_list_element $course
1089 * @return string
1091 protected function course_enrolment_icons(core_course_list_element $course): string {
1092 $content = '';
1093 if ($icons = enrol_get_course_info_icons($course)) {
1094 $content .= html_writer::start_tag('div', ['class' => 'enrolmenticons']);
1095 foreach ($icons as $icon) {
1096 $content .= $this->render($icon);
1098 $content .= html_writer::end_tag('div');
1100 return $content;
1104 * Displays one course in the list of courses.
1106 * This is an internal function, to display an information about just one course
1107 * please use {@link core_course_renderer::course_info_box()}
1109 * @param coursecat_helper $chelper various display options
1110 * @param core_course_list_element|stdClass $course
1111 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1112 * depend on the course position in list - first/last/even/odd)
1113 * @return string
1115 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1116 if (!isset($this->strings->summary)) {
1117 $this->strings->summary = get_string('summary');
1119 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1120 return '';
1122 if ($course instanceof stdClass) {
1123 $course = new core_course_list_element($course);
1125 $content = '';
1126 $classes = trim('coursebox clearfix '. $additionalclasses);
1127 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1128 $classes .= ' collapsed';
1131 // .coursebox
1132 $content .= html_writer::start_tag('div', array(
1133 'class' => $classes,
1134 'data-courseid' => $course->id,
1135 'data-type' => self::COURSECAT_TYPE_COURSE,
1138 $content .= html_writer::start_tag('div', array('class' => 'info'));
1139 $content .= $this->course_name($chelper, $course);
1140 $content .= $this->course_enrolment_icons($course);
1141 $content .= html_writer::end_tag('div');
1143 $content .= html_writer::start_tag('div', array('class' => 'content'));
1144 $content .= $this->coursecat_coursebox_content($chelper, $course);
1145 $content .= html_writer::end_tag('div');
1147 $content .= html_writer::end_tag('div'); // .coursebox
1148 return $content;
1152 * Returns HTML to display course summary.
1154 * @param coursecat_helper $chelper
1155 * @param core_course_list_element $course
1156 * @return string
1158 protected function course_summary(coursecat_helper $chelper, core_course_list_element $course): string {
1159 $content = '';
1160 if ($course->has_summary()) {
1161 $content .= html_writer::start_tag('div', ['class' => 'summary']);
1162 $content .= $chelper->get_course_formatted_summary($course,
1163 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1164 $content .= html_writer::end_tag('div');
1166 return $content;
1170 * Returns HTML to display course contacts.
1172 * @param core_course_list_element $course
1173 * @return string
1175 protected function course_contacts(core_course_list_element $course) {
1176 $content = '';
1177 if ($course->has_course_contacts()) {
1178 $content .= html_writer::start_tag('ul', ['class' => 'teachers']);
1179 foreach ($course->get_course_contacts() as $coursecontact) {
1180 $rolenames = array_map(function ($role) {
1181 return $role->displayname;
1182 }, $coursecontact['roles']);
1183 $name = implode(", ", $rolenames).': '.
1184 html_writer::link(new moodle_url('/user/view.php',
1185 ['id' => $coursecontact['user']->id, 'course' => SITEID]),
1186 $coursecontact['username']);
1187 $content .= html_writer::tag('li', $name);
1189 $content .= html_writer::end_tag('ul');
1191 return $content;
1195 * Returns HTML to display course overview files.
1197 * @param core_course_list_element $course
1198 * @return string
1200 protected function course_overview_files(core_course_list_element $course): string {
1201 global $CFG;
1203 $contentimages = $contentfiles = '';
1204 foreach ($course->get_course_overviewfiles() as $file) {
1205 $isimage = $file->is_valid_image();
1206 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php",
1207 '/' . $file->get_contextid() . '/' . $file->get_component() . '/' .
1208 $file->get_filearea() . $file->get_filepath() . $file->get_filename(), !$isimage);
1209 if ($isimage) {
1210 $contentimages .= html_writer::tag('div',
1211 html_writer::empty_tag('img', ['src' => $url]),
1212 ['class' => 'courseimage']);
1213 } else {
1214 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1215 $filename = html_writer::tag('span', $image, ['class' => 'fp-icon']).
1216 html_writer::tag('span', $file->get_filename(), ['class' => 'fp-filename']);
1217 $contentfiles .= html_writer::tag('span',
1218 html_writer::link($url, $filename),
1219 ['class' => 'coursefile fp-filename-icon']);
1222 return $contentimages . $contentfiles;
1226 * Returns HTML to display course category name.
1228 * @param coursecat_helper $chelper
1229 * @param core_course_list_element $course
1230 * @return string
1232 protected function course_category_name(coursecat_helper $chelper, core_course_list_element $course): string {
1233 $content = '';
1234 // Display course category if necessary (for example in search results).
1235 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1236 if ($cat = core_course_category::get($course->category, IGNORE_MISSING)) {
1237 $content .= html_writer::start_tag('div', ['class' => 'coursecat']);
1238 $content .= get_string('category').': '.
1239 html_writer::link(new moodle_url('/course/index.php', ['categoryid' => $cat->id]),
1240 $cat->get_formatted_name(), ['class' => $cat->visible ? '' : 'dimmed']);
1241 $content .= html_writer::end_tag('div');
1244 return $content;
1248 * Returns HTML to display course custom fields.
1250 * @param core_course_list_element $course
1251 * @return string
1253 protected function course_custom_fields(core_course_list_element $course): string {
1254 $content = '';
1255 if ($course->has_custom_fields()) {
1256 $handler = core_course\customfield\course_handler::create();
1257 $customfields = $handler->display_custom_fields_data($course->get_custom_fields());
1258 $content .= \html_writer::tag('div', $customfields, ['class' => 'customfields-container']);
1260 return $content;
1264 * Returns HTML to display course content (summary, course contacts and optionally category name)
1266 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1268 * @param coursecat_helper $chelper various display options
1269 * @param stdClass|core_course_list_element $course
1270 * @return string
1272 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1273 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1274 return '';
1276 if ($course instanceof stdClass) {
1277 $course = new core_course_list_element($course);
1279 $content = $this->course_summary($chelper, $course);
1280 $content .= $this->course_overview_files($course);
1281 $content .= $this->course_contacts($course);
1282 $content .= $this->course_category_name($chelper, $course);
1283 $content .= $this->course_custom_fields($course);
1284 return $content;
1288 * Renders the list of courses
1290 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1291 * method from outside of the class
1293 * If list of courses is specified in $courses; the argument $chelper is only used
1294 * to retrieve display options and attributes, only methods get_show_courses(),
1295 * get_courses_display_option() and get_and_erase_attributes() are called.
1297 * @param coursecat_helper $chelper various display options
1298 * @param array $courses the list of courses to display
1299 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1300 * defaulted to count($courses)
1301 * @return string
1303 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1304 global $CFG;
1305 if ($totalcount === null) {
1306 $totalcount = count($courses);
1308 if (!$totalcount) {
1309 // Courses count is cached during courses retrieval.
1310 return '';
1313 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1314 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1315 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1316 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1317 } else {
1318 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1322 // prepare content of paging bar if it is needed
1323 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1324 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1325 if ($totalcount > count($courses)) {
1326 // there are more results that can fit on one page
1327 if ($paginationurl) {
1328 // the option paginationurl was specified, display pagingbar
1329 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1330 $page = $chelper->get_courses_display_option('offset') / $perpage;
1331 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1332 $paginationurl->out(false, array('perpage' => $perpage)));
1333 if ($paginationallowall) {
1334 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1335 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1337 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1338 // the option for 'View more' link was specified, display more link
1339 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1340 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1341 array('class' => 'paging paging-morelink'));
1343 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1344 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1345 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1346 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1349 // display list of courses
1350 $attributes = $chelper->get_and_erase_attributes('courses');
1351 $content = html_writer::start_tag('div', $attributes);
1353 if (!empty($pagingbar)) {
1354 $content .= $pagingbar;
1357 $coursecount = 0;
1358 foreach ($courses as $course) {
1359 $coursecount ++;
1360 $classes = ($coursecount%2) ? 'odd' : 'even';
1361 if ($coursecount == 1) {
1362 $classes .= ' first';
1364 if ($coursecount >= count($courses)) {
1365 $classes .= ' last';
1367 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1370 if (!empty($pagingbar)) {
1371 $content .= $pagingbar;
1373 if (!empty($morelink)) {
1374 $content .= $morelink;
1377 $content .= html_writer::end_tag('div'); // .courses
1378 return $content;
1382 * Renders the list of subcategories in a category
1384 * @param coursecat_helper $chelper various display options
1385 * @param core_course_category $coursecat
1386 * @param int $depth depth of the category in the current tree
1387 * @return string
1389 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1390 global $CFG;
1391 $subcategories = array();
1392 if (!$chelper->get_categories_display_option('nodisplay')) {
1393 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1395 $totalcount = $coursecat->get_children_count();
1396 if (!$totalcount) {
1397 // Note that we call core_course_category::get_children_count() AFTER core_course_category::get_children()
1398 // to avoid extra DB requests.
1399 // Categories count is cached during children categories retrieval.
1400 return '';
1403 // prepare content of paging bar or more link if it is needed
1404 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1405 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1406 if ($totalcount > count($subcategories)) {
1407 if ($paginationurl) {
1408 // the option 'paginationurl was specified, display pagingbar
1409 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1410 $page = $chelper->get_categories_display_option('offset') / $perpage;
1411 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1412 $paginationurl->out(false, array('perpage' => $perpage)));
1413 if ($paginationallowall) {
1414 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1415 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1417 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1418 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1419 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1420 $viewmoreurl->param('categoryid', $coursecat->id);
1422 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1423 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1424 array('class' => 'paging paging-morelink'));
1426 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1427 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1428 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1429 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1432 // display list of subcategories
1433 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1435 if (!empty($pagingbar)) {
1436 $content .= $pagingbar;
1439 foreach ($subcategories as $subcategory) {
1440 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1443 if (!empty($pagingbar)) {
1444 $content .= $pagingbar;
1446 if (!empty($morelink)) {
1447 $content .= $morelink;
1450 $content .= html_writer::end_tag('div');
1451 return $content;
1455 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1457 protected function coursecat_include_js() {
1458 if (!$this->page->requires->should_create_one_time_item_now('core_course_categoryexpanderjsinit')) {
1459 return;
1462 // We must only load this module once.
1463 $this->page->requires->yui_module('moodle-course-categoryexpander',
1464 'Y.Moodle.course.categoryexpander.init');
1468 * Returns HTML to display the subcategories and courses in the given category
1470 * This method is re-used by AJAX to expand content of not loaded category
1472 * @param coursecat_helper $chelper various display options
1473 * @param core_course_category $coursecat
1474 * @param int $depth depth of the category in the current tree
1475 * @return string
1477 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1478 $content = '';
1479 // Subcategories
1480 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1482 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1483 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1484 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1485 if ($showcoursesauto && $depth) {
1486 // this is definitely collapsed mode
1487 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1490 // Courses
1491 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1492 $courses = array();
1493 if (!$chelper->get_courses_display_option('nodisplay')) {
1494 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1496 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1497 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1498 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1499 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1502 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1505 if ($showcoursesauto) {
1506 // restore the show_courses back to AUTO
1507 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1510 return $content;
1514 * Returns HTML to display a course category as a part of a tree
1516 * This is an internal function, to display a particular category and all its contents
1517 * use {@link core_course_renderer::course_category()}
1519 * @param coursecat_helper $chelper various display options
1520 * @param core_course_category $coursecat
1521 * @param int $depth depth of this category in the current tree
1522 * @return string
1524 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1525 // open category tag
1526 $classes = array('category');
1527 if (empty($coursecat->visible)) {
1528 $classes[] = 'dimmed_category';
1530 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1531 // do not load content
1532 $categorycontent = '';
1533 $classes[] = 'notloaded';
1534 if ($coursecat->get_children_count() ||
1535 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1536 $classes[] = 'with_children';
1537 $classes[] = 'collapsed';
1539 } else {
1540 // load category content
1541 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1542 $classes[] = 'loaded';
1543 if (!empty($categorycontent)) {
1544 $classes[] = 'with_children';
1545 // Category content loaded with children.
1546 $this->categoryexpandedonload = true;
1550 // Make sure JS file to expand category content is included.
1551 $this->coursecat_include_js();
1553 $content = html_writer::start_tag('div', array(
1554 'class' => join(' ', $classes),
1555 'data-categoryid' => $coursecat->id,
1556 'data-depth' => $depth,
1557 'data-showcourses' => $chelper->get_show_courses(),
1558 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1561 // category name
1562 $categoryname = $coursecat->get_formatted_name();
1563 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1564 array('categoryid' => $coursecat->id)),
1565 $categoryname);
1566 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1567 && ($coursescount = $coursecat->get_courses_count())) {
1568 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1569 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1571 $content .= html_writer::start_tag('div', array('class' => 'info'));
1573 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname aabtn'));
1574 $content .= html_writer::end_tag('div'); // .info
1576 // add category content to the output
1577 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1579 $content .= html_writer::end_tag('div'); // .category
1581 // Return the course category tree HTML
1582 return $content;
1586 * Returns HTML to display a tree of subcategories and courses in the given category
1588 * @param coursecat_helper $chelper various display options
1589 * @param core_course_category $coursecat top category (this category's name and description will NOT be added to the tree)
1590 * @return string
1592 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1593 // Reset the category expanded flag for this course category tree first.
1594 $this->categoryexpandedonload = false;
1595 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1596 if (empty($categorycontent)) {
1597 return '';
1600 // Start content generation
1601 $content = '';
1602 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1603 $content .= html_writer::start_tag('div', $attributes);
1605 if ($coursecat->get_children_count()) {
1606 $classes = array(
1607 'collapseexpand', 'aabtn'
1610 // Check if the category content contains subcategories with children's content loaded.
1611 if ($this->categoryexpandedonload) {
1612 $classes[] = 'collapse-all';
1613 $linkname = get_string('collapseall');
1614 } else {
1615 $linkname = get_string('expandall');
1618 // Only show the collapse/expand if there are children to expand.
1619 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1620 $content .= html_writer::link('#', $linkname, array('class' => implode(' ', $classes)));
1621 $content .= html_writer::end_tag('div');
1622 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1625 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1627 $content .= html_writer::end_tag('div'); // .course_category_tree
1629 return $content;
1633 * Renders HTML to display particular course category - list of it's subcategories and courses
1635 * Invoked from /course/index.php
1637 * @param int|stdClass|core_course_category $category
1639 public function course_category($category) {
1640 global $CFG;
1641 $usertop = core_course_category::user_top();
1642 if (empty($category)) {
1643 $coursecat = $usertop;
1644 } else if (is_object($category) && $category instanceof core_course_category) {
1645 $coursecat = $category;
1646 } else {
1647 $coursecat = core_course_category::get(is_object($category) ? $category->id : $category);
1649 $site = get_site();
1650 $output = '';
1652 if ($coursecat->can_create_course() || $coursecat->has_manage_capability()) {
1653 // Add 'Manage' button if user has permissions to edit this category.
1654 $managebutton = $this->single_button(new moodle_url('/course/management.php',
1655 array('categoryid' => $coursecat->id)), get_string('managecourses'), 'get');
1656 $this->page->set_button($managebutton);
1659 if (core_course_category::is_simple_site()) {
1660 // There is only one category in the system, do not display link to it.
1661 $strfulllistofcourses = get_string('fulllistofcourses');
1662 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1663 } else if (!$coursecat->id || !$coursecat->is_uservisible()) {
1664 $strcategories = get_string('categories');
1665 $this->page->set_title("$site->shortname: $strcategories");
1666 } else {
1667 $strfulllistofcourses = get_string('fulllistofcourses');
1668 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1670 // Print the category selector
1671 $categorieslist = core_course_category::make_categories_list();
1672 if (count($categorieslist) > 1) {
1673 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1674 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1675 core_course_category::make_categories_list(), $coursecat->id, null, 'switchcategory');
1676 $select->set_label(get_string('categories').':');
1677 $output .= $this->render($select);
1678 $output .= html_writer::end_tag('div'); // .categorypicker
1682 // Print current category description
1683 $chelper = new coursecat_helper();
1684 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1685 $output .= $this->box($description, array('class' => 'generalbox info'));
1688 // Prepare parameters for courses and categories lists in the tree
1689 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1690 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1692 $coursedisplayoptions = array();
1693 $catdisplayoptions = array();
1694 $browse = optional_param('browse', null, PARAM_ALPHA);
1695 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1696 $page = optional_param('page', 0, PARAM_INT);
1697 $baseurl = new moodle_url('/course/index.php');
1698 if ($coursecat->id) {
1699 $baseurl->param('categoryid', $coursecat->id);
1701 if ($perpage != $CFG->coursesperpage) {
1702 $baseurl->param('perpage', $perpage);
1704 $coursedisplayoptions['limit'] = $perpage;
1705 $catdisplayoptions['limit'] = $perpage;
1706 if ($browse === 'courses' || !$coursecat->get_children_count()) {
1707 $coursedisplayoptions['offset'] = $page * $perpage;
1708 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1709 $catdisplayoptions['nodisplay'] = true;
1710 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1711 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1712 } else if ($browse === 'categories' || !$coursecat->get_courses_count()) {
1713 $coursedisplayoptions['nodisplay'] = true;
1714 $catdisplayoptions['offset'] = $page * $perpage;
1715 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1716 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1717 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1718 } else {
1719 // we have a category that has both subcategories and courses, display pagination separately
1720 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1721 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1723 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1724 // Add course search form.
1725 $output .= $this->course_search_form();
1727 // Display course category tree.
1728 $output .= $this->coursecat_tree($chelper, $coursecat);
1730 // Add action buttons
1731 $output .= $this->container_start('buttons');
1732 if ($coursecat->is_uservisible()) {
1733 $context = get_category_or_system_context($coursecat->id);
1734 if (has_capability('moodle/course:create', $context)) {
1735 // Print link to create a new course, for the 1st available category.
1736 if ($coursecat->id) {
1737 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1738 } else {
1739 $url = new moodle_url('/course/edit.php',
1740 array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1742 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1744 ob_start();
1745 print_course_request_buttons($context);
1746 $output .= ob_get_contents();
1747 ob_end_clean();
1749 $output .= $this->container_end();
1751 return $output;
1755 * Serves requests to /course/category.ajax.php
1757 * In this renderer implementation it may expand the category content or
1758 * course content.
1760 * @return string
1761 * @throws coding_exception
1763 public function coursecat_ajax() {
1764 global $DB, $CFG;
1766 $type = required_param('type', PARAM_INT);
1768 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1769 // This is a request for a category list of some kind.
1770 $categoryid = required_param('categoryid', PARAM_INT);
1771 $showcourses = required_param('showcourses', PARAM_INT);
1772 $depth = required_param('depth', PARAM_INT);
1774 $category = core_course_category::get($categoryid);
1776 $chelper = new coursecat_helper();
1777 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1778 $coursedisplayoptions = array(
1779 'limit' => $CFG->coursesperpage,
1780 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1782 $catdisplayoptions = array(
1783 'limit' => $CFG->coursesperpage,
1784 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1786 $chelper->set_show_courses($showcourses)->
1787 set_courses_display_options($coursedisplayoptions)->
1788 set_categories_display_options($catdisplayoptions);
1790 return $this->coursecat_category_content($chelper, $category, $depth);
1791 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1792 // This is a request for the course information.
1793 $courseid = required_param('courseid', PARAM_INT);
1795 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1797 $chelper = new coursecat_helper();
1798 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1799 return $this->coursecat_coursebox_content($chelper, $course);
1800 } else {
1801 throw new coding_exception('Invalid request type');
1806 * Renders html to display search result page
1808 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1809 * @return string
1811 public function search_courses($searchcriteria) {
1812 global $CFG;
1813 $content = '';
1815 $search = '';
1816 if (!empty($searchcriteria['search'])) {
1817 $search = $searchcriteria['search'];
1819 $content .= $this->course_search_form($search);
1821 if (!empty($searchcriteria)) {
1822 // print search results
1824 $displayoptions = array('sort' => array('displayname' => 1));
1825 // take the current page and number of results per page from query
1826 $perpage = optional_param('perpage', 0, PARAM_RAW);
1827 if ($perpage !== 'all') {
1828 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1829 $page = optional_param('page', 0, PARAM_INT);
1830 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1832 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1833 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1834 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1836 $class = 'course-search-result';
1837 foreach ($searchcriteria as $key => $value) {
1838 if (!empty($value)) {
1839 $class .= ' course-search-result-'. $key;
1842 $chelper = new coursecat_helper();
1843 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1844 set_courses_display_options($displayoptions)->
1845 set_search_criteria($searchcriteria)->
1846 set_attributes(array('class' => $class));
1848 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1849 $totalcount = core_course_category::search_courses_count($searchcriteria);
1850 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1852 if (!$totalcount) {
1853 if (!empty($searchcriteria['search'])) {
1854 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1855 } else {
1856 $content .= $this->heading(get_string('novalidcourses'));
1858 } else {
1859 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1860 $content .= $courseslist;
1863 return $content;
1867 * Renders html to print list of courses tagged with particular tag
1869 * @param int $tagid id of the tag
1870 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1871 * are displayed on the page and the per-page limit may be bigger
1872 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1873 * to display items in the same context first
1874 * @param int $ctx context id where to search for records
1875 * @param bool $rec search in subcontexts as well
1876 * @param array $displayoptions
1877 * @return string empty string if no courses are marked with this tag or rendered list of courses
1879 public function tagged_courses($tagid, $exclusivemode = true, $ctx = 0, $rec = true, $displayoptions = null) {
1880 global $CFG;
1881 if (empty($displayoptions)) {
1882 $displayoptions = array();
1884 $showcategories = !core_course_category::is_simple_site();
1885 $displayoptions += array('limit' => $CFG->coursesperpage, 'offset' => 0);
1886 $chelper = new coursecat_helper();
1887 $searchcriteria = array('tagid' => $tagid, 'ctx' => $ctx, 'rec' => $rec);
1888 $chelper->set_show_courses($showcategories ? self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT :
1889 self::COURSECAT_SHOW_COURSES_EXPANDED)->
1890 set_search_criteria($searchcriteria)->
1891 set_courses_display_options($displayoptions)->
1892 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1893 // (we set the same css class as in search results by tagid)
1894 if ($totalcount = core_course_category::search_courses_count($searchcriteria)) {
1895 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1896 if ($exclusivemode) {
1897 return $this->coursecat_courses($chelper, $courses, $totalcount);
1898 } else {
1899 $tagfeed = new core_tag\output\tagfeed();
1900 $img = $this->output->pix_icon('i/course', '');
1901 foreach ($courses as $course) {
1902 $url = course_get_url($course);
1903 $imgwithlink = html_writer::link($url, $img);
1904 $coursename = html_writer::link($url, $course->get_formatted_name());
1905 $details = '';
1906 if ($showcategories && ($cat = core_course_category::get($course->category, IGNORE_MISSING))) {
1907 $details = get_string('category').': '.
1908 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1909 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1911 $tagfeed->add($imgwithlink, $coursename, $details);
1913 return $this->output->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($this->output));
1916 return '';
1920 * Returns HTML to display one remote course
1922 * @param stdClass $course remote course information, contains properties:
1923 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1924 * @return string
1926 protected function frontpage_remote_course(stdClass $course) {
1927 $url = new moodle_url('/auth/mnet/jump.php', array(
1928 'hostid' => $course->hostid,
1929 'wantsurl' => '/course/view.php?id='. $course->remoteid
1932 $output = '';
1933 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1934 $output .= html_writer::start_tag('div', array('class' => 'info'));
1935 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1936 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1937 $output .= html_writer::end_tag('h3'); // .name
1938 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1939 $output .= html_writer::end_tag('div'); // .info
1940 $output .= html_writer::start_tag('div', array('class' => 'content'));
1941 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1942 $options = new stdClass();
1943 $options->noclean = true;
1944 $options->para = false;
1945 $options->overflowdiv = true;
1946 $output .= format_text($course->summary, $course->summaryformat, $options);
1947 $output .= html_writer::end_tag('div'); // .summary
1948 $addinfo = format_string($course->hostname) . ' : '
1949 . format_string($course->cat_name) . ' : '
1950 . format_string($course->shortname);
1951 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1952 $output .= html_writer::end_tag('div'); // .content
1953 $output .= html_writer::end_tag('div'); // .coursebox
1954 return $output;
1958 * Returns HTML to display one remote host
1960 * @param array $host host information, contains properties: name, url, count
1961 * @return string
1963 protected function frontpage_remote_host($host) {
1964 $output = '';
1965 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1966 $output .= html_writer::start_tag('div', array('class' => 'info'));
1967 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1968 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1969 $output .= html_writer::end_tag('h3'); // .name
1970 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1971 $output .= html_writer::end_tag('div'); // .info
1972 $output .= html_writer::start_tag('div', array('class' => 'content'));
1973 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1974 $output .= $host['count'] . ' ' . get_string('courses');
1975 $output .= html_writer::end_tag('div'); // .content
1976 $output .= html_writer::end_tag('div'); // .coursebox
1977 return $output;
1981 * Returns HTML to print list of courses user is enrolled to for the frontpage
1983 * Also lists remote courses or remote hosts if MNET authorisation is used
1985 * @return string
1987 public function frontpage_my_courses() {
1988 global $USER, $CFG, $DB;
1990 if (!isloggedin() or isguestuser()) {
1991 return '';
1994 $output = '';
1995 $courses = enrol_get_my_courses('summary, summaryformat');
1996 $rhosts = array();
1997 $rcourses = array();
1998 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1999 $rcourses = get_my_remotecourses($USER->id);
2000 $rhosts = get_my_remotehosts();
2003 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2005 $chelper = new coursecat_helper();
2006 $totalcount = count($courses);
2007 if (count($courses) > $CFG->frontpagecourselimit) {
2008 // There are more enrolled courses than we can display, display link to 'My courses'.
2009 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
2010 $chelper->set_courses_display_options(array(
2011 'viewmoreurl' => new moodle_url('/my/'),
2012 'viewmoretext' => new lang_string('mycourses')
2014 } else if (core_course_category::top()->is_uservisible()) {
2015 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
2016 $chelper->set_courses_display_options(array(
2017 'viewmoreurl' => new moodle_url('/course/index.php'),
2018 'viewmoretext' => new lang_string('fulllistofcourses')
2020 $totalcount = $DB->count_records('course') - 1;
2022 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2023 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
2024 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
2026 // MNET
2027 if (!empty($rcourses)) {
2028 // at the IDP, we know of all the remote courses
2029 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2030 foreach ($rcourses as $course) {
2031 $output .= $this->frontpage_remote_course($course);
2033 $output .= html_writer::end_tag('div'); // .courses
2034 } elseif (!empty($rhosts)) {
2035 // non-IDP, we know of all the remote servers, but not courses
2036 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2037 foreach ($rhosts as $host) {
2038 $output .= $this->frontpage_remote_host($host);
2040 $output .= html_writer::end_tag('div'); // .courses
2043 return $output;
2047 * Returns HTML to print list of available courses for the frontpage
2049 * @return string
2051 public function frontpage_available_courses() {
2052 global $CFG;
2054 $chelper = new coursecat_helper();
2055 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2056 set_courses_display_options(array(
2057 'recursive' => true,
2058 'limit' => $CFG->frontpagecourselimit,
2059 'viewmoreurl' => new moodle_url('/course/index.php'),
2060 'viewmoretext' => new lang_string('fulllistofcourses')));
2062 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
2063 $courses = core_course_category::top()->get_courses($chelper->get_courses_display_options());
2064 $totalcount = core_course_category::top()->get_courses_count($chelper->get_courses_display_options());
2065 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
2066 // Print link to create a new course, for the 1st available category.
2067 return $this->add_new_course_button();
2069 return $this->coursecat_courses($chelper, $courses, $totalcount);
2073 * Returns HTML to the "add new course" button for the page
2075 * @return string
2077 public function add_new_course_button() {
2078 global $CFG;
2079 // Print link to create a new course, for the 1st available category.
2080 $output = $this->container_start('buttons');
2081 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2082 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2083 $output .= $this->container_end('buttons');
2084 return $output;
2088 * Returns HTML to print tree with course categories and courses for the frontpage
2090 * @return string
2092 public function frontpage_combo_list() {
2093 global $CFG;
2094 // TODO MDL-10965 improve.
2095 $tree = core_course_category::top();
2096 if (!$tree->get_children_count()) {
2097 return '';
2099 $chelper = new coursecat_helper();
2100 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2101 set_categories_display_options(array(
2102 'limit' => $CFG->coursesperpage,
2103 'viewmoreurl' => new moodle_url('/course/index.php',
2104 array('browse' => 'categories', 'page' => 1))
2105 ))->
2106 set_courses_display_options(array(
2107 'limit' => $CFG->coursesperpage,
2108 'viewmoreurl' => new moodle_url('/course/index.php',
2109 array('browse' => 'courses', 'page' => 1))
2110 ))->
2111 set_attributes(array('class' => 'frontpage-category-combo'));
2112 return $this->coursecat_tree($chelper, $tree);
2116 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2118 * @return string
2120 public function frontpage_categories_list() {
2121 global $CFG;
2122 // TODO MDL-10965 improve.
2123 $tree = core_course_category::top();
2124 if (!$tree->get_children_count()) {
2125 return '';
2127 $chelper = new coursecat_helper();
2128 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2129 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2130 set_categories_display_options(array(
2131 'limit' => $CFG->coursesperpage,
2132 'viewmoreurl' => new moodle_url('/course/index.php',
2133 array('browse' => 'categories', 'page' => 1))
2134 ))->
2135 set_attributes(array('class' => 'frontpage-category-names'));
2136 return $this->coursecat_tree($chelper, $tree);
2140 * Renders the activity information.
2142 * Defer to template.
2144 * @param \core_course\output\activity_information $page
2145 * @return string html for the page
2147 public function render_activity_information(\core_course\output\activity_information $page) {
2148 $data = $page->export_for_template($this->output);
2149 return $this->output->render_from_template('core_course/activity_info', $data);
2153 * Renders the activity navigation.
2155 * Defer to template.
2157 * @param \core_course\output\activity_navigation $page
2158 * @return string html for the page
2160 public function render_activity_navigation(\core_course\output\activity_navigation $page) {
2161 $data = $page->export_for_template($this->output);
2162 return $this->output->render_from_template('core_course/activity_navigation', $data);
2166 * Display waiting information about backup size during uploading backup process
2167 * @param object $backupfile the backup stored_file
2168 * @return $html string
2170 public function sendingbackupinfo($backupfile) {
2171 $sizeinfo = new stdClass();
2172 $sizeinfo->total = number_format($backupfile->get_filesize() / 1000000, 2);
2173 $html = html_writer::tag('div', get_string('sendingsize', 'hub', $sizeinfo),
2174 array('class' => 'courseuploadtextinfo'));
2175 return $html;
2179 * Hub information (logo - name - description - link)
2180 * @param object $hubinfo
2181 * @return string html code
2183 public function hubinfo($hubinfo) {
2184 $screenshothtml = html_writer::empty_tag('img',
2185 array('src' => $hubinfo['imgurl'], 'alt' => $hubinfo['name']));
2186 $hubdescription = html_writer::tag('div', $screenshothtml,
2187 array('class' => 'hubscreenshot'));
2189 $hubdescription .= html_writer::tag('a', $hubinfo['name'],
2190 array('class' => 'hublink', 'href' => $hubinfo['url'],
2191 'onclick' => 'this.target="_blank"'));
2193 $hubdescription .= html_writer::tag('div', format_text($hubinfo['description'], FORMAT_PLAIN),
2194 array('class' => 'hubdescription'));
2195 $hubdescription = html_writer::tag('div', $hubdescription, array('class' => 'hubinfo clearfix'));
2197 return $hubdescription;
2201 * Output frontpage summary text and frontpage modules (stored as section 1 in site course)
2203 * This may be disabled in settings
2205 * @return string
2207 public function frontpage_section1() {
2208 global $SITE, $USER;
2210 $output = '';
2211 $editing = $this->page->user_is_editing();
2213 if ($editing) {
2214 // Make sure section with number 1 exists.
2215 course_create_sections_if_missing($SITE, 1);
2218 $modinfo = get_fast_modinfo($SITE);
2219 $section = $modinfo->get_section_info(1);
2222 if (($section && (!empty($modinfo->sections[1]) or !empty($section->summary))) or $editing) {
2224 $format = course_get_format($SITE);
2225 $frontpageclass = $format->get_output_classname('content\\frontpagesection');
2226 $frontpagesection = new $frontpageclass($format, $section);
2228 // The course outputs works with format renderers, not with course renderers.
2229 $renderer = $format->get_renderer($this->page);
2230 $output .= $renderer->render($frontpagesection);
2233 return $output;
2237 * Output news for the frontpage (extract from site-wide news forum)
2239 * @param stdClass $forum record from db table 'forum' that represents the site news forum
2240 * @return string
2242 protected function frontpage_news($forum) {
2243 global $CFG, $SITE, $SESSION, $USER;
2244 require_once($CFG->dirroot .'/mod/forum/lib.php');
2246 $output = '';
2248 if (isloggedin()) {
2249 $SESSION->fromdiscussion = $CFG->wwwroot;
2250 $subtext = '';
2251 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forum)) {
2252 if (!\mod_forum\subscriptions::is_forcesubscribed($forum)) {
2253 $subtext = get_string('unsubscribe', 'forum');
2255 } else {
2256 $subtext = get_string('subscribe', 'forum');
2258 $suburl = new moodle_url('/mod/forum/subscribe.php', array('id' => $forum->id, 'sesskey' => sesskey()));
2259 $output .= html_writer::tag('div', html_writer::link($suburl, $subtext), array('class' => 'subscribelink'));
2262 $coursemodule = get_coursemodule_from_instance('forum', $forum->id);
2263 $context = context_module::instance($coursemodule->id);
2265 $entityfactory = mod_forum\local\container::get_entity_factory();
2266 $forumentity = $entityfactory->get_forum_from_stdclass($forum, $context, $coursemodule, $SITE);
2268 $rendererfactory = mod_forum\local\container::get_renderer_factory();
2269 $discussionsrenderer = $rendererfactory->get_frontpage_news_discussion_list_renderer($forumentity);
2270 $cm = \cm_info::create($coursemodule);
2271 return $output . $discussionsrenderer->render($USER, $cm, null, null, 0, $SITE->newsitems);
2275 * Renders part of frontpage with a skip link (i.e. "My courses", "Site news", etc.)
2277 * @param string $skipdivid
2278 * @param string $contentsdivid
2279 * @param string $header Header of the part
2280 * @param string $contents Contents of the part
2281 * @return string
2283 protected function frontpage_part($skipdivid, $contentsdivid, $header, $contents) {
2284 if (strval($contents) === '') {
2285 return '';
2287 $output = html_writer::link('#' . $skipdivid,
2288 get_string('skipa', 'access', core_text::strtolower(strip_tags($header))),
2289 array('class' => 'skip-block skip aabtn'));
2291 // Wrap frontpage part in div container.
2292 $output .= html_writer::start_tag('div', array('id' => $contentsdivid));
2293 $output .= $this->heading($header);
2295 $output .= $contents;
2297 // End frontpage part div container.
2298 $output .= html_writer::end_tag('div');
2300 $output .= html_writer::tag('span', '', array('class' => 'skip-block-to', 'id' => $skipdivid));
2301 return $output;
2305 * Outputs contents for frontpage as configured in $CFG->frontpage or $CFG->frontpageloggedin
2307 * @return string
2309 public function frontpage() {
2310 global $CFG, $SITE;
2312 $output = '';
2314 if (isloggedin() and !isguestuser() and isset($CFG->frontpageloggedin)) {
2315 $frontpagelayout = $CFG->frontpageloggedin;
2316 } else {
2317 $frontpagelayout = $CFG->frontpage;
2320 foreach (explode(',', $frontpagelayout) as $v) {
2321 switch ($v) {
2322 // Display the main part of the front page.
2323 case FRONTPAGENEWS:
2324 if ($SITE->newsitems) {
2325 // Print forums only when needed.
2326 require_once($CFG->dirroot .'/mod/forum/lib.php');
2327 if (($newsforum = forum_get_course_forum($SITE->id, 'news')) &&
2328 ($forumcontents = $this->frontpage_news($newsforum))) {
2329 $newsforumcm = get_fast_modinfo($SITE)->instances['forum'][$newsforum->id];
2330 $output .= $this->frontpage_part('skipsitenews', 'site-news-forum',
2331 $newsforumcm->get_formatted_name(), $forumcontents);
2334 break;
2336 case FRONTPAGEENROLLEDCOURSELIST:
2337 $mycourseshtml = $this->frontpage_my_courses();
2338 if (!empty($mycourseshtml)) {
2339 $output .= $this->frontpage_part('skipmycourses', 'frontpage-course-list',
2340 get_string('mycourses'), $mycourseshtml);
2342 break;
2344 case FRONTPAGEALLCOURSELIST:
2345 $availablecourseshtml = $this->frontpage_available_courses();
2346 $output .= $this->frontpage_part('skipavailablecourses', 'frontpage-available-course-list',
2347 get_string('availablecourses'), $availablecourseshtml);
2348 break;
2350 case FRONTPAGECATEGORYNAMES:
2351 $output .= $this->frontpage_part('skipcategories', 'frontpage-category-names',
2352 get_string('categories'), $this->frontpage_categories_list());
2353 break;
2355 case FRONTPAGECATEGORYCOMBO:
2356 $output .= $this->frontpage_part('skipcourses', 'frontpage-category-combo',
2357 get_string('courses'), $this->frontpage_combo_list());
2358 break;
2360 case FRONTPAGECOURSESEARCH:
2361 $output .= $this->box($this->course_search_form(''), 'd-flex justify-content-center');
2362 break;
2365 $output .= '<br />';
2368 return $output;
2373 * Class storing display options and functions to help display course category and/or courses lists
2375 * This is a wrapper for core_course_category objects that also stores display options
2376 * and functions to retrieve sorted and paginated lists of categories/courses.
2378 * If theme overrides methods in core_course_renderers that access this class
2379 * it may as well not use this class at all or extend it.
2381 * @package core
2382 * @copyright 2013 Marina Glancy
2383 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2385 class coursecat_helper {
2386 /** @var string [none, collapsed, expanded] how (if) display courses list */
2387 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2388 /** @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) */
2389 protected $subcatdepth = 1;
2390 /** @var array options to display courses list */
2391 protected $coursesdisplayoptions = array();
2392 /** @var array options to display subcategories list */
2393 protected $categoriesdisplayoptions = array();
2394 /** @var array additional HTML attributes */
2395 protected $attributes = array();
2396 /** @var array search criteria if the list is a search result */
2397 protected $searchcriteria = null;
2400 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2402 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2403 * @return coursecat_helper
2405 public function set_show_courses($showcourses) {
2406 $this->showcourses = $showcourses;
2407 // Automatically set the options to preload summary and coursecontacts for core_course_category::get_courses()
2408 // and core_course_category::search_courses().
2409 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2410 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2411 $this->coursesdisplayoptions['customfields'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED;
2412 return $this;
2416 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2418 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2420 public function get_show_courses() {
2421 return $this->showcourses;
2425 * Sets the maximum depth to expand subcategories in the tree
2427 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2429 * @param int $subcatdepth
2430 * @return coursecat_helper
2432 public function set_subcat_depth($subcatdepth) {
2433 $this->subcatdepth = $subcatdepth;
2434 return $this;
2438 * Returns the maximum depth to expand subcategories in the tree
2440 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2442 * @return int
2444 public function get_subcat_depth() {
2445 return $this->subcatdepth;
2449 * Sets options to display list of courses
2451 * Options are later submitted as argument to core_course_category::get_courses() and/or core_course_category::search_courses()
2453 * Options that core_course_category::get_courses() accept:
2454 * - recursive - return courses from subcategories as well. Use with care,
2455 * this may be a huge list!
2456 * - summary - preloads fields 'summary' and 'summaryformat'
2457 * - coursecontacts - preloads course contacts
2458 * - customfields - preloads custom fields data
2459 * - isenrolled - preloads indication whether this user is enrolled in the course
2460 * - sort - list of fields to sort. Example
2461 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2462 * will sort by idnumber asc, shortname asc and id desc.
2463 * Default: array('sortorder' => 1)
2464 * Only cached fields may be used for sorting!
2465 * - offset
2466 * - limit - maximum number of children to return, 0 or null for no limit
2468 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2470 * Also renderer can set here any additional options it wants to pass between renderer functions.
2472 * @param array $options
2473 * @return coursecat_helper
2475 public function set_courses_display_options($options) {
2476 $this->coursesdisplayoptions = $options;
2477 $this->set_show_courses($this->showcourses); // this will calculate special display options
2478 return $this;
2482 * Sets one option to display list of courses
2484 * @see coursecat_helper::set_courses_display_options()
2486 * @param string $key
2487 * @param mixed $value
2488 * @return coursecat_helper
2490 public function set_courses_display_option($key, $value) {
2491 $this->coursesdisplayoptions[$key] = $value;
2492 return $this;
2496 * Return the specified option to display list of courses
2498 * @param string $optionname option name
2499 * @param mixed $defaultvalue default value for option if it is not specified
2500 * @return mixed
2502 public function get_courses_display_option($optionname, $defaultvalue = null) {
2503 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2504 return $this->coursesdisplayoptions[$optionname];
2505 } else {
2506 return $defaultvalue;
2511 * Returns all options to display the courses
2513 * This array is usually passed to {@link core_course_category::get_courses()} or
2514 * {@link core_course_category::search_courses()}
2516 * @return array
2518 public function get_courses_display_options() {
2519 return $this->coursesdisplayoptions;
2523 * Sets options to display list of subcategories
2525 * Options 'sort', 'offset' and 'limit' are passed to core_course_category::get_children().
2526 * Any other options may be used by renderer functions
2528 * @param array $options
2529 * @return coursecat_helper
2531 public function set_categories_display_options($options) {
2532 $this->categoriesdisplayoptions = $options;
2533 return $this;
2537 * Return the specified option to display list of subcategories
2539 * @param string $optionname option name
2540 * @param mixed $defaultvalue default value for option if it is not specified
2541 * @return mixed
2543 public function get_categories_display_option($optionname, $defaultvalue = null) {
2544 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2545 return $this->categoriesdisplayoptions[$optionname];
2546 } else {
2547 return $defaultvalue;
2552 * Returns all options to display list of subcategories
2554 * This array is usually passed to {@link core_course_category::get_children()}
2556 * @return array
2558 public function get_categories_display_options() {
2559 return $this->categoriesdisplayoptions;
2563 * Sets additional general options to pass between renderer functions, usually HTML attributes
2565 * @param array $attributes
2566 * @return coursecat_helper
2568 public function set_attributes($attributes) {
2569 $this->attributes = $attributes;
2570 return $this;
2574 * Return all attributes and erases them so they are not applied again
2576 * @param string $classname adds additional class name to the beginning of $attributes['class']
2577 * @return array
2579 public function get_and_erase_attributes($classname) {
2580 $attributes = $this->attributes;
2581 $this->attributes = array();
2582 if (empty($attributes['class'])) {
2583 $attributes['class'] = '';
2585 $attributes['class'] = $classname . ' '. $attributes['class'];
2586 return $attributes;
2590 * Sets the search criteria if the course is a search result
2592 * Search string will be used to highlight terms in course name and description
2594 * @param array $searchcriteria
2595 * @return coursecat_helper
2597 public function set_search_criteria($searchcriteria) {
2598 $this->searchcriteria = $searchcriteria;
2599 return $this;
2603 * Returns formatted and filtered description of the given category
2605 * @param core_course_category $coursecat category
2606 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2607 * if context is not specified it will be added automatically
2608 * @return string|null
2610 public function get_category_formatted_description($coursecat, $options = null) {
2611 if ($coursecat->id && $coursecat->is_uservisible() && !empty($coursecat->description)) {
2612 if (!isset($coursecat->descriptionformat)) {
2613 $descriptionformat = FORMAT_MOODLE;
2614 } else {
2615 $descriptionformat = $coursecat->descriptionformat;
2617 if ($options === null) {
2618 $options = array('noclean' => true, 'overflowdiv' => true);
2619 } else {
2620 $options = (array)$options;
2622 $context = context_coursecat::instance($coursecat->id);
2623 if (!isset($options['context'])) {
2624 $options['context'] = $context;
2626 $text = file_rewrite_pluginfile_urls($coursecat->description,
2627 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2628 return format_text($text, $descriptionformat, $options);
2630 return null;
2634 * Returns given course's summary with proper embedded files urls and formatted
2636 * @param core_course_list_element $course
2637 * @param array|stdClass $options additional formatting options
2638 * @return string
2640 public function get_course_formatted_summary($course, $options = array()) {
2641 global $CFG;
2642 require_once($CFG->libdir. '/filelib.php');
2643 if (!$course->has_summary()) {
2644 return '';
2646 $options = (array)$options;
2647 $context = context_course::instance($course->id);
2648 if (!isset($options['context'])) {
2649 // TODO see MDL-38521
2650 // option 1 (current), page context - no code required
2651 // option 2, system context
2652 // $options['context'] = context_system::instance();
2653 // option 3, course context:
2654 // $options['context'] = $context;
2655 // option 4, course category context:
2656 // $options['context'] = $context->get_parent_context();
2658 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2659 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2660 if (!empty($this->searchcriteria['search'])) {
2661 $summary = highlight($this->searchcriteria['search'], $summary);
2663 return $summary;
2667 * Returns course name as it is configured to appear in courses lists formatted to course context
2669 * @param core_course_list_element $course
2670 * @param array|stdClass $options additional formatting options
2671 * @return string
2673 public function get_course_formatted_name($course, $options = array()) {
2674 $options = (array)$options;
2675 if (!isset($options['context'])) {
2676 $options['context'] = context_course::instance($course->id);
2678 $name = format_string(get_course_display_name_for_list($course), true, $options);
2679 if (!empty($this->searchcriteria['search'])) {
2680 $name = highlight($this->searchcriteria['search'], $name);
2682 return $name;