Moodle release 3.8.4
[moodle.git] / course / renderer.php
blob51b5254878225763f70e0226b8371c72d0ceb3dd
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 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchooser')) {
145 return '';
147 $modchooser = new \core_course\output\modchooser($course, $modules);
148 return $this->render($modchooser);
152 * Build the HTML for a specified set of modules
154 * @param array $modules A set of modules as used by the
155 * course_modchooser_module function
156 * @return string The composed HTML for the module
158 protected function course_modchooser_module_types($modules) {
159 debugging('Method core_course_renderer::course_modchooser_module_types() is deprecated, ' .
160 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
161 return '';
165 * Return the HTML for the specified module adding any required classes
167 * @param object $module An object containing the title, and link. An
168 * icon, and help text may optionally be specified. If the module
169 * contains subtypes in the types option, then these will also be
170 * displayed.
171 * @param array $classes Additional classes to add to the encompassing
172 * div element
173 * @return string The composed HTML for the module
175 protected function course_modchooser_module($module, $classes = array('option')) {
176 debugging('Method core_course_renderer::course_modchooser_module() is deprecated, ' .
177 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
178 return '';
181 protected function course_modchooser_title($title, $identifier = null) {
182 debugging('Method core_course_renderer::course_modchooser_title() is deprecated, ' .
183 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
184 return '';
188 * Renders HTML for displaying the sequence of course module editing buttons
190 * @see course_get_cm_edit_actions()
192 * @param action_link[] $actions Array of action_link objects
193 * @param cm_info $mod The module we are displaying actions for.
194 * @param array $displayoptions additional display options:
195 * ownerselector => A JS/CSS selector that can be used to find an cm node.
196 * If specified the owning node will be given the class 'action-menu-shown' when the action
197 * menu is being displayed.
198 * constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
199 * the action menu to when it is being displayed.
200 * donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
201 * @return string
203 public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
204 global $CFG;
206 if (empty($actions)) {
207 return '';
210 if (isset($displayoptions['ownerselector'])) {
211 $ownerselector = $displayoptions['ownerselector'];
212 } else if ($mod) {
213 $ownerselector = '#module-'.$mod->id;
214 } else {
215 debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
216 $ownerselector = 'li.activity';
219 if (isset($displayoptions['constraintselector'])) {
220 $constraint = $displayoptions['constraintselector'];
221 } else {
222 $constraint = '.course-content';
225 $menu = new action_menu();
226 $menu->set_owner_selector($ownerselector);
227 $menu->set_constraint($constraint);
228 $menu->set_alignment(action_menu::TR, action_menu::BR);
229 $menu->set_menu_trigger(get_string('edit'));
231 foreach ($actions as $action) {
232 if ($action instanceof action_menu_link) {
233 $action->add_class('cm-edit-action');
235 $menu->add($action);
237 $menu->attributes['class'] .= ' section-cm-edit-actions commands';
239 // Prioritise the menu ahead of all other actions.
240 $menu->prioritise = true;
242 return $this->render($menu);
246 * Renders HTML for the menus to add activities and resources to the current course
248 * @param stdClass $course
249 * @param int $section relative section number (field course_sections.section)
250 * @param int $sectionreturn The section to link back to
251 * @param array $displayoptions additional display options, for example blocks add
252 * option 'inblock' => true, suggesting to display controls vertically
253 * @return string
255 function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
256 global $CFG;
258 $vertical = !empty($displayoptions['inblock']);
260 // check to see if user can add menus and there are modules to add
261 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
262 || !$this->page->user_is_editing()
263 || !($modnames = get_module_types_names()) || empty($modnames)) {
264 return '';
267 // Retrieve all modules with associated metadata
268 $modules = get_module_metadata($course, $modnames, $sectionreturn);
269 $urlparams = array('section' => $section);
271 // We'll sort resources and activities into two lists
272 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
274 foreach ($modules as $module) {
275 $activityclass = MOD_CLASS_ACTIVITY;
276 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
277 $activityclass = MOD_CLASS_RESOURCE;
278 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
279 // System modules cannot be added by user, do not add to dropdown.
280 continue;
282 $link = $module->link->out(true, $urlparams);
283 $activities[$activityclass][$link] = $module->title;
286 $straddactivity = get_string('addactivity');
287 $straddresource = get_string('addresource');
288 $sectionname = get_section_name($course, $section);
289 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
290 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
292 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
294 if (!$vertical) {
295 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
298 if (!empty($activities[MOD_CLASS_RESOURCE])) {
299 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array(''=>$straddresource), "ressection$section");
300 $select->set_help_icon('resources');
301 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
302 $output .= $this->output->render($select);
305 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
306 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array(''=>$straddactivity), "section$section");
307 $select->set_help_icon('activities');
308 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
309 $output .= $this->output->render($select);
312 if (!$vertical) {
313 $output .= html_writer::end_tag('div');
316 $output .= html_writer::end_tag('div');
318 if (course_ajax_enabled($course) && $course->id == $this->page->course->id) {
319 // modchooser can be added only for the current course set on the page!
320 $straddeither = get_string('addresourceoractivity');
321 // The module chooser link
322 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
323 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
324 $icon = $this->output->pix_icon('t/add', '');
325 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
326 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
327 $modchooser.= html_writer::end_tag('div');
328 $modchooser.= html_writer::end_tag('div');
330 // Wrap the normal output in a noscript div
331 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
332 if ($usemodchooser) {
333 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
334 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
335 } else {
336 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
337 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
338 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
340 $output = $this->course_modchooser($modules, $course) . $modchooser . $output;
343 return $output;
347 * Renders html to display a course search form.
349 * @param string $value default value to populate the search field
350 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
351 * @return string
353 public function course_search_form($value = '', $format = 'plain') {
354 static $count = 0;
355 $formid = 'coursesearch';
356 if ((++$count) > 1) {
357 $formid .= $count;
360 switch ($format) {
361 case 'navbar' :
362 $formid = 'coursesearchnavbar';
363 $inputid = 'navsearchbox';
364 $inputsize = 20;
365 break;
366 case 'short' :
367 $inputid = 'shortsearchbox';
368 $inputsize = 12;
369 break;
370 default :
371 $inputid = 'coursesearchbox';
372 $inputsize = 30;
375 $data = new stdClass();
376 $data->searchurl = \core_search\manager::get_course_search_url()->out(false);
377 $data->id = $formid;
378 $data->inputid = $inputid;
379 $data->inputsize = $inputsize;
380 $data->value = $value;
381 $data->areaids = 'core_course-course';
383 if ($format != 'navbar') {
384 $helpicon = new \help_icon('coursesearch', 'core');
385 $data->helpicon = $helpicon->export_for_template($this);
388 return $this->render_from_template('core_course/course_search_form', $data);
392 * Renders html for completion box on course page
394 * If completion is disabled, returns empty string
395 * If completion is automatic, returns an icon of the current completion state
396 * If completion is manual, returns a form (with an icon inside) that allows user to
397 * toggle completion
399 * @param stdClass $course course object
400 * @param completion_info $completioninfo completion info for the course, it is recommended
401 * to fetch once for all modules in course/section for performance
402 * @param cm_info $mod module to show completion for
403 * @param array $displayoptions display options, not used in core
404 * @return string
406 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
407 global $CFG, $DB, $USER;
408 $output = '';
410 $istrackeduser = $completioninfo->is_tracked_user($USER->id);
411 $isediting = $this->page->user_is_editing();
413 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
414 return $output;
416 if ($completioninfo === null) {
417 $completioninfo = new completion_info($course);
419 $completion = $completioninfo->is_enabled($mod);
421 if ($completion == COMPLETION_TRACKING_NONE) {
422 if ($isediting) {
423 $output .= html_writer::span('&nbsp;', 'filler');
425 return $output;
428 $completionicon = '';
430 if ($isediting || !$istrackeduser) {
431 switch ($completion) {
432 case COMPLETION_TRACKING_MANUAL :
433 $completionicon = 'manual-enabled'; break;
434 case COMPLETION_TRACKING_AUTOMATIC :
435 $completionicon = 'auto-enabled'; break;
437 } else {
438 $completiondata = $completioninfo->get_data($mod, true);
439 if ($completion == COMPLETION_TRACKING_MANUAL) {
440 switch($completiondata->completionstate) {
441 case COMPLETION_INCOMPLETE:
442 $completionicon = 'manual-n' . ($completiondata->overrideby ? '-override' : '');
443 break;
444 case COMPLETION_COMPLETE:
445 $completionicon = 'manual-y' . ($completiondata->overrideby ? '-override' : '');
446 break;
448 } else { // Automatic
449 switch($completiondata->completionstate) {
450 case COMPLETION_INCOMPLETE:
451 $completionicon = 'auto-n' . ($completiondata->overrideby ? '-override' : '');
452 break;
453 case COMPLETION_COMPLETE:
454 $completionicon = 'auto-y' . ($completiondata->overrideby ? '-override' : '');
455 break;
456 case COMPLETION_COMPLETE_PASS:
457 $completionicon = 'auto-pass'; break;
458 case COMPLETION_COMPLETE_FAIL:
459 $completionicon = 'auto-fail'; break;
463 if ($completionicon) {
464 $formattedname = html_entity_decode($mod->get_formatted_name(), ENT_QUOTES, 'UTF-8');
465 if (!$isediting && $istrackeduser && $completiondata->overrideby) {
466 $args = new stdClass();
467 $args->modname = $formattedname;
468 $overridebyuser = \core_user::get_user($completiondata->overrideby, '*', MUST_EXIST);
469 $args->overrideuser = fullname($overridebyuser);
470 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $args);
471 } else {
472 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
475 if ($isediting || !$istrackeduser || !has_capability('moodle/course:togglecompletion', $mod->context)) {
476 // When editing, the icon is just an image.
477 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
478 array('title' => $imgalt, 'class' => 'iconsmall'));
479 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
480 array('class' => 'autocompletion'));
481 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
482 $newstate =
483 $completiondata->completionstate == COMPLETION_COMPLETE
484 ? COMPLETION_INCOMPLETE
485 : COMPLETION_COMPLETE;
486 // In manual mode the icon is a toggle form...
488 // If this completion state is used by the
489 // conditional activities system, we need to turn
490 // off the JS.
491 $extraclass = '';
492 if (!empty($CFG->enableavailability) &&
493 core_availability\info::completion_value_used($course, $mod->id)) {
494 $extraclass = ' preventjs';
496 $output .= html_writer::start_tag('form', array('method' => 'post',
497 'action' => new moodle_url('/course/togglecompletion.php'),
498 'class' => 'togglecompletion'. $extraclass));
499 $output .= html_writer::start_tag('div');
500 $output .= html_writer::empty_tag('input', array(
501 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
502 $output .= html_writer::empty_tag('input', array(
503 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
504 $output .= html_writer::empty_tag('input', array(
505 'type' => 'hidden', 'name' => 'modulename', 'value' => $formattedname));
506 $output .= html_writer::empty_tag('input', array(
507 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
508 $output .= html_writer::tag('button',
509 $this->output->pix_icon('i/completion-' . $completionicon, $imgalt),
510 array('class' => 'btn btn-link', 'aria-live' => 'assertive'));
511 $output .= html_writer::end_tag('div');
512 $output .= html_writer::end_tag('form');
513 } else {
514 // In auto mode, the icon is just an image.
515 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
516 array('title' => $imgalt));
517 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
518 array('class' => 'autocompletion'));
521 return $output;
525 * Checks if course module has any conditions that may make it unavailable for
526 * all or some of the students
528 * This function is internal and is only used to create CSS classes for the module name/text
530 * @param cm_info $mod
531 * @return bool
533 protected function is_cm_conditionally_hidden(cm_info $mod) {
534 global $CFG;
535 $conditionalhidden = false;
536 if (!empty($CFG->enableavailability)) {
537 $info = new \core_availability\info_module($mod);
538 $conditionalhidden = !$info->is_available_for_all();
540 return $conditionalhidden;
544 * Renders html to display a name with the link to the course module on a course page
546 * If module is unavailable for user but still needs to be displayed
547 * in the list, just the name is returned without a link
549 * Note, that for course modules that never have separate pages (i.e. labels)
550 * this function return an empty string
552 * @param cm_info $mod
553 * @param array $displayoptions
554 * @return string
556 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
557 if (!$mod->is_visible_on_course_page() || !$mod->url) {
558 // Nothing to be displayed to the user.
559 return '';
562 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
563 $groupinglabel = $mod->get_grouping_label($textclasses);
565 // Render element that allows to edit activity name inline. It calls {@link course_section_cm_name_title()}
566 // to get the display title of the activity.
567 $tmpl = new \core_course\output\course_module_name($mod, $this->page->user_is_editing(), $displayoptions);
568 return $this->output->render_from_template('core/inplace_editable', $tmpl->export_for_template($this->output)) .
569 $groupinglabel;
573 * Returns the CSS classes for the activity name/content
575 * For items which are hidden, unavailable or stealth but should be displayed
576 * to current user ($mod->is_visible_on_course_page()), we show those as dimmed.
577 * Students will also see as dimmed activities names that are not yet available
578 * but should still be displayed (without link) with availability info.
580 * @param cm_info $mod
581 * @return array array of two elements ($linkclasses, $textclasses)
583 protected function course_section_cm_classes(cm_info $mod) {
584 $linkclasses = '';
585 $textclasses = '';
586 if ($mod->uservisible) {
587 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
588 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
589 has_capability('moodle/course:viewhiddenactivities', $mod->context);
590 if ($accessiblebutdim) {
591 $linkclasses .= ' dimmed';
592 $textclasses .= ' dimmed_text';
593 if ($conditionalhidden) {
594 $linkclasses .= ' conditionalhidden';
595 $textclasses .= ' conditionalhidden';
598 if ($mod->is_stealth()) {
599 // Stealth activity is the one that is not visible on course page.
600 // It still may be displayed to the users who can manage it.
601 $linkclasses .= ' stealth';
602 $textclasses .= ' stealth';
604 } else {
605 $linkclasses .= ' dimmed';
606 $textclasses .= ' dimmed dimmed_text';
608 return array($linkclasses, $textclasses);
612 * Renders html to display a name with the link to the course module on a course page
614 * If module is unavailable for user but still needs to be displayed
615 * in the list, just the name is returned without a link
617 * Note, that for course modules that never have separate pages (i.e. labels)
618 * this function return an empty string
620 * @param cm_info $mod
621 * @param array $displayoptions
622 * @return string
624 public function course_section_cm_name_title(cm_info $mod, $displayoptions = array()) {
625 $output = '';
626 $url = $mod->url;
627 if (!$mod->is_visible_on_course_page() || !$url) {
628 // Nothing to be displayed to the user.
629 return $output;
632 //Accessibility: for files get description via icon, this is very ugly hack!
633 $instancename = $mod->get_formatted_name();
634 $altname = $mod->modfullname;
635 // Avoid unnecessary duplication: if e.g. a forum name already
636 // includes the word forum (or Forum, etc) then it is unhelpful
637 // to include that in the accessible description that is added.
638 if (false !== strpos(core_text::strtolower($instancename),
639 core_text::strtolower($altname))) {
640 $altname = '';
642 // File type after name, for alphabetic lists (screen reader).
643 if ($altname) {
644 $altname = get_accesshide(' '.$altname);
647 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
649 // Get on-click attribute value if specified and decode the onclick - it
650 // has already been encoded for display (puke).
651 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
653 // Display link itself.
654 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
655 'class' => 'iconlarge activityicon', 'alt' => '', 'role' => 'presentation', 'aria-hidden' => 'true')) .
656 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
657 if ($mod->uservisible) {
658 $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick));
659 } else {
660 // We may be displaying this just in order to show information
661 // about visibility, without the actual link ($mod->is_visible_on_course_page()).
662 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses));
664 return $output;
668 * Renders html to display the module content on the course page (i.e. text of the labels)
670 * @param cm_info $mod
671 * @param array $displayoptions
672 * @return string
674 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
675 $output = '';
676 if (!$mod->is_visible_on_course_page()) {
677 // nothing to be displayed to the user
678 return $output;
680 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
681 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
682 if ($mod->url && $mod->uservisible) {
683 if ($content) {
684 // If specified, display extra content after link.
685 $output = html_writer::tag('div', $content, array('class' =>
686 trim('contentafterlink ' . $textclasses)));
688 } else {
689 $groupinglabel = $mod->get_grouping_label($textclasses);
691 // No link, so display only content.
692 $output = html_writer::tag('div', $content . $groupinglabel,
693 array('class' => 'contentwithoutlink ' . $textclasses));
695 return $output;
699 * Displays availability info for a course section or course module
701 * @param string $text
702 * @param string $additionalclasses
703 * @return string
705 public function availability_info($text, $additionalclasses = '') {
707 $data = ['text' => $text, 'classes' => $additionalclasses];
708 $additionalclasses = array_filter(explode(' ', $additionalclasses));
710 if (in_array('ishidden', $additionalclasses)) {
711 $data['ishidden'] = 1;
713 } else if (in_array('isstealth', $additionalclasses)) {
714 $data['isstealth'] = 1;
716 } else if (in_array('isrestricted', $additionalclasses)) {
717 $data['isrestricted'] = 1;
719 if (in_array('isfullinfo', $additionalclasses)) {
720 $data['isfullinfo'] = 1;
724 return $this->render_from_template('core/availability_info', $data);
728 * Renders HTML to show course module availability information (for someone who isn't allowed
729 * to see the activity itself, or for staff)
731 * @param cm_info $mod
732 * @param array $displayoptions
733 * @return string
735 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
736 global $CFG;
737 $output = '';
738 if (!$mod->is_visible_on_course_page()) {
739 return $output;
741 if (!$mod->uservisible) {
742 // this is a student who is not allowed to see the module but might be allowed
743 // to see availability info (i.e. "Available from ...")
744 if (!empty($mod->availableinfo)) {
745 $formattedinfo = \core_availability\info::format_info(
746 $mod->availableinfo, $mod->get_course());
747 $output = $this->availability_info($formattedinfo, 'isrestricted');
749 return $output;
751 // this is a teacher who is allowed to see module but still should see the
752 // information that module is not available to all/some students
753 $modcontext = context_module::instance($mod->id);
754 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
755 if ($canviewhidden && !$mod->visible) {
756 // This module is hidden but current user has capability to see it.
757 // Do not display the availability info if the whole section is hidden.
758 if ($mod->get_section_info()->visible) {
759 $output .= $this->availability_info(get_string('hiddenfromstudents'), 'ishidden');
761 } else if ($mod->is_stealth()) {
762 // This module is available but is normally not displayed on the course page
763 // (this user can see it because they can manage it).
764 $output .= $this->availability_info(get_string('hiddenoncoursepage'), 'isstealth');
766 if ($canviewhidden && !empty($CFG->enableavailability)) {
767 // Display information about conditional availability.
768 // Don't add availability information if user is not editing and activity is hidden.
769 if ($mod->visible || $this->page->user_is_editing()) {
770 $hidinfoclass = 'isrestricted isfullinfo';
771 if (!$mod->visible) {
772 $hidinfoclass .= ' hide';
774 $ci = new \core_availability\info_module($mod);
775 $fullinfo = $ci->get_full_information();
776 if ($fullinfo) {
777 $formattedinfo = \core_availability\info::format_info(
778 $fullinfo, $mod->get_course());
779 $output .= $this->availability_info($formattedinfo, $hidinfoclass);
783 return $output;
787 * Renders HTML to display one course module for display within a section.
789 * This function calls:
790 * {@link core_course_renderer::course_section_cm()}
792 * @param stdClass $course
793 * @param completion_info $completioninfo
794 * @param cm_info $mod
795 * @param int|null $sectionreturn
796 * @param array $displayoptions
797 * @return String
799 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
800 $output = '';
801 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
802 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
803 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
805 return $output;
809 * Renders HTML to display one course module in a course section
811 * This includes link, content, availability, completion info and additional information
812 * that module type wants to display (i.e. number of unread forum posts)
814 * This function calls:
815 * {@link core_course_renderer::course_section_cm_name()}
816 * {@link core_course_renderer::course_section_cm_text()}
817 * {@link core_course_renderer::course_section_cm_availability()}
818 * {@link core_course_renderer::course_section_cm_completion()}
819 * {@link course_get_cm_edit_actions()}
820 * {@link core_course_renderer::course_section_cm_edit_actions()}
822 * @param stdClass $course
823 * @param completion_info $completioninfo
824 * @param cm_info $mod
825 * @param int|null $sectionreturn
826 * @param array $displayoptions
827 * @return string
829 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
830 $output = '';
831 // We return empty string (because course module will not be displayed at all)
832 // if:
833 // 1) The activity is not visible to users
834 // and
835 // 2) The 'availableinfo' is empty, i.e. the activity was
836 // hidden in a way that leaves no info, such as using the
837 // eye icon.
838 if (!$mod->is_visible_on_course_page()) {
839 return $output;
842 $indentclasses = 'mod-indent';
843 if (!empty($mod->indent)) {
844 $indentclasses .= ' mod-indent-'.$mod->indent;
845 if ($mod->indent > 15) {
846 $indentclasses .= ' mod-indent-huge';
850 $output .= html_writer::start_tag('div');
852 if ($this->page->user_is_editing()) {
853 $output .= course_get_cm_move($mod, $sectionreturn);
856 $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer'));
858 // This div is used to indent the content.
859 $output .= html_writer::div('', $indentclasses);
861 // Start a wrapper for the actual content to keep the indentation consistent
862 $output .= html_writer::start_tag('div');
864 // Display the link to the module (or do nothing if module has no url)
865 $cmname = $this->course_section_cm_name($mod, $displayoptions);
867 if (!empty($cmname)) {
868 // Start the div for the activity title, excluding the edit icons.
869 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
870 $output .= $cmname;
873 // Module can put text after the link (e.g. forum unread)
874 $output .= $mod->afterlink;
876 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
877 $output .= html_writer::end_tag('div'); // .activityinstance
880 // If there is content but NO link (eg label), then display the
881 // content here (BEFORE any icons). In this case cons must be
882 // displayed after the content so that it makes more sense visually
883 // and for accessibility reasons, e.g. if you have a one-line label
884 // it should work similarly (at least in terms of ordering) to an
885 // activity.
886 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
887 $url = $mod->url;
888 if (empty($url)) {
889 $output .= $contentpart;
892 $modicons = '';
893 if ($this->page->user_is_editing()) {
894 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
895 $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
896 $modicons .= $mod->afterediticons;
899 $modicons .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
901 if (!empty($modicons)) {
902 $output .= html_writer::span($modicons, 'actions');
905 // Show availability info (if module is not available).
906 $output .= $this->course_section_cm_availability($mod, $displayoptions);
908 // If there is content AND a link, then display the content here
909 // (AFTER any icons). Otherwise it was displayed before
910 if (!empty($url)) {
911 $output .= $contentpart;
914 $output .= html_writer::end_tag('div'); // $indentclasses
916 // End of indentation div.
917 $output .= html_writer::end_tag('div');
919 $output .= html_writer::end_tag('div');
920 return $output;
924 * Message displayed to the user when they try to access unavailable activity following URL
926 * This method is a very simplified version of {@link course_section_cm()} to be part of the error
927 * notification only. It also does not check if module is visible on course page or not.
929 * The message will be displayed inside notification!
931 * @param cm_info $cm
932 * @return string
934 public function course_section_cm_unavailable_error_message(cm_info $cm) {
935 if ($cm->uservisible) {
936 return null;
938 if (!$cm->availableinfo) {
939 return get_string('activityiscurrentlyhidden');
942 $altname = get_accesshide(' ' . $cm->modfullname);
943 $name = html_writer::empty_tag('img', array('src' => $cm->get_icon_url(),
944 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
945 html_writer::tag('span', ' '.$cm->get_formatted_name() . $altname, array('class' => 'instancename'));
946 $formattedinfo = \core_availability\info::format_info($cm->availableinfo, $cm->get_course());
947 return html_writer::div($name, 'activityinstance-error') .
948 html_writer::div($formattedinfo, 'availabilityinfo-error');
952 * Renders HTML to display a list of course modules in a course section
953 * Also displays "move here" controls in Javascript-disabled mode
955 * This function calls {@link core_course_renderer::course_section_cm()}
957 * @param stdClass $course course object
958 * @param int|stdClass|section_info $section relative section number or section object
959 * @param int $sectionreturn section number to return to
960 * @param int $displayoptions
961 * @return void
963 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
964 global $USER;
966 $output = '';
967 $modinfo = get_fast_modinfo($course);
968 if (is_object($section)) {
969 $section = $modinfo->get_section_info($section->section);
970 } else {
971 $section = $modinfo->get_section_info($section);
973 $completioninfo = new completion_info($course);
975 // check if we are currently in the process of moving a module with JavaScript disabled
976 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
977 if ($ismoving) {
978 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
979 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
982 // Get the list of modules visible to user (excluding the module being moved if there is one)
983 $moduleshtml = array();
984 if (!empty($modinfo->sections[$section->section])) {
985 foreach ($modinfo->sections[$section->section] as $modnumber) {
986 $mod = $modinfo->cms[$modnumber];
988 if ($ismoving and $mod->id == $USER->activitycopy) {
989 // do not display moving mod
990 continue;
993 if ($modulehtml = $this->course_section_cm_list_item($course,
994 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
995 $moduleshtml[$modnumber] = $modulehtml;
1000 $sectionoutput = '';
1001 if (!empty($moduleshtml) || $ismoving) {
1002 foreach ($moduleshtml as $modnumber => $modulehtml) {
1003 if ($ismoving) {
1004 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
1005 $sectionoutput .= html_writer::tag('li',
1006 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1007 array('class' => 'movehere'));
1010 $sectionoutput .= $modulehtml;
1013 if ($ismoving) {
1014 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1015 $sectionoutput .= html_writer::tag('li',
1016 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1017 array('class' => 'movehere'));
1021 // Always output the section module list.
1022 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1024 return $output;
1028 * Displays a custom list of courses with paging bar if necessary
1030 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1031 * appears under the list.
1033 * If both $paginationurl and $totalcount are specified, and $totalcount is
1034 * bigger than count($courses), a paging bar is displayed above and under the
1035 * courses list.
1037 * @param array $courses array of course records (or instances of core_course_list_element) to show on this page
1038 * @param bool $showcategoryname whether to add category name to the course description
1039 * @param string $additionalclasses additional CSS classes to add to the div.courses
1040 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1041 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1042 * @param int $page current page number (defaults to 0 referring to the first page)
1043 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1044 * @return string
1046 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1047 global $CFG;
1048 // create instance of coursecat_helper to pass display options to function rendering courses list
1049 $chelper = new coursecat_helper();
1050 if ($showcategoryname) {
1051 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1052 } else {
1053 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1055 if ($totalcount !== null && $paginationurl !== null) {
1056 // add options to display pagination
1057 if ($perpage === null) {
1058 $perpage = $CFG->coursesperpage;
1060 $chelper->set_courses_display_options(array(
1061 'limit' => $perpage,
1062 'offset' => ((int)$page) * $perpage,
1063 'paginationurl' => $paginationurl,
1065 } else if ($paginationurl !== null) {
1066 // add options to display 'View more' link
1067 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1068 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1070 $chelper->set_attributes(array('class' => $additionalclasses));
1071 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1072 return $content;
1076 * Displays one course in the list of courses.
1078 * This is an internal function, to display an information about just one course
1079 * please use {@link core_course_renderer::course_info_box()}
1081 * @param coursecat_helper $chelper various display options
1082 * @param core_course_list_element|stdClass $course
1083 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1084 * depend on the course position in list - first/last/even/odd)
1085 * @return string
1087 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1088 if (!isset($this->strings->summary)) {
1089 $this->strings->summary = get_string('summary');
1091 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1092 return '';
1094 if ($course instanceof stdClass) {
1095 $course = new core_course_list_element($course);
1097 $content = '';
1098 $classes = trim('coursebox clearfix '. $additionalclasses);
1099 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1100 $nametag = 'h3';
1101 } else {
1102 $classes .= ' collapsed';
1103 $nametag = 'div';
1106 // .coursebox
1107 $content .= html_writer::start_tag('div', array(
1108 'class' => $classes,
1109 'data-courseid' => $course->id,
1110 'data-type' => self::COURSECAT_TYPE_COURSE,
1113 $content .= html_writer::start_tag('div', array('class' => 'info'));
1115 // course name
1116 $coursename = $chelper->get_course_formatted_name($course);
1117 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', array('id' => $course->id)),
1118 $coursename, array('class' => $course->visible ? '' : 'dimmed'));
1119 $content .= html_writer::tag($nametag, $coursenamelink, array('class' => 'coursename'));
1120 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1121 $content .= html_writer::start_tag('div', array('class' => 'moreinfo'));
1122 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1123 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()
1124 || $course->has_custom_fields()) {
1125 $url = new moodle_url('/course/info.php', array('id' => $course->id));
1126 $image = $this->output->pix_icon('i/info', $this->strings->summary);
1127 $content .= html_writer::link($url, $image, array('title' => $this->strings->summary));
1128 // Make sure JS file to expand course content is included.
1129 $this->coursecat_include_js();
1132 $content .= html_writer::end_tag('div'); // .moreinfo
1134 // print enrolmenticons
1135 if ($icons = enrol_get_course_info_icons($course)) {
1136 $content .= html_writer::start_tag('div', array('class' => 'enrolmenticons'));
1137 foreach ($icons as $pix_icon) {
1138 $content .= $this->render($pix_icon);
1140 $content .= html_writer::end_tag('div'); // .enrolmenticons
1143 $content .= html_writer::end_tag('div'); // .info
1145 $content .= html_writer::start_tag('div', array('class' => 'content'));
1146 $content .= $this->coursecat_coursebox_content($chelper, $course);
1147 $content .= html_writer::end_tag('div'); // .content
1149 $content .= html_writer::end_tag('div'); // .coursebox
1150 return $content;
1154 * Returns HTML to display course content (summary, course contacts and optionally category name)
1156 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1158 * @param coursecat_helper $chelper various display options
1159 * @param stdClass|core_course_list_element $course
1160 * @return string
1162 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1163 global $CFG;
1164 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1165 return '';
1167 if ($course instanceof stdClass) {
1168 $course = new core_course_list_element($course);
1170 $content = '';
1172 // display course summary
1173 if ($course->has_summary()) {
1174 $content .= html_writer::start_tag('div', array('class' => 'summary'));
1175 $content .= $chelper->get_course_formatted_summary($course,
1176 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1177 $content .= html_writer::end_tag('div'); // .summary
1180 // display course overview files
1181 $contentimages = $contentfiles = '';
1182 foreach ($course->get_course_overviewfiles() as $file) {
1183 $isimage = $file->is_valid_image();
1184 $url = file_encode_url("$CFG->wwwroot/pluginfile.php",
1185 '/'. $file->get_contextid(). '/'. $file->get_component(). '/'.
1186 $file->get_filearea(). $file->get_filepath(). $file->get_filename(), !$isimage);
1187 if ($isimage) {
1188 $contentimages .= html_writer::tag('div',
1189 html_writer::empty_tag('img', array('src' => $url)),
1190 array('class' => 'courseimage'));
1191 } else {
1192 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1193 $filename = html_writer::tag('span', $image, array('class' => 'fp-icon')).
1194 html_writer::tag('span', $file->get_filename(), array('class' => 'fp-filename'));
1195 $contentfiles .= html_writer::tag('span',
1196 html_writer::link($url, $filename),
1197 array('class' => 'coursefile fp-filename-icon'));
1200 $content .= $contentimages. $contentfiles;
1202 // Display course contacts. See core_course_list_element::get_course_contacts().
1203 if ($course->has_course_contacts()) {
1204 $content .= html_writer::start_tag('ul', array('class' => 'teachers'));
1205 foreach ($course->get_course_contacts() as $coursecontact) {
1206 $rolenames = array_map(function ($role) {
1207 return $role->displayname;
1208 }, $coursecontact['roles']);
1209 $name = implode(", ", $rolenames).': '.
1210 html_writer::link(new moodle_url('/user/view.php',
1211 array('id' => $coursecontact['user']->id, 'course' => SITEID)),
1212 $coursecontact['username']);
1213 $content .= html_writer::tag('li', $name);
1215 $content .= html_writer::end_tag('ul'); // .teachers
1218 // display course category if necessary (for example in search results)
1219 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1220 if ($cat = core_course_category::get($course->category, IGNORE_MISSING)) {
1221 $content .= html_writer::start_tag('div', array('class' => 'coursecat'));
1222 $content .= get_string('category').': '.
1223 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1224 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1225 $content .= html_writer::end_tag('div'); // .coursecat
1229 // Display custom fields.
1230 if ($course->has_custom_fields()) {
1231 $handler = core_course\customfield\course_handler::create();
1232 $customfields = $handler->display_custom_fields_data($course->get_custom_fields());
1233 $content .= \html_writer::tag('div', $customfields, ['class' => 'customfields-container']);
1236 return $content;
1240 * Renders the list of courses
1242 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1243 * method from outside of the class
1245 * If list of courses is specified in $courses; the argument $chelper is only used
1246 * to retrieve display options and attributes, only methods get_show_courses(),
1247 * get_courses_display_option() and get_and_erase_attributes() are called.
1249 * @param coursecat_helper $chelper various display options
1250 * @param array $courses the list of courses to display
1251 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1252 * defaulted to count($courses)
1253 * @return string
1255 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1256 global $CFG;
1257 if ($totalcount === null) {
1258 $totalcount = count($courses);
1260 if (!$totalcount) {
1261 // Courses count is cached during courses retrieval.
1262 return '';
1265 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1266 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1267 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1268 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1269 } else {
1270 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1274 // prepare content of paging bar if it is needed
1275 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1276 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1277 if ($totalcount > count($courses)) {
1278 // there are more results that can fit on one page
1279 if ($paginationurl) {
1280 // the option paginationurl was specified, display pagingbar
1281 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1282 $page = $chelper->get_courses_display_option('offset') / $perpage;
1283 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1284 $paginationurl->out(false, array('perpage' => $perpage)));
1285 if ($paginationallowall) {
1286 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1287 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1289 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1290 // the option for 'View more' link was specified, display more link
1291 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1292 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1293 array('class' => 'paging paging-morelink'));
1295 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1296 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1297 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1298 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1301 // display list of courses
1302 $attributes = $chelper->get_and_erase_attributes('courses');
1303 $content = html_writer::start_tag('div', $attributes);
1305 if (!empty($pagingbar)) {
1306 $content .= $pagingbar;
1309 $coursecount = 0;
1310 foreach ($courses as $course) {
1311 $coursecount ++;
1312 $classes = ($coursecount%2) ? 'odd' : 'even';
1313 if ($coursecount == 1) {
1314 $classes .= ' first';
1316 if ($coursecount >= count($courses)) {
1317 $classes .= ' last';
1319 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1322 if (!empty($pagingbar)) {
1323 $content .= $pagingbar;
1325 if (!empty($morelink)) {
1326 $content .= $morelink;
1329 $content .= html_writer::end_tag('div'); // .courses
1330 return $content;
1334 * Renders the list of subcategories in a category
1336 * @param coursecat_helper $chelper various display options
1337 * @param core_course_category $coursecat
1338 * @param int $depth depth of the category in the current tree
1339 * @return string
1341 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1342 global $CFG;
1343 $subcategories = array();
1344 if (!$chelper->get_categories_display_option('nodisplay')) {
1345 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1347 $totalcount = $coursecat->get_children_count();
1348 if (!$totalcount) {
1349 // Note that we call core_course_category::get_children_count() AFTER core_course_category::get_children()
1350 // to avoid extra DB requests.
1351 // Categories count is cached during children categories retrieval.
1352 return '';
1355 // prepare content of paging bar or more link if it is needed
1356 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1357 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1358 if ($totalcount > count($subcategories)) {
1359 if ($paginationurl) {
1360 // the option 'paginationurl was specified, display pagingbar
1361 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1362 $page = $chelper->get_categories_display_option('offset') / $perpage;
1363 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1364 $paginationurl->out(false, array('perpage' => $perpage)));
1365 if ($paginationallowall) {
1366 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1367 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1369 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1370 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1371 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1372 $viewmoreurl->param('categoryid', $coursecat->id);
1374 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1375 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1376 array('class' => 'paging paging-morelink'));
1378 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1379 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1380 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1381 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1384 // display list of subcategories
1385 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1387 if (!empty($pagingbar)) {
1388 $content .= $pagingbar;
1391 foreach ($subcategories as $subcategory) {
1392 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1395 if (!empty($pagingbar)) {
1396 $content .= $pagingbar;
1398 if (!empty($morelink)) {
1399 $content .= $morelink;
1402 $content .= html_writer::end_tag('div');
1403 return $content;
1407 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1409 protected function coursecat_include_js() {
1410 if (!$this->page->requires->should_create_one_time_item_now('core_course_categoryexpanderjsinit')) {
1411 return;
1414 // We must only load this module once.
1415 $this->page->requires->yui_module('moodle-course-categoryexpander',
1416 'Y.Moodle.course.categoryexpander.init');
1420 * Returns HTML to display the subcategories and courses in the given category
1422 * This method is re-used by AJAX to expand content of not loaded category
1424 * @param coursecat_helper $chelper various display options
1425 * @param core_course_category $coursecat
1426 * @param int $depth depth of the category in the current tree
1427 * @return string
1429 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1430 $content = '';
1431 // Subcategories
1432 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1434 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1435 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1436 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1437 if ($showcoursesauto && $depth) {
1438 // this is definitely collapsed mode
1439 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1442 // Courses
1443 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1444 $courses = array();
1445 if (!$chelper->get_courses_display_option('nodisplay')) {
1446 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1448 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1449 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1450 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1451 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1454 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1457 if ($showcoursesauto) {
1458 // restore the show_courses back to AUTO
1459 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1462 return $content;
1466 * Returns HTML to display a course category as a part of a tree
1468 * This is an internal function, to display a particular category and all its contents
1469 * use {@link core_course_renderer::course_category()}
1471 * @param coursecat_helper $chelper various display options
1472 * @param core_course_category $coursecat
1473 * @param int $depth depth of this category in the current tree
1474 * @return string
1476 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1477 // open category tag
1478 $classes = array('category');
1479 if (empty($coursecat->visible)) {
1480 $classes[] = 'dimmed_category';
1482 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1483 // do not load content
1484 $categorycontent = '';
1485 $classes[] = 'notloaded';
1486 if ($coursecat->get_children_count() ||
1487 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1488 $classes[] = 'with_children';
1489 $classes[] = 'collapsed';
1491 } else {
1492 // load category content
1493 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1494 $classes[] = 'loaded';
1495 if (!empty($categorycontent)) {
1496 $classes[] = 'with_children';
1497 // Category content loaded with children.
1498 $this->categoryexpandedonload = true;
1502 // Make sure JS file to expand category content is included.
1503 $this->coursecat_include_js();
1505 $content = html_writer::start_tag('div', array(
1506 'class' => join(' ', $classes),
1507 'data-categoryid' => $coursecat->id,
1508 'data-depth' => $depth,
1509 'data-showcourses' => $chelper->get_show_courses(),
1510 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1513 // category name
1514 $categoryname = $coursecat->get_formatted_name();
1515 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1516 array('categoryid' => $coursecat->id)),
1517 $categoryname);
1518 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1519 && ($coursescount = $coursecat->get_courses_count())) {
1520 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1521 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1523 $content .= html_writer::start_tag('div', array('class' => 'info'));
1525 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname'));
1526 $content .= html_writer::end_tag('div'); // .info
1528 // add category content to the output
1529 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1531 $content .= html_writer::end_tag('div'); // .category
1533 // Return the course category tree HTML
1534 return $content;
1538 * Returns HTML to display a tree of subcategories and courses in the given category
1540 * @param coursecat_helper $chelper various display options
1541 * @param core_course_category $coursecat top category (this category's name and description will NOT be added to the tree)
1542 * @return string
1544 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1545 // Reset the category expanded flag for this course category tree first.
1546 $this->categoryexpandedonload = false;
1547 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1548 if (empty($categorycontent)) {
1549 return '';
1552 // Start content generation
1553 $content = '';
1554 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1555 $content .= html_writer::start_tag('div', $attributes);
1557 if ($coursecat->get_children_count()) {
1558 $classes = array(
1559 'collapseexpand',
1562 // Check if the category content contains subcategories with children's content loaded.
1563 if ($this->categoryexpandedonload) {
1564 $classes[] = 'collapse-all';
1565 $linkname = get_string('collapseall');
1566 } else {
1567 $linkname = get_string('expandall');
1570 // Only show the collapse/expand if there are children to expand.
1571 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1572 $content .= html_writer::link('#', $linkname, array('class' => implode(' ', $classes)));
1573 $content .= html_writer::end_tag('div');
1574 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1577 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1579 $content .= html_writer::end_tag('div'); // .course_category_tree
1581 return $content;
1585 * Renders HTML to display particular course category - list of it's subcategories and courses
1587 * Invoked from /course/index.php
1589 * @param int|stdClass|core_course_category $category
1591 public function course_category($category) {
1592 global $CFG;
1593 $usertop = core_course_category::user_top();
1594 if (empty($category)) {
1595 $coursecat = $usertop;
1596 } else if (is_object($category) && $category instanceof core_course_category) {
1597 $coursecat = $category;
1598 } else {
1599 $coursecat = core_course_category::get(is_object($category) ? $category->id : $category);
1601 $site = get_site();
1602 $output = '';
1604 if ($coursecat->can_create_course() || $coursecat->has_manage_capability()) {
1605 // Add 'Manage' button if user has permissions to edit this category.
1606 $managebutton = $this->single_button(new moodle_url('/course/management.php',
1607 array('categoryid' => $coursecat->id)), get_string('managecourses'), 'get');
1608 $this->page->set_button($managebutton);
1611 if (core_course_category::is_simple_site()) {
1612 // There is only one category in the system, do not display link to it.
1613 $strfulllistofcourses = get_string('fulllistofcourses');
1614 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1615 } else if (!$coursecat->id || !$coursecat->is_uservisible()) {
1616 $strcategories = get_string('categories');
1617 $this->page->set_title("$site->shortname: $strcategories");
1618 } else {
1619 $strfulllistofcourses = get_string('fulllistofcourses');
1620 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1622 // Print the category selector
1623 $categorieslist = core_course_category::make_categories_list();
1624 if (count($categorieslist) > 1) {
1625 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1626 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1627 core_course_category::make_categories_list(), $coursecat->id, null, 'switchcategory');
1628 $select->set_label(get_string('categories').':');
1629 $output .= $this->render($select);
1630 $output .= html_writer::end_tag('div'); // .categorypicker
1634 // Print current category description
1635 $chelper = new coursecat_helper();
1636 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1637 $output .= $this->box($description, array('class' => 'generalbox info'));
1640 // Prepare parameters for courses and categories lists in the tree
1641 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1642 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1644 $coursedisplayoptions = array();
1645 $catdisplayoptions = array();
1646 $browse = optional_param('browse', null, PARAM_ALPHA);
1647 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1648 $page = optional_param('page', 0, PARAM_INT);
1649 $baseurl = new moodle_url('/course/index.php');
1650 if ($coursecat->id) {
1651 $baseurl->param('categoryid', $coursecat->id);
1653 if ($perpage != $CFG->coursesperpage) {
1654 $baseurl->param('perpage', $perpage);
1656 $coursedisplayoptions['limit'] = $perpage;
1657 $catdisplayoptions['limit'] = $perpage;
1658 if ($browse === 'courses' || !$coursecat->get_children_count()) {
1659 $coursedisplayoptions['offset'] = $page * $perpage;
1660 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1661 $catdisplayoptions['nodisplay'] = true;
1662 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1663 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1664 } else if ($browse === 'categories' || !$coursecat->get_courses_count()) {
1665 $coursedisplayoptions['nodisplay'] = true;
1666 $catdisplayoptions['offset'] = $page * $perpage;
1667 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1668 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1669 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1670 } else {
1671 // we have a category that has both subcategories and courses, display pagination separately
1672 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1673 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1675 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1676 // Add course search form.
1677 $output .= $this->course_search_form();
1679 // Display course category tree.
1680 $output .= $this->coursecat_tree($chelper, $coursecat);
1682 // Add action buttons
1683 $output .= $this->container_start('buttons');
1684 if ($coursecat->is_uservisible()) {
1685 $context = get_category_or_system_context($coursecat->id);
1686 if (has_capability('moodle/course:create', $context)) {
1687 // Print link to create a new course, for the 1st available category.
1688 if ($coursecat->id) {
1689 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1690 } else {
1691 $url = new moodle_url('/course/edit.php',
1692 array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1694 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1696 ob_start();
1697 print_course_request_buttons($context);
1698 $output .= ob_get_contents();
1699 ob_end_clean();
1701 $output .= $this->container_end();
1703 return $output;
1707 * Serves requests to /course/category.ajax.php
1709 * In this renderer implementation it may expand the category content or
1710 * course content.
1712 * @return string
1713 * @throws coding_exception
1715 public function coursecat_ajax() {
1716 global $DB, $CFG;
1718 $type = required_param('type', PARAM_INT);
1720 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1721 // This is a request for a category list of some kind.
1722 $categoryid = required_param('categoryid', PARAM_INT);
1723 $showcourses = required_param('showcourses', PARAM_INT);
1724 $depth = required_param('depth', PARAM_INT);
1726 $category = core_course_category::get($categoryid);
1728 $chelper = new coursecat_helper();
1729 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1730 $coursedisplayoptions = array(
1731 'limit' => $CFG->coursesperpage,
1732 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1734 $catdisplayoptions = array(
1735 'limit' => $CFG->coursesperpage,
1736 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1738 $chelper->set_show_courses($showcourses)->
1739 set_courses_display_options($coursedisplayoptions)->
1740 set_categories_display_options($catdisplayoptions);
1742 return $this->coursecat_category_content($chelper, $category, $depth);
1743 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1744 // This is a request for the course information.
1745 $courseid = required_param('courseid', PARAM_INT);
1747 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1749 $chelper = new coursecat_helper();
1750 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1751 return $this->coursecat_coursebox_content($chelper, $course);
1752 } else {
1753 throw new coding_exception('Invalid request type');
1758 * Renders html to display search result page
1760 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1761 * @return string
1763 public function search_courses($searchcriteria) {
1764 global $CFG;
1765 $content = '';
1766 if (!empty($searchcriteria)) {
1767 // print search results
1769 $displayoptions = array('sort' => array('displayname' => 1));
1770 // take the current page and number of results per page from query
1771 $perpage = optional_param('perpage', 0, PARAM_RAW);
1772 if ($perpage !== 'all') {
1773 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1774 $page = optional_param('page', 0, PARAM_INT);
1775 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1777 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1778 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1779 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1781 $class = 'course-search-result';
1782 foreach ($searchcriteria as $key => $value) {
1783 if (!empty($value)) {
1784 $class .= ' course-search-result-'. $key;
1787 $chelper = new coursecat_helper();
1788 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1789 set_courses_display_options($displayoptions)->
1790 set_search_criteria($searchcriteria)->
1791 set_attributes(array('class' => $class));
1793 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1794 $totalcount = core_course_category::search_courses_count($searchcriteria);
1795 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1797 if (!$totalcount) {
1798 if (!empty($searchcriteria['search'])) {
1799 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1800 } else {
1801 $content .= $this->heading(get_string('novalidcourses'));
1803 } else {
1804 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1805 $content .= $courseslist;
1808 if (!empty($searchcriteria['search'])) {
1809 // print search form only if there was a search by search string, otherwise it is confusing
1810 $content .= $this->box_start('generalbox mdl-align');
1811 $content .= $this->course_search_form($searchcriteria['search']);
1812 $content .= $this->box_end();
1814 } else {
1815 // just print search form
1816 $content .= $this->box_start('generalbox mdl-align');
1817 $content .= $this->course_search_form();
1818 $content .= $this->box_end();
1820 return $content;
1824 * Renders html to print list of courses tagged with particular tag
1826 * @param int $tagid id of the tag
1827 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1828 * are displayed on the page and the per-page limit may be bigger
1829 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1830 * to display items in the same context first
1831 * @param int $ctx context id where to search for records
1832 * @param bool $rec search in subcontexts as well
1833 * @param array $displayoptions
1834 * @return string empty string if no courses are marked with this tag or rendered list of courses
1836 public function tagged_courses($tagid, $exclusivemode = true, $ctx = 0, $rec = true, $displayoptions = null) {
1837 global $CFG;
1838 if (empty($displayoptions)) {
1839 $displayoptions = array();
1841 $showcategories = !core_course_category::is_simple_site();
1842 $displayoptions += array('limit' => $CFG->coursesperpage, 'offset' => 0);
1843 $chelper = new coursecat_helper();
1844 $searchcriteria = array('tagid' => $tagid, 'ctx' => $ctx, 'rec' => $rec);
1845 $chelper->set_show_courses($showcategories ? self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT :
1846 self::COURSECAT_SHOW_COURSES_EXPANDED)->
1847 set_search_criteria($searchcriteria)->
1848 set_courses_display_options($displayoptions)->
1849 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1850 // (we set the same css class as in search results by tagid)
1851 if ($totalcount = core_course_category::search_courses_count($searchcriteria)) {
1852 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1853 if ($exclusivemode) {
1854 return $this->coursecat_courses($chelper, $courses, $totalcount);
1855 } else {
1856 $tagfeed = new core_tag\output\tagfeed();
1857 $img = $this->output->pix_icon('i/course', '');
1858 foreach ($courses as $course) {
1859 $url = course_get_url($course);
1860 $imgwithlink = html_writer::link($url, $img);
1861 $coursename = html_writer::link($url, $course->get_formatted_name());
1862 $details = '';
1863 if ($showcategories && ($cat = core_course_category::get($course->category, IGNORE_MISSING))) {
1864 $details = get_string('category').': '.
1865 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1866 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1868 $tagfeed->add($imgwithlink, $coursename, $details);
1870 return $this->output->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($this->output));
1873 return '';
1877 * Returns HTML to display one remote course
1879 * @param stdClass $course remote course information, contains properties:
1880 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1881 * @return string
1883 protected function frontpage_remote_course(stdClass $course) {
1884 $url = new moodle_url('/auth/mnet/jump.php', array(
1885 'hostid' => $course->hostid,
1886 'wantsurl' => '/course/view.php?id='. $course->remoteid
1889 $output = '';
1890 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1891 $output .= html_writer::start_tag('div', array('class' => 'info'));
1892 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1893 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1894 $output .= html_writer::end_tag('h3'); // .name
1895 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1896 $output .= html_writer::end_tag('div'); // .info
1897 $output .= html_writer::start_tag('div', array('class' => 'content'));
1898 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1899 $options = new stdClass();
1900 $options->noclean = true;
1901 $options->para = false;
1902 $options->overflowdiv = true;
1903 $output .= format_text($course->summary, $course->summaryformat, $options);
1904 $output .= html_writer::end_tag('div'); // .summary
1905 $addinfo = format_string($course->hostname) . ' : '
1906 . format_string($course->cat_name) . ' : '
1907 . format_string($course->shortname);
1908 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1909 $output .= html_writer::end_tag('div'); // .content
1910 $output .= html_writer::end_tag('div'); // .coursebox
1911 return $output;
1915 * Returns HTML to display one remote host
1917 * @param array $host host information, contains properties: name, url, count
1918 * @return string
1920 protected function frontpage_remote_host($host) {
1921 $output = '';
1922 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1923 $output .= html_writer::start_tag('div', array('class' => 'info'));
1924 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1925 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1926 $output .= html_writer::end_tag('h3'); // .name
1927 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1928 $output .= html_writer::end_tag('div'); // .info
1929 $output .= html_writer::start_tag('div', array('class' => 'content'));
1930 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1931 $output .= $host['count'] . ' ' . get_string('courses');
1932 $output .= html_writer::end_tag('div'); // .content
1933 $output .= html_writer::end_tag('div'); // .coursebox
1934 return $output;
1938 * Returns HTML to print list of courses user is enrolled to for the frontpage
1940 * Also lists remote courses or remote hosts if MNET authorisation is used
1942 * @return string
1944 public function frontpage_my_courses() {
1945 global $USER, $CFG, $DB;
1947 if (!isloggedin() or isguestuser()) {
1948 return '';
1951 $output = '';
1952 $courses = enrol_get_my_courses('summary, summaryformat');
1953 $rhosts = array();
1954 $rcourses = array();
1955 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1956 $rcourses = get_my_remotecourses($USER->id);
1957 $rhosts = get_my_remotehosts();
1960 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1962 $chelper = new coursecat_helper();
1963 $totalcount = count($courses);
1964 if (count($courses) > $CFG->frontpagecourselimit) {
1965 // There are more enrolled courses than we can display, display link to 'My courses'.
1966 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
1967 $chelper->set_courses_display_options(array(
1968 'viewmoreurl' => new moodle_url('/my/'),
1969 'viewmoretext' => new lang_string('mycourses')
1971 } else if (core_course_category::top()->is_uservisible()) {
1972 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
1973 $chelper->set_courses_display_options(array(
1974 'viewmoreurl' => new moodle_url('/course/index.php'),
1975 'viewmoretext' => new lang_string('fulllistofcourses')
1977 $totalcount = $DB->count_records('course') - 1;
1979 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
1980 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
1981 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
1983 // MNET
1984 if (!empty($rcourses)) {
1985 // at the IDP, we know of all the remote courses
1986 $output .= html_writer::start_tag('div', array('class' => 'courses'));
1987 foreach ($rcourses as $course) {
1988 $output .= $this->frontpage_remote_course($course);
1990 $output .= html_writer::end_tag('div'); // .courses
1991 } elseif (!empty($rhosts)) {
1992 // non-IDP, we know of all the remote servers, but not courses
1993 $output .= html_writer::start_tag('div', array('class' => 'courses'));
1994 foreach ($rhosts as $host) {
1995 $output .= $this->frontpage_remote_host($host);
1997 $output .= html_writer::end_tag('div'); // .courses
2000 return $output;
2004 * Returns HTML to print list of available courses for the frontpage
2006 * @return string
2008 public function frontpage_available_courses() {
2009 global $CFG;
2011 $chelper = new coursecat_helper();
2012 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2013 set_courses_display_options(array(
2014 'recursive' => true,
2015 'limit' => $CFG->frontpagecourselimit,
2016 'viewmoreurl' => new moodle_url('/course/index.php'),
2017 'viewmoretext' => new lang_string('fulllistofcourses')));
2019 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
2020 $courses = core_course_category::top()->get_courses($chelper->get_courses_display_options());
2021 $totalcount = core_course_category::top()->get_courses_count($chelper->get_courses_display_options());
2022 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
2023 // Print link to create a new course, for the 1st available category.
2024 return $this->add_new_course_button();
2026 return $this->coursecat_courses($chelper, $courses, $totalcount);
2030 * Returns HTML to the "add new course" button for the page
2032 * @return string
2034 public function add_new_course_button() {
2035 global $CFG;
2036 // Print link to create a new course, for the 1st available category.
2037 $output = $this->container_start('buttons');
2038 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2039 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2040 $output .= $this->container_end('buttons');
2041 return $output;
2045 * Returns HTML to print tree with course categories and courses for the frontpage
2047 * @return string
2049 public function frontpage_combo_list() {
2050 global $CFG;
2051 // TODO MDL-10965 improve.
2052 $tree = core_course_category::top();
2053 if (!$tree->get_children_count()) {
2054 return '';
2056 $chelper = new coursecat_helper();
2057 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2058 set_categories_display_options(array(
2059 'limit' => $CFG->coursesperpage,
2060 'viewmoreurl' => new moodle_url('/course/index.php',
2061 array('browse' => 'categories', 'page' => 1))
2062 ))->
2063 set_courses_display_options(array(
2064 'limit' => $CFG->coursesperpage,
2065 'viewmoreurl' => new moodle_url('/course/index.php',
2066 array('browse' => 'courses', 'page' => 1))
2067 ))->
2068 set_attributes(array('class' => 'frontpage-category-combo'));
2069 return $this->coursecat_tree($chelper, $tree);
2073 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2075 * @return string
2077 public function frontpage_categories_list() {
2078 global $CFG;
2079 // TODO MDL-10965 improve.
2080 $tree = core_course_category::top();
2081 if (!$tree->get_children_count()) {
2082 return '';
2084 $chelper = new coursecat_helper();
2085 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2086 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2087 set_categories_display_options(array(
2088 'limit' => $CFG->coursesperpage,
2089 'viewmoreurl' => new moodle_url('/course/index.php',
2090 array('browse' => 'categories', 'page' => 1))
2091 ))->
2092 set_attributes(array('class' => 'frontpage-category-names'));
2093 return $this->coursecat_tree($chelper, $tree);
2097 * Renders the activity navigation.
2099 * Defer to template.
2101 * @param \core_course\output\activity_navigation $page
2102 * @return string html for the page
2104 public function render_activity_navigation(\core_course\output\activity_navigation $page) {
2105 $data = $page->export_for_template($this->output);
2106 return $this->output->render_from_template('core_course/activity_navigation', $data);
2110 * Display waiting information about backup size during uploading backup process
2111 * @param object $backupfile the backup stored_file
2112 * @return $html string
2114 public function sendingbackupinfo($backupfile) {
2115 $sizeinfo = new stdClass();
2116 $sizeinfo->total = number_format($backupfile->get_filesize() / 1000000, 2);
2117 $html = html_writer::tag('div', get_string('sendingsize', 'hub', $sizeinfo),
2118 array('class' => 'courseuploadtextinfo'));
2119 return $html;
2123 * Hub information (logo - name - description - link)
2124 * @param object $hubinfo
2125 * @return string html code
2127 public function hubinfo($hubinfo) {
2128 $screenshothtml = html_writer::empty_tag('img',
2129 array('src' => $hubinfo['imgurl'], 'alt' => $hubinfo['name']));
2130 $hubdescription = html_writer::tag('div', $screenshothtml,
2131 array('class' => 'hubscreenshot'));
2133 $hubdescription .= html_writer::tag('a', $hubinfo['name'],
2134 array('class' => 'hublink', 'href' => $hubinfo['url'],
2135 'onclick' => 'this.target="_blank"'));
2137 $hubdescription .= html_writer::tag('div', format_text($hubinfo['description'], FORMAT_PLAIN),
2138 array('class' => 'hubdescription'));
2139 $hubdescription = html_writer::tag('div', $hubdescription, array('class' => 'hubinfo clearfix'));
2141 return $hubdescription;
2145 * Output frontpage summary text and frontpage modules (stored as section 1 in site course)
2147 * This may be disabled in settings
2149 * @return string
2151 public function frontpage_section1() {
2152 global $SITE, $USER;
2154 $output = '';
2155 $editing = $this->page->user_is_editing();
2157 if ($editing) {
2158 // Make sure section with number 1 exists.
2159 course_create_sections_if_missing($SITE, 1);
2162 $modinfo = get_fast_modinfo($SITE);
2163 $section = $modinfo->get_section_info(1);
2164 if (($section && (!empty($modinfo->sections[1]) or !empty($section->summary))) or $editing) {
2165 $output .= $this->box_start('generalbox sitetopic');
2167 // If currently moving a file then show the current clipboard.
2168 if (ismoving($SITE->id)) {
2169 $stractivityclipboard = strip_tags(get_string('activityclipboard', '', $USER->activitycopyname));
2170 $output .= '<p><font size="2">';
2171 $cancelcopyurl = new moodle_url('/course/mod.php', ['cancelcopy' => 'true', 'sesskey' => sesskey()]);
2172 $output .= "$stractivityclipboard&nbsp;&nbsp;(" . html_writer::link($cancelcopyurl, get_string('cancel')) .')';
2173 $output .= '</font></p>';
2176 $context = context_course::instance(SITEID);
2178 // If the section name is set we show it.
2179 if (trim($section->name) !== '') {
2180 $output .= $this->heading(
2181 format_string($section->name, true, array('context' => $context)),
2183 'sectionname'
2187 $summarytext = file_rewrite_pluginfile_urls($section->summary,
2188 'pluginfile.php',
2189 $context->id,
2190 'course',
2191 'section',
2192 $section->id);
2193 $summaryformatoptions = new stdClass();
2194 $summaryformatoptions->noclean = true;
2195 $summaryformatoptions->overflowdiv = true;
2197 $output .= format_text($summarytext, $section->summaryformat, $summaryformatoptions);
2199 if ($editing && has_capability('moodle/course:update', $context)) {
2200 $streditsummary = get_string('editsummary');
2201 $editsectionurl = new moodle_url('/course/editsection.php', ['id' => $section->id]);
2202 $output .= html_writer::link($editsectionurl, $this->pix_icon('t/edit', $streditsummary)) .
2203 "<br /><br />";
2206 $output .= $this->course_section_cm_list($SITE, $section);
2208 $output .= $this->course_section_add_cm_control($SITE, $section->section);
2209 $output .= $this->box_end();
2212 return $output;
2216 * Output news for the frontpage (extract from site-wide news forum)
2218 * @param stdClass $forum record from db table 'forum' that represents the site news forum
2219 * @return string
2221 protected function frontpage_news($forum) {
2222 global $CFG, $SITE, $SESSION, $USER;
2223 require_once($CFG->dirroot .'/mod/forum/lib.php');
2225 $output = '';
2227 if (isloggedin()) {
2228 $SESSION->fromdiscussion = $CFG->wwwroot;
2229 $subtext = '';
2230 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forum)) {
2231 if (!\mod_forum\subscriptions::is_forcesubscribed($forum)) {
2232 $subtext = get_string('unsubscribe', 'forum');
2234 } else {
2235 $subtext = get_string('subscribe', 'forum');
2237 $suburl = new moodle_url('/mod/forum/subscribe.php', array('id' => $forum->id, 'sesskey' => sesskey()));
2238 $output .= html_writer::tag('div', html_writer::link($suburl, $subtext), array('class' => 'subscribelink'));
2241 $coursemodule = get_coursemodule_from_instance('forum', $forum->id);
2242 $context = context_module::instance($coursemodule->id);
2244 $entityfactory = mod_forum\local\container::get_entity_factory();
2245 $forumentity = $entityfactory->get_forum_from_stdclass($forum, $context, $coursemodule, $SITE);
2247 $rendererfactory = mod_forum\local\container::get_renderer_factory();
2248 $discussionsrenderer = $rendererfactory->get_frontpage_news_discussion_list_renderer($forumentity);
2249 $cm = \cm_info::create($coursemodule);
2250 return $output . $discussionsrenderer->render($USER, $cm, null, null, 0, $SITE->newsitems);
2254 * Renders part of frontpage with a skip link (i.e. "My courses", "Site news", etc.)
2256 * @param string $skipdivid
2257 * @param string $contentsdivid
2258 * @param string $header Header of the part
2259 * @param string $contents Contents of the part
2260 * @return string
2262 protected function frontpage_part($skipdivid, $contentsdivid, $header, $contents) {
2263 if (strval($contents) === '') {
2264 return '';
2266 $output = html_writer::link('#' . $skipdivid,
2267 get_string('skipa', 'access', core_text::strtolower(strip_tags($header))),
2268 array('class' => 'skip-block skip'));
2270 // Wrap frontpage part in div container.
2271 $output .= html_writer::start_tag('div', array('id' => $contentsdivid));
2272 $output .= $this->heading($header);
2274 $output .= $contents;
2276 // End frontpage part div container.
2277 $output .= html_writer::end_tag('div');
2279 $output .= html_writer::tag('span', '', array('class' => 'skip-block-to', 'id' => $skipdivid));
2280 return $output;
2284 * Outputs contents for frontpage as configured in $CFG->frontpage or $CFG->frontpageloggedin
2286 * @return string
2288 public function frontpage() {
2289 global $CFG, $SITE;
2291 $output = '';
2293 if (isloggedin() and !isguestuser() and isset($CFG->frontpageloggedin)) {
2294 $frontpagelayout = $CFG->frontpageloggedin;
2295 } else {
2296 $frontpagelayout = $CFG->frontpage;
2299 foreach (explode(',', $frontpagelayout) as $v) {
2300 switch ($v) {
2301 // Display the main part of the front page.
2302 case FRONTPAGENEWS:
2303 if ($SITE->newsitems) {
2304 // Print forums only when needed.
2305 require_once($CFG->dirroot .'/mod/forum/lib.php');
2306 if (($newsforum = forum_get_course_forum($SITE->id, 'news')) &&
2307 ($forumcontents = $this->frontpage_news($newsforum))) {
2308 $newsforumcm = get_fast_modinfo($SITE)->instances['forum'][$newsforum->id];
2309 $output .= $this->frontpage_part('skipsitenews', 'site-news-forum',
2310 $newsforumcm->get_formatted_name(), $forumcontents);
2313 break;
2315 case FRONTPAGEENROLLEDCOURSELIST:
2316 $mycourseshtml = $this->frontpage_my_courses();
2317 if (!empty($mycourseshtml)) {
2318 $output .= $this->frontpage_part('skipmycourses', 'frontpage-course-list',
2319 get_string('mycourses'), $mycourseshtml);
2321 break;
2323 case FRONTPAGEALLCOURSELIST:
2324 $availablecourseshtml = $this->frontpage_available_courses();
2325 $output .= $this->frontpage_part('skipavailablecourses', 'frontpage-available-course-list',
2326 get_string('availablecourses'), $availablecourseshtml);
2327 break;
2329 case FRONTPAGECATEGORYNAMES:
2330 $output .= $this->frontpage_part('skipcategories', 'frontpage-category-names',
2331 get_string('categories'), $this->frontpage_categories_list());
2332 break;
2334 case FRONTPAGECATEGORYCOMBO:
2335 $output .= $this->frontpage_part('skipcourses', 'frontpage-category-combo',
2336 get_string('courses'), $this->frontpage_combo_list());
2337 break;
2339 case FRONTPAGECOURSESEARCH:
2340 $output .= $this->box($this->course_search_form('', 'short'), 'mdl-align');
2341 break;
2344 $output .= '<br />';
2347 return $output;
2352 * Class storing display options and functions to help display course category and/or courses lists
2354 * This is a wrapper for core_course_category objects that also stores display options
2355 * and functions to retrieve sorted and paginated lists of categories/courses.
2357 * If theme overrides methods in core_course_renderers that access this class
2358 * it may as well not use this class at all or extend it.
2360 * @package core
2361 * @copyright 2013 Marina Glancy
2362 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2364 class coursecat_helper {
2365 /** @var string [none, collapsed, expanded] how (if) display courses list */
2366 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2367 /** @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) */
2368 protected $subcatdepth = 1;
2369 /** @var array options to display courses list */
2370 protected $coursesdisplayoptions = array();
2371 /** @var array options to display subcategories list */
2372 protected $categoriesdisplayoptions = array();
2373 /** @var array additional HTML attributes */
2374 protected $attributes = array();
2375 /** @var array search criteria if the list is a search result */
2376 protected $searchcriteria = null;
2379 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2381 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2382 * @return coursecat_helper
2384 public function set_show_courses($showcourses) {
2385 $this->showcourses = $showcourses;
2386 // Automatically set the options to preload summary and coursecontacts for core_course_category::get_courses()
2387 // and core_course_category::search_courses().
2388 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2389 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2390 $this->coursesdisplayoptions['customfields'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED;
2391 return $this;
2395 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2397 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2399 public function get_show_courses() {
2400 return $this->showcourses;
2404 * Sets the maximum depth to expand subcategories in the tree
2406 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2408 * @param int $subcatdepth
2409 * @return coursecat_helper
2411 public function set_subcat_depth($subcatdepth) {
2412 $this->subcatdepth = $subcatdepth;
2413 return $this;
2417 * Returns the maximum depth to expand subcategories in the tree
2419 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2421 * @return int
2423 public function get_subcat_depth() {
2424 return $this->subcatdepth;
2428 * Sets options to display list of courses
2430 * Options are later submitted as argument to core_course_category::get_courses() and/or core_course_category::search_courses()
2432 * Options that core_course_category::get_courses() accept:
2433 * - recursive - return courses from subcategories as well. Use with care,
2434 * this may be a huge list!
2435 * - summary - preloads fields 'summary' and 'summaryformat'
2436 * - coursecontacts - preloads course contacts
2437 * - customfields - preloads custom fields data
2438 * - isenrolled - preloads indication whether this user is enrolled in the course
2439 * - sort - list of fields to sort. Example
2440 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2441 * will sort by idnumber asc, shortname asc and id desc.
2442 * Default: array('sortorder' => 1)
2443 * Only cached fields may be used for sorting!
2444 * - offset
2445 * - limit - maximum number of children to return, 0 or null for no limit
2447 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2449 * Also renderer can set here any additional options it wants to pass between renderer functions.
2451 * @param array $options
2452 * @return coursecat_helper
2454 public function set_courses_display_options($options) {
2455 $this->coursesdisplayoptions = $options;
2456 $this->set_show_courses($this->showcourses); // this will calculate special display options
2457 return $this;
2461 * Sets one option to display list of courses
2463 * @see coursecat_helper::set_courses_display_options()
2465 * @param string $key
2466 * @param mixed $value
2467 * @return coursecat_helper
2469 public function set_courses_display_option($key, $value) {
2470 $this->coursesdisplayoptions[$key] = $value;
2471 return $this;
2475 * Return the specified option to display list of courses
2477 * @param string $optionname option name
2478 * @param mixed $defaultvalue default value for option if it is not specified
2479 * @return mixed
2481 public function get_courses_display_option($optionname, $defaultvalue = null) {
2482 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2483 return $this->coursesdisplayoptions[$optionname];
2484 } else {
2485 return $defaultvalue;
2490 * Returns all options to display the courses
2492 * This array is usually passed to {@link core_course_category::get_courses()} or
2493 * {@link core_course_category::search_courses()}
2495 * @return array
2497 public function get_courses_display_options() {
2498 return $this->coursesdisplayoptions;
2502 * Sets options to display list of subcategories
2504 * Options 'sort', 'offset' and 'limit' are passed to core_course_category::get_children().
2505 * Any other options may be used by renderer functions
2507 * @param array $options
2508 * @return coursecat_helper
2510 public function set_categories_display_options($options) {
2511 $this->categoriesdisplayoptions = $options;
2512 return $this;
2516 * Return the specified option to display list of subcategories
2518 * @param string $optionname option name
2519 * @param mixed $defaultvalue default value for option if it is not specified
2520 * @return mixed
2522 public function get_categories_display_option($optionname, $defaultvalue = null) {
2523 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2524 return $this->categoriesdisplayoptions[$optionname];
2525 } else {
2526 return $defaultvalue;
2531 * Returns all options to display list of subcategories
2533 * This array is usually passed to {@link core_course_category::get_children()}
2535 * @return array
2537 public function get_categories_display_options() {
2538 return $this->categoriesdisplayoptions;
2542 * Sets additional general options to pass between renderer functions, usually HTML attributes
2544 * @param array $attributes
2545 * @return coursecat_helper
2547 public function set_attributes($attributes) {
2548 $this->attributes = $attributes;
2549 return $this;
2553 * Return all attributes and erases them so they are not applied again
2555 * @param string $classname adds additional class name to the beginning of $attributes['class']
2556 * @return array
2558 public function get_and_erase_attributes($classname) {
2559 $attributes = $this->attributes;
2560 $this->attributes = array();
2561 if (empty($attributes['class'])) {
2562 $attributes['class'] = '';
2564 $attributes['class'] = $classname . ' '. $attributes['class'];
2565 return $attributes;
2569 * Sets the search criteria if the course is a search result
2571 * Search string will be used to highlight terms in course name and description
2573 * @param array $searchcriteria
2574 * @return coursecat_helper
2576 public function set_search_criteria($searchcriteria) {
2577 $this->searchcriteria = $searchcriteria;
2578 return $this;
2582 * Returns formatted and filtered description of the given category
2584 * @param core_course_category $coursecat category
2585 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2586 * if context is not specified it will be added automatically
2587 * @return string|null
2589 public function get_category_formatted_description($coursecat, $options = null) {
2590 if ($coursecat->id && $coursecat->is_uservisible() && !empty($coursecat->description)) {
2591 if (!isset($coursecat->descriptionformat)) {
2592 $descriptionformat = FORMAT_MOODLE;
2593 } else {
2594 $descriptionformat = $coursecat->descriptionformat;
2596 if ($options === null) {
2597 $options = array('noclean' => true, 'overflowdiv' => true);
2598 } else {
2599 $options = (array)$options;
2601 $context = context_coursecat::instance($coursecat->id);
2602 if (!isset($options['context'])) {
2603 $options['context'] = $context;
2605 $text = file_rewrite_pluginfile_urls($coursecat->description,
2606 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2607 return format_text($text, $descriptionformat, $options);
2609 return null;
2613 * Returns given course's summary with proper embedded files urls and formatted
2615 * @param core_course_list_element $course
2616 * @param array|stdClass $options additional formatting options
2617 * @return string
2619 public function get_course_formatted_summary($course, $options = array()) {
2620 global $CFG;
2621 require_once($CFG->libdir. '/filelib.php');
2622 if (!$course->has_summary()) {
2623 return '';
2625 $options = (array)$options;
2626 $context = context_course::instance($course->id);
2627 if (!isset($options['context'])) {
2628 // TODO see MDL-38521
2629 // option 1 (current), page context - no code required
2630 // option 2, system context
2631 // $options['context'] = context_system::instance();
2632 // option 3, course context:
2633 // $options['context'] = $context;
2634 // option 4, course category context:
2635 // $options['context'] = $context->get_parent_context();
2637 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2638 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2639 if (!empty($this->searchcriteria['search'])) {
2640 $summary = highlight($this->searchcriteria['search'], $summary);
2642 return $summary;
2646 * Returns course name as it is configured to appear in courses lists formatted to course context
2648 * @param core_course_list_element $course
2649 * @param array|stdClass $options additional formatting options
2650 * @return string
2652 public function get_course_formatted_name($course, $options = array()) {
2653 $options = (array)$options;
2654 if (!isset($options['context'])) {
2655 $options['context'] = context_course::instance($course->id);
2657 $name = format_string(get_course_display_name_for_list($course), true, $options);
2658 if (!empty($this->searchcriteria['search'])) {
2659 $name = highlight($this->searchcriteria['search'], $name);
2661 return $name;