weekly release 3.9.6+
[moodle.git] / course / renderer.php
blob5003ef4d6bd5b259ecb9ffd4a593bf448d75abcd
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Renderer for use with the course section and all the goodness that falls
20 * within it.
22 * This renderer should contain methods useful to courses, and categories.
24 * @package moodlecore
25 * @copyright 2010 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 /**
30 * The core course renderer
32 * Can be retrieved with the following:
33 * $renderer = $PAGE->get_renderer('core','course');
35 class core_course_renderer extends plugin_renderer_base {
36 const COURSECAT_SHOW_COURSES_NONE = 0; /* do not show courses at all */
37 const COURSECAT_SHOW_COURSES_COUNT = 5; /* do not show courses but show number of courses next to category name */
38 const COURSECAT_SHOW_COURSES_COLLAPSED = 10;
39 const COURSECAT_SHOW_COURSES_AUTO = 15; /* will choose between collapsed and expanded automatically */
40 const COURSECAT_SHOW_COURSES_EXPANDED = 20;
41 const COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT = 30;
43 const COURSECAT_TYPE_CATEGORY = 0;
44 const COURSECAT_TYPE_COURSE = 1;
46 /**
47 * A cache of strings
48 * @var stdClass
50 protected $strings;
52 /**
53 * Whether a category content is being initially rendered with children. This is mainly used by the
54 * core_course_renderer::corsecat_tree() to render the appropriate action for the Expand/Collapse all link on
55 * page load.
56 * @var bool
58 protected $categoryexpandedonload = false;
60 /**
61 * Override the constructor so that we can initialise the string cache
63 * @param moodle_page $page
64 * @param string $target
66 public function __construct(moodle_page $page, $target) {
67 $this->strings = new stdClass;
68 parent::__construct($page, $target);
71 /**
72 * @deprecated since 3.2
74 protected function add_modchoosertoggle() {
75 throw new coding_exception('core_course_renderer::add_modchoosertoggle() can not be used anymore.');
78 /**
79 * Renders course info box.
81 * @param stdClass $course
82 * @return string
84 public function course_info_box(stdClass $course) {
85 $content = '';
86 $content .= $this->output->box_start('generalbox info');
87 $chelper = new coursecat_helper();
88 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
89 $content .= $this->coursecat_coursebox($chelper, $course);
90 $content .= $this->output->box_end();
91 return $content;
94 /**
95 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
97 * @deprecated since 2.5
99 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
101 * @param array $ignored argument ignored
102 * @return string
104 public final function course_category_tree(array $ignored) {
105 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
106 return $this->frontpage_combo_list();
110 * Renderers a category for use with course_category_tree
112 * @deprecated since 2.5
114 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
116 * @param array $category
117 * @param int $depth
118 * @return string
120 protected final function course_category_tree_category(stdClass $category, $depth=1) {
121 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
122 return '';
126 * Render a modchooser.
128 * @param renderable $modchooser The chooser.
129 * @return string
131 public function render_modchooser(renderable $modchooser) {
132 return $this->render_from_template('core_course/modchooser', $modchooser->export_for_template($this));
136 * Build the HTML for the module chooser javascript popup
138 * @param array $modules A set of modules as returned form @see
139 * get_module_metadata
140 * @param object $course The course that will be displayed
141 * @return string The composed HTML for the module
143 public function course_modchooser($modules, $course) {
144 debugging('course_modchooser() is deprecated. Please use course_activitychooser() instead.', DEBUG_DEVELOPER);
146 return $this->course_activitychooser($course->id);
150 * Build the HTML for the module chooser javascript popup.
152 * @param int $courseid The course id to fetch modules for.
153 * @return string
155 public function course_activitychooser($courseid) {
157 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchooser')) {
158 return '';
161 // Build an object of config settings that we can then hook into in the Activity Chooser.
162 $chooserconfig = (object) [
163 'tabmode' => get_config('core', 'activitychoosertabmode'),
165 $this->page->requires->js_call_amd('core_course/activitychooser', 'init', [$courseid, $chooserconfig]);
167 return '';
171 * Build the HTML for a specified set of modules
173 * @param array $modules A set of modules as used by the
174 * course_modchooser_module function
175 * @return string The composed HTML for the module
177 protected function course_modchooser_module_types($modules) {
178 debugging('Method core_course_renderer::course_modchooser_module_types() is deprecated, ' .
179 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
180 return '';
184 * Return the HTML for the specified module adding any required classes
186 * @param object $module An object containing the title, and link. An
187 * icon, and help text may optionally be specified. If the module
188 * contains subtypes in the types option, then these will also be
189 * displayed.
190 * @param array $classes Additional classes to add to the encompassing
191 * div element
192 * @return string The composed HTML for the module
194 protected function course_modchooser_module($module, $classes = array('option')) {
195 debugging('Method core_course_renderer::course_modchooser_module() is deprecated, ' .
196 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
197 return '';
200 protected function course_modchooser_title($title, $identifier = null) {
201 debugging('Method core_course_renderer::course_modchooser_title() is deprecated, ' .
202 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
203 return '';
207 * Renders HTML for displaying the sequence of course module editing buttons
209 * @see course_get_cm_edit_actions()
211 * @param action_link[] $actions Array of action_link objects
212 * @param cm_info $mod The module we are displaying actions for.
213 * @param array $displayoptions additional display options:
214 * ownerselector => A JS/CSS selector that can be used to find an cm node.
215 * If specified the owning node will be given the class 'action-menu-shown' when the action
216 * menu is being displayed.
217 * constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
218 * the action menu to when it is being displayed.
219 * donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
220 * @return string
222 public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
223 global $CFG;
225 if (empty($actions)) {
226 return '';
229 if (isset($displayoptions['ownerselector'])) {
230 $ownerselector = $displayoptions['ownerselector'];
231 } else if ($mod) {
232 $ownerselector = '#module-'.$mod->id;
233 } else {
234 debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
235 $ownerselector = 'li.activity';
238 if (isset($displayoptions['constraintselector'])) {
239 $constraint = $displayoptions['constraintselector'];
240 } else {
241 $constraint = '.course-content';
244 $menu = new action_menu();
245 $menu->set_owner_selector($ownerselector);
246 $menu->set_constraint($constraint);
247 $menu->set_alignment(action_menu::TR, action_menu::BR);
248 $menu->set_menu_trigger(get_string('edit'));
250 foreach ($actions as $action) {
251 if ($action instanceof action_menu_link) {
252 $action->add_class('cm-edit-action');
254 $menu->add($action);
256 $menu->attributes['class'] .= ' section-cm-edit-actions commands';
258 // Prioritise the menu ahead of all other actions.
259 $menu->prioritise = true;
261 return $this->render($menu);
265 * Renders HTML for the menus to add activities and resources to the current course
267 * @param stdClass $course
268 * @param int $section relative section number (field course_sections.section)
269 * @param int $sectionreturn The section to link back to
270 * @param array $displayoptions additional display options, for example blocks add
271 * option 'inblock' => true, suggesting to display controls vertically
272 * @return string
274 function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
275 global $CFG, $USER;
277 // The returned control HTML can be one of the following:
278 // - Only the non-ajax control (select menus of activities and resources) with a noscript fallback for non js clients.
279 // - Only the ajax control (the link which when clicked produces the activity chooser modal). No noscript fallback.
280 // - [Behat only]: The non-ajax control and optionally the ajax control (depending on site settings). If included, the link
281 // takes priority and the non-ajax control is wrapped in a <noscript>.
282 // Behat requires the third case because some features run with JS, some do not. We must include the noscript fallback.
283 $behatsite = defined('BEHAT_SITE_RUNNING');
284 $nonajaxcontrol = '';
285 $ajaxcontrol = '';
286 $courseajaxenabled = course_ajax_enabled($course);
287 $userchooserenabled = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
289 // Decide what combination of controls to output:
290 // During behat runs, both controls can be used in conjunction to provide non-js fallback.
291 // During normal use only one control or the other will be output. No non-js fallback is needed.
292 $rendernonajaxcontrol = $behatsite || !$courseajaxenabled || !$userchooserenabled || $course->id != $this->page->course->id;
293 $renderajaxcontrol = $courseajaxenabled && $userchooserenabled && $course->id == $this->page->course->id;
295 // The non-ajax control, which includes an entirely non-js (<noscript>) fallback too.
296 if ($rendernonajaxcontrol) {
297 $vertical = !empty($displayoptions['inblock']);
299 // Check to see if user can add menus.
300 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
301 || !$this->page->user_is_editing()) {
302 return '';
305 // Retrieve all modules with associated metadata.
306 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
307 $urlparams = ['section' => $section];
308 if (!is_null($sectionreturn)) {
309 $urlparams['sr'] = $sectionreturn;
311 $modules = $contentitemservice->get_content_items_for_user_in_course($USER, $course, $urlparams);
313 // Return if there are no content items to add.
314 if (empty($modules)) {
315 return '';
318 // We'll sort resources and activities into two lists.
319 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
321 foreach ($modules as $module) {
322 $activityclass = MOD_CLASS_ACTIVITY;
323 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
324 $activityclass = MOD_CLASS_RESOURCE;
325 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
326 // System modules cannot be added by user, do not add to dropdown.
327 continue;
329 $link = $module->link;
330 $activities[$activityclass][$link] = $module->title;
333 $straddactivity = get_string('addactivity');
334 $straddresource = get_string('addresource');
335 $sectionname = get_section_name($course, $section);
336 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
337 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
339 $nonajaxcontrol = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-'
340 . $section));
342 if (!$vertical) {
343 $nonajaxcontrol .= html_writer::start_tag('div', array('class' => 'horizontal'));
346 if (!empty($activities[MOD_CLASS_RESOURCE])) {
347 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array('' => $straddresource), "ressection$section");
348 $select->set_help_icon('resources');
349 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
350 $nonajaxcontrol .= $this->output->render($select);
353 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
354 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array('' => $straddactivity), "section$section");
355 $select->set_help_icon('activities');
356 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
357 $nonajaxcontrol .= $this->output->render($select);
360 if (!$vertical) {
361 $nonajaxcontrol .= html_writer::end_tag('div');
364 $nonajaxcontrol .= html_writer::end_tag('div');
367 // The ajax control - the 'Add an activity or resource' link.
368 if ($renderajaxcontrol) {
369 // The module chooser link.
370 $straddeither = get_string('addresourceoractivity');
371 $ajaxcontrol = html_writer::start_tag('div', array('class' => 'mdl-right'));
372 $ajaxcontrol .= html_writer::start_tag('div', array('class' => 'section-modchooser'));
373 $icon = $this->output->pix_icon('t/add', '');
374 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
375 $ajaxcontrol .= html_writer::tag('button', $icon . $span, [
376 'class' => 'section-modchooser-link btn btn-link',
377 'data-action' => 'open-chooser',
378 'data-sectionid' => $section,
379 'data-sectionreturnid' => $sectionreturn,
382 $ajaxcontrol .= html_writer::end_tag('div');
383 $ajaxcontrol .= html_writer::end_tag('div');
385 // Load the JS for the modal.
386 $this->course_activitychooser($course->id);
389 // Behat only: If both controls are being included in the HTML,
390 // show the link by default and only fall back to the selects if js is disabled.
391 if ($behatsite && $renderajaxcontrol) {
392 $nonajaxcontrol = html_writer::tag('div', $nonajaxcontrol, array('class' => 'hiddenifjs addresourcedropdown'));
393 $ajaxcontrol = html_writer::tag('div', $ajaxcontrol, array('class' => 'visibleifjs addresourcemodchooser'));
396 // If behat is running, we should have the non-ajax control + the ajax control.
397 // Otherwise, we'll have one or the other.
398 return $ajaxcontrol . $nonajaxcontrol;
402 * Renders html to display a course search form.
404 * @param string $value default value to populate the search field
405 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
406 * @return string
408 public function course_search_form($value = '', $format = 'plain') {
409 static $count = 0;
410 $formid = 'coursesearch';
411 if ((++$count) > 1) {
412 $formid .= $count;
415 switch ($format) {
416 case 'navbar' :
417 $formid = 'coursesearchnavbar';
418 $inputid = 'navsearchbox';
419 $inputsize = 20;
420 break;
421 case 'short' :
422 $inputid = 'shortsearchbox';
423 $inputsize = 12;
424 break;
425 default :
426 $inputid = 'coursesearchbox';
427 $inputsize = 30;
430 $data = new stdClass();
431 $data->searchurl = \core_search\manager::get_course_search_url()->out(false);
432 $data->id = $formid;
433 $data->inputid = $inputid;
434 $data->inputsize = $inputsize;
435 $data->value = $value;
436 $data->areaids = 'core_course-course';
438 if ($format != 'navbar') {
439 $helpicon = new \help_icon('coursesearch', 'core');
440 $data->helpicon = $helpicon->export_for_template($this);
443 return $this->render_from_template('core_course/course_search_form', $data);
447 * Renders html for completion box on course page
449 * If completion is disabled, returns empty string
450 * If completion is automatic, returns an icon of the current completion state
451 * If completion is manual, returns a form (with an icon inside) that allows user to
452 * toggle completion
454 * @param stdClass $course course object
455 * @param completion_info $completioninfo completion info for the course, it is recommended
456 * to fetch once for all modules in course/section for performance
457 * @param cm_info $mod module to show completion for
458 * @param array $displayoptions display options, not used in core
459 * @return string
461 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
462 global $CFG, $DB, $USER;
463 $output = '';
465 $istrackeduser = $completioninfo->is_tracked_user($USER->id);
466 $isediting = $this->page->user_is_editing();
468 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
469 return $output;
471 if ($completioninfo === null) {
472 $completioninfo = new completion_info($course);
474 $completion = $completioninfo->is_enabled($mod);
476 if ($completion == COMPLETION_TRACKING_NONE) {
477 if ($isediting) {
478 $output .= html_writer::span('&nbsp;', 'filler');
480 return $output;
483 $completionicon = '';
485 if ($isediting || !$istrackeduser) {
486 switch ($completion) {
487 case COMPLETION_TRACKING_MANUAL :
488 $completionicon = 'manual-enabled'; break;
489 case COMPLETION_TRACKING_AUTOMATIC :
490 $completionicon = 'auto-enabled'; break;
492 } else {
493 $completiondata = $completioninfo->get_data($mod, true);
494 if ($completion == COMPLETION_TRACKING_MANUAL) {
495 switch($completiondata->completionstate) {
496 case COMPLETION_INCOMPLETE:
497 $completionicon = 'manual-n' . ($completiondata->overrideby ? '-override' : '');
498 break;
499 case COMPLETION_COMPLETE:
500 $completionicon = 'manual-y' . ($completiondata->overrideby ? '-override' : '');
501 break;
503 } else { // Automatic
504 switch($completiondata->completionstate) {
505 case COMPLETION_INCOMPLETE:
506 $completionicon = 'auto-n' . ($completiondata->overrideby ? '-override' : '');
507 break;
508 case COMPLETION_COMPLETE:
509 $completionicon = 'auto-y' . ($completiondata->overrideby ? '-override' : '');
510 break;
511 case COMPLETION_COMPLETE_PASS:
512 $completionicon = 'auto-pass'; break;
513 case COMPLETION_COMPLETE_FAIL:
514 $completionicon = 'auto-fail'; break;
518 if ($completionicon) {
519 $formattedname = html_entity_decode($mod->get_formatted_name(), ENT_QUOTES, 'UTF-8');
520 if (!$isediting && $istrackeduser && $completiondata->overrideby) {
521 $args = new stdClass();
522 $args->modname = $formattedname;
523 $overridebyuser = \core_user::get_user($completiondata->overrideby, '*', MUST_EXIST);
524 $args->overrideuser = fullname($overridebyuser);
525 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $args);
526 } else {
527 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
530 if ($isediting || !$istrackeduser || !has_capability('moodle/course:togglecompletion', $mod->context)) {
531 // When editing, the icon is just an image.
532 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
533 array('title' => $imgalt, 'class' => 'iconsmall'));
534 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
535 array('class' => 'autocompletion'));
536 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
537 $newstate =
538 $completiondata->completionstate == COMPLETION_COMPLETE
539 ? COMPLETION_INCOMPLETE
540 : COMPLETION_COMPLETE;
541 // In manual mode the icon is a toggle form...
543 // If this completion state is used by the
544 // conditional activities system, we need to turn
545 // off the JS.
546 $extraclass = '';
547 if (!empty($CFG->enableavailability) &&
548 core_availability\info::completion_value_used($course, $mod->id)) {
549 $extraclass = ' preventjs';
551 $output .= html_writer::start_tag('form', array('method' => 'post',
552 'action' => new moodle_url('/course/togglecompletion.php'),
553 'class' => 'togglecompletion'. $extraclass));
554 $output .= html_writer::start_tag('div');
555 $output .= html_writer::empty_tag('input', array(
556 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
557 $output .= html_writer::empty_tag('input', array(
558 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
559 $output .= html_writer::empty_tag('input', array(
560 'type' => 'hidden', 'name' => 'modulename', 'value' => $formattedname));
561 $output .= html_writer::empty_tag('input', array(
562 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
563 $output .= html_writer::tag('button',
564 $this->output->pix_icon('i/completion-' . $completionicon, $imgalt),
565 array('class' => 'btn btn-link', 'aria-live' => 'assertive'));
566 $output .= html_writer::end_tag('div');
567 $output .= html_writer::end_tag('form');
568 } else {
569 // In auto mode, the icon is just an image.
570 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
571 array('title' => $imgalt));
572 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
573 array('class' => 'autocompletion'));
576 return $output;
580 * Checks if course module has any conditions that may make it unavailable for
581 * all or some of the students
583 * This function is internal and is only used to create CSS classes for the module name/text
585 * @param cm_info $mod
586 * @return bool
588 protected function is_cm_conditionally_hidden(cm_info $mod) {
589 global $CFG;
590 $conditionalhidden = false;
591 if (!empty($CFG->enableavailability)) {
592 $info = new \core_availability\info_module($mod);
593 $conditionalhidden = !$info->is_available_for_all();
595 return $conditionalhidden;
599 * Renders html to display a name with the link to the course module on a course page
601 * If module is unavailable for user but still needs to be displayed
602 * in the list, just the name is returned without a link
604 * Note, that for course modules that never have separate pages (i.e. labels)
605 * this function return an empty string
607 * @param cm_info $mod
608 * @param array $displayoptions
609 * @return string
611 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
612 if (!$mod->is_visible_on_course_page() || !$mod->url) {
613 // Nothing to be displayed to the user.
614 return '';
617 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
618 $groupinglabel = $mod->get_grouping_label($textclasses);
620 // Render element that allows to edit activity name inline. It calls {@link course_section_cm_name_title()}
621 // to get the display title of the activity.
622 $tmpl = new \core_course\output\course_module_name($mod, $this->page->user_is_editing(), $displayoptions);
623 return $this->output->render_from_template('core/inplace_editable', $tmpl->export_for_template($this->output)) .
624 $groupinglabel;
628 * Returns the CSS classes for the activity name/content
630 * For items which are hidden, unavailable or stealth but should be displayed
631 * to current user ($mod->is_visible_on_course_page()), we show those as dimmed.
632 * Students will also see as dimmed activities names that are not yet available
633 * but should still be displayed (without link) with availability info.
635 * @param cm_info $mod
636 * @return array array of two elements ($linkclasses, $textclasses)
638 protected function course_section_cm_classes(cm_info $mod) {
639 $linkclasses = '';
640 $textclasses = '';
641 if ($mod->uservisible) {
642 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
643 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
644 has_capability('moodle/course:viewhiddenactivities', $mod->context);
645 if ($accessiblebutdim) {
646 $linkclasses .= ' dimmed';
647 $textclasses .= ' dimmed_text';
648 if ($conditionalhidden) {
649 $linkclasses .= ' conditionalhidden';
650 $textclasses .= ' conditionalhidden';
653 if ($mod->is_stealth()) {
654 // Stealth activity is the one that is not visible on course page.
655 // It still may be displayed to the users who can manage it.
656 $linkclasses .= ' stealth';
657 $textclasses .= ' stealth';
659 } else {
660 $linkclasses .= ' dimmed';
661 $textclasses .= ' dimmed dimmed_text';
663 return array($linkclasses, $textclasses);
667 * Renders html to display a name with the link to the course module on a course page
669 * If module is unavailable for user but still needs to be displayed
670 * in the list, just the name is returned without a link
672 * Note, that for course modules that never have separate pages (i.e. labels)
673 * this function return an empty string
675 * @param cm_info $mod
676 * @param array $displayoptions
677 * @return string
679 public function course_section_cm_name_title(cm_info $mod, $displayoptions = array()) {
680 $output = '';
681 $url = $mod->url;
682 if (!$mod->is_visible_on_course_page() || !$url) {
683 // Nothing to be displayed to the user.
684 return $output;
687 //Accessibility: for files get description via icon, this is very ugly hack!
688 $instancename = $mod->get_formatted_name();
689 $altname = $mod->modfullname;
690 // Avoid unnecessary duplication: if e.g. a forum name already
691 // includes the word forum (or Forum, etc) then it is unhelpful
692 // to include that in the accessible description that is added.
693 if (false !== strpos(core_text::strtolower($instancename),
694 core_text::strtolower($altname))) {
695 $altname = '';
697 // File type after name, for alphabetic lists (screen reader).
698 if ($altname) {
699 $altname = get_accesshide(' '.$altname);
702 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
704 // Get on-click attribute value if specified and decode the onclick - it
705 // has already been encoded for display (puke).
706 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
708 // Display link itself.
709 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
710 'class' => 'iconlarge activityicon', 'alt' => '', 'role' => 'presentation', 'aria-hidden' => 'true')) .
711 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
712 if ($mod->uservisible) {
713 $output .= html_writer::link($url, $activitylink, array('class' => 'aalink' . $linkclasses, 'onclick' => $onclick));
714 } else {
715 // We may be displaying this just in order to show information
716 // about visibility, without the actual link ($mod->is_visible_on_course_page()).
717 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses));
719 return $output;
723 * Renders html to display the module content on the course page (i.e. text of the labels)
725 * @param cm_info $mod
726 * @param array $displayoptions
727 * @return string
729 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
730 $output = '';
731 if (!$mod->is_visible_on_course_page()) {
732 // nothing to be displayed to the user
733 return $output;
735 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
736 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
737 if ($mod->url && $mod->uservisible) {
738 if ($content) {
739 // If specified, display extra content after link.
740 $output = html_writer::tag('div', $content, array('class' =>
741 trim('contentafterlink ' . $textclasses)));
743 } else {
744 $groupinglabel = $mod->get_grouping_label($textclasses);
746 // No link, so display only content.
747 $output = html_writer::tag('div', $content . $groupinglabel,
748 array('class' => 'contentwithoutlink ' . $textclasses));
750 return $output;
754 * Displays availability info for a course section or course module
756 * @param string $text
757 * @param string $additionalclasses
758 * @return string
760 public function availability_info($text, $additionalclasses = '') {
762 $data = ['text' => $text, 'classes' => $additionalclasses];
763 $additionalclasses = array_filter(explode(' ', $additionalclasses));
765 if (in_array('ishidden', $additionalclasses)) {
766 $data['ishidden'] = 1;
768 } else if (in_array('isstealth', $additionalclasses)) {
769 $data['isstealth'] = 1;
771 } else if (in_array('isrestricted', $additionalclasses)) {
772 $data['isrestricted'] = 1;
774 if (in_array('isfullinfo', $additionalclasses)) {
775 $data['isfullinfo'] = 1;
779 return $this->render_from_template('core/availability_info', $data);
783 * Renders HTML to show course module availability information (for someone who isn't allowed
784 * to see the activity itself, or for staff)
786 * @param cm_info $mod
787 * @param array $displayoptions
788 * @return string
790 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
791 global $CFG;
792 $output = '';
793 if (!$mod->is_visible_on_course_page()) {
794 return $output;
796 if (!$mod->uservisible) {
797 // this is a student who is not allowed to see the module but might be allowed
798 // to see availability info (i.e. "Available from ...")
799 if (!empty($mod->availableinfo)) {
800 $formattedinfo = \core_availability\info::format_info(
801 $mod->availableinfo, $mod->get_course());
802 $output = $this->availability_info($formattedinfo, 'isrestricted');
804 return $output;
806 // this is a teacher who is allowed to see module but still should see the
807 // information that module is not available to all/some students
808 $modcontext = context_module::instance($mod->id);
809 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
810 if ($canviewhidden && !$mod->visible) {
811 // This module is hidden but current user has capability to see it.
812 // Do not display the availability info if the whole section is hidden.
813 if ($mod->get_section_info()->visible) {
814 $output .= $this->availability_info(get_string('hiddenfromstudents'), 'ishidden');
816 } else if ($mod->is_stealth()) {
817 // This module is available but is normally not displayed on the course page
818 // (this user can see it because they can manage it).
819 $output .= $this->availability_info(get_string('hiddenoncoursepage'), 'isstealth');
821 if ($canviewhidden && !empty($CFG->enableavailability)) {
822 // Display information about conditional availability.
823 // Don't add availability information if user is not editing and activity is hidden.
824 if ($mod->visible || $this->page->user_is_editing()) {
825 $hidinfoclass = 'isrestricted isfullinfo';
826 if (!$mod->visible) {
827 $hidinfoclass .= ' hide';
829 $ci = new \core_availability\info_module($mod);
830 $fullinfo = $ci->get_full_information();
831 if ($fullinfo) {
832 $formattedinfo = \core_availability\info::format_info(
833 $fullinfo, $mod->get_course());
834 $output .= $this->availability_info($formattedinfo, $hidinfoclass);
838 return $output;
842 * Renders HTML to display one course module for display within a section.
844 * This function calls:
845 * {@link core_course_renderer::course_section_cm()}
847 * @param stdClass $course
848 * @param completion_info $completioninfo
849 * @param cm_info $mod
850 * @param int|null $sectionreturn
851 * @param array $displayoptions
852 * @return String
854 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
855 $output = '';
856 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
857 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
858 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
860 return $output;
864 * Renders HTML to display one course module in a course section
866 * This includes link, content, availability, completion info and additional information
867 * that module type wants to display (i.e. number of unread forum posts)
869 * This function calls:
870 * {@link core_course_renderer::course_section_cm_name()}
871 * {@link core_course_renderer::course_section_cm_text()}
872 * {@link core_course_renderer::course_section_cm_availability()}
873 * {@link core_course_renderer::course_section_cm_completion()}
874 * {@link course_get_cm_edit_actions()}
875 * {@link core_course_renderer::course_section_cm_edit_actions()}
877 * @param stdClass $course
878 * @param completion_info $completioninfo
879 * @param cm_info $mod
880 * @param int|null $sectionreturn
881 * @param array $displayoptions
882 * @return string
884 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
885 $output = '';
886 // We return empty string (because course module will not be displayed at all)
887 // if:
888 // 1) The activity is not visible to users
889 // and
890 // 2) The 'availableinfo' is empty, i.e. the activity was
891 // hidden in a way that leaves no info, such as using the
892 // eye icon.
893 if (!$mod->is_visible_on_course_page()) {
894 return $output;
897 $indentclasses = 'mod-indent';
898 if (!empty($mod->indent)) {
899 $indentclasses .= ' mod-indent-'.$mod->indent;
900 if ($mod->indent > 15) {
901 $indentclasses .= ' mod-indent-huge';
905 $output .= html_writer::start_tag('div');
907 if ($this->page->user_is_editing()) {
908 $output .= course_get_cm_move($mod, $sectionreturn);
911 $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer w-100'));
913 // This div is used to indent the content.
914 $output .= html_writer::div('', $indentclasses);
916 // Start a wrapper for the actual content to keep the indentation consistent
917 $output .= html_writer::start_tag('div');
919 // Display the link to the module (or do nothing if module has no url)
920 $cmname = $this->course_section_cm_name($mod, $displayoptions);
922 if (!empty($cmname)) {
923 // Start the div for the activity title, excluding the edit icons.
924 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
925 $output .= $cmname;
928 // Module can put text after the link (e.g. forum unread)
929 $output .= $mod->afterlink;
931 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
932 $output .= html_writer::end_tag('div'); // .activityinstance
935 // If there is content but NO link (eg label), then display the
936 // content here (BEFORE any icons). In this case cons must be
937 // displayed after the content so that it makes more sense visually
938 // and for accessibility reasons, e.g. if you have a one-line label
939 // it should work similarly (at least in terms of ordering) to an
940 // activity.
941 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
942 $url = $mod->url;
943 if (empty($url)) {
944 $output .= $contentpart;
947 $modicons = '';
948 if ($this->page->user_is_editing()) {
949 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
950 $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
951 $modicons .= $mod->afterediticons;
954 $modicons .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
956 if (!empty($modicons)) {
957 $output .= html_writer::div($modicons, 'actions');
960 // Show availability info (if module is not available).
961 $output .= $this->course_section_cm_availability($mod, $displayoptions);
963 // If there is content AND a link, then display the content here
964 // (AFTER any icons). Otherwise it was displayed before
965 if (!empty($url)) {
966 $output .= $contentpart;
969 $output .= html_writer::end_tag('div'); // $indentclasses
971 // End of indentation div.
972 $output .= html_writer::end_tag('div');
974 $output .= html_writer::end_tag('div');
975 return $output;
979 * Message displayed to the user when they try to access unavailable activity following URL
981 * This method is a very simplified version of {@link course_section_cm()} to be part of the error
982 * notification only. It also does not check if module is visible on course page or not.
984 * The message will be displayed inside notification!
986 * @param cm_info $cm
987 * @return string
989 public function course_section_cm_unavailable_error_message(cm_info $cm) {
990 if ($cm->uservisible) {
991 return null;
993 if (!$cm->availableinfo) {
994 return get_string('activityiscurrentlyhidden');
997 $altname = get_accesshide(' ' . $cm->modfullname);
998 $name = html_writer::empty_tag('img', array('src' => $cm->get_icon_url(),
999 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
1000 html_writer::tag('span', ' '.$cm->get_formatted_name() . $altname, array('class' => 'instancename'));
1001 $formattedinfo = \core_availability\info::format_info($cm->availableinfo, $cm->get_course());
1002 return html_writer::div($name, 'activityinstance-error') .
1003 html_writer::div($formattedinfo, 'availabilityinfo-error');
1007 * Renders HTML to display a list of course modules in a course section
1008 * Also displays "move here" controls in Javascript-disabled mode
1010 * This function calls {@link core_course_renderer::course_section_cm()}
1012 * @param stdClass $course course object
1013 * @param int|stdClass|section_info $section relative section number or section object
1014 * @param int $sectionreturn section number to return to
1015 * @param int $displayoptions
1016 * @return void
1018 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
1019 global $USER;
1021 $output = '';
1022 $modinfo = get_fast_modinfo($course);
1023 if (is_object($section)) {
1024 $section = $modinfo->get_section_info($section->section);
1025 } else {
1026 $section = $modinfo->get_section_info($section);
1028 $completioninfo = new completion_info($course);
1030 // check if we are currently in the process of moving a module with JavaScript disabled
1031 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
1032 if ($ismoving) {
1033 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
1034 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1037 // Get the list of modules visible to user (excluding the module being moved if there is one)
1038 $moduleshtml = array();
1039 if (!empty($modinfo->sections[$section->section])) {
1040 foreach ($modinfo->sections[$section->section] as $modnumber) {
1041 $mod = $modinfo->cms[$modnumber];
1043 if ($ismoving and $mod->id == $USER->activitycopy) {
1044 // do not display moving mod
1045 continue;
1048 if ($modulehtml = $this->course_section_cm_list_item($course,
1049 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
1050 $moduleshtml[$modnumber] = $modulehtml;
1055 $sectionoutput = '';
1056 if (!empty($moduleshtml) || $ismoving) {
1057 foreach ($moduleshtml as $modnumber => $modulehtml) {
1058 if ($ismoving) {
1059 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
1060 $sectionoutput .= html_writer::tag('li',
1061 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1062 array('class' => 'movehere'));
1065 $sectionoutput .= $modulehtml;
1068 if ($ismoving) {
1069 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1070 $sectionoutput .= html_writer::tag('li',
1071 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1072 array('class' => 'movehere'));
1076 // Always output the section module list.
1077 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1079 return $output;
1083 * Displays a custom list of courses with paging bar if necessary
1085 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1086 * appears under the list.
1088 * If both $paginationurl and $totalcount are specified, and $totalcount is
1089 * bigger than count($courses), a paging bar is displayed above and under the
1090 * courses list.
1092 * @param array $courses array of course records (or instances of core_course_list_element) to show on this page
1093 * @param bool $showcategoryname whether to add category name to the course description
1094 * @param string $additionalclasses additional CSS classes to add to the div.courses
1095 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1096 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1097 * @param int $page current page number (defaults to 0 referring to the first page)
1098 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1099 * @return string
1101 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1102 global $CFG;
1103 // create instance of coursecat_helper to pass display options to function rendering courses list
1104 $chelper = new coursecat_helper();
1105 if ($showcategoryname) {
1106 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1107 } else {
1108 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1110 if ($totalcount !== null && $paginationurl !== null) {
1111 // add options to display pagination
1112 if ($perpage === null) {
1113 $perpage = $CFG->coursesperpage;
1115 $chelper->set_courses_display_options(array(
1116 'limit' => $perpage,
1117 'offset' => ((int)$page) * $perpage,
1118 'paginationurl' => $paginationurl,
1120 } else if ($paginationurl !== null) {
1121 // add options to display 'View more' link
1122 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1123 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1125 $chelper->set_attributes(array('class' => $additionalclasses));
1126 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1127 return $content;
1131 * Returns HTML to display course name.
1133 * @param coursecat_helper $chelper
1134 * @param core_course_list_element $course
1135 * @return string
1137 protected function course_name(coursecat_helper $chelper, core_course_list_element $course): string {
1138 $content = '';
1139 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1140 $nametag = 'h3';
1141 } else {
1142 $nametag = 'div';
1144 $coursename = $chelper->get_course_formatted_name($course);
1145 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', ['id' => $course->id]),
1146 $coursename, ['class' => $course->visible ? 'aalink' : 'aalink dimmed']);
1147 $content .= html_writer::tag($nametag, $coursenamelink, ['class' => 'coursename']);
1148 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1149 $content .= html_writer::start_tag('div', ['class' => 'moreinfo']);
1150 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1151 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()
1152 || $course->has_custom_fields()) {
1153 $url = new moodle_url('/course/info.php', ['id' => $course->id]);
1154 $image = $this->output->pix_icon('i/info', $this->strings->summary);
1155 $content .= html_writer::link($url, $image, ['title' => $this->strings->summary]);
1156 // Make sure JS file to expand course content is included.
1157 $this->coursecat_include_js();
1160 $content .= html_writer::end_tag('div');
1161 return $content;
1165 * Returns HTML to display course enrolment icons.
1167 * @param core_course_list_element $course
1168 * @return string
1170 protected function course_enrolment_icons(core_course_list_element $course): string {
1171 $content = '';
1172 if ($icons = enrol_get_course_info_icons($course)) {
1173 $content .= html_writer::start_tag('div', ['class' => 'enrolmenticons']);
1174 foreach ($icons as $icon) {
1175 $content .= $this->render($icon);
1177 $content .= html_writer::end_tag('div');
1179 return $content;
1183 * Displays one course in the list of courses.
1185 * This is an internal function, to display an information about just one course
1186 * please use {@link core_course_renderer::course_info_box()}
1188 * @param coursecat_helper $chelper various display options
1189 * @param core_course_list_element|stdClass $course
1190 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1191 * depend on the course position in list - first/last/even/odd)
1192 * @return string
1194 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1195 if (!isset($this->strings->summary)) {
1196 $this->strings->summary = get_string('summary');
1198 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1199 return '';
1201 if ($course instanceof stdClass) {
1202 $course = new core_course_list_element($course);
1204 $content = '';
1205 $classes = trim('coursebox clearfix '. $additionalclasses);
1206 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1207 $classes .= ' collapsed';
1210 // .coursebox
1211 $content .= html_writer::start_tag('div', array(
1212 'class' => $classes,
1213 'data-courseid' => $course->id,
1214 'data-type' => self::COURSECAT_TYPE_COURSE,
1217 $content .= html_writer::start_tag('div', array('class' => 'info'));
1218 $content .= $this->course_name($chelper, $course);
1219 $content .= $this->course_enrolment_icons($course);
1220 $content .= html_writer::end_tag('div');
1222 $content .= html_writer::start_tag('div', array('class' => 'content'));
1223 $content .= $this->coursecat_coursebox_content($chelper, $course);
1224 $content .= html_writer::end_tag('div');
1226 $content .= html_writer::end_tag('div'); // .coursebox
1227 return $content;
1231 * Returns HTML to display course summary.
1233 * @param coursecat_helper $chelper
1234 * @param core_course_list_element $course
1235 * @return string
1237 protected function course_summary(coursecat_helper $chelper, core_course_list_element $course): string {
1238 $content = '';
1239 if ($course->has_summary()) {
1240 $content .= html_writer::start_tag('div', ['class' => 'summary']);
1241 $content .= $chelper->get_course_formatted_summary($course,
1242 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1243 $content .= html_writer::end_tag('div');
1245 return $content;
1249 * Returns HTML to display course contacts.
1251 * @param core_course_list_element $course
1252 * @return string
1254 protected function course_contacts(core_course_list_element $course) {
1255 $content = '';
1256 if ($course->has_course_contacts()) {
1257 $content .= html_writer::start_tag('ul', ['class' => 'teachers']);
1258 foreach ($course->get_course_contacts() as $coursecontact) {
1259 $rolenames = array_map(function ($role) {
1260 return $role->displayname;
1261 }, $coursecontact['roles']);
1262 $name = implode(", ", $rolenames).': '.
1263 html_writer::link(new moodle_url('/user/view.php',
1264 ['id' => $coursecontact['user']->id, 'course' => SITEID]),
1265 $coursecontact['username']);
1266 $content .= html_writer::tag('li', $name);
1268 $content .= html_writer::end_tag('ul');
1270 return $content;
1274 * Returns HTML to display course overview files.
1276 * @param core_course_list_element $course
1277 * @return string
1279 protected function course_overview_files(core_course_list_element $course): string {
1280 global $CFG;
1282 $contentimages = $contentfiles = '';
1283 foreach ($course->get_course_overviewfiles() as $file) {
1284 $isimage = $file->is_valid_image();
1285 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php",
1286 '/' . $file->get_contextid() . '/' . $file->get_component() . '/' .
1287 $file->get_filearea() . $file->get_filepath() . $file->get_filename(), !$isimage);
1288 if ($isimage) {
1289 $contentimages .= html_writer::tag('div',
1290 html_writer::empty_tag('img', ['src' => $url]),
1291 ['class' => 'courseimage']);
1292 } else {
1293 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1294 $filename = html_writer::tag('span', $image, ['class' => 'fp-icon']).
1295 html_writer::tag('span', $file->get_filename(), ['class' => 'fp-filename']);
1296 $contentfiles .= html_writer::tag('span',
1297 html_writer::link($url, $filename),
1298 ['class' => 'coursefile fp-filename-icon']);
1301 return $contentimages . $contentfiles;
1305 * Returns HTML to display course category name.
1307 * @param coursecat_helper $chelper
1308 * @param core_course_list_element $course
1309 * @return string
1311 protected function course_category_name(coursecat_helper $chelper, core_course_list_element $course): string {
1312 $content = '';
1313 // Display course category if necessary (for example in search results).
1314 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1315 if ($cat = core_course_category::get($course->category, IGNORE_MISSING)) {
1316 $content .= html_writer::start_tag('div', ['class' => 'coursecat']);
1317 $content .= get_string('category').': '.
1318 html_writer::link(new moodle_url('/course/index.php', ['categoryid' => $cat->id]),
1319 $cat->get_formatted_name(), ['class' => $cat->visible ? '' : 'dimmed']);
1320 $content .= html_writer::end_tag('div');
1323 return $content;
1327 * Returns HTML to display course custom fields.
1329 * @param core_course_list_element $course
1330 * @return string
1332 protected function course_custom_fields(core_course_list_element $course): string {
1333 $content = '';
1334 if ($course->has_custom_fields()) {
1335 $handler = core_course\customfield\course_handler::create();
1336 $customfields = $handler->display_custom_fields_data($course->get_custom_fields());
1337 $content .= \html_writer::tag('div', $customfields, ['class' => 'customfields-container']);
1339 return $content;
1343 * Returns HTML to display course content (summary, course contacts and optionally category name)
1345 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1347 * @param coursecat_helper $chelper various display options
1348 * @param stdClass|core_course_list_element $course
1349 * @return string
1351 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1352 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1353 return '';
1355 if ($course instanceof stdClass) {
1356 $course = new core_course_list_element($course);
1358 $content = $this->course_summary($chelper, $course);
1359 $content .= $this->course_overview_files($course);
1360 $content .= $this->course_contacts($course);
1361 $content .= $this->course_category_name($chelper, $course);
1362 $content .= $this->course_custom_fields($course);
1363 return $content;
1367 * Renders the list of courses
1369 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1370 * method from outside of the class
1372 * If list of courses is specified in $courses; the argument $chelper is only used
1373 * to retrieve display options and attributes, only methods get_show_courses(),
1374 * get_courses_display_option() and get_and_erase_attributes() are called.
1376 * @param coursecat_helper $chelper various display options
1377 * @param array $courses the list of courses to display
1378 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1379 * defaulted to count($courses)
1380 * @return string
1382 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1383 global $CFG;
1384 if ($totalcount === null) {
1385 $totalcount = count($courses);
1387 if (!$totalcount) {
1388 // Courses count is cached during courses retrieval.
1389 return '';
1392 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1393 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1394 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1395 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1396 } else {
1397 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1401 // prepare content of paging bar if it is needed
1402 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1403 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1404 if ($totalcount > count($courses)) {
1405 // there are more results that can fit on one page
1406 if ($paginationurl) {
1407 // the option paginationurl was specified, display pagingbar
1408 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1409 $page = $chelper->get_courses_display_option('offset') / $perpage;
1410 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1411 $paginationurl->out(false, array('perpage' => $perpage)));
1412 if ($paginationallowall) {
1413 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1414 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1416 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1417 // the option for 'View more' link was specified, display more link
1418 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1419 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1420 array('class' => 'paging paging-morelink'));
1422 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1423 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1424 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1425 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1428 // display list of courses
1429 $attributes = $chelper->get_and_erase_attributes('courses');
1430 $content = html_writer::start_tag('div', $attributes);
1432 if (!empty($pagingbar)) {
1433 $content .= $pagingbar;
1436 $coursecount = 0;
1437 foreach ($courses as $course) {
1438 $coursecount ++;
1439 $classes = ($coursecount%2) ? 'odd' : 'even';
1440 if ($coursecount == 1) {
1441 $classes .= ' first';
1443 if ($coursecount >= count($courses)) {
1444 $classes .= ' last';
1446 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1449 if (!empty($pagingbar)) {
1450 $content .= $pagingbar;
1452 if (!empty($morelink)) {
1453 $content .= $morelink;
1456 $content .= html_writer::end_tag('div'); // .courses
1457 return $content;
1461 * Renders the list of subcategories in a category
1463 * @param coursecat_helper $chelper various display options
1464 * @param core_course_category $coursecat
1465 * @param int $depth depth of the category in the current tree
1466 * @return string
1468 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1469 global $CFG;
1470 $subcategories = array();
1471 if (!$chelper->get_categories_display_option('nodisplay')) {
1472 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1474 $totalcount = $coursecat->get_children_count();
1475 if (!$totalcount) {
1476 // Note that we call core_course_category::get_children_count() AFTER core_course_category::get_children()
1477 // to avoid extra DB requests.
1478 // Categories count is cached during children categories retrieval.
1479 return '';
1482 // prepare content of paging bar or more link if it is needed
1483 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1484 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1485 if ($totalcount > count($subcategories)) {
1486 if ($paginationurl) {
1487 // the option 'paginationurl was specified, display pagingbar
1488 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1489 $page = $chelper->get_categories_display_option('offset') / $perpage;
1490 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1491 $paginationurl->out(false, array('perpage' => $perpage)));
1492 if ($paginationallowall) {
1493 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1494 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1496 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1497 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1498 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1499 $viewmoreurl->param('categoryid', $coursecat->id);
1501 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1502 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1503 array('class' => 'paging paging-morelink'));
1505 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1506 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1507 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1508 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1511 // display list of subcategories
1512 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1514 if (!empty($pagingbar)) {
1515 $content .= $pagingbar;
1518 foreach ($subcategories as $subcategory) {
1519 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1522 if (!empty($pagingbar)) {
1523 $content .= $pagingbar;
1525 if (!empty($morelink)) {
1526 $content .= $morelink;
1529 $content .= html_writer::end_tag('div');
1530 return $content;
1534 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1536 protected function coursecat_include_js() {
1537 if (!$this->page->requires->should_create_one_time_item_now('core_course_categoryexpanderjsinit')) {
1538 return;
1541 // We must only load this module once.
1542 $this->page->requires->yui_module('moodle-course-categoryexpander',
1543 'Y.Moodle.course.categoryexpander.init');
1547 * Returns HTML to display the subcategories and courses in the given category
1549 * This method is re-used by AJAX to expand content of not loaded category
1551 * @param coursecat_helper $chelper various display options
1552 * @param core_course_category $coursecat
1553 * @param int $depth depth of the category in the current tree
1554 * @return string
1556 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1557 $content = '';
1558 // Subcategories
1559 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1561 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1562 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1563 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1564 if ($showcoursesauto && $depth) {
1565 // this is definitely collapsed mode
1566 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1569 // Courses
1570 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1571 $courses = array();
1572 if (!$chelper->get_courses_display_option('nodisplay')) {
1573 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1575 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1576 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1577 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1578 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1581 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1584 if ($showcoursesauto) {
1585 // restore the show_courses back to AUTO
1586 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1589 return $content;
1593 * Returns HTML to display a course category as a part of a tree
1595 * This is an internal function, to display a particular category and all its contents
1596 * use {@link core_course_renderer::course_category()}
1598 * @param coursecat_helper $chelper various display options
1599 * @param core_course_category $coursecat
1600 * @param int $depth depth of this category in the current tree
1601 * @return string
1603 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1604 // open category tag
1605 $classes = array('category');
1606 if (empty($coursecat->visible)) {
1607 $classes[] = 'dimmed_category';
1609 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1610 // do not load content
1611 $categorycontent = '';
1612 $classes[] = 'notloaded';
1613 if ($coursecat->get_children_count() ||
1614 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1615 $classes[] = 'with_children';
1616 $classes[] = 'collapsed';
1618 } else {
1619 // load category content
1620 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1621 $classes[] = 'loaded';
1622 if (!empty($categorycontent)) {
1623 $classes[] = 'with_children';
1624 // Category content loaded with children.
1625 $this->categoryexpandedonload = true;
1629 // Make sure JS file to expand category content is included.
1630 $this->coursecat_include_js();
1632 $content = html_writer::start_tag('div', array(
1633 'class' => join(' ', $classes),
1634 'data-categoryid' => $coursecat->id,
1635 'data-depth' => $depth,
1636 'data-showcourses' => $chelper->get_show_courses(),
1637 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1640 // category name
1641 $categoryname = $coursecat->get_formatted_name();
1642 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1643 array('categoryid' => $coursecat->id)),
1644 $categoryname);
1645 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1646 && ($coursescount = $coursecat->get_courses_count())) {
1647 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1648 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1650 $content .= html_writer::start_tag('div', array('class' => 'info'));
1652 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname aabtn'));
1653 $content .= html_writer::end_tag('div'); // .info
1655 // add category content to the output
1656 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1658 $content .= html_writer::end_tag('div'); // .category
1660 // Return the course category tree HTML
1661 return $content;
1665 * Returns HTML to display a tree of subcategories and courses in the given category
1667 * @param coursecat_helper $chelper various display options
1668 * @param core_course_category $coursecat top category (this category's name and description will NOT be added to the tree)
1669 * @return string
1671 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1672 // Reset the category expanded flag for this course category tree first.
1673 $this->categoryexpandedonload = false;
1674 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1675 if (empty($categorycontent)) {
1676 return '';
1679 // Start content generation
1680 $content = '';
1681 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1682 $content .= html_writer::start_tag('div', $attributes);
1684 if ($coursecat->get_children_count()) {
1685 $classes = array(
1686 'collapseexpand', 'aabtn'
1689 // Check if the category content contains subcategories with children's content loaded.
1690 if ($this->categoryexpandedonload) {
1691 $classes[] = 'collapse-all';
1692 $linkname = get_string('collapseall');
1693 } else {
1694 $linkname = get_string('expandall');
1697 // Only show the collapse/expand if there are children to expand.
1698 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1699 $content .= html_writer::link('#', $linkname, array('class' => implode(' ', $classes)));
1700 $content .= html_writer::end_tag('div');
1701 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1704 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1706 $content .= html_writer::end_tag('div'); // .course_category_tree
1708 return $content;
1712 * Renders HTML to display particular course category - list of it's subcategories and courses
1714 * Invoked from /course/index.php
1716 * @param int|stdClass|core_course_category $category
1718 public function course_category($category) {
1719 global $CFG;
1720 $usertop = core_course_category::user_top();
1721 if (empty($category)) {
1722 $coursecat = $usertop;
1723 } else if (is_object($category) && $category instanceof core_course_category) {
1724 $coursecat = $category;
1725 } else {
1726 $coursecat = core_course_category::get(is_object($category) ? $category->id : $category);
1728 $site = get_site();
1729 $output = '';
1731 if ($coursecat->can_create_course() || $coursecat->has_manage_capability()) {
1732 // Add 'Manage' button if user has permissions to edit this category.
1733 $managebutton = $this->single_button(new moodle_url('/course/management.php',
1734 array('categoryid' => $coursecat->id)), get_string('managecourses'), 'get');
1735 $this->page->set_button($managebutton);
1738 if (core_course_category::is_simple_site()) {
1739 // There is only one category in the system, do not display link to it.
1740 $strfulllistofcourses = get_string('fulllistofcourses');
1741 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1742 } else if (!$coursecat->id || !$coursecat->is_uservisible()) {
1743 $strcategories = get_string('categories');
1744 $this->page->set_title("$site->shortname: $strcategories");
1745 } else {
1746 $strfulllistofcourses = get_string('fulllistofcourses');
1747 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1749 // Print the category selector
1750 $categorieslist = core_course_category::make_categories_list();
1751 if (count($categorieslist) > 1) {
1752 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1753 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1754 core_course_category::make_categories_list(), $coursecat->id, null, 'switchcategory');
1755 $select->set_label(get_string('categories').':');
1756 $output .= $this->render($select);
1757 $output .= html_writer::end_tag('div'); // .categorypicker
1761 // Print current category description
1762 $chelper = new coursecat_helper();
1763 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1764 $output .= $this->box($description, array('class' => 'generalbox info'));
1767 // Prepare parameters for courses and categories lists in the tree
1768 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1769 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1771 $coursedisplayoptions = array();
1772 $catdisplayoptions = array();
1773 $browse = optional_param('browse', null, PARAM_ALPHA);
1774 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1775 $page = optional_param('page', 0, PARAM_INT);
1776 $baseurl = new moodle_url('/course/index.php');
1777 if ($coursecat->id) {
1778 $baseurl->param('categoryid', $coursecat->id);
1780 if ($perpage != $CFG->coursesperpage) {
1781 $baseurl->param('perpage', $perpage);
1783 $coursedisplayoptions['limit'] = $perpage;
1784 $catdisplayoptions['limit'] = $perpage;
1785 if ($browse === 'courses' || !$coursecat->get_children_count()) {
1786 $coursedisplayoptions['offset'] = $page * $perpage;
1787 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1788 $catdisplayoptions['nodisplay'] = true;
1789 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1790 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1791 } else if ($browse === 'categories' || !$coursecat->get_courses_count()) {
1792 $coursedisplayoptions['nodisplay'] = true;
1793 $catdisplayoptions['offset'] = $page * $perpage;
1794 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1795 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1796 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1797 } else {
1798 // we have a category that has both subcategories and courses, display pagination separately
1799 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1800 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1802 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1803 // Add course search form.
1804 $output .= $this->course_search_form();
1806 // Display course category tree.
1807 $output .= $this->coursecat_tree($chelper, $coursecat);
1809 // Add action buttons
1810 $output .= $this->container_start('buttons');
1811 if ($coursecat->is_uservisible()) {
1812 $context = get_category_or_system_context($coursecat->id);
1813 if (has_capability('moodle/course:create', $context)) {
1814 // Print link to create a new course, for the 1st available category.
1815 if ($coursecat->id) {
1816 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1817 } else {
1818 $url = new moodle_url('/course/edit.php',
1819 array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1821 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1823 ob_start();
1824 print_course_request_buttons($context);
1825 $output .= ob_get_contents();
1826 ob_end_clean();
1828 $output .= $this->container_end();
1830 return $output;
1834 * Serves requests to /course/category.ajax.php
1836 * In this renderer implementation it may expand the category content or
1837 * course content.
1839 * @return string
1840 * @throws coding_exception
1842 public function coursecat_ajax() {
1843 global $DB, $CFG;
1845 $type = required_param('type', PARAM_INT);
1847 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1848 // This is a request for a category list of some kind.
1849 $categoryid = required_param('categoryid', PARAM_INT);
1850 $showcourses = required_param('showcourses', PARAM_INT);
1851 $depth = required_param('depth', PARAM_INT);
1853 $category = core_course_category::get($categoryid);
1855 $chelper = new coursecat_helper();
1856 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1857 $coursedisplayoptions = array(
1858 'limit' => $CFG->coursesperpage,
1859 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1861 $catdisplayoptions = array(
1862 'limit' => $CFG->coursesperpage,
1863 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1865 $chelper->set_show_courses($showcourses)->
1866 set_courses_display_options($coursedisplayoptions)->
1867 set_categories_display_options($catdisplayoptions);
1869 return $this->coursecat_category_content($chelper, $category, $depth);
1870 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1871 // This is a request for the course information.
1872 $courseid = required_param('courseid', PARAM_INT);
1874 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1876 $chelper = new coursecat_helper();
1877 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1878 return $this->coursecat_coursebox_content($chelper, $course);
1879 } else {
1880 throw new coding_exception('Invalid request type');
1885 * Renders html to display search result page
1887 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1888 * @return string
1890 public function search_courses($searchcriteria) {
1891 global $CFG;
1892 $content = '';
1893 if (!empty($searchcriteria)) {
1894 // print search results
1896 $displayoptions = array('sort' => array('displayname' => 1));
1897 // take the current page and number of results per page from query
1898 $perpage = optional_param('perpage', 0, PARAM_RAW);
1899 if ($perpage !== 'all') {
1900 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1901 $page = optional_param('page', 0, PARAM_INT);
1902 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1904 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1905 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1906 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1908 $class = 'course-search-result';
1909 foreach ($searchcriteria as $key => $value) {
1910 if (!empty($value)) {
1911 $class .= ' course-search-result-'. $key;
1914 $chelper = new coursecat_helper();
1915 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1916 set_courses_display_options($displayoptions)->
1917 set_search_criteria($searchcriteria)->
1918 set_attributes(array('class' => $class));
1920 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1921 $totalcount = core_course_category::search_courses_count($searchcriteria);
1922 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1924 if (!$totalcount) {
1925 if (!empty($searchcriteria['search'])) {
1926 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1927 } else {
1928 $content .= $this->heading(get_string('novalidcourses'));
1930 } else {
1931 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1932 $content .= $courseslist;
1935 if (!empty($searchcriteria['search'])) {
1936 // print search form only if there was a search by search string, otherwise it is confusing
1937 $content .= $this->box_start('generalbox mdl-align');
1938 $content .= $this->course_search_form($searchcriteria['search']);
1939 $content .= $this->box_end();
1941 } else {
1942 // just print search form
1943 $content .= $this->box_start('generalbox mdl-align');
1944 $content .= $this->course_search_form();
1945 $content .= $this->box_end();
1947 return $content;
1951 * Renders html to print list of courses tagged with particular tag
1953 * @param int $tagid id of the tag
1954 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1955 * are displayed on the page and the per-page limit may be bigger
1956 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1957 * to display items in the same context first
1958 * @param int $ctx context id where to search for records
1959 * @param bool $rec search in subcontexts as well
1960 * @param array $displayoptions
1961 * @return string empty string if no courses are marked with this tag or rendered list of courses
1963 public function tagged_courses($tagid, $exclusivemode = true, $ctx = 0, $rec = true, $displayoptions = null) {
1964 global $CFG;
1965 if (empty($displayoptions)) {
1966 $displayoptions = array();
1968 $showcategories = !core_course_category::is_simple_site();
1969 $displayoptions += array('limit' => $CFG->coursesperpage, 'offset' => 0);
1970 $chelper = new coursecat_helper();
1971 $searchcriteria = array('tagid' => $tagid, 'ctx' => $ctx, 'rec' => $rec);
1972 $chelper->set_show_courses($showcategories ? self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT :
1973 self::COURSECAT_SHOW_COURSES_EXPANDED)->
1974 set_search_criteria($searchcriteria)->
1975 set_courses_display_options($displayoptions)->
1976 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1977 // (we set the same css class as in search results by tagid)
1978 if ($totalcount = core_course_category::search_courses_count($searchcriteria)) {
1979 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1980 if ($exclusivemode) {
1981 return $this->coursecat_courses($chelper, $courses, $totalcount);
1982 } else {
1983 $tagfeed = new core_tag\output\tagfeed();
1984 $img = $this->output->pix_icon('i/course', '');
1985 foreach ($courses as $course) {
1986 $url = course_get_url($course);
1987 $imgwithlink = html_writer::link($url, $img);
1988 $coursename = html_writer::link($url, $course->get_formatted_name());
1989 $details = '';
1990 if ($showcategories && ($cat = core_course_category::get($course->category, IGNORE_MISSING))) {
1991 $details = get_string('category').': '.
1992 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1993 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1995 $tagfeed->add($imgwithlink, $coursename, $details);
1997 return $this->output->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($this->output));
2000 return '';
2004 * Returns HTML to display one remote course
2006 * @param stdClass $course remote course information, contains properties:
2007 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
2008 * @return string
2010 protected function frontpage_remote_course(stdClass $course) {
2011 $url = new moodle_url('/auth/mnet/jump.php', array(
2012 'hostid' => $course->hostid,
2013 'wantsurl' => '/course/view.php?id='. $course->remoteid
2016 $output = '';
2017 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
2018 $output .= html_writer::start_tag('div', array('class' => 'info'));
2019 $output .= html_writer::start_tag('h3', array('class' => 'name'));
2020 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
2021 $output .= html_writer::end_tag('h3'); // .name
2022 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
2023 $output .= html_writer::end_tag('div'); // .info
2024 $output .= html_writer::start_tag('div', array('class' => 'content'));
2025 $output .= html_writer::start_tag('div', array('class' => 'summary'));
2026 $options = new stdClass();
2027 $options->noclean = true;
2028 $options->para = false;
2029 $options->overflowdiv = true;
2030 $output .= format_text($course->summary, $course->summaryformat, $options);
2031 $output .= html_writer::end_tag('div'); // .summary
2032 $addinfo = format_string($course->hostname) . ' : '
2033 . format_string($course->cat_name) . ' : '
2034 . format_string($course->shortname);
2035 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
2036 $output .= html_writer::end_tag('div'); // .content
2037 $output .= html_writer::end_tag('div'); // .coursebox
2038 return $output;
2042 * Returns HTML to display one remote host
2044 * @param array $host host information, contains properties: name, url, count
2045 * @return string
2047 protected function frontpage_remote_host($host) {
2048 $output = '';
2049 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
2050 $output .= html_writer::start_tag('div', array('class' => 'info'));
2051 $output .= html_writer::start_tag('h3', array('class' => 'name'));
2052 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
2053 $output .= html_writer::end_tag('h3'); // .name
2054 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
2055 $output .= html_writer::end_tag('div'); // .info
2056 $output .= html_writer::start_tag('div', array('class' => 'content'));
2057 $output .= html_writer::start_tag('div', array('class' => 'summary'));
2058 $output .= $host['count'] . ' ' . get_string('courses');
2059 $output .= html_writer::end_tag('div'); // .content
2060 $output .= html_writer::end_tag('div'); // .coursebox
2061 return $output;
2065 * Returns HTML to print list of courses user is enrolled to for the frontpage
2067 * Also lists remote courses or remote hosts if MNET authorisation is used
2069 * @return string
2071 public function frontpage_my_courses() {
2072 global $USER, $CFG, $DB;
2074 if (!isloggedin() or isguestuser()) {
2075 return '';
2078 $output = '';
2079 $courses = enrol_get_my_courses('summary, summaryformat');
2080 $rhosts = array();
2081 $rcourses = array();
2082 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2083 $rcourses = get_my_remotecourses($USER->id);
2084 $rhosts = get_my_remotehosts();
2087 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2089 $chelper = new coursecat_helper();
2090 $totalcount = count($courses);
2091 if (count($courses) > $CFG->frontpagecourselimit) {
2092 // There are more enrolled courses than we can display, display link to 'My courses'.
2093 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
2094 $chelper->set_courses_display_options(array(
2095 'viewmoreurl' => new moodle_url('/my/'),
2096 'viewmoretext' => new lang_string('mycourses')
2098 } else if (core_course_category::top()->is_uservisible()) {
2099 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
2100 $chelper->set_courses_display_options(array(
2101 'viewmoreurl' => new moodle_url('/course/index.php'),
2102 'viewmoretext' => new lang_string('fulllistofcourses')
2104 $totalcount = $DB->count_records('course') - 1;
2106 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2107 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
2108 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
2110 // MNET
2111 if (!empty($rcourses)) {
2112 // at the IDP, we know of all the remote courses
2113 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2114 foreach ($rcourses as $course) {
2115 $output .= $this->frontpage_remote_course($course);
2117 $output .= html_writer::end_tag('div'); // .courses
2118 } elseif (!empty($rhosts)) {
2119 // non-IDP, we know of all the remote servers, but not courses
2120 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2121 foreach ($rhosts as $host) {
2122 $output .= $this->frontpage_remote_host($host);
2124 $output .= html_writer::end_tag('div'); // .courses
2127 return $output;
2131 * Returns HTML to print list of available courses for the frontpage
2133 * @return string
2135 public function frontpage_available_courses() {
2136 global $CFG;
2138 $chelper = new coursecat_helper();
2139 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2140 set_courses_display_options(array(
2141 'recursive' => true,
2142 'limit' => $CFG->frontpagecourselimit,
2143 'viewmoreurl' => new moodle_url('/course/index.php'),
2144 'viewmoretext' => new lang_string('fulllistofcourses')));
2146 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
2147 $courses = core_course_category::top()->get_courses($chelper->get_courses_display_options());
2148 $totalcount = core_course_category::top()->get_courses_count($chelper->get_courses_display_options());
2149 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
2150 // Print link to create a new course, for the 1st available category.
2151 return $this->add_new_course_button();
2153 return $this->coursecat_courses($chelper, $courses, $totalcount);
2157 * Returns HTML to the "add new course" button for the page
2159 * @return string
2161 public function add_new_course_button() {
2162 global $CFG;
2163 // Print link to create a new course, for the 1st available category.
2164 $output = $this->container_start('buttons');
2165 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2166 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2167 $output .= $this->container_end('buttons');
2168 return $output;
2172 * Returns HTML to print tree with course categories and courses for the frontpage
2174 * @return string
2176 public function frontpage_combo_list() {
2177 global $CFG;
2178 // TODO MDL-10965 improve.
2179 $tree = core_course_category::top();
2180 if (!$tree->get_children_count()) {
2181 return '';
2183 $chelper = new coursecat_helper();
2184 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2185 set_categories_display_options(array(
2186 'limit' => $CFG->coursesperpage,
2187 'viewmoreurl' => new moodle_url('/course/index.php',
2188 array('browse' => 'categories', 'page' => 1))
2189 ))->
2190 set_courses_display_options(array(
2191 'limit' => $CFG->coursesperpage,
2192 'viewmoreurl' => new moodle_url('/course/index.php',
2193 array('browse' => 'courses', 'page' => 1))
2194 ))->
2195 set_attributes(array('class' => 'frontpage-category-combo'));
2196 return $this->coursecat_tree($chelper, $tree);
2200 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2202 * @return string
2204 public function frontpage_categories_list() {
2205 global $CFG;
2206 // TODO MDL-10965 improve.
2207 $tree = core_course_category::top();
2208 if (!$tree->get_children_count()) {
2209 return '';
2211 $chelper = new coursecat_helper();
2212 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2213 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2214 set_categories_display_options(array(
2215 'limit' => $CFG->coursesperpage,
2216 'viewmoreurl' => new moodle_url('/course/index.php',
2217 array('browse' => 'categories', 'page' => 1))
2218 ))->
2219 set_attributes(array('class' => 'frontpage-category-names'));
2220 return $this->coursecat_tree($chelper, $tree);
2224 * Renders the activity navigation.
2226 * Defer to template.
2228 * @param \core_course\output\activity_navigation $page
2229 * @return string html for the page
2231 public function render_activity_navigation(\core_course\output\activity_navigation $page) {
2232 $data = $page->export_for_template($this->output);
2233 return $this->output->render_from_template('core_course/activity_navigation', $data);
2237 * Display waiting information about backup size during uploading backup process
2238 * @param object $backupfile the backup stored_file
2239 * @return $html string
2241 public function sendingbackupinfo($backupfile) {
2242 $sizeinfo = new stdClass();
2243 $sizeinfo->total = number_format($backupfile->get_filesize() / 1000000, 2);
2244 $html = html_writer::tag('div', get_string('sendingsize', 'hub', $sizeinfo),
2245 array('class' => 'courseuploadtextinfo'));
2246 return $html;
2250 * Hub information (logo - name - description - link)
2251 * @param object $hubinfo
2252 * @return string html code
2254 public function hubinfo($hubinfo) {
2255 $screenshothtml = html_writer::empty_tag('img',
2256 array('src' => $hubinfo['imgurl'], 'alt' => $hubinfo['name']));
2257 $hubdescription = html_writer::tag('div', $screenshothtml,
2258 array('class' => 'hubscreenshot'));
2260 $hubdescription .= html_writer::tag('a', $hubinfo['name'],
2261 array('class' => 'hublink', 'href' => $hubinfo['url'],
2262 'onclick' => 'this.target="_blank"'));
2264 $hubdescription .= html_writer::tag('div', format_text($hubinfo['description'], FORMAT_PLAIN),
2265 array('class' => 'hubdescription'));
2266 $hubdescription = html_writer::tag('div', $hubdescription, array('class' => 'hubinfo clearfix'));
2268 return $hubdescription;
2272 * Output frontpage summary text and frontpage modules (stored as section 1 in site course)
2274 * This may be disabled in settings
2276 * @return string
2278 public function frontpage_section1() {
2279 global $SITE, $USER;
2281 $output = '';
2282 $editing = $this->page->user_is_editing();
2284 if ($editing) {
2285 // Make sure section with number 1 exists.
2286 course_create_sections_if_missing($SITE, 1);
2289 $modinfo = get_fast_modinfo($SITE);
2290 $section = $modinfo->get_section_info(1);
2291 if (($section && (!empty($modinfo->sections[1]) or !empty($section->summary))) or $editing) {
2292 $output .= $this->box_start('generalbox sitetopic');
2294 // If currently moving a file then show the current clipboard.
2295 if (ismoving($SITE->id)) {
2296 $stractivityclipboard = strip_tags(get_string('activityclipboard', '', $USER->activitycopyname));
2297 $output .= '<p><font size="2">';
2298 $cancelcopyurl = new moodle_url('/course/mod.php', ['cancelcopy' => 'true', 'sesskey' => sesskey()]);
2299 $output .= "$stractivityclipboard&nbsp;&nbsp;(" . html_writer::link($cancelcopyurl, get_string('cancel')) .')';
2300 $output .= '</font></p>';
2303 $context = context_course::instance(SITEID);
2305 // If the section name is set we show it.
2306 if (trim($section->name) !== '') {
2307 $output .= $this->heading(
2308 format_string($section->name, true, array('context' => $context)),
2310 'sectionname'
2314 $summarytext = file_rewrite_pluginfile_urls($section->summary,
2315 'pluginfile.php',
2316 $context->id,
2317 'course',
2318 'section',
2319 $section->id);
2320 $summaryformatoptions = new stdClass();
2321 $summaryformatoptions->noclean = true;
2322 $summaryformatoptions->overflowdiv = true;
2324 $output .= format_text($summarytext, $section->summaryformat, $summaryformatoptions);
2326 if ($editing && has_capability('moodle/course:update', $context)) {
2327 $streditsummary = get_string('editsummary');
2328 $editsectionurl = new moodle_url('/course/editsection.php', ['id' => $section->id]);
2329 $attributes = ['title' => $streditsummary, 'aria-label' => $streditsummary];
2330 $output .= html_writer::link($editsectionurl, $this->pix_icon('t/edit', ''), $attributes) .
2331 "<br /><br />";
2334 $output .= $this->course_section_cm_list($SITE, $section);
2336 $output .= $this->course_section_add_cm_control($SITE, $section->section);
2337 $output .= $this->box_end();
2340 return $output;
2344 * Output news for the frontpage (extract from site-wide news forum)
2346 * @param stdClass $forum record from db table 'forum' that represents the site news forum
2347 * @return string
2349 protected function frontpage_news($forum) {
2350 global $CFG, $SITE, $SESSION, $USER;
2351 require_once($CFG->dirroot .'/mod/forum/lib.php');
2353 $output = '';
2355 if (isloggedin()) {
2356 $SESSION->fromdiscussion = $CFG->wwwroot;
2357 $subtext = '';
2358 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forum)) {
2359 if (!\mod_forum\subscriptions::is_forcesubscribed($forum)) {
2360 $subtext = get_string('unsubscribe', 'forum');
2362 } else {
2363 $subtext = get_string('subscribe', 'forum');
2365 $suburl = new moodle_url('/mod/forum/subscribe.php', array('id' => $forum->id, 'sesskey' => sesskey()));
2366 $output .= html_writer::tag('div', html_writer::link($suburl, $subtext), array('class' => 'subscribelink'));
2369 $coursemodule = get_coursemodule_from_instance('forum', $forum->id);
2370 $context = context_module::instance($coursemodule->id);
2372 $entityfactory = mod_forum\local\container::get_entity_factory();
2373 $forumentity = $entityfactory->get_forum_from_stdclass($forum, $context, $coursemodule, $SITE);
2375 $rendererfactory = mod_forum\local\container::get_renderer_factory();
2376 $discussionsrenderer = $rendererfactory->get_frontpage_news_discussion_list_renderer($forumentity);
2377 $cm = \cm_info::create($coursemodule);
2378 return $output . $discussionsrenderer->render($USER, $cm, null, null, 0, $SITE->newsitems);
2382 * Renders part of frontpage with a skip link (i.e. "My courses", "Site news", etc.)
2384 * @param string $skipdivid
2385 * @param string $contentsdivid
2386 * @param string $header Header of the part
2387 * @param string $contents Contents of the part
2388 * @return string
2390 protected function frontpage_part($skipdivid, $contentsdivid, $header, $contents) {
2391 if (strval($contents) === '') {
2392 return '';
2394 $output = html_writer::link('#' . $skipdivid,
2395 get_string('skipa', 'access', core_text::strtolower(strip_tags($header))),
2396 array('class' => 'skip-block skip aabtn'));
2398 // Wrap frontpage part in div container.
2399 $output .= html_writer::start_tag('div', array('id' => $contentsdivid));
2400 $output .= $this->heading($header);
2402 $output .= $contents;
2404 // End frontpage part div container.
2405 $output .= html_writer::end_tag('div');
2407 $output .= html_writer::tag('span', '', array('class' => 'skip-block-to', 'id' => $skipdivid));
2408 return $output;
2412 * Outputs contents for frontpage as configured in $CFG->frontpage or $CFG->frontpageloggedin
2414 * @return string
2416 public function frontpage() {
2417 global $CFG, $SITE;
2419 $output = '';
2421 if (isloggedin() and !isguestuser() and isset($CFG->frontpageloggedin)) {
2422 $frontpagelayout = $CFG->frontpageloggedin;
2423 } else {
2424 $frontpagelayout = $CFG->frontpage;
2427 foreach (explode(',', $frontpagelayout) as $v) {
2428 switch ($v) {
2429 // Display the main part of the front page.
2430 case FRONTPAGENEWS:
2431 if ($SITE->newsitems) {
2432 // Print forums only when needed.
2433 require_once($CFG->dirroot .'/mod/forum/lib.php');
2434 if (($newsforum = forum_get_course_forum($SITE->id, 'news')) &&
2435 ($forumcontents = $this->frontpage_news($newsforum))) {
2436 $newsforumcm = get_fast_modinfo($SITE)->instances['forum'][$newsforum->id];
2437 $output .= $this->frontpage_part('skipsitenews', 'site-news-forum',
2438 $newsforumcm->get_formatted_name(), $forumcontents);
2441 break;
2443 case FRONTPAGEENROLLEDCOURSELIST:
2444 $mycourseshtml = $this->frontpage_my_courses();
2445 if (!empty($mycourseshtml)) {
2446 $output .= $this->frontpage_part('skipmycourses', 'frontpage-course-list',
2447 get_string('mycourses'), $mycourseshtml);
2449 break;
2451 case FRONTPAGEALLCOURSELIST:
2452 $availablecourseshtml = $this->frontpage_available_courses();
2453 $output .= $this->frontpage_part('skipavailablecourses', 'frontpage-available-course-list',
2454 get_string('availablecourses'), $availablecourseshtml);
2455 break;
2457 case FRONTPAGECATEGORYNAMES:
2458 $output .= $this->frontpage_part('skipcategories', 'frontpage-category-names',
2459 get_string('categories'), $this->frontpage_categories_list());
2460 break;
2462 case FRONTPAGECATEGORYCOMBO:
2463 $output .= $this->frontpage_part('skipcourses', 'frontpage-category-combo',
2464 get_string('courses'), $this->frontpage_combo_list());
2465 break;
2467 case FRONTPAGECOURSESEARCH:
2468 $output .= $this->box($this->course_search_form('', 'short'), 'mdl-align');
2469 break;
2472 $output .= '<br />';
2475 return $output;
2480 * Class storing display options and functions to help display course category and/or courses lists
2482 * This is a wrapper for core_course_category objects that also stores display options
2483 * and functions to retrieve sorted and paginated lists of categories/courses.
2485 * If theme overrides methods in core_course_renderers that access this class
2486 * it may as well not use this class at all or extend it.
2488 * @package core
2489 * @copyright 2013 Marina Glancy
2490 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2492 class coursecat_helper {
2493 /** @var string [none, collapsed, expanded] how (if) display courses list */
2494 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2495 /** @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) */
2496 protected $subcatdepth = 1;
2497 /** @var array options to display courses list */
2498 protected $coursesdisplayoptions = array();
2499 /** @var array options to display subcategories list */
2500 protected $categoriesdisplayoptions = array();
2501 /** @var array additional HTML attributes */
2502 protected $attributes = array();
2503 /** @var array search criteria if the list is a search result */
2504 protected $searchcriteria = null;
2507 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2509 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2510 * @return coursecat_helper
2512 public function set_show_courses($showcourses) {
2513 $this->showcourses = $showcourses;
2514 // Automatically set the options to preload summary and coursecontacts for core_course_category::get_courses()
2515 // and core_course_category::search_courses().
2516 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2517 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2518 $this->coursesdisplayoptions['customfields'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED;
2519 return $this;
2523 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2525 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2527 public function get_show_courses() {
2528 return $this->showcourses;
2532 * Sets the maximum depth to expand subcategories in the tree
2534 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2536 * @param int $subcatdepth
2537 * @return coursecat_helper
2539 public function set_subcat_depth($subcatdepth) {
2540 $this->subcatdepth = $subcatdepth;
2541 return $this;
2545 * Returns the maximum depth to expand subcategories in the tree
2547 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2549 * @return int
2551 public function get_subcat_depth() {
2552 return $this->subcatdepth;
2556 * Sets options to display list of courses
2558 * Options are later submitted as argument to core_course_category::get_courses() and/or core_course_category::search_courses()
2560 * Options that core_course_category::get_courses() accept:
2561 * - recursive - return courses from subcategories as well. Use with care,
2562 * this may be a huge list!
2563 * - summary - preloads fields 'summary' and 'summaryformat'
2564 * - coursecontacts - preloads course contacts
2565 * - customfields - preloads custom fields data
2566 * - isenrolled - preloads indication whether this user is enrolled in the course
2567 * - sort - list of fields to sort. Example
2568 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2569 * will sort by idnumber asc, shortname asc and id desc.
2570 * Default: array('sortorder' => 1)
2571 * Only cached fields may be used for sorting!
2572 * - offset
2573 * - limit - maximum number of children to return, 0 or null for no limit
2575 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2577 * Also renderer can set here any additional options it wants to pass between renderer functions.
2579 * @param array $options
2580 * @return coursecat_helper
2582 public function set_courses_display_options($options) {
2583 $this->coursesdisplayoptions = $options;
2584 $this->set_show_courses($this->showcourses); // this will calculate special display options
2585 return $this;
2589 * Sets one option to display list of courses
2591 * @see coursecat_helper::set_courses_display_options()
2593 * @param string $key
2594 * @param mixed $value
2595 * @return coursecat_helper
2597 public function set_courses_display_option($key, $value) {
2598 $this->coursesdisplayoptions[$key] = $value;
2599 return $this;
2603 * Return the specified option to display list of courses
2605 * @param string $optionname option name
2606 * @param mixed $defaultvalue default value for option if it is not specified
2607 * @return mixed
2609 public function get_courses_display_option($optionname, $defaultvalue = null) {
2610 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2611 return $this->coursesdisplayoptions[$optionname];
2612 } else {
2613 return $defaultvalue;
2618 * Returns all options to display the courses
2620 * This array is usually passed to {@link core_course_category::get_courses()} or
2621 * {@link core_course_category::search_courses()}
2623 * @return array
2625 public function get_courses_display_options() {
2626 return $this->coursesdisplayoptions;
2630 * Sets options to display list of subcategories
2632 * Options 'sort', 'offset' and 'limit' are passed to core_course_category::get_children().
2633 * Any other options may be used by renderer functions
2635 * @param array $options
2636 * @return coursecat_helper
2638 public function set_categories_display_options($options) {
2639 $this->categoriesdisplayoptions = $options;
2640 return $this;
2644 * Return the specified option to display list of subcategories
2646 * @param string $optionname option name
2647 * @param mixed $defaultvalue default value for option if it is not specified
2648 * @return mixed
2650 public function get_categories_display_option($optionname, $defaultvalue = null) {
2651 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2652 return $this->categoriesdisplayoptions[$optionname];
2653 } else {
2654 return $defaultvalue;
2659 * Returns all options to display list of subcategories
2661 * This array is usually passed to {@link core_course_category::get_children()}
2663 * @return array
2665 public function get_categories_display_options() {
2666 return $this->categoriesdisplayoptions;
2670 * Sets additional general options to pass between renderer functions, usually HTML attributes
2672 * @param array $attributes
2673 * @return coursecat_helper
2675 public function set_attributes($attributes) {
2676 $this->attributes = $attributes;
2677 return $this;
2681 * Return all attributes and erases them so they are not applied again
2683 * @param string $classname adds additional class name to the beginning of $attributes['class']
2684 * @return array
2686 public function get_and_erase_attributes($classname) {
2687 $attributes = $this->attributes;
2688 $this->attributes = array();
2689 if (empty($attributes['class'])) {
2690 $attributes['class'] = '';
2692 $attributes['class'] = $classname . ' '. $attributes['class'];
2693 return $attributes;
2697 * Sets the search criteria if the course is a search result
2699 * Search string will be used to highlight terms in course name and description
2701 * @param array $searchcriteria
2702 * @return coursecat_helper
2704 public function set_search_criteria($searchcriteria) {
2705 $this->searchcriteria = $searchcriteria;
2706 return $this;
2710 * Returns formatted and filtered description of the given category
2712 * @param core_course_category $coursecat category
2713 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2714 * if context is not specified it will be added automatically
2715 * @return string|null
2717 public function get_category_formatted_description($coursecat, $options = null) {
2718 if ($coursecat->id && $coursecat->is_uservisible() && !empty($coursecat->description)) {
2719 if (!isset($coursecat->descriptionformat)) {
2720 $descriptionformat = FORMAT_MOODLE;
2721 } else {
2722 $descriptionformat = $coursecat->descriptionformat;
2724 if ($options === null) {
2725 $options = array('noclean' => true, 'overflowdiv' => true);
2726 } else {
2727 $options = (array)$options;
2729 $context = context_coursecat::instance($coursecat->id);
2730 if (!isset($options['context'])) {
2731 $options['context'] = $context;
2733 $text = file_rewrite_pluginfile_urls($coursecat->description,
2734 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2735 return format_text($text, $descriptionformat, $options);
2737 return null;
2741 * Returns given course's summary with proper embedded files urls and formatted
2743 * @param core_course_list_element $course
2744 * @param array|stdClass $options additional formatting options
2745 * @return string
2747 public function get_course_formatted_summary($course, $options = array()) {
2748 global $CFG;
2749 require_once($CFG->libdir. '/filelib.php');
2750 if (!$course->has_summary()) {
2751 return '';
2753 $options = (array)$options;
2754 $context = context_course::instance($course->id);
2755 if (!isset($options['context'])) {
2756 // TODO see MDL-38521
2757 // option 1 (current), page context - no code required
2758 // option 2, system context
2759 // $options['context'] = context_system::instance();
2760 // option 3, course context:
2761 // $options['context'] = $context;
2762 // option 4, course category context:
2763 // $options['context'] = $context->get_parent_context();
2765 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2766 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2767 if (!empty($this->searchcriteria['search'])) {
2768 $summary = highlight($this->searchcriteria['search'], $summary);
2770 return $summary;
2774 * Returns course name as it is configured to appear in courses lists formatted to course context
2776 * @param core_course_list_element $course
2777 * @param array|stdClass $options additional formatting options
2778 * @return string
2780 public function get_course_formatted_name($course, $options = array()) {
2781 $options = (array)$options;
2782 if (!isset($options['context'])) {
2783 $options['context'] = context_course::instance($course->id);
2785 $name = format_string(get_course_display_name_for_list($course), true, $options);
2786 if (!empty($this->searchcriteria['search'])) {
2787 $name = highlight($this->searchcriteria['search'], $name);
2789 return $name;