MDL-68314 core_contentbank: Backup and restore tests
[moodle.git] / course / renderer.php
blob8d58bc8998c8919d6c3051aa4d2899ff3b377d0a
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Renderer for use with the course section and all the goodness that falls
20 * within it.
22 * This renderer should contain methods useful to courses, and categories.
24 * @package moodlecore
25 * @copyright 2010 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 /**
30 * The core course renderer
32 * Can be retrieved with the following:
33 * $renderer = $PAGE->get_renderer('core','course');
35 class core_course_renderer extends plugin_renderer_base {
36 const COURSECAT_SHOW_COURSES_NONE = 0; /* do not show courses at all */
37 const COURSECAT_SHOW_COURSES_COUNT = 5; /* do not show courses but show number of courses next to category name */
38 const COURSECAT_SHOW_COURSES_COLLAPSED = 10;
39 const COURSECAT_SHOW_COURSES_AUTO = 15; /* will choose between collapsed and expanded automatically */
40 const COURSECAT_SHOW_COURSES_EXPANDED = 20;
41 const COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT = 30;
43 const COURSECAT_TYPE_CATEGORY = 0;
44 const COURSECAT_TYPE_COURSE = 1;
46 /**
47 * A cache of strings
48 * @var stdClass
50 protected $strings;
52 /**
53 * Whether a category content is being initially rendered with children. This is mainly used by the
54 * core_course_renderer::corsecat_tree() to render the appropriate action for the Expand/Collapse all link on
55 * page load.
56 * @var bool
58 protected $categoryexpandedonload = false;
60 /**
61 * Override the constructor so that we can initialise the string cache
63 * @param moodle_page $page
64 * @param string $target
66 public function __construct(moodle_page $page, $target) {
67 $this->strings = new stdClass;
68 parent::__construct($page, $target);
71 /**
72 * @deprecated since 3.2
74 protected function add_modchoosertoggle() {
75 throw new coding_exception('core_course_renderer::add_modchoosertoggle() can not be used anymore.');
78 /**
79 * Renders course info box.
81 * @param stdClass $course
82 * @return string
84 public function course_info_box(stdClass $course) {
85 $content = '';
86 $content .= $this->output->box_start('generalbox info');
87 $chelper = new coursecat_helper();
88 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
89 $content .= $this->coursecat_coursebox($chelper, $course);
90 $content .= $this->output->box_end();
91 return $content;
94 /**
95 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
97 * @deprecated since 2.5
99 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
101 * @param array $ignored argument ignored
102 * @return string
104 public final function course_category_tree(array $ignored) {
105 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
106 return $this->frontpage_combo_list();
110 * Renderers a category for use with course_category_tree
112 * @deprecated since 2.5
114 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
116 * @param array $category
117 * @param int $depth
118 * @return string
120 protected final function course_category_tree_category(stdClass $category, $depth=1) {
121 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
122 return '';
126 * Render a modchooser.
128 * @param renderable $modchooser The chooser.
129 * @return string
131 public function render_modchooser(renderable $modchooser) {
132 return $this->render_from_template('core_course/modchooser', $modchooser->export_for_template($this));
136 * Build the HTML for the module chooser javascript popup
138 * @param array $modules A set of modules as returned form @see
139 * get_module_metadata
140 * @param object $course The course that will be displayed
141 * @return string The composed HTML for the module
143 public function course_modchooser($modules, $course) {
144 debugging('course_modchooser() is deprecated. Please use course_activitychooser() instead.', DEBUG_DEVELOPER);
146 return $this->course_activitychooser($course->id);
150 * Build the HTML for the module chooser javascript popup.
152 * @param int $courseid The course id to fetch modules for.
153 * @return string
155 public function course_activitychooser($courseid) {
157 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchooser')) {
158 return '';
161 $this->page->requires->js_call_amd('core_course/activitychooser', 'init', [$courseid]);
163 return '';
167 * Build the HTML for a specified set of modules
169 * @param array $modules A set of modules as used by the
170 * course_modchooser_module function
171 * @return string The composed HTML for the module
173 protected function course_modchooser_module_types($modules) {
174 debugging('Method core_course_renderer::course_modchooser_module_types() is deprecated, ' .
175 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
176 return '';
180 * Return the HTML for the specified module adding any required classes
182 * @param object $module An object containing the title, and link. An
183 * icon, and help text may optionally be specified. If the module
184 * contains subtypes in the types option, then these will also be
185 * displayed.
186 * @param array $classes Additional classes to add to the encompassing
187 * div element
188 * @return string The composed HTML for the module
190 protected function course_modchooser_module($module, $classes = array('option')) {
191 debugging('Method core_course_renderer::course_modchooser_module() is deprecated, ' .
192 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
193 return '';
196 protected function course_modchooser_title($title, $identifier = null) {
197 debugging('Method core_course_renderer::course_modchooser_title() is deprecated, ' .
198 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
199 return '';
203 * Renders HTML for displaying the sequence of course module editing buttons
205 * @see course_get_cm_edit_actions()
207 * @param action_link[] $actions Array of action_link objects
208 * @param cm_info $mod The module we are displaying actions for.
209 * @param array $displayoptions additional display options:
210 * ownerselector => A JS/CSS selector that can be used to find an cm node.
211 * If specified the owning node will be given the class 'action-menu-shown' when the action
212 * menu is being displayed.
213 * constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
214 * the action menu to when it is being displayed.
215 * donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
216 * @return string
218 public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
219 global $CFG;
221 if (empty($actions)) {
222 return '';
225 if (isset($displayoptions['ownerselector'])) {
226 $ownerselector = $displayoptions['ownerselector'];
227 } else if ($mod) {
228 $ownerselector = '#module-'.$mod->id;
229 } else {
230 debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
231 $ownerselector = 'li.activity';
234 if (isset($displayoptions['constraintselector'])) {
235 $constraint = $displayoptions['constraintselector'];
236 } else {
237 $constraint = '.course-content';
240 $menu = new action_menu();
241 $menu->set_owner_selector($ownerselector);
242 $menu->set_constraint($constraint);
243 $menu->set_alignment(action_menu::TR, action_menu::BR);
244 $menu->set_menu_trigger(get_string('edit'));
246 foreach ($actions as $action) {
247 if ($action instanceof action_menu_link) {
248 $action->add_class('cm-edit-action');
250 $menu->add($action);
252 $menu->attributes['class'] .= ' section-cm-edit-actions commands';
254 // Prioritise the menu ahead of all other actions.
255 $menu->prioritise = true;
257 return $this->render($menu);
261 * Renders HTML for the menus to add activities and resources to the current course
263 * @param stdClass $course
264 * @param int $section relative section number (field course_sections.section)
265 * @param int $sectionreturn The section to link back to
266 * @param array $displayoptions additional display options, for example blocks add
267 * option 'inblock' => true, suggesting to display controls vertically
268 * @return string
270 function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
271 global $CFG, $USER;
273 // The returned control HTML can be one of the following:
274 // - Only the non-ajax control (select menus of activities and resources) with a noscript fallback for non js clients.
275 // - Only the ajax control (the link which when clicked produces the activity chooser modal). No noscript fallback.
276 // - [Behat only]: The non-ajax control and optionally the ajax control (depending on site settings). If included, the link
277 // takes priority and the non-ajax control is wrapped in a <noscript>.
278 // Behat requires the third case because some features run with JS, some do not. We must include the noscript fallback.
279 $behatsite = defined('BEHAT_SITE_RUNNING');
280 $nonajaxcontrol = '';
281 $ajaxcontrol = '';
282 $courseajaxenabled = course_ajax_enabled($course);
283 $userchooserenabled = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
285 // Decide what combination of controls to output:
286 // During behat runs, both controls can be used in conjunction to provide non-js fallback.
287 // During normal use only one control or the other will be output. No non-js fallback is needed.
288 $rendernonajaxcontrol = $behatsite || !$courseajaxenabled || !$userchooserenabled || $course->id != $this->page->course->id;
289 $renderajaxcontrol = $courseajaxenabled && $userchooserenabled && $course->id == $this->page->course->id;
291 // The non-ajax control, which includes an entirely non-js (<noscript>) fallback too.
292 if ($rendernonajaxcontrol) {
293 $vertical = !empty($displayoptions['inblock']);
295 // Check to see if user can add menus.
296 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
297 || !$this->page->user_is_editing()) {
298 return '';
301 // Retrieve all modules with associated metadata.
302 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
303 $urlparams = ['section' => $section];
304 if (!is_null($sectionreturn)) {
305 $urlparams['sr'] = $sectionreturn;
307 $modules = $contentitemservice->get_content_items_for_user_in_course($USER, $course, $urlparams);
309 // Return if there are no content items to add.
310 if (empty($modules)) {
311 return '';
314 // We'll sort resources and activities into two lists.
315 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
317 foreach ($modules as $module) {
318 $activityclass = MOD_CLASS_ACTIVITY;
319 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
320 $activityclass = MOD_CLASS_RESOURCE;
321 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
322 // System modules cannot be added by user, do not add to dropdown.
323 continue;
325 $link = $module->link;
326 $activities[$activityclass][$link] = $module->title;
329 $straddactivity = get_string('addactivity');
330 $straddresource = get_string('addresource');
331 $sectionname = get_section_name($course, $section);
332 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
333 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
335 $nonajaxcontrol = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-'
336 . $section));
338 if (!$vertical) {
339 $nonajaxcontrol .= html_writer::start_tag('div', array('class' => 'horizontal'));
342 if (!empty($activities[MOD_CLASS_RESOURCE])) {
343 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array('' => $straddresource), "ressection$section");
344 $select->set_help_icon('resources');
345 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
346 $nonajaxcontrol .= $this->output->render($select);
349 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
350 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array('' => $straddactivity), "section$section");
351 $select->set_help_icon('activities');
352 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
353 $nonajaxcontrol .= $this->output->render($select);
356 if (!$vertical) {
357 $nonajaxcontrol .= html_writer::end_tag('div');
360 $nonajaxcontrol .= html_writer::end_tag('div');
363 // The ajax control - the 'Add an activity or resource' link.
364 if ($renderajaxcontrol) {
365 // The module chooser link.
366 $straddeither = get_string('addresourceoractivity');
367 $ajaxcontrol = html_writer::start_tag('div', array('class' => 'mdl-right'));
368 $ajaxcontrol .= html_writer::start_tag('div', array('class' => 'section-modchooser'));
369 $icon = $this->output->pix_icon('t/add', '');
370 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
371 $ajaxcontrol .= html_writer::tag('button', $icon . $span, [
372 'class' => 'section-modchooser-link btn btn-link',
373 'data-action' => 'open-chooser',
374 'data-sectionid' => $section,
377 $ajaxcontrol .= html_writer::end_tag('div');
378 $ajaxcontrol .= html_writer::end_tag('div');
380 // Load the JS for the modal.
381 $this->course_activitychooser($course->id);
384 // Behat only: If both controls are being included in the HTML,
385 // show the link by default and only fall back to the selects if js is disabled.
386 if ($behatsite && $renderajaxcontrol) {
387 $nonajaxcontrol = html_writer::tag('div', $nonajaxcontrol, array('class' => 'hiddenifjs addresourcedropdown'));
388 $ajaxcontrol = html_writer::tag('div', $ajaxcontrol, array('class' => 'visibleifjs addresourcemodchooser'));
391 // If behat is running, we should have the non-ajax control + the ajax control.
392 // Otherwise, we'll have one or the other.
393 return $ajaxcontrol . $nonajaxcontrol;
397 * Renders html to display a course search form.
399 * @param string $value default value to populate the search field
400 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
401 * @return string
403 public function course_search_form($value = '', $format = 'plain') {
404 static $count = 0;
405 $formid = 'coursesearch';
406 if ((++$count) > 1) {
407 $formid .= $count;
410 switch ($format) {
411 case 'navbar' :
412 $formid = 'coursesearchnavbar';
413 $inputid = 'navsearchbox';
414 $inputsize = 20;
415 break;
416 case 'short' :
417 $inputid = 'shortsearchbox';
418 $inputsize = 12;
419 break;
420 default :
421 $inputid = 'coursesearchbox';
422 $inputsize = 30;
425 $data = new stdClass();
426 $data->searchurl = \core_search\manager::get_course_search_url()->out(false);
427 $data->id = $formid;
428 $data->inputid = $inputid;
429 $data->inputsize = $inputsize;
430 $data->value = $value;
431 $data->areaids = 'core_course-course';
433 if ($format != 'navbar') {
434 $helpicon = new \help_icon('coursesearch', 'core');
435 $data->helpicon = $helpicon->export_for_template($this);
438 return $this->render_from_template('core_course/course_search_form', $data);
442 * Renders html for completion box on course page
444 * If completion is disabled, returns empty string
445 * If completion is automatic, returns an icon of the current completion state
446 * If completion is manual, returns a form (with an icon inside) that allows user to
447 * toggle completion
449 * @param stdClass $course course object
450 * @param completion_info $completioninfo completion info for the course, it is recommended
451 * to fetch once for all modules in course/section for performance
452 * @param cm_info $mod module to show completion for
453 * @param array $displayoptions display options, not used in core
454 * @return string
456 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
457 global $CFG, $DB, $USER;
458 $output = '';
460 $istrackeduser = $completioninfo->is_tracked_user($USER->id);
461 $isediting = $this->page->user_is_editing();
463 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
464 return $output;
466 if ($completioninfo === null) {
467 $completioninfo = new completion_info($course);
469 $completion = $completioninfo->is_enabled($mod);
471 if ($completion == COMPLETION_TRACKING_NONE) {
472 if ($isediting) {
473 $output .= html_writer::span('&nbsp;', 'filler');
475 return $output;
478 $completionicon = '';
480 if ($isediting || !$istrackeduser) {
481 switch ($completion) {
482 case COMPLETION_TRACKING_MANUAL :
483 $completionicon = 'manual-enabled'; break;
484 case COMPLETION_TRACKING_AUTOMATIC :
485 $completionicon = 'auto-enabled'; break;
487 } else {
488 $completiondata = $completioninfo->get_data($mod, true);
489 if ($completion == COMPLETION_TRACKING_MANUAL) {
490 switch($completiondata->completionstate) {
491 case COMPLETION_INCOMPLETE:
492 $completionicon = 'manual-n' . ($completiondata->overrideby ? '-override' : '');
493 break;
494 case COMPLETION_COMPLETE:
495 $completionicon = 'manual-y' . ($completiondata->overrideby ? '-override' : '');
496 break;
498 } else { // Automatic
499 switch($completiondata->completionstate) {
500 case COMPLETION_INCOMPLETE:
501 $completionicon = 'auto-n' . ($completiondata->overrideby ? '-override' : '');
502 break;
503 case COMPLETION_COMPLETE:
504 $completionicon = 'auto-y' . ($completiondata->overrideby ? '-override' : '');
505 break;
506 case COMPLETION_COMPLETE_PASS:
507 $completionicon = 'auto-pass'; break;
508 case COMPLETION_COMPLETE_FAIL:
509 $completionicon = 'auto-fail'; break;
513 if ($completionicon) {
514 $formattedname = html_entity_decode($mod->get_formatted_name(), ENT_QUOTES, 'UTF-8');
515 if (!$isediting && $istrackeduser && $completiondata->overrideby) {
516 $args = new stdClass();
517 $args->modname = $formattedname;
518 $overridebyuser = \core_user::get_user($completiondata->overrideby, '*', MUST_EXIST);
519 $args->overrideuser = fullname($overridebyuser);
520 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $args);
521 } else {
522 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
525 if ($isediting || !$istrackeduser || !has_capability('moodle/course:togglecompletion', $mod->context)) {
526 // When editing, the icon is just an image.
527 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
528 array('title' => $imgalt, 'class' => 'iconsmall'));
529 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
530 array('class' => 'autocompletion'));
531 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
532 $newstate =
533 $completiondata->completionstate == COMPLETION_COMPLETE
534 ? COMPLETION_INCOMPLETE
535 : COMPLETION_COMPLETE;
536 // In manual mode the icon is a toggle form...
538 // If this completion state is used by the
539 // conditional activities system, we need to turn
540 // off the JS.
541 $extraclass = '';
542 if (!empty($CFG->enableavailability) &&
543 core_availability\info::completion_value_used($course, $mod->id)) {
544 $extraclass = ' preventjs';
546 $output .= html_writer::start_tag('form', array('method' => 'post',
547 'action' => new moodle_url('/course/togglecompletion.php'),
548 'class' => 'togglecompletion'. $extraclass));
549 $output .= html_writer::start_tag('div');
550 $output .= html_writer::empty_tag('input', array(
551 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
552 $output .= html_writer::empty_tag('input', array(
553 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
554 $output .= html_writer::empty_tag('input', array(
555 'type' => 'hidden', 'name' => 'modulename', 'value' => $formattedname));
556 $output .= html_writer::empty_tag('input', array(
557 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
558 $output .= html_writer::tag('button',
559 $this->output->pix_icon('i/completion-' . $completionicon, $imgalt),
560 array('class' => 'btn btn-link', 'aria-live' => 'assertive'));
561 $output .= html_writer::end_tag('div');
562 $output .= html_writer::end_tag('form');
563 } else {
564 // In auto mode, the icon is just an image.
565 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
566 array('title' => $imgalt));
567 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
568 array('class' => 'autocompletion'));
571 return $output;
575 * Checks if course module has any conditions that may make it unavailable for
576 * all or some of the students
578 * This function is internal and is only used to create CSS classes for the module name/text
580 * @param cm_info $mod
581 * @return bool
583 protected function is_cm_conditionally_hidden(cm_info $mod) {
584 global $CFG;
585 $conditionalhidden = false;
586 if (!empty($CFG->enableavailability)) {
587 $info = new \core_availability\info_module($mod);
588 $conditionalhidden = !$info->is_available_for_all();
590 return $conditionalhidden;
594 * Renders html to display a name with the link to the course module on a course page
596 * If module is unavailable for user but still needs to be displayed
597 * in the list, just the name is returned without a link
599 * Note, that for course modules that never have separate pages (i.e. labels)
600 * this function return an empty string
602 * @param cm_info $mod
603 * @param array $displayoptions
604 * @return string
606 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
607 if (!$mod->is_visible_on_course_page() || !$mod->url) {
608 // Nothing to be displayed to the user.
609 return '';
612 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
613 $groupinglabel = $mod->get_grouping_label($textclasses);
615 // Render element that allows to edit activity name inline. It calls {@link course_section_cm_name_title()}
616 // to get the display title of the activity.
617 $tmpl = new \core_course\output\course_module_name($mod, $this->page->user_is_editing(), $displayoptions);
618 return $this->output->render_from_template('core/inplace_editable', $tmpl->export_for_template($this->output)) .
619 $groupinglabel;
623 * Returns the CSS classes for the activity name/content
625 * For items which are hidden, unavailable or stealth but should be displayed
626 * to current user ($mod->is_visible_on_course_page()), we show those as dimmed.
627 * Students will also see as dimmed activities names that are not yet available
628 * but should still be displayed (without link) with availability info.
630 * @param cm_info $mod
631 * @return array array of two elements ($linkclasses, $textclasses)
633 protected function course_section_cm_classes(cm_info $mod) {
634 $linkclasses = '';
635 $textclasses = '';
636 if ($mod->uservisible) {
637 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
638 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
639 has_capability('moodle/course:viewhiddenactivities', $mod->context);
640 if ($accessiblebutdim) {
641 $linkclasses .= ' dimmed';
642 $textclasses .= ' dimmed_text';
643 if ($conditionalhidden) {
644 $linkclasses .= ' conditionalhidden';
645 $textclasses .= ' conditionalhidden';
648 if ($mod->is_stealth()) {
649 // Stealth activity is the one that is not visible on course page.
650 // It still may be displayed to the users who can manage it.
651 $linkclasses .= ' stealth';
652 $textclasses .= ' stealth';
654 } else {
655 $linkclasses .= ' dimmed';
656 $textclasses .= ' dimmed dimmed_text';
658 return array($linkclasses, $textclasses);
662 * Renders html to display a name with the link to the course module on a course page
664 * If module is unavailable for user but still needs to be displayed
665 * in the list, just the name is returned without a link
667 * Note, that for course modules that never have separate pages (i.e. labels)
668 * this function return an empty string
670 * @param cm_info $mod
671 * @param array $displayoptions
672 * @return string
674 public function course_section_cm_name_title(cm_info $mod, $displayoptions = array()) {
675 $output = '';
676 $url = $mod->url;
677 if (!$mod->is_visible_on_course_page() || !$url) {
678 // Nothing to be displayed to the user.
679 return $output;
682 //Accessibility: for files get description via icon, this is very ugly hack!
683 $instancename = $mod->get_formatted_name();
684 $altname = $mod->modfullname;
685 // Avoid unnecessary duplication: if e.g. a forum name already
686 // includes the word forum (or Forum, etc) then it is unhelpful
687 // to include that in the accessible description that is added.
688 if (false !== strpos(core_text::strtolower($instancename),
689 core_text::strtolower($altname))) {
690 $altname = '';
692 // File type after name, for alphabetic lists (screen reader).
693 if ($altname) {
694 $altname = get_accesshide(' '.$altname);
697 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
699 // Get on-click attribute value if specified and decode the onclick - it
700 // has already been encoded for display (puke).
701 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
703 // Display link itself.
704 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
705 'class' => 'iconlarge activityicon', 'alt' => '', 'role' => 'presentation', 'aria-hidden' => 'true')) .
706 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
707 if ($mod->uservisible) {
708 $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick));
709 } else {
710 // We may be displaying this just in order to show information
711 // about visibility, without the actual link ($mod->is_visible_on_course_page()).
712 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses));
714 return $output;
718 * Renders html to display the module content on the course page (i.e. text of the labels)
720 * @param cm_info $mod
721 * @param array $displayoptions
722 * @return string
724 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
725 $output = '';
726 if (!$mod->is_visible_on_course_page()) {
727 // nothing to be displayed to the user
728 return $output;
730 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
731 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
732 if ($mod->url && $mod->uservisible) {
733 if ($content) {
734 // If specified, display extra content after link.
735 $output = html_writer::tag('div', $content, array('class' =>
736 trim('contentafterlink ' . $textclasses)));
738 } else {
739 $groupinglabel = $mod->get_grouping_label($textclasses);
741 // No link, so display only content.
742 $output = html_writer::tag('div', $content . $groupinglabel,
743 array('class' => 'contentwithoutlink ' . $textclasses));
745 return $output;
749 * Displays availability info for a course section or course module
751 * @param string $text
752 * @param string $additionalclasses
753 * @return string
755 public function availability_info($text, $additionalclasses = '') {
757 $data = ['text' => $text, 'classes' => $additionalclasses];
758 $additionalclasses = array_filter(explode(' ', $additionalclasses));
760 if (in_array('ishidden', $additionalclasses)) {
761 $data['ishidden'] = 1;
763 } else if (in_array('isstealth', $additionalclasses)) {
764 $data['isstealth'] = 1;
766 } else if (in_array('isrestricted', $additionalclasses)) {
767 $data['isrestricted'] = 1;
769 if (in_array('isfullinfo', $additionalclasses)) {
770 $data['isfullinfo'] = 1;
774 return $this->render_from_template('core/availability_info', $data);
778 * Renders HTML to show course module availability information (for someone who isn't allowed
779 * to see the activity itself, or for staff)
781 * @param cm_info $mod
782 * @param array $displayoptions
783 * @return string
785 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
786 global $CFG;
787 $output = '';
788 if (!$mod->is_visible_on_course_page()) {
789 return $output;
791 if (!$mod->uservisible) {
792 // this is a student who is not allowed to see the module but might be allowed
793 // to see availability info (i.e. "Available from ...")
794 if (!empty($mod->availableinfo)) {
795 $formattedinfo = \core_availability\info::format_info(
796 $mod->availableinfo, $mod->get_course());
797 $output = $this->availability_info($formattedinfo, 'isrestricted');
799 return $output;
801 // this is a teacher who is allowed to see module but still should see the
802 // information that module is not available to all/some students
803 $modcontext = context_module::instance($mod->id);
804 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
805 if ($canviewhidden && !$mod->visible) {
806 // This module is hidden but current user has capability to see it.
807 // Do not display the availability info if the whole section is hidden.
808 if ($mod->get_section_info()->visible) {
809 $output .= $this->availability_info(get_string('hiddenfromstudents'), 'ishidden');
811 } else if ($mod->is_stealth()) {
812 // This module is available but is normally not displayed on the course page
813 // (this user can see it because they can manage it).
814 $output .= $this->availability_info(get_string('hiddenoncoursepage'), 'isstealth');
816 if ($canviewhidden && !empty($CFG->enableavailability)) {
817 // Display information about conditional availability.
818 // Don't add availability information if user is not editing and activity is hidden.
819 if ($mod->visible || $this->page->user_is_editing()) {
820 $hidinfoclass = 'isrestricted isfullinfo';
821 if (!$mod->visible) {
822 $hidinfoclass .= ' hide';
824 $ci = new \core_availability\info_module($mod);
825 $fullinfo = $ci->get_full_information();
826 if ($fullinfo) {
827 $formattedinfo = \core_availability\info::format_info(
828 $fullinfo, $mod->get_course());
829 $output .= $this->availability_info($formattedinfo, $hidinfoclass);
833 return $output;
837 * Renders HTML to display one course module for display within a section.
839 * This function calls:
840 * {@link core_course_renderer::course_section_cm()}
842 * @param stdClass $course
843 * @param completion_info $completioninfo
844 * @param cm_info $mod
845 * @param int|null $sectionreturn
846 * @param array $displayoptions
847 * @return String
849 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
850 $output = '';
851 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
852 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
853 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
855 return $output;
859 * Renders HTML to display one course module in a course section
861 * This includes link, content, availability, completion info and additional information
862 * that module type wants to display (i.e. number of unread forum posts)
864 * This function calls:
865 * {@link core_course_renderer::course_section_cm_name()}
866 * {@link core_course_renderer::course_section_cm_text()}
867 * {@link core_course_renderer::course_section_cm_availability()}
868 * {@link core_course_renderer::course_section_cm_completion()}
869 * {@link course_get_cm_edit_actions()}
870 * {@link core_course_renderer::course_section_cm_edit_actions()}
872 * @param stdClass $course
873 * @param completion_info $completioninfo
874 * @param cm_info $mod
875 * @param int|null $sectionreturn
876 * @param array $displayoptions
877 * @return string
879 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
880 $output = '';
881 // We return empty string (because course module will not be displayed at all)
882 // if:
883 // 1) The activity is not visible to users
884 // and
885 // 2) The 'availableinfo' is empty, i.e. the activity was
886 // hidden in a way that leaves no info, such as using the
887 // eye icon.
888 if (!$mod->is_visible_on_course_page()) {
889 return $output;
892 $indentclasses = 'mod-indent';
893 if (!empty($mod->indent)) {
894 $indentclasses .= ' mod-indent-'.$mod->indent;
895 if ($mod->indent > 15) {
896 $indentclasses .= ' mod-indent-huge';
900 $output .= html_writer::start_tag('div');
902 if ($this->page->user_is_editing()) {
903 $output .= course_get_cm_move($mod, $sectionreturn);
906 $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer w-100'));
908 // This div is used to indent the content.
909 $output .= html_writer::div('', $indentclasses);
911 // Start a wrapper for the actual content to keep the indentation consistent
912 $output .= html_writer::start_tag('div');
914 // Display the link to the module (or do nothing if module has no url)
915 $cmname = $this->course_section_cm_name($mod, $displayoptions);
917 if (!empty($cmname)) {
918 // Start the div for the activity title, excluding the edit icons.
919 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
920 $output .= $cmname;
923 // Module can put text after the link (e.g. forum unread)
924 $output .= $mod->afterlink;
926 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
927 $output .= html_writer::end_tag('div'); // .activityinstance
930 // If there is content but NO link (eg label), then display the
931 // content here (BEFORE any icons). In this case cons must be
932 // displayed after the content so that it makes more sense visually
933 // and for accessibility reasons, e.g. if you have a one-line label
934 // it should work similarly (at least in terms of ordering) to an
935 // activity.
936 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
937 $url = $mod->url;
938 if (empty($url)) {
939 $output .= $contentpart;
942 $modicons = '';
943 if ($this->page->user_is_editing()) {
944 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
945 $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
946 $modicons .= $mod->afterediticons;
949 $modicons .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
951 if (!empty($modicons)) {
952 $output .= html_writer::div($modicons, 'actions');
955 // Show availability info (if module is not available).
956 $output .= $this->course_section_cm_availability($mod, $displayoptions);
958 // If there is content AND a link, then display the content here
959 // (AFTER any icons). Otherwise it was displayed before
960 if (!empty($url)) {
961 $output .= $contentpart;
964 $output .= html_writer::end_tag('div'); // $indentclasses
966 // End of indentation div.
967 $output .= html_writer::end_tag('div');
969 $output .= html_writer::end_tag('div');
970 return $output;
974 * Message displayed to the user when they try to access unavailable activity following URL
976 * This method is a very simplified version of {@link course_section_cm()} to be part of the error
977 * notification only. It also does not check if module is visible on course page or not.
979 * The message will be displayed inside notification!
981 * @param cm_info $cm
982 * @return string
984 public function course_section_cm_unavailable_error_message(cm_info $cm) {
985 if ($cm->uservisible) {
986 return null;
988 if (!$cm->availableinfo) {
989 return get_string('activityiscurrentlyhidden');
992 $altname = get_accesshide(' ' . $cm->modfullname);
993 $name = html_writer::empty_tag('img', array('src' => $cm->get_icon_url(),
994 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
995 html_writer::tag('span', ' '.$cm->get_formatted_name() . $altname, array('class' => 'instancename'));
996 $formattedinfo = \core_availability\info::format_info($cm->availableinfo, $cm->get_course());
997 return html_writer::div($name, 'activityinstance-error') .
998 html_writer::div($formattedinfo, 'availabilityinfo-error');
1002 * Renders HTML to display a list of course modules in a course section
1003 * Also displays "move here" controls in Javascript-disabled mode
1005 * This function calls {@link core_course_renderer::course_section_cm()}
1007 * @param stdClass $course course object
1008 * @param int|stdClass|section_info $section relative section number or section object
1009 * @param int $sectionreturn section number to return to
1010 * @param int $displayoptions
1011 * @return void
1013 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
1014 global $USER;
1016 $output = '';
1017 $modinfo = get_fast_modinfo($course);
1018 if (is_object($section)) {
1019 $section = $modinfo->get_section_info($section->section);
1020 } else {
1021 $section = $modinfo->get_section_info($section);
1023 $completioninfo = new completion_info($course);
1025 // check if we are currently in the process of moving a module with JavaScript disabled
1026 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
1027 if ($ismoving) {
1028 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
1029 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1032 // Get the list of modules visible to user (excluding the module being moved if there is one)
1033 $moduleshtml = array();
1034 if (!empty($modinfo->sections[$section->section])) {
1035 foreach ($modinfo->sections[$section->section] as $modnumber) {
1036 $mod = $modinfo->cms[$modnumber];
1038 if ($ismoving and $mod->id == $USER->activitycopy) {
1039 // do not display moving mod
1040 continue;
1043 if ($modulehtml = $this->course_section_cm_list_item($course,
1044 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
1045 $moduleshtml[$modnumber] = $modulehtml;
1050 $sectionoutput = '';
1051 if (!empty($moduleshtml) || $ismoving) {
1052 foreach ($moduleshtml as $modnumber => $modulehtml) {
1053 if ($ismoving) {
1054 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
1055 $sectionoutput .= html_writer::tag('li',
1056 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1057 array('class' => 'movehere'));
1060 $sectionoutput .= $modulehtml;
1063 if ($ismoving) {
1064 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1065 $sectionoutput .= html_writer::tag('li',
1066 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1067 array('class' => 'movehere'));
1071 // Always output the section module list.
1072 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1074 return $output;
1078 * Displays a custom list of courses with paging bar if necessary
1080 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1081 * appears under the list.
1083 * If both $paginationurl and $totalcount are specified, and $totalcount is
1084 * bigger than count($courses), a paging bar is displayed above and under the
1085 * courses list.
1087 * @param array $courses array of course records (or instances of core_course_list_element) to show on this page
1088 * @param bool $showcategoryname whether to add category name to the course description
1089 * @param string $additionalclasses additional CSS classes to add to the div.courses
1090 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1091 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1092 * @param int $page current page number (defaults to 0 referring to the first page)
1093 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1094 * @return string
1096 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1097 global $CFG;
1098 // create instance of coursecat_helper to pass display options to function rendering courses list
1099 $chelper = new coursecat_helper();
1100 if ($showcategoryname) {
1101 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1102 } else {
1103 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1105 if ($totalcount !== null && $paginationurl !== null) {
1106 // add options to display pagination
1107 if ($perpage === null) {
1108 $perpage = $CFG->coursesperpage;
1110 $chelper->set_courses_display_options(array(
1111 'limit' => $perpage,
1112 'offset' => ((int)$page) * $perpage,
1113 'paginationurl' => $paginationurl,
1115 } else if ($paginationurl !== null) {
1116 // add options to display 'View more' link
1117 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1118 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1120 $chelper->set_attributes(array('class' => $additionalclasses));
1121 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1122 return $content;
1126 * Displays one course in the list of courses.
1128 * This is an internal function, to display an information about just one course
1129 * please use {@link core_course_renderer::course_info_box()}
1131 * @param coursecat_helper $chelper various display options
1132 * @param core_course_list_element|stdClass $course
1133 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1134 * depend on the course position in list - first/last/even/odd)
1135 * @return string
1137 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1138 if (!isset($this->strings->summary)) {
1139 $this->strings->summary = get_string('summary');
1141 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1142 return '';
1144 if ($course instanceof stdClass) {
1145 $course = new core_course_list_element($course);
1147 $content = '';
1148 $classes = trim('coursebox clearfix '. $additionalclasses);
1149 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1150 $nametag = 'h3';
1151 } else {
1152 $classes .= ' collapsed';
1153 $nametag = 'div';
1156 // .coursebox
1157 $content .= html_writer::start_tag('div', array(
1158 'class' => $classes,
1159 'data-courseid' => $course->id,
1160 'data-type' => self::COURSECAT_TYPE_COURSE,
1163 $content .= html_writer::start_tag('div', array('class' => 'info'));
1165 // course name
1166 $coursename = $chelper->get_course_formatted_name($course);
1167 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', array('id' => $course->id)),
1168 $coursename, array('class' => $course->visible ? '' : 'dimmed'));
1169 $content .= html_writer::tag($nametag, $coursenamelink, array('class' => 'coursename'));
1170 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1171 $content .= html_writer::start_tag('div', array('class' => 'moreinfo'));
1172 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1173 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()
1174 || $course->has_custom_fields()) {
1175 $url = new moodle_url('/course/info.php', array('id' => $course->id));
1176 $image = $this->output->pix_icon('i/info', $this->strings->summary);
1177 $content .= html_writer::link($url, $image, array('title' => $this->strings->summary));
1178 // Make sure JS file to expand course content is included.
1179 $this->coursecat_include_js();
1182 $content .= html_writer::end_tag('div'); // .moreinfo
1184 // print enrolmenticons
1185 if ($icons = enrol_get_course_info_icons($course)) {
1186 $content .= html_writer::start_tag('div', array('class' => 'enrolmenticons'));
1187 foreach ($icons as $pix_icon) {
1188 $content .= $this->render($pix_icon);
1190 $content .= html_writer::end_tag('div'); // .enrolmenticons
1193 $content .= html_writer::end_tag('div'); // .info
1195 $content .= html_writer::start_tag('div', array('class' => 'content'));
1196 $content .= $this->coursecat_coursebox_content($chelper, $course);
1197 $content .= html_writer::end_tag('div'); // .content
1199 $content .= html_writer::end_tag('div'); // .coursebox
1200 return $content;
1204 * Returns HTML to display course content (summary, course contacts and optionally category name)
1206 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1208 * @param coursecat_helper $chelper various display options
1209 * @param stdClass|core_course_list_element $course
1210 * @return string
1212 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1213 global $CFG;
1214 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1215 return '';
1217 if ($course instanceof stdClass) {
1218 $course = new core_course_list_element($course);
1220 $content = '';
1222 // display course summary
1223 if ($course->has_summary()) {
1224 $content .= html_writer::start_tag('div', array('class' => 'summary'));
1225 $content .= $chelper->get_course_formatted_summary($course,
1226 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1227 $content .= html_writer::end_tag('div'); // .summary
1230 // display course overview files
1231 $contentimages = $contentfiles = '';
1232 foreach ($course->get_course_overviewfiles() as $file) {
1233 $isimage = $file->is_valid_image();
1234 $url = file_encode_url("$CFG->wwwroot/pluginfile.php",
1235 '/'. $file->get_contextid(). '/'. $file->get_component(). '/'.
1236 $file->get_filearea(). $file->get_filepath(). $file->get_filename(), !$isimage);
1237 if ($isimage) {
1238 $contentimages .= html_writer::tag('div',
1239 html_writer::empty_tag('img', array('src' => $url)),
1240 array('class' => 'courseimage'));
1241 } else {
1242 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1243 $filename = html_writer::tag('span', $image, array('class' => 'fp-icon')).
1244 html_writer::tag('span', $file->get_filename(), array('class' => 'fp-filename'));
1245 $contentfiles .= html_writer::tag('span',
1246 html_writer::link($url, $filename),
1247 array('class' => 'coursefile fp-filename-icon'));
1250 $content .= $contentimages. $contentfiles;
1252 // Display course contacts. See core_course_list_element::get_course_contacts().
1253 if ($course->has_course_contacts()) {
1254 $content .= html_writer::start_tag('ul', array('class' => 'teachers'));
1255 foreach ($course->get_course_contacts() as $coursecontact) {
1256 $rolenames = array_map(function ($role) {
1257 return $role->displayname;
1258 }, $coursecontact['roles']);
1259 $name = implode(", ", $rolenames).': '.
1260 html_writer::link(new moodle_url('/user/view.php',
1261 array('id' => $coursecontact['user']->id, 'course' => SITEID)),
1262 $coursecontact['username']);
1263 $content .= html_writer::tag('li', $name);
1265 $content .= html_writer::end_tag('ul'); // .teachers
1268 // display course category if necessary (for example in search results)
1269 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1270 if ($cat = core_course_category::get($course->category, IGNORE_MISSING)) {
1271 $content .= html_writer::start_tag('div', array('class' => 'coursecat'));
1272 $content .= get_string('category').': '.
1273 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1274 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1275 $content .= html_writer::end_tag('div'); // .coursecat
1279 // Display custom fields.
1280 if ($course->has_custom_fields()) {
1281 $handler = core_course\customfield\course_handler::create();
1282 $customfields = $handler->display_custom_fields_data($course->get_custom_fields());
1283 $content .= \html_writer::tag('div', $customfields, ['class' => 'customfields-container']);
1286 return $content;
1290 * Renders the list of courses
1292 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1293 * method from outside of the class
1295 * If list of courses is specified in $courses; the argument $chelper is only used
1296 * to retrieve display options and attributes, only methods get_show_courses(),
1297 * get_courses_display_option() and get_and_erase_attributes() are called.
1299 * @param coursecat_helper $chelper various display options
1300 * @param array $courses the list of courses to display
1301 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1302 * defaulted to count($courses)
1303 * @return string
1305 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1306 global $CFG;
1307 if ($totalcount === null) {
1308 $totalcount = count($courses);
1310 if (!$totalcount) {
1311 // Courses count is cached during courses retrieval.
1312 return '';
1315 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1316 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1317 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1318 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1319 } else {
1320 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1324 // prepare content of paging bar if it is needed
1325 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1326 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1327 if ($totalcount > count($courses)) {
1328 // there are more results that can fit on one page
1329 if ($paginationurl) {
1330 // the option paginationurl was specified, display pagingbar
1331 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1332 $page = $chelper->get_courses_display_option('offset') / $perpage;
1333 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1334 $paginationurl->out(false, array('perpage' => $perpage)));
1335 if ($paginationallowall) {
1336 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1337 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1339 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1340 // the option for 'View more' link was specified, display more link
1341 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1342 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1343 array('class' => 'paging paging-morelink'));
1345 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1346 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1347 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1348 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1351 // display list of courses
1352 $attributes = $chelper->get_and_erase_attributes('courses');
1353 $content = html_writer::start_tag('div', $attributes);
1355 if (!empty($pagingbar)) {
1356 $content .= $pagingbar;
1359 $coursecount = 0;
1360 foreach ($courses as $course) {
1361 $coursecount ++;
1362 $classes = ($coursecount%2) ? 'odd' : 'even';
1363 if ($coursecount == 1) {
1364 $classes .= ' first';
1366 if ($coursecount >= count($courses)) {
1367 $classes .= ' last';
1369 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1372 if (!empty($pagingbar)) {
1373 $content .= $pagingbar;
1375 if (!empty($morelink)) {
1376 $content .= $morelink;
1379 $content .= html_writer::end_tag('div'); // .courses
1380 return $content;
1384 * Renders the list of subcategories in a category
1386 * @param coursecat_helper $chelper various display options
1387 * @param core_course_category $coursecat
1388 * @param int $depth depth of the category in the current tree
1389 * @return string
1391 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1392 global $CFG;
1393 $subcategories = array();
1394 if (!$chelper->get_categories_display_option('nodisplay')) {
1395 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1397 $totalcount = $coursecat->get_children_count();
1398 if (!$totalcount) {
1399 // Note that we call core_course_category::get_children_count() AFTER core_course_category::get_children()
1400 // to avoid extra DB requests.
1401 // Categories count is cached during children categories retrieval.
1402 return '';
1405 // prepare content of paging bar or more link if it is needed
1406 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1407 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1408 if ($totalcount > count($subcategories)) {
1409 if ($paginationurl) {
1410 // the option 'paginationurl was specified, display pagingbar
1411 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1412 $page = $chelper->get_categories_display_option('offset') / $perpage;
1413 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1414 $paginationurl->out(false, array('perpage' => $perpage)));
1415 if ($paginationallowall) {
1416 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1417 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1419 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1420 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1421 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1422 $viewmoreurl->param('categoryid', $coursecat->id);
1424 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1425 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1426 array('class' => 'paging paging-morelink'));
1428 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1429 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1430 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1431 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1434 // display list of subcategories
1435 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1437 if (!empty($pagingbar)) {
1438 $content .= $pagingbar;
1441 foreach ($subcategories as $subcategory) {
1442 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1445 if (!empty($pagingbar)) {
1446 $content .= $pagingbar;
1448 if (!empty($morelink)) {
1449 $content .= $morelink;
1452 $content .= html_writer::end_tag('div');
1453 return $content;
1457 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1459 protected function coursecat_include_js() {
1460 if (!$this->page->requires->should_create_one_time_item_now('core_course_categoryexpanderjsinit')) {
1461 return;
1464 // We must only load this module once.
1465 $this->page->requires->yui_module('moodle-course-categoryexpander',
1466 'Y.Moodle.course.categoryexpander.init');
1470 * Returns HTML to display the subcategories and courses in the given category
1472 * This method is re-used by AJAX to expand content of not loaded category
1474 * @param coursecat_helper $chelper various display options
1475 * @param core_course_category $coursecat
1476 * @param int $depth depth of the category in the current tree
1477 * @return string
1479 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1480 $content = '';
1481 // Subcategories
1482 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1484 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1485 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1486 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1487 if ($showcoursesauto && $depth) {
1488 // this is definitely collapsed mode
1489 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1492 // Courses
1493 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1494 $courses = array();
1495 if (!$chelper->get_courses_display_option('nodisplay')) {
1496 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1498 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1499 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1500 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1501 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1504 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1507 if ($showcoursesauto) {
1508 // restore the show_courses back to AUTO
1509 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1512 return $content;
1516 * Returns HTML to display a course category as a part of a tree
1518 * This is an internal function, to display a particular category and all its contents
1519 * use {@link core_course_renderer::course_category()}
1521 * @param coursecat_helper $chelper various display options
1522 * @param core_course_category $coursecat
1523 * @param int $depth depth of this category in the current tree
1524 * @return string
1526 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1527 // open category tag
1528 $classes = array('category');
1529 if (empty($coursecat->visible)) {
1530 $classes[] = 'dimmed_category';
1532 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1533 // do not load content
1534 $categorycontent = '';
1535 $classes[] = 'notloaded';
1536 if ($coursecat->get_children_count() ||
1537 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1538 $classes[] = 'with_children';
1539 $classes[] = 'collapsed';
1541 } else {
1542 // load category content
1543 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1544 $classes[] = 'loaded';
1545 if (!empty($categorycontent)) {
1546 $classes[] = 'with_children';
1547 // Category content loaded with children.
1548 $this->categoryexpandedonload = true;
1552 // Make sure JS file to expand category content is included.
1553 $this->coursecat_include_js();
1555 $content = html_writer::start_tag('div', array(
1556 'class' => join(' ', $classes),
1557 'data-categoryid' => $coursecat->id,
1558 'data-depth' => $depth,
1559 'data-showcourses' => $chelper->get_show_courses(),
1560 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1563 // category name
1564 $categoryname = $coursecat->get_formatted_name();
1565 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1566 array('categoryid' => $coursecat->id)),
1567 $categoryname);
1568 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1569 && ($coursescount = $coursecat->get_courses_count())) {
1570 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1571 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1573 $content .= html_writer::start_tag('div', array('class' => 'info'));
1575 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname'));
1576 $content .= html_writer::end_tag('div'); // .info
1578 // add category content to the output
1579 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1581 $content .= html_writer::end_tag('div'); // .category
1583 // Return the course category tree HTML
1584 return $content;
1588 * Returns HTML to display a tree of subcategories and courses in the given category
1590 * @param coursecat_helper $chelper various display options
1591 * @param core_course_category $coursecat top category (this category's name and description will NOT be added to the tree)
1592 * @return string
1594 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1595 // Reset the category expanded flag for this course category tree first.
1596 $this->categoryexpandedonload = false;
1597 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1598 if (empty($categorycontent)) {
1599 return '';
1602 // Start content generation
1603 $content = '';
1604 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1605 $content .= html_writer::start_tag('div', $attributes);
1607 if ($coursecat->get_children_count()) {
1608 $classes = array(
1609 'collapseexpand',
1612 // Check if the category content contains subcategories with children's content loaded.
1613 if ($this->categoryexpandedonload) {
1614 $classes[] = 'collapse-all';
1615 $linkname = get_string('collapseall');
1616 } else {
1617 $linkname = get_string('expandall');
1620 // Only show the collapse/expand if there are children to expand.
1621 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1622 $content .= html_writer::link('#', $linkname, array('class' => implode(' ', $classes)));
1623 $content .= html_writer::end_tag('div');
1624 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1627 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1629 $content .= html_writer::end_tag('div'); // .course_category_tree
1631 return $content;
1635 * Renders HTML to display particular course category - list of it's subcategories and courses
1637 * Invoked from /course/index.php
1639 * @param int|stdClass|core_course_category $category
1641 public function course_category($category) {
1642 global $CFG;
1643 $usertop = core_course_category::user_top();
1644 if (empty($category)) {
1645 $coursecat = $usertop;
1646 } else if (is_object($category) && $category instanceof core_course_category) {
1647 $coursecat = $category;
1648 } else {
1649 $coursecat = core_course_category::get(is_object($category) ? $category->id : $category);
1651 $site = get_site();
1652 $output = '';
1654 if ($coursecat->can_create_course() || $coursecat->has_manage_capability()) {
1655 // Add 'Manage' button if user has permissions to edit this category.
1656 $managebutton = $this->single_button(new moodle_url('/course/management.php',
1657 array('categoryid' => $coursecat->id)), get_string('managecourses'), 'get');
1658 $this->page->set_button($managebutton);
1661 if (core_course_category::is_simple_site()) {
1662 // There is only one category in the system, do not display link to it.
1663 $strfulllistofcourses = get_string('fulllistofcourses');
1664 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1665 } else if (!$coursecat->id || !$coursecat->is_uservisible()) {
1666 $strcategories = get_string('categories');
1667 $this->page->set_title("$site->shortname: $strcategories");
1668 } else {
1669 $strfulllistofcourses = get_string('fulllistofcourses');
1670 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1672 // Print the category selector
1673 $categorieslist = core_course_category::make_categories_list();
1674 if (count($categorieslist) > 1) {
1675 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1676 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1677 core_course_category::make_categories_list(), $coursecat->id, null, 'switchcategory');
1678 $select->set_label(get_string('categories').':');
1679 $output .= $this->render($select);
1680 $output .= html_writer::end_tag('div'); // .categorypicker
1684 // Print current category description
1685 $chelper = new coursecat_helper();
1686 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1687 $output .= $this->box($description, array('class' => 'generalbox info'));
1690 // Prepare parameters for courses and categories lists in the tree
1691 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1692 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1694 $coursedisplayoptions = array();
1695 $catdisplayoptions = array();
1696 $browse = optional_param('browse', null, PARAM_ALPHA);
1697 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1698 $page = optional_param('page', 0, PARAM_INT);
1699 $baseurl = new moodle_url('/course/index.php');
1700 if ($coursecat->id) {
1701 $baseurl->param('categoryid', $coursecat->id);
1703 if ($perpage != $CFG->coursesperpage) {
1704 $baseurl->param('perpage', $perpage);
1706 $coursedisplayoptions['limit'] = $perpage;
1707 $catdisplayoptions['limit'] = $perpage;
1708 if ($browse === 'courses' || !$coursecat->get_children_count()) {
1709 $coursedisplayoptions['offset'] = $page * $perpage;
1710 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1711 $catdisplayoptions['nodisplay'] = true;
1712 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1713 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1714 } else if ($browse === 'categories' || !$coursecat->get_courses_count()) {
1715 $coursedisplayoptions['nodisplay'] = true;
1716 $catdisplayoptions['offset'] = $page * $perpage;
1717 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1718 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1719 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1720 } else {
1721 // we have a category that has both subcategories and courses, display pagination separately
1722 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1723 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1725 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1726 // Add course search form.
1727 $output .= $this->course_search_form();
1729 // Display course category tree.
1730 $output .= $this->coursecat_tree($chelper, $coursecat);
1732 // Add action buttons
1733 $output .= $this->container_start('buttons');
1734 if ($coursecat->is_uservisible()) {
1735 $context = get_category_or_system_context($coursecat->id);
1736 if (has_capability('moodle/course:create', $context)) {
1737 // Print link to create a new course, for the 1st available category.
1738 if ($coursecat->id) {
1739 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1740 } else {
1741 $url = new moodle_url('/course/edit.php',
1742 array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1744 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1746 ob_start();
1747 print_course_request_buttons($context);
1748 $output .= ob_get_contents();
1749 ob_end_clean();
1751 $output .= $this->container_end();
1753 return $output;
1757 * Serves requests to /course/category.ajax.php
1759 * In this renderer implementation it may expand the category content or
1760 * course content.
1762 * @return string
1763 * @throws coding_exception
1765 public function coursecat_ajax() {
1766 global $DB, $CFG;
1768 $type = required_param('type', PARAM_INT);
1770 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1771 // This is a request for a category list of some kind.
1772 $categoryid = required_param('categoryid', PARAM_INT);
1773 $showcourses = required_param('showcourses', PARAM_INT);
1774 $depth = required_param('depth', PARAM_INT);
1776 $category = core_course_category::get($categoryid);
1778 $chelper = new coursecat_helper();
1779 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1780 $coursedisplayoptions = array(
1781 'limit' => $CFG->coursesperpage,
1782 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1784 $catdisplayoptions = array(
1785 'limit' => $CFG->coursesperpage,
1786 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1788 $chelper->set_show_courses($showcourses)->
1789 set_courses_display_options($coursedisplayoptions)->
1790 set_categories_display_options($catdisplayoptions);
1792 return $this->coursecat_category_content($chelper, $category, $depth);
1793 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1794 // This is a request for the course information.
1795 $courseid = required_param('courseid', PARAM_INT);
1797 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1799 $chelper = new coursecat_helper();
1800 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1801 return $this->coursecat_coursebox_content($chelper, $course);
1802 } else {
1803 throw new coding_exception('Invalid request type');
1808 * Renders html to display search result page
1810 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1811 * @return string
1813 public function search_courses($searchcriteria) {
1814 global $CFG;
1815 $content = '';
1816 if (!empty($searchcriteria)) {
1817 // print search results
1819 $displayoptions = array('sort' => array('displayname' => 1));
1820 // take the current page and number of results per page from query
1821 $perpage = optional_param('perpage', 0, PARAM_RAW);
1822 if ($perpage !== 'all') {
1823 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1824 $page = optional_param('page', 0, PARAM_INT);
1825 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1827 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1828 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1829 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1831 $class = 'course-search-result';
1832 foreach ($searchcriteria as $key => $value) {
1833 if (!empty($value)) {
1834 $class .= ' course-search-result-'. $key;
1837 $chelper = new coursecat_helper();
1838 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1839 set_courses_display_options($displayoptions)->
1840 set_search_criteria($searchcriteria)->
1841 set_attributes(array('class' => $class));
1843 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1844 $totalcount = core_course_category::search_courses_count($searchcriteria);
1845 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1847 if (!$totalcount) {
1848 if (!empty($searchcriteria['search'])) {
1849 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1850 } else {
1851 $content .= $this->heading(get_string('novalidcourses'));
1853 } else {
1854 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1855 $content .= $courseslist;
1858 if (!empty($searchcriteria['search'])) {
1859 // print search form only if there was a search by search string, otherwise it is confusing
1860 $content .= $this->box_start('generalbox mdl-align');
1861 $content .= $this->course_search_form($searchcriteria['search']);
1862 $content .= $this->box_end();
1864 } else {
1865 // just print search form
1866 $content .= $this->box_start('generalbox mdl-align');
1867 $content .= $this->course_search_form();
1868 $content .= $this->box_end();
1870 return $content;
1874 * Renders html to print list of courses tagged with particular tag
1876 * @param int $tagid id of the tag
1877 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1878 * are displayed on the page and the per-page limit may be bigger
1879 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1880 * to display items in the same context first
1881 * @param int $ctx context id where to search for records
1882 * @param bool $rec search in subcontexts as well
1883 * @param array $displayoptions
1884 * @return string empty string if no courses are marked with this tag or rendered list of courses
1886 public function tagged_courses($tagid, $exclusivemode = true, $ctx = 0, $rec = true, $displayoptions = null) {
1887 global $CFG;
1888 if (empty($displayoptions)) {
1889 $displayoptions = array();
1891 $showcategories = !core_course_category::is_simple_site();
1892 $displayoptions += array('limit' => $CFG->coursesperpage, 'offset' => 0);
1893 $chelper = new coursecat_helper();
1894 $searchcriteria = array('tagid' => $tagid, 'ctx' => $ctx, 'rec' => $rec);
1895 $chelper->set_show_courses($showcategories ? self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT :
1896 self::COURSECAT_SHOW_COURSES_EXPANDED)->
1897 set_search_criteria($searchcriteria)->
1898 set_courses_display_options($displayoptions)->
1899 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1900 // (we set the same css class as in search results by tagid)
1901 if ($totalcount = core_course_category::search_courses_count($searchcriteria)) {
1902 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1903 if ($exclusivemode) {
1904 return $this->coursecat_courses($chelper, $courses, $totalcount);
1905 } else {
1906 $tagfeed = new core_tag\output\tagfeed();
1907 $img = $this->output->pix_icon('i/course', '');
1908 foreach ($courses as $course) {
1909 $url = course_get_url($course);
1910 $imgwithlink = html_writer::link($url, $img);
1911 $coursename = html_writer::link($url, $course->get_formatted_name());
1912 $details = '';
1913 if ($showcategories && ($cat = core_course_category::get($course->category, IGNORE_MISSING))) {
1914 $details = get_string('category').': '.
1915 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1916 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1918 $tagfeed->add($imgwithlink, $coursename, $details);
1920 return $this->output->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($this->output));
1923 return '';
1927 * Returns HTML to display one remote course
1929 * @param stdClass $course remote course information, contains properties:
1930 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1931 * @return string
1933 protected function frontpage_remote_course(stdClass $course) {
1934 $url = new moodle_url('/auth/mnet/jump.php', array(
1935 'hostid' => $course->hostid,
1936 'wantsurl' => '/course/view.php?id='. $course->remoteid
1939 $output = '';
1940 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1941 $output .= html_writer::start_tag('div', array('class' => 'info'));
1942 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1943 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1944 $output .= html_writer::end_tag('h3'); // .name
1945 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1946 $output .= html_writer::end_tag('div'); // .info
1947 $output .= html_writer::start_tag('div', array('class' => 'content'));
1948 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1949 $options = new stdClass();
1950 $options->noclean = true;
1951 $options->para = false;
1952 $options->overflowdiv = true;
1953 $output .= format_text($course->summary, $course->summaryformat, $options);
1954 $output .= html_writer::end_tag('div'); // .summary
1955 $addinfo = format_string($course->hostname) . ' : '
1956 . format_string($course->cat_name) . ' : '
1957 . format_string($course->shortname);
1958 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1959 $output .= html_writer::end_tag('div'); // .content
1960 $output .= html_writer::end_tag('div'); // .coursebox
1961 return $output;
1965 * Returns HTML to display one remote host
1967 * @param array $host host information, contains properties: name, url, count
1968 * @return string
1970 protected function frontpage_remote_host($host) {
1971 $output = '';
1972 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1973 $output .= html_writer::start_tag('div', array('class' => 'info'));
1974 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1975 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1976 $output .= html_writer::end_tag('h3'); // .name
1977 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1978 $output .= html_writer::end_tag('div'); // .info
1979 $output .= html_writer::start_tag('div', array('class' => 'content'));
1980 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1981 $output .= $host['count'] . ' ' . get_string('courses');
1982 $output .= html_writer::end_tag('div'); // .content
1983 $output .= html_writer::end_tag('div'); // .coursebox
1984 return $output;
1988 * Returns HTML to print list of courses user is enrolled to for the frontpage
1990 * Also lists remote courses or remote hosts if MNET authorisation is used
1992 * @return string
1994 public function frontpage_my_courses() {
1995 global $USER, $CFG, $DB;
1997 if (!isloggedin() or isguestuser()) {
1998 return '';
2001 $output = '';
2002 $courses = enrol_get_my_courses('summary, summaryformat');
2003 $rhosts = array();
2004 $rcourses = array();
2005 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2006 $rcourses = get_my_remotecourses($USER->id);
2007 $rhosts = get_my_remotehosts();
2010 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2012 $chelper = new coursecat_helper();
2013 $totalcount = count($courses);
2014 if (count($courses) > $CFG->frontpagecourselimit) {
2015 // There are more enrolled courses than we can display, display link to 'My courses'.
2016 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
2017 $chelper->set_courses_display_options(array(
2018 'viewmoreurl' => new moodle_url('/my/'),
2019 'viewmoretext' => new lang_string('mycourses')
2021 } else if (core_course_category::top()->is_uservisible()) {
2022 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
2023 $chelper->set_courses_display_options(array(
2024 'viewmoreurl' => new moodle_url('/course/index.php'),
2025 'viewmoretext' => new lang_string('fulllistofcourses')
2027 $totalcount = $DB->count_records('course') - 1;
2029 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2030 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
2031 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
2033 // MNET
2034 if (!empty($rcourses)) {
2035 // at the IDP, we know of all the remote courses
2036 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2037 foreach ($rcourses as $course) {
2038 $output .= $this->frontpage_remote_course($course);
2040 $output .= html_writer::end_tag('div'); // .courses
2041 } elseif (!empty($rhosts)) {
2042 // non-IDP, we know of all the remote servers, but not courses
2043 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2044 foreach ($rhosts as $host) {
2045 $output .= $this->frontpage_remote_host($host);
2047 $output .= html_writer::end_tag('div'); // .courses
2050 return $output;
2054 * Returns HTML to print list of available courses for the frontpage
2056 * @return string
2058 public function frontpage_available_courses() {
2059 global $CFG;
2061 $chelper = new coursecat_helper();
2062 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2063 set_courses_display_options(array(
2064 'recursive' => true,
2065 'limit' => $CFG->frontpagecourselimit,
2066 'viewmoreurl' => new moodle_url('/course/index.php'),
2067 'viewmoretext' => new lang_string('fulllistofcourses')));
2069 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
2070 $courses = core_course_category::top()->get_courses($chelper->get_courses_display_options());
2071 $totalcount = core_course_category::top()->get_courses_count($chelper->get_courses_display_options());
2072 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
2073 // Print link to create a new course, for the 1st available category.
2074 return $this->add_new_course_button();
2076 return $this->coursecat_courses($chelper, $courses, $totalcount);
2080 * Returns HTML to the "add new course" button for the page
2082 * @return string
2084 public function add_new_course_button() {
2085 global $CFG;
2086 // Print link to create a new course, for the 1st available category.
2087 $output = $this->container_start('buttons');
2088 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2089 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2090 $output .= $this->container_end('buttons');
2091 return $output;
2095 * Returns HTML to print tree with course categories and courses for the frontpage
2097 * @return string
2099 public function frontpage_combo_list() {
2100 global $CFG;
2101 // TODO MDL-10965 improve.
2102 $tree = core_course_category::top();
2103 if (!$tree->get_children_count()) {
2104 return '';
2106 $chelper = new coursecat_helper();
2107 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2108 set_categories_display_options(array(
2109 'limit' => $CFG->coursesperpage,
2110 'viewmoreurl' => new moodle_url('/course/index.php',
2111 array('browse' => 'categories', 'page' => 1))
2112 ))->
2113 set_courses_display_options(array(
2114 'limit' => $CFG->coursesperpage,
2115 'viewmoreurl' => new moodle_url('/course/index.php',
2116 array('browse' => 'courses', 'page' => 1))
2117 ))->
2118 set_attributes(array('class' => 'frontpage-category-combo'));
2119 return $this->coursecat_tree($chelper, $tree);
2123 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2125 * @return string
2127 public function frontpage_categories_list() {
2128 global $CFG;
2129 // TODO MDL-10965 improve.
2130 $tree = core_course_category::top();
2131 if (!$tree->get_children_count()) {
2132 return '';
2134 $chelper = new coursecat_helper();
2135 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2136 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2137 set_categories_display_options(array(
2138 'limit' => $CFG->coursesperpage,
2139 'viewmoreurl' => new moodle_url('/course/index.php',
2140 array('browse' => 'categories', 'page' => 1))
2141 ))->
2142 set_attributes(array('class' => 'frontpage-category-names'));
2143 return $this->coursecat_tree($chelper, $tree);
2147 * Renders the activity navigation.
2149 * Defer to template.
2151 * @param \core_course\output\activity_navigation $page
2152 * @return string html for the page
2154 public function render_activity_navigation(\core_course\output\activity_navigation $page) {
2155 $data = $page->export_for_template($this->output);
2156 return $this->output->render_from_template('core_course/activity_navigation', $data);
2160 * Display waiting information about backup size during uploading backup process
2161 * @param object $backupfile the backup stored_file
2162 * @return $html string
2164 public function sendingbackupinfo($backupfile) {
2165 $sizeinfo = new stdClass();
2166 $sizeinfo->total = number_format($backupfile->get_filesize() / 1000000, 2);
2167 $html = html_writer::tag('div', get_string('sendingsize', 'hub', $sizeinfo),
2168 array('class' => 'courseuploadtextinfo'));
2169 return $html;
2173 * Hub information (logo - name - description - link)
2174 * @param object $hubinfo
2175 * @return string html code
2177 public function hubinfo($hubinfo) {
2178 $screenshothtml = html_writer::empty_tag('img',
2179 array('src' => $hubinfo['imgurl'], 'alt' => $hubinfo['name']));
2180 $hubdescription = html_writer::tag('div', $screenshothtml,
2181 array('class' => 'hubscreenshot'));
2183 $hubdescription .= html_writer::tag('a', $hubinfo['name'],
2184 array('class' => 'hublink', 'href' => $hubinfo['url'],
2185 'onclick' => 'this.target="_blank"'));
2187 $hubdescription .= html_writer::tag('div', format_text($hubinfo['description'], FORMAT_PLAIN),
2188 array('class' => 'hubdescription'));
2189 $hubdescription = html_writer::tag('div', $hubdescription, array('class' => 'hubinfo clearfix'));
2191 return $hubdescription;
2195 * Output frontpage summary text and frontpage modules (stored as section 1 in site course)
2197 * This may be disabled in settings
2199 * @return string
2201 public function frontpage_section1() {
2202 global $SITE, $USER;
2204 $output = '';
2205 $editing = $this->page->user_is_editing();
2207 if ($editing) {
2208 // Make sure section with number 1 exists.
2209 course_create_sections_if_missing($SITE, 1);
2212 $modinfo = get_fast_modinfo($SITE);
2213 $section = $modinfo->get_section_info(1);
2214 if (($section && (!empty($modinfo->sections[1]) or !empty($section->summary))) or $editing) {
2215 $output .= $this->box_start('generalbox sitetopic');
2217 // If currently moving a file then show the current clipboard.
2218 if (ismoving($SITE->id)) {
2219 $stractivityclipboard = strip_tags(get_string('activityclipboard', '', $USER->activitycopyname));
2220 $output .= '<p><font size="2">';
2221 $cancelcopyurl = new moodle_url('/course/mod.php', ['cancelcopy' => 'true', 'sesskey' => sesskey()]);
2222 $output .= "$stractivityclipboard&nbsp;&nbsp;(" . html_writer::link($cancelcopyurl, get_string('cancel')) .')';
2223 $output .= '</font></p>';
2226 $context = context_course::instance(SITEID);
2228 // If the section name is set we show it.
2229 if (trim($section->name) !== '') {
2230 $output .= $this->heading(
2231 format_string($section->name, true, array('context' => $context)),
2233 'sectionname'
2237 $summarytext = file_rewrite_pluginfile_urls($section->summary,
2238 'pluginfile.php',
2239 $context->id,
2240 'course',
2241 'section',
2242 $section->id);
2243 $summaryformatoptions = new stdClass();
2244 $summaryformatoptions->noclean = true;
2245 $summaryformatoptions->overflowdiv = true;
2247 $output .= format_text($summarytext, $section->summaryformat, $summaryformatoptions);
2249 if ($editing && has_capability('moodle/course:update', $context)) {
2250 $streditsummary = get_string('editsummary');
2251 $editsectionurl = new moodle_url('/course/editsection.php', ['id' => $section->id]);
2252 $output .= html_writer::link($editsectionurl, $this->pix_icon('t/edit', $streditsummary)) .
2253 "<br /><br />";
2256 $output .= $this->course_section_cm_list($SITE, $section);
2258 $output .= $this->course_section_add_cm_control($SITE, $section->section);
2259 $output .= $this->box_end();
2262 return $output;
2266 * Output news for the frontpage (extract from site-wide news forum)
2268 * @param stdClass $forum record from db table 'forum' that represents the site news forum
2269 * @return string
2271 protected function frontpage_news($forum) {
2272 global $CFG, $SITE, $SESSION, $USER;
2273 require_once($CFG->dirroot .'/mod/forum/lib.php');
2275 $output = '';
2277 if (isloggedin()) {
2278 $SESSION->fromdiscussion = $CFG->wwwroot;
2279 $subtext = '';
2280 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forum)) {
2281 if (!\mod_forum\subscriptions::is_forcesubscribed($forum)) {
2282 $subtext = get_string('unsubscribe', 'forum');
2284 } else {
2285 $subtext = get_string('subscribe', 'forum');
2287 $suburl = new moodle_url('/mod/forum/subscribe.php', array('id' => $forum->id, 'sesskey' => sesskey()));
2288 $output .= html_writer::tag('div', html_writer::link($suburl, $subtext), array('class' => 'subscribelink'));
2291 $coursemodule = get_coursemodule_from_instance('forum', $forum->id);
2292 $context = context_module::instance($coursemodule->id);
2294 $entityfactory = mod_forum\local\container::get_entity_factory();
2295 $forumentity = $entityfactory->get_forum_from_stdclass($forum, $context, $coursemodule, $SITE);
2297 $rendererfactory = mod_forum\local\container::get_renderer_factory();
2298 $discussionsrenderer = $rendererfactory->get_frontpage_news_discussion_list_renderer($forumentity);
2299 $cm = \cm_info::create($coursemodule);
2300 return $output . $discussionsrenderer->render($USER, $cm, null, null, 0, $SITE->newsitems);
2304 * Renders part of frontpage with a skip link (i.e. "My courses", "Site news", etc.)
2306 * @param string $skipdivid
2307 * @param string $contentsdivid
2308 * @param string $header Header of the part
2309 * @param string $contents Contents of the part
2310 * @return string
2312 protected function frontpage_part($skipdivid, $contentsdivid, $header, $contents) {
2313 if (strval($contents) === '') {
2314 return '';
2316 $output = html_writer::link('#' . $skipdivid,
2317 get_string('skipa', 'access', core_text::strtolower(strip_tags($header))),
2318 array('class' => 'skip-block skip'));
2320 // Wrap frontpage part in div container.
2321 $output .= html_writer::start_tag('div', array('id' => $contentsdivid));
2322 $output .= $this->heading($header);
2324 $output .= $contents;
2326 // End frontpage part div container.
2327 $output .= html_writer::end_tag('div');
2329 $output .= html_writer::tag('span', '', array('class' => 'skip-block-to', 'id' => $skipdivid));
2330 return $output;
2334 * Outputs contents for frontpage as configured in $CFG->frontpage or $CFG->frontpageloggedin
2336 * @return string
2338 public function frontpage() {
2339 global $CFG, $SITE;
2341 $output = '';
2343 if (isloggedin() and !isguestuser() and isset($CFG->frontpageloggedin)) {
2344 $frontpagelayout = $CFG->frontpageloggedin;
2345 } else {
2346 $frontpagelayout = $CFG->frontpage;
2349 foreach (explode(',', $frontpagelayout) as $v) {
2350 switch ($v) {
2351 // Display the main part of the front page.
2352 case FRONTPAGENEWS:
2353 if ($SITE->newsitems) {
2354 // Print forums only when needed.
2355 require_once($CFG->dirroot .'/mod/forum/lib.php');
2356 if (($newsforum = forum_get_course_forum($SITE->id, 'news')) &&
2357 ($forumcontents = $this->frontpage_news($newsforum))) {
2358 $newsforumcm = get_fast_modinfo($SITE)->instances['forum'][$newsforum->id];
2359 $output .= $this->frontpage_part('skipsitenews', 'site-news-forum',
2360 $newsforumcm->get_formatted_name(), $forumcontents);
2363 break;
2365 case FRONTPAGEENROLLEDCOURSELIST:
2366 $mycourseshtml = $this->frontpage_my_courses();
2367 if (!empty($mycourseshtml)) {
2368 $output .= $this->frontpage_part('skipmycourses', 'frontpage-course-list',
2369 get_string('mycourses'), $mycourseshtml);
2371 break;
2373 case FRONTPAGEALLCOURSELIST:
2374 $availablecourseshtml = $this->frontpage_available_courses();
2375 $output .= $this->frontpage_part('skipavailablecourses', 'frontpage-available-course-list',
2376 get_string('availablecourses'), $availablecourseshtml);
2377 break;
2379 case FRONTPAGECATEGORYNAMES:
2380 $output .= $this->frontpage_part('skipcategories', 'frontpage-category-names',
2381 get_string('categories'), $this->frontpage_categories_list());
2382 break;
2384 case FRONTPAGECATEGORYCOMBO:
2385 $output .= $this->frontpage_part('skipcourses', 'frontpage-category-combo',
2386 get_string('courses'), $this->frontpage_combo_list());
2387 break;
2389 case FRONTPAGECOURSESEARCH:
2390 $output .= $this->box($this->course_search_form('', 'short'), 'mdl-align');
2391 break;
2394 $output .= '<br />';
2397 return $output;
2402 * Class storing display options and functions to help display course category and/or courses lists
2404 * This is a wrapper for core_course_category objects that also stores display options
2405 * and functions to retrieve sorted and paginated lists of categories/courses.
2407 * If theme overrides methods in core_course_renderers that access this class
2408 * it may as well not use this class at all or extend it.
2410 * @package core
2411 * @copyright 2013 Marina Glancy
2412 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2414 class coursecat_helper {
2415 /** @var string [none, collapsed, expanded] how (if) display courses list */
2416 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2417 /** @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) */
2418 protected $subcatdepth = 1;
2419 /** @var array options to display courses list */
2420 protected $coursesdisplayoptions = array();
2421 /** @var array options to display subcategories list */
2422 protected $categoriesdisplayoptions = array();
2423 /** @var array additional HTML attributes */
2424 protected $attributes = array();
2425 /** @var array search criteria if the list is a search result */
2426 protected $searchcriteria = null;
2429 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2431 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2432 * @return coursecat_helper
2434 public function set_show_courses($showcourses) {
2435 $this->showcourses = $showcourses;
2436 // Automatically set the options to preload summary and coursecontacts for core_course_category::get_courses()
2437 // and core_course_category::search_courses().
2438 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2439 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2440 $this->coursesdisplayoptions['customfields'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED;
2441 return $this;
2445 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2447 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2449 public function get_show_courses() {
2450 return $this->showcourses;
2454 * Sets the maximum depth to expand subcategories in the tree
2456 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2458 * @param int $subcatdepth
2459 * @return coursecat_helper
2461 public function set_subcat_depth($subcatdepth) {
2462 $this->subcatdepth = $subcatdepth;
2463 return $this;
2467 * Returns the maximum depth to expand subcategories in the tree
2469 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2471 * @return int
2473 public function get_subcat_depth() {
2474 return $this->subcatdepth;
2478 * Sets options to display list of courses
2480 * Options are later submitted as argument to core_course_category::get_courses() and/or core_course_category::search_courses()
2482 * Options that core_course_category::get_courses() accept:
2483 * - recursive - return courses from subcategories as well. Use with care,
2484 * this may be a huge list!
2485 * - summary - preloads fields 'summary' and 'summaryformat'
2486 * - coursecontacts - preloads course contacts
2487 * - customfields - preloads custom fields data
2488 * - isenrolled - preloads indication whether this user is enrolled in the course
2489 * - sort - list of fields to sort. Example
2490 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2491 * will sort by idnumber asc, shortname asc and id desc.
2492 * Default: array('sortorder' => 1)
2493 * Only cached fields may be used for sorting!
2494 * - offset
2495 * - limit - maximum number of children to return, 0 or null for no limit
2497 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2499 * Also renderer can set here any additional options it wants to pass between renderer functions.
2501 * @param array $options
2502 * @return coursecat_helper
2504 public function set_courses_display_options($options) {
2505 $this->coursesdisplayoptions = $options;
2506 $this->set_show_courses($this->showcourses); // this will calculate special display options
2507 return $this;
2511 * Sets one option to display list of courses
2513 * @see coursecat_helper::set_courses_display_options()
2515 * @param string $key
2516 * @param mixed $value
2517 * @return coursecat_helper
2519 public function set_courses_display_option($key, $value) {
2520 $this->coursesdisplayoptions[$key] = $value;
2521 return $this;
2525 * Return the specified option to display list of courses
2527 * @param string $optionname option name
2528 * @param mixed $defaultvalue default value for option if it is not specified
2529 * @return mixed
2531 public function get_courses_display_option($optionname, $defaultvalue = null) {
2532 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2533 return $this->coursesdisplayoptions[$optionname];
2534 } else {
2535 return $defaultvalue;
2540 * Returns all options to display the courses
2542 * This array is usually passed to {@link core_course_category::get_courses()} or
2543 * {@link core_course_category::search_courses()}
2545 * @return array
2547 public function get_courses_display_options() {
2548 return $this->coursesdisplayoptions;
2552 * Sets options to display list of subcategories
2554 * Options 'sort', 'offset' and 'limit' are passed to core_course_category::get_children().
2555 * Any other options may be used by renderer functions
2557 * @param array $options
2558 * @return coursecat_helper
2560 public function set_categories_display_options($options) {
2561 $this->categoriesdisplayoptions = $options;
2562 return $this;
2566 * Return the specified option to display list of subcategories
2568 * @param string $optionname option name
2569 * @param mixed $defaultvalue default value for option if it is not specified
2570 * @return mixed
2572 public function get_categories_display_option($optionname, $defaultvalue = null) {
2573 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2574 return $this->categoriesdisplayoptions[$optionname];
2575 } else {
2576 return $defaultvalue;
2581 * Returns all options to display list of subcategories
2583 * This array is usually passed to {@link core_course_category::get_children()}
2585 * @return array
2587 public function get_categories_display_options() {
2588 return $this->categoriesdisplayoptions;
2592 * Sets additional general options to pass between renderer functions, usually HTML attributes
2594 * @param array $attributes
2595 * @return coursecat_helper
2597 public function set_attributes($attributes) {
2598 $this->attributes = $attributes;
2599 return $this;
2603 * Return all attributes and erases them so they are not applied again
2605 * @param string $classname adds additional class name to the beginning of $attributes['class']
2606 * @return array
2608 public function get_and_erase_attributes($classname) {
2609 $attributes = $this->attributes;
2610 $this->attributes = array();
2611 if (empty($attributes['class'])) {
2612 $attributes['class'] = '';
2614 $attributes['class'] = $classname . ' '. $attributes['class'];
2615 return $attributes;
2619 * Sets the search criteria if the course is a search result
2621 * Search string will be used to highlight terms in course name and description
2623 * @param array $searchcriteria
2624 * @return coursecat_helper
2626 public function set_search_criteria($searchcriteria) {
2627 $this->searchcriteria = $searchcriteria;
2628 return $this;
2632 * Returns formatted and filtered description of the given category
2634 * @param core_course_category $coursecat category
2635 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2636 * if context is not specified it will be added automatically
2637 * @return string|null
2639 public function get_category_formatted_description($coursecat, $options = null) {
2640 if ($coursecat->id && $coursecat->is_uservisible() && !empty($coursecat->description)) {
2641 if (!isset($coursecat->descriptionformat)) {
2642 $descriptionformat = FORMAT_MOODLE;
2643 } else {
2644 $descriptionformat = $coursecat->descriptionformat;
2646 if ($options === null) {
2647 $options = array('noclean' => true, 'overflowdiv' => true);
2648 } else {
2649 $options = (array)$options;
2651 $context = context_coursecat::instance($coursecat->id);
2652 if (!isset($options['context'])) {
2653 $options['context'] = $context;
2655 $text = file_rewrite_pluginfile_urls($coursecat->description,
2656 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2657 return format_text($text, $descriptionformat, $options);
2659 return null;
2663 * Returns given course's summary with proper embedded files urls and formatted
2665 * @param core_course_list_element $course
2666 * @param array|stdClass $options additional formatting options
2667 * @return string
2669 public function get_course_formatted_summary($course, $options = array()) {
2670 global $CFG;
2671 require_once($CFG->libdir. '/filelib.php');
2672 if (!$course->has_summary()) {
2673 return '';
2675 $options = (array)$options;
2676 $context = context_course::instance($course->id);
2677 if (!isset($options['context'])) {
2678 // TODO see MDL-38521
2679 // option 1 (current), page context - no code required
2680 // option 2, system context
2681 // $options['context'] = context_system::instance();
2682 // option 3, course context:
2683 // $options['context'] = $context;
2684 // option 4, course category context:
2685 // $options['context'] = $context->get_parent_context();
2687 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2688 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2689 if (!empty($this->searchcriteria['search'])) {
2690 $summary = highlight($this->searchcriteria['search'], $summary);
2692 return $summary;
2696 * Returns course name as it is configured to appear in courses lists formatted to course context
2698 * @param core_course_list_element $course
2699 * @param array|stdClass $options additional formatting options
2700 * @return string
2702 public function get_course_formatted_name($course, $options = array()) {
2703 $options = (array)$options;
2704 if (!isset($options['context'])) {
2705 $options['context'] = context_course::instance($course->id);
2707 $name = format_string(get_course_display_name_for_list($course), true, $options);
2708 if (!empty($this->searchcriteria['search'])) {
2709 $name = highlight($this->searchcriteria['search'], $name);
2711 return $name;