Merge branch 'MDL-68854-master' of git://github.com/vmdef/moodle
[moodle.git] / course / renderer.php
blobbb7b3b9867e45d541d3b809911a99f98231a7421
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,
381 $ajaxcontrol .= html_writer::end_tag('div');
382 $ajaxcontrol .= html_writer::end_tag('div');
384 // Load the JS for the modal.
385 $this->course_activitychooser($course->id);
388 // Behat only: If both controls are being included in the HTML,
389 // show the link by default and only fall back to the selects if js is disabled.
390 if ($behatsite && $renderajaxcontrol) {
391 $nonajaxcontrol = html_writer::tag('div', $nonajaxcontrol, array('class' => 'hiddenifjs addresourcedropdown'));
392 $ajaxcontrol = html_writer::tag('div', $ajaxcontrol, array('class' => 'visibleifjs addresourcemodchooser'));
395 // If behat is running, we should have the non-ajax control + the ajax control.
396 // Otherwise, we'll have one or the other.
397 return $ajaxcontrol . $nonajaxcontrol;
401 * Renders html to display a course search form.
403 * @param string $value default value to populate the search field
404 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
405 * @return string
407 public function course_search_form($value = '', $format = 'plain') {
408 static $count = 0;
409 $formid = 'coursesearch';
410 if ((++$count) > 1) {
411 $formid .= $count;
414 switch ($format) {
415 case 'navbar' :
416 $formid = 'coursesearchnavbar';
417 $inputid = 'navsearchbox';
418 $inputsize = 20;
419 break;
420 case 'short' :
421 $inputid = 'shortsearchbox';
422 $inputsize = 12;
423 break;
424 default :
425 $inputid = 'coursesearchbox';
426 $inputsize = 30;
429 $data = new stdClass();
430 $data->searchurl = \core_search\manager::get_course_search_url()->out(false);
431 $data->id = $formid;
432 $data->inputid = $inputid;
433 $data->inputsize = $inputsize;
434 $data->value = $value;
435 $data->areaids = 'core_course-course';
437 if ($format != 'navbar') {
438 $helpicon = new \help_icon('coursesearch', 'core');
439 $data->helpicon = $helpicon->export_for_template($this);
442 return $this->render_from_template('core_course/course_search_form', $data);
446 * Renders html for completion box on course page
448 * If completion is disabled, returns empty string
449 * If completion is automatic, returns an icon of the current completion state
450 * If completion is manual, returns a form (with an icon inside) that allows user to
451 * toggle completion
453 * @param stdClass $course course object
454 * @param completion_info $completioninfo completion info for the course, it is recommended
455 * to fetch once for all modules in course/section for performance
456 * @param cm_info $mod module to show completion for
457 * @param array $displayoptions display options, not used in core
458 * @return string
460 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
461 global $CFG, $DB, $USER;
462 $output = '';
464 $istrackeduser = $completioninfo->is_tracked_user($USER->id);
465 $isediting = $this->page->user_is_editing();
467 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
468 return $output;
470 if ($completioninfo === null) {
471 $completioninfo = new completion_info($course);
473 $completion = $completioninfo->is_enabled($mod);
475 if ($completion == COMPLETION_TRACKING_NONE) {
476 if ($isediting) {
477 $output .= html_writer::span('&nbsp;', 'filler');
479 return $output;
482 $completionicon = '';
484 if ($isediting || !$istrackeduser) {
485 switch ($completion) {
486 case COMPLETION_TRACKING_MANUAL :
487 $completionicon = 'manual-enabled'; break;
488 case COMPLETION_TRACKING_AUTOMATIC :
489 $completionicon = 'auto-enabled'; break;
491 } else {
492 $completiondata = $completioninfo->get_data($mod, true);
493 if ($completion == COMPLETION_TRACKING_MANUAL) {
494 switch($completiondata->completionstate) {
495 case COMPLETION_INCOMPLETE:
496 $completionicon = 'manual-n' . ($completiondata->overrideby ? '-override' : '');
497 break;
498 case COMPLETION_COMPLETE:
499 $completionicon = 'manual-y' . ($completiondata->overrideby ? '-override' : '');
500 break;
502 } else { // Automatic
503 switch($completiondata->completionstate) {
504 case COMPLETION_INCOMPLETE:
505 $completionicon = 'auto-n' . ($completiondata->overrideby ? '-override' : '');
506 break;
507 case COMPLETION_COMPLETE:
508 $completionicon = 'auto-y' . ($completiondata->overrideby ? '-override' : '');
509 break;
510 case COMPLETION_COMPLETE_PASS:
511 $completionicon = 'auto-pass'; break;
512 case COMPLETION_COMPLETE_FAIL:
513 $completionicon = 'auto-fail'; break;
517 if ($completionicon) {
518 $formattedname = html_entity_decode($mod->get_formatted_name(), ENT_QUOTES, 'UTF-8');
519 if (!$isediting && $istrackeduser && $completiondata->overrideby) {
520 $args = new stdClass();
521 $args->modname = $formattedname;
522 $overridebyuser = \core_user::get_user($completiondata->overrideby, '*', MUST_EXIST);
523 $args->overrideuser = fullname($overridebyuser);
524 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $args);
525 } else {
526 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
529 if ($isediting || !$istrackeduser || !has_capability('moodle/course:togglecompletion', $mod->context)) {
530 // When editing, the icon is just an image.
531 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
532 array('title' => $imgalt, 'class' => 'iconsmall'));
533 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
534 array('class' => 'autocompletion'));
535 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
536 $newstate =
537 $completiondata->completionstate == COMPLETION_COMPLETE
538 ? COMPLETION_INCOMPLETE
539 : COMPLETION_COMPLETE;
540 // In manual mode the icon is a toggle form...
542 // If this completion state is used by the
543 // conditional activities system, we need to turn
544 // off the JS.
545 $extraclass = '';
546 if (!empty($CFG->enableavailability) &&
547 core_availability\info::completion_value_used($course, $mod->id)) {
548 $extraclass = ' preventjs';
550 $output .= html_writer::start_tag('form', array('method' => 'post',
551 'action' => new moodle_url('/course/togglecompletion.php'),
552 'class' => 'togglecompletion'. $extraclass));
553 $output .= html_writer::start_tag('div');
554 $output .= html_writer::empty_tag('input', array(
555 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
556 $output .= html_writer::empty_tag('input', array(
557 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
558 $output .= html_writer::empty_tag('input', array(
559 'type' => 'hidden', 'name' => 'modulename', 'value' => $formattedname));
560 $output .= html_writer::empty_tag('input', array(
561 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
562 $output .= html_writer::tag('button',
563 $this->output->pix_icon('i/completion-' . $completionicon, $imgalt),
564 array('class' => 'btn btn-link', 'aria-live' => 'assertive'));
565 $output .= html_writer::end_tag('div');
566 $output .= html_writer::end_tag('form');
567 } else {
568 // In auto mode, the icon is just an image.
569 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
570 array('title' => $imgalt));
571 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
572 array('class' => 'autocompletion'));
575 return $output;
579 * Checks if course module has any conditions that may make it unavailable for
580 * all or some of the students
582 * This function is internal and is only used to create CSS classes for the module name/text
584 * @param cm_info $mod
585 * @return bool
587 protected function is_cm_conditionally_hidden(cm_info $mod) {
588 global $CFG;
589 $conditionalhidden = false;
590 if (!empty($CFG->enableavailability)) {
591 $info = new \core_availability\info_module($mod);
592 $conditionalhidden = !$info->is_available_for_all();
594 return $conditionalhidden;
598 * Renders html to display a name with the link to the course module on a course page
600 * If module is unavailable for user but still needs to be displayed
601 * in the list, just the name is returned without a link
603 * Note, that for course modules that never have separate pages (i.e. labels)
604 * this function return an empty string
606 * @param cm_info $mod
607 * @param array $displayoptions
608 * @return string
610 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
611 if (!$mod->is_visible_on_course_page() || !$mod->url) {
612 // Nothing to be displayed to the user.
613 return '';
616 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
617 $groupinglabel = $mod->get_grouping_label($textclasses);
619 // Render element that allows to edit activity name inline. It calls {@link course_section_cm_name_title()}
620 // to get the display title of the activity.
621 $tmpl = new \core_course\output\course_module_name($mod, $this->page->user_is_editing(), $displayoptions);
622 return $this->output->render_from_template('core/inplace_editable', $tmpl->export_for_template($this->output)) .
623 $groupinglabel;
627 * Returns the CSS classes for the activity name/content
629 * For items which are hidden, unavailable or stealth but should be displayed
630 * to current user ($mod->is_visible_on_course_page()), we show those as dimmed.
631 * Students will also see as dimmed activities names that are not yet available
632 * but should still be displayed (without link) with availability info.
634 * @param cm_info $mod
635 * @return array array of two elements ($linkclasses, $textclasses)
637 protected function course_section_cm_classes(cm_info $mod) {
638 $linkclasses = '';
639 $textclasses = '';
640 if ($mod->uservisible) {
641 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
642 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
643 has_capability('moodle/course:viewhiddenactivities', $mod->context);
644 if ($accessiblebutdim) {
645 $linkclasses .= ' dimmed';
646 $textclasses .= ' dimmed_text';
647 if ($conditionalhidden) {
648 $linkclasses .= ' conditionalhidden';
649 $textclasses .= ' conditionalhidden';
652 if ($mod->is_stealth()) {
653 // Stealth activity is the one that is not visible on course page.
654 // It still may be displayed to the users who can manage it.
655 $linkclasses .= ' stealth';
656 $textclasses .= ' stealth';
658 } else {
659 $linkclasses .= ' dimmed';
660 $textclasses .= ' dimmed dimmed_text';
662 return array($linkclasses, $textclasses);
666 * Renders html to display a name with the link to the course module on a course page
668 * If module is unavailable for user but still needs to be displayed
669 * in the list, just the name is returned without a link
671 * Note, that for course modules that never have separate pages (i.e. labels)
672 * this function return an empty string
674 * @param cm_info $mod
675 * @param array $displayoptions
676 * @return string
678 public function course_section_cm_name_title(cm_info $mod, $displayoptions = array()) {
679 $output = '';
680 $url = $mod->url;
681 if (!$mod->is_visible_on_course_page() || !$url) {
682 // Nothing to be displayed to the user.
683 return $output;
686 //Accessibility: for files get description via icon, this is very ugly hack!
687 $instancename = $mod->get_formatted_name();
688 $altname = $mod->modfullname;
689 // Avoid unnecessary duplication: if e.g. a forum name already
690 // includes the word forum (or Forum, etc) then it is unhelpful
691 // to include that in the accessible description that is added.
692 if (false !== strpos(core_text::strtolower($instancename),
693 core_text::strtolower($altname))) {
694 $altname = '';
696 // File type after name, for alphabetic lists (screen reader).
697 if ($altname) {
698 $altname = get_accesshide(' '.$altname);
701 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
703 // Get on-click attribute value if specified and decode the onclick - it
704 // has already been encoded for display (puke).
705 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
707 // Display link itself.
708 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
709 'class' => 'iconlarge activityicon', 'alt' => '', 'role' => 'presentation', 'aria-hidden' => 'true')) .
710 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
711 if ($mod->uservisible) {
712 $output .= html_writer::link($url, $activitylink, array('class' => 'aalink' . $linkclasses, 'onclick' => $onclick));
713 } else {
714 // We may be displaying this just in order to show information
715 // about visibility, without the actual link ($mod->is_visible_on_course_page()).
716 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses));
718 return $output;
722 * Renders html to display the module content on the course page (i.e. text of the labels)
724 * @param cm_info $mod
725 * @param array $displayoptions
726 * @return string
728 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
729 $output = '';
730 if (!$mod->is_visible_on_course_page()) {
731 // nothing to be displayed to the user
732 return $output;
734 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
735 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
736 if ($mod->url && $mod->uservisible) {
737 if ($content) {
738 // If specified, display extra content after link.
739 $output = html_writer::tag('div', $content, array('class' =>
740 trim('contentafterlink ' . $textclasses)));
742 } else {
743 $groupinglabel = $mod->get_grouping_label($textclasses);
745 // No link, so display only content.
746 $output = html_writer::tag('div', $content . $groupinglabel,
747 array('class' => 'contentwithoutlink ' . $textclasses));
749 return $output;
753 * Displays availability info for a course section or course module
755 * @param string $text
756 * @param string $additionalclasses
757 * @return string
759 public function availability_info($text, $additionalclasses = '') {
761 $data = ['text' => $text, 'classes' => $additionalclasses];
762 $additionalclasses = array_filter(explode(' ', $additionalclasses));
764 if (in_array('ishidden', $additionalclasses)) {
765 $data['ishidden'] = 1;
767 } else if (in_array('isstealth', $additionalclasses)) {
768 $data['isstealth'] = 1;
770 } else if (in_array('isrestricted', $additionalclasses)) {
771 $data['isrestricted'] = 1;
773 if (in_array('isfullinfo', $additionalclasses)) {
774 $data['isfullinfo'] = 1;
778 return $this->render_from_template('core/availability_info', $data);
782 * Renders HTML to show course module availability information (for someone who isn't allowed
783 * to see the activity itself, or for staff)
785 * @param cm_info $mod
786 * @param array $displayoptions
787 * @return string
789 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
790 global $CFG;
791 $output = '';
792 if (!$mod->is_visible_on_course_page()) {
793 return $output;
795 if (!$mod->uservisible) {
796 // this is a student who is not allowed to see the module but might be allowed
797 // to see availability info (i.e. "Available from ...")
798 if (!empty($mod->availableinfo)) {
799 $formattedinfo = \core_availability\info::format_info(
800 $mod->availableinfo, $mod->get_course());
801 $output = $this->availability_info($formattedinfo, 'isrestricted');
803 return $output;
805 // this is a teacher who is allowed to see module but still should see the
806 // information that module is not available to all/some students
807 $modcontext = context_module::instance($mod->id);
808 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
809 if ($canviewhidden && !$mod->visible) {
810 // This module is hidden but current user has capability to see it.
811 // Do not display the availability info if the whole section is hidden.
812 if ($mod->get_section_info()->visible) {
813 $output .= $this->availability_info(get_string('hiddenfromstudents'), 'ishidden');
815 } else if ($mod->is_stealth()) {
816 // This module is available but is normally not displayed on the course page
817 // (this user can see it because they can manage it).
818 $output .= $this->availability_info(get_string('hiddenoncoursepage'), 'isstealth');
820 if ($canviewhidden && !empty($CFG->enableavailability)) {
821 // Display information about conditional availability.
822 // Don't add availability information if user is not editing and activity is hidden.
823 if ($mod->visible || $this->page->user_is_editing()) {
824 $hidinfoclass = 'isrestricted isfullinfo';
825 if (!$mod->visible) {
826 $hidinfoclass .= ' hide';
828 $ci = new \core_availability\info_module($mod);
829 $fullinfo = $ci->get_full_information();
830 if ($fullinfo) {
831 $formattedinfo = \core_availability\info::format_info(
832 $fullinfo, $mod->get_course());
833 $output .= $this->availability_info($formattedinfo, $hidinfoclass);
837 return $output;
841 * Renders HTML to display one course module for display within a section.
843 * This function calls:
844 * {@link core_course_renderer::course_section_cm()}
846 * @param stdClass $course
847 * @param completion_info $completioninfo
848 * @param cm_info $mod
849 * @param int|null $sectionreturn
850 * @param array $displayoptions
851 * @return String
853 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
854 $output = '';
855 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
856 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
857 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
859 return $output;
863 * Renders HTML to display one course module in a course section
865 * This includes link, content, availability, completion info and additional information
866 * that module type wants to display (i.e. number of unread forum posts)
868 * This function calls:
869 * {@link core_course_renderer::course_section_cm_name()}
870 * {@link core_course_renderer::course_section_cm_text()}
871 * {@link core_course_renderer::course_section_cm_availability()}
872 * {@link core_course_renderer::course_section_cm_completion()}
873 * {@link course_get_cm_edit_actions()}
874 * {@link core_course_renderer::course_section_cm_edit_actions()}
876 * @param stdClass $course
877 * @param completion_info $completioninfo
878 * @param cm_info $mod
879 * @param int|null $sectionreturn
880 * @param array $displayoptions
881 * @return string
883 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
884 $output = '';
885 // We return empty string (because course module will not be displayed at all)
886 // if:
887 // 1) The activity is not visible to users
888 // and
889 // 2) The 'availableinfo' is empty, i.e. the activity was
890 // hidden in a way that leaves no info, such as using the
891 // eye icon.
892 if (!$mod->is_visible_on_course_page()) {
893 return $output;
896 $indentclasses = 'mod-indent';
897 if (!empty($mod->indent)) {
898 $indentclasses .= ' mod-indent-'.$mod->indent;
899 if ($mod->indent > 15) {
900 $indentclasses .= ' mod-indent-huge';
904 $output .= html_writer::start_tag('div');
906 if ($this->page->user_is_editing()) {
907 $output .= course_get_cm_move($mod, $sectionreturn);
910 $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer w-100'));
912 // This div is used to indent the content.
913 $output .= html_writer::div('', $indentclasses);
915 // Start a wrapper for the actual content to keep the indentation consistent
916 $output .= html_writer::start_tag('div');
918 // Display the link to the module (or do nothing if module has no url)
919 $cmname = $this->course_section_cm_name($mod, $displayoptions);
921 if (!empty($cmname)) {
922 // Start the div for the activity title, excluding the edit icons.
923 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
924 $output .= $cmname;
927 // Module can put text after the link (e.g. forum unread)
928 $output .= $mod->afterlink;
930 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
931 $output .= html_writer::end_tag('div'); // .activityinstance
934 // If there is content but NO link (eg label), then display the
935 // content here (BEFORE any icons). In this case cons must be
936 // displayed after the content so that it makes more sense visually
937 // and for accessibility reasons, e.g. if you have a one-line label
938 // it should work similarly (at least in terms of ordering) to an
939 // activity.
940 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
941 $url = $mod->url;
942 if (empty($url)) {
943 $output .= $contentpart;
946 $modicons = '';
947 if ($this->page->user_is_editing()) {
948 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
949 $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
950 $modicons .= $mod->afterediticons;
953 $modicons .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
955 if (!empty($modicons)) {
956 $output .= html_writer::div($modicons, 'actions');
959 // Show availability info (if module is not available).
960 $output .= $this->course_section_cm_availability($mod, $displayoptions);
962 // If there is content AND a link, then display the content here
963 // (AFTER any icons). Otherwise it was displayed before
964 if (!empty($url)) {
965 $output .= $contentpart;
968 $output .= html_writer::end_tag('div'); // $indentclasses
970 // End of indentation div.
971 $output .= html_writer::end_tag('div');
973 $output .= html_writer::end_tag('div');
974 return $output;
978 * Message displayed to the user when they try to access unavailable activity following URL
980 * This method is a very simplified version of {@link course_section_cm()} to be part of the error
981 * notification only. It also does not check if module is visible on course page or not.
983 * The message will be displayed inside notification!
985 * @param cm_info $cm
986 * @return string
988 public function course_section_cm_unavailable_error_message(cm_info $cm) {
989 if ($cm->uservisible) {
990 return null;
992 if (!$cm->availableinfo) {
993 return get_string('activityiscurrentlyhidden');
996 $altname = get_accesshide(' ' . $cm->modfullname);
997 $name = html_writer::empty_tag('img', array('src' => $cm->get_icon_url(),
998 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
999 html_writer::tag('span', ' '.$cm->get_formatted_name() . $altname, array('class' => 'instancename'));
1000 $formattedinfo = \core_availability\info::format_info($cm->availableinfo, $cm->get_course());
1001 return html_writer::div($name, 'activityinstance-error') .
1002 html_writer::div($formattedinfo, 'availabilityinfo-error');
1006 * Renders HTML to display a list of course modules in a course section
1007 * Also displays "move here" controls in Javascript-disabled mode
1009 * This function calls {@link core_course_renderer::course_section_cm()}
1011 * @param stdClass $course course object
1012 * @param int|stdClass|section_info $section relative section number or section object
1013 * @param int $sectionreturn section number to return to
1014 * @param int $displayoptions
1015 * @return void
1017 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
1018 global $USER;
1020 $output = '';
1021 $modinfo = get_fast_modinfo($course);
1022 if (is_object($section)) {
1023 $section = $modinfo->get_section_info($section->section);
1024 } else {
1025 $section = $modinfo->get_section_info($section);
1027 $completioninfo = new completion_info($course);
1029 // check if we are currently in the process of moving a module with JavaScript disabled
1030 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
1031 if ($ismoving) {
1032 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
1033 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1036 // Get the list of modules visible to user (excluding the module being moved if there is one)
1037 $moduleshtml = array();
1038 if (!empty($modinfo->sections[$section->section])) {
1039 foreach ($modinfo->sections[$section->section] as $modnumber) {
1040 $mod = $modinfo->cms[$modnumber];
1042 if ($ismoving and $mod->id == $USER->activitycopy) {
1043 // do not display moving mod
1044 continue;
1047 if ($modulehtml = $this->course_section_cm_list_item($course,
1048 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
1049 $moduleshtml[$modnumber] = $modulehtml;
1054 $sectionoutput = '';
1055 if (!empty($moduleshtml) || $ismoving) {
1056 foreach ($moduleshtml as $modnumber => $modulehtml) {
1057 if ($ismoving) {
1058 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
1059 $sectionoutput .= html_writer::tag('li',
1060 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1061 array('class' => 'movehere'));
1064 $sectionoutput .= $modulehtml;
1067 if ($ismoving) {
1068 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1069 $sectionoutput .= html_writer::tag('li',
1070 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1071 array('class' => 'movehere'));
1075 // Always output the section module list.
1076 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1078 return $output;
1082 * Displays a custom list of courses with paging bar if necessary
1084 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1085 * appears under the list.
1087 * If both $paginationurl and $totalcount are specified, and $totalcount is
1088 * bigger than count($courses), a paging bar is displayed above and under the
1089 * courses list.
1091 * @param array $courses array of course records (or instances of core_course_list_element) to show on this page
1092 * @param bool $showcategoryname whether to add category name to the course description
1093 * @param string $additionalclasses additional CSS classes to add to the div.courses
1094 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1095 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1096 * @param int $page current page number (defaults to 0 referring to the first page)
1097 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1098 * @return string
1100 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1101 global $CFG;
1102 // create instance of coursecat_helper to pass display options to function rendering courses list
1103 $chelper = new coursecat_helper();
1104 if ($showcategoryname) {
1105 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1106 } else {
1107 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1109 if ($totalcount !== null && $paginationurl !== null) {
1110 // add options to display pagination
1111 if ($perpage === null) {
1112 $perpage = $CFG->coursesperpage;
1114 $chelper->set_courses_display_options(array(
1115 'limit' => $perpage,
1116 'offset' => ((int)$page) * $perpage,
1117 'paginationurl' => $paginationurl,
1119 } else if ($paginationurl !== null) {
1120 // add options to display 'View more' link
1121 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1122 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1124 $chelper->set_attributes(array('class' => $additionalclasses));
1125 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1126 return $content;
1130 * Returns HTML to display course name.
1132 * @param coursecat_helper $chelper
1133 * @param core_course_list_element $course
1134 * @return string
1136 protected function course_name(coursecat_helper $chelper, core_course_list_element $course): string {
1137 $content = '';
1138 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1139 $nametag = 'h3';
1140 } else {
1141 $nametag = 'div';
1143 $coursename = $chelper->get_course_formatted_name($course);
1144 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', ['id' => $course->id]),
1145 $coursename, ['class' => $course->visible ? 'aalink' : 'aalink dimmed']);
1146 $content .= html_writer::tag($nametag, $coursenamelink, ['class' => 'coursename']);
1147 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1148 $content .= html_writer::start_tag('div', ['class' => 'moreinfo']);
1149 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1150 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()
1151 || $course->has_custom_fields()) {
1152 $url = new moodle_url('/course/info.php', ['id' => $course->id]);
1153 $image = $this->output->pix_icon('i/info', $this->strings->summary);
1154 $content .= html_writer::link($url, $image, ['title' => $this->strings->summary]);
1155 // Make sure JS file to expand course content is included.
1156 $this->coursecat_include_js();
1159 $content .= html_writer::end_tag('div');
1160 return $content;
1164 * Returns HTML to display course enrolment icons.
1166 * @param core_course_list_element $course
1167 * @return string
1169 protected function course_enrolment_icons(core_course_list_element $course): string {
1170 $content = '';
1171 if ($icons = enrol_get_course_info_icons($course)) {
1172 $content .= html_writer::start_tag('div', ['class' => 'enrolmenticons']);
1173 foreach ($icons as $icon) {
1174 $content .= $this->render($icon);
1176 $content .= html_writer::end_tag('div');
1178 return $content;
1182 * Displays one course in the list of courses.
1184 * This is an internal function, to display an information about just one course
1185 * please use {@link core_course_renderer::course_info_box()}
1187 * @param coursecat_helper $chelper various display options
1188 * @param core_course_list_element|stdClass $course
1189 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1190 * depend on the course position in list - first/last/even/odd)
1191 * @return string
1193 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1194 if (!isset($this->strings->summary)) {
1195 $this->strings->summary = get_string('summary');
1197 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1198 return '';
1200 if ($course instanceof stdClass) {
1201 $course = new core_course_list_element($course);
1203 $content = '';
1204 $classes = trim('coursebox clearfix '. $additionalclasses);
1205 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1206 $classes .= ' collapsed';
1209 // .coursebox
1210 $content .= html_writer::start_tag('div', array(
1211 'class' => $classes,
1212 'data-courseid' => $course->id,
1213 'data-type' => self::COURSECAT_TYPE_COURSE,
1216 $content .= html_writer::start_tag('div', array('class' => 'info'));
1217 $content .= $this->course_name($chelper, $course);
1218 $content .= $this->course_enrolment_icons($course);
1219 $content .= html_writer::end_tag('div');
1221 $content .= html_writer::start_tag('div', array('class' => 'content'));
1222 $content .= $this->coursecat_coursebox_content($chelper, $course);
1223 $content .= html_writer::end_tag('div');
1225 $content .= html_writer::end_tag('div'); // .coursebox
1226 return $content;
1230 * Returns HTML to display course summary.
1232 * @param coursecat_helper $chelper
1233 * @param core_course_list_element $course
1234 * @return string
1236 protected function course_summary(coursecat_helper $chelper, core_course_list_element $course): string {
1237 $content = '';
1238 if ($course->has_summary()) {
1239 $content .= html_writer::start_tag('div', ['class' => 'summary']);
1240 $content .= $chelper->get_course_formatted_summary($course,
1241 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1242 $content .= html_writer::end_tag('div');
1244 return $content;
1248 * Returns HTML to display course contacts.
1250 * @param core_course_list_element $course
1251 * @return string
1253 protected function course_contacts(core_course_list_element $course) {
1254 $content = '';
1255 if ($course->has_course_contacts()) {
1256 $content .= html_writer::start_tag('ul', ['class' => 'teachers']);
1257 foreach ($course->get_course_contacts() as $coursecontact) {
1258 $rolenames = array_map(function ($role) {
1259 return $role->displayname;
1260 }, $coursecontact['roles']);
1261 $name = implode(", ", $rolenames).': '.
1262 html_writer::link(new moodle_url('/user/view.php',
1263 ['id' => $coursecontact['user']->id, 'course' => SITEID]),
1264 $coursecontact['username']);
1265 $content .= html_writer::tag('li', $name);
1267 $content .= html_writer::end_tag('ul');
1269 return $content;
1273 * Returns HTML to display course overview files.
1275 * @param core_course_list_element $course
1276 * @return string
1278 protected function course_overview_files(core_course_list_element $course): string {
1279 global $CFG;
1281 $contentimages = $contentfiles = '';
1282 foreach ($course->get_course_overviewfiles() as $file) {
1283 $isimage = $file->is_valid_image();
1284 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php",
1285 '/' . $file->get_contextid() . '/' . $file->get_component() . '/' .
1286 $file->get_filearea() . $file->get_filepath() . $file->get_filename(), !$isimage);
1287 if ($isimage) {
1288 $contentimages .= html_writer::tag('div',
1289 html_writer::empty_tag('img', ['src' => $url]),
1290 ['class' => 'courseimage']);
1291 } else {
1292 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1293 $filename = html_writer::tag('span', $image, ['class' => 'fp-icon']).
1294 html_writer::tag('span', $file->get_filename(), ['class' => 'fp-filename']);
1295 $contentfiles .= html_writer::tag('span',
1296 html_writer::link($url, $filename),
1297 ['class' => 'coursefile fp-filename-icon']);
1300 return $contentimages . $contentfiles;
1304 * Returns HTML to display course category name.
1306 * @param coursecat_helper $chelper
1307 * @param core_course_list_element $course
1308 * @return string
1310 protected function course_category_name(coursecat_helper $chelper, core_course_list_element $course): string {
1311 $content = '';
1312 // Display course category if necessary (for example in search results).
1313 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1314 if ($cat = core_course_category::get($course->category, IGNORE_MISSING)) {
1315 $content .= html_writer::start_tag('div', ['class' => 'coursecat']);
1316 $content .= get_string('category').': '.
1317 html_writer::link(new moodle_url('/course/index.php', ['categoryid' => $cat->id]),
1318 $cat->get_formatted_name(), ['class' => $cat->visible ? '' : 'dimmed']);
1319 $content .= html_writer::end_tag('div');
1322 return $content;
1326 * Returns HTML to display course custom fields.
1328 * @param core_course_list_element $course
1329 * @return string
1331 protected function course_custom_fields(core_course_list_element $course): string {
1332 $content = '';
1333 if ($course->has_custom_fields()) {
1334 $handler = core_course\customfield\course_handler::create();
1335 $customfields = $handler->display_custom_fields_data($course->get_custom_fields());
1336 $content .= \html_writer::tag('div', $customfields, ['class' => 'customfields-container']);
1338 return $content;
1342 * Returns HTML to display course content (summary, course contacts and optionally category name)
1344 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1346 * @param coursecat_helper $chelper various display options
1347 * @param stdClass|core_course_list_element $course
1348 * @return string
1350 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1351 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1352 return '';
1354 if ($course instanceof stdClass) {
1355 $course = new core_course_list_element($course);
1357 $content = $this->course_summary($chelper, $course);
1358 $content .= $this->course_overview_files($course);
1359 $content .= $this->course_contacts($course);
1360 $content .= $this->course_category_name($chelper, $course);
1361 $content .= $this->course_custom_fields($course);
1362 return $content;
1366 * Renders the list of courses
1368 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1369 * method from outside of the class
1371 * If list of courses is specified in $courses; the argument $chelper is only used
1372 * to retrieve display options and attributes, only methods get_show_courses(),
1373 * get_courses_display_option() and get_and_erase_attributes() are called.
1375 * @param coursecat_helper $chelper various display options
1376 * @param array $courses the list of courses to display
1377 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1378 * defaulted to count($courses)
1379 * @return string
1381 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1382 global $CFG;
1383 if ($totalcount === null) {
1384 $totalcount = count($courses);
1386 if (!$totalcount) {
1387 // Courses count is cached during courses retrieval.
1388 return '';
1391 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1392 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1393 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1394 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1395 } else {
1396 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1400 // prepare content of paging bar if it is needed
1401 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1402 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1403 if ($totalcount > count($courses)) {
1404 // there are more results that can fit on one page
1405 if ($paginationurl) {
1406 // the option paginationurl was specified, display pagingbar
1407 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1408 $page = $chelper->get_courses_display_option('offset') / $perpage;
1409 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1410 $paginationurl->out(false, array('perpage' => $perpage)));
1411 if ($paginationallowall) {
1412 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1413 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1415 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1416 // the option for 'View more' link was specified, display more link
1417 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1418 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1419 array('class' => 'paging paging-morelink'));
1421 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1422 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1423 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1424 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1427 // display list of courses
1428 $attributes = $chelper->get_and_erase_attributes('courses');
1429 $content = html_writer::start_tag('div', $attributes);
1431 if (!empty($pagingbar)) {
1432 $content .= $pagingbar;
1435 $coursecount = 0;
1436 foreach ($courses as $course) {
1437 $coursecount ++;
1438 $classes = ($coursecount%2) ? 'odd' : 'even';
1439 if ($coursecount == 1) {
1440 $classes .= ' first';
1442 if ($coursecount >= count($courses)) {
1443 $classes .= ' last';
1445 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1448 if (!empty($pagingbar)) {
1449 $content .= $pagingbar;
1451 if (!empty($morelink)) {
1452 $content .= $morelink;
1455 $content .= html_writer::end_tag('div'); // .courses
1456 return $content;
1460 * Renders the list of subcategories in a category
1462 * @param coursecat_helper $chelper various display options
1463 * @param core_course_category $coursecat
1464 * @param int $depth depth of the category in the current tree
1465 * @return string
1467 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1468 global $CFG;
1469 $subcategories = array();
1470 if (!$chelper->get_categories_display_option('nodisplay')) {
1471 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1473 $totalcount = $coursecat->get_children_count();
1474 if (!$totalcount) {
1475 // Note that we call core_course_category::get_children_count() AFTER core_course_category::get_children()
1476 // to avoid extra DB requests.
1477 // Categories count is cached during children categories retrieval.
1478 return '';
1481 // prepare content of paging bar or more link if it is needed
1482 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1483 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1484 if ($totalcount > count($subcategories)) {
1485 if ($paginationurl) {
1486 // the option 'paginationurl was specified, display pagingbar
1487 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1488 $page = $chelper->get_categories_display_option('offset') / $perpage;
1489 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1490 $paginationurl->out(false, array('perpage' => $perpage)));
1491 if ($paginationallowall) {
1492 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1493 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1495 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1496 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1497 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1498 $viewmoreurl->param('categoryid', $coursecat->id);
1500 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1501 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1502 array('class' => 'paging paging-morelink'));
1504 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1505 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1506 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1507 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1510 // display list of subcategories
1511 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1513 if (!empty($pagingbar)) {
1514 $content .= $pagingbar;
1517 foreach ($subcategories as $subcategory) {
1518 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1521 if (!empty($pagingbar)) {
1522 $content .= $pagingbar;
1524 if (!empty($morelink)) {
1525 $content .= $morelink;
1528 $content .= html_writer::end_tag('div');
1529 return $content;
1533 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1535 protected function coursecat_include_js() {
1536 if (!$this->page->requires->should_create_one_time_item_now('core_course_categoryexpanderjsinit')) {
1537 return;
1540 // We must only load this module once.
1541 $this->page->requires->yui_module('moodle-course-categoryexpander',
1542 'Y.Moodle.course.categoryexpander.init');
1546 * Returns HTML to display the subcategories and courses in the given category
1548 * This method is re-used by AJAX to expand content of not loaded category
1550 * @param coursecat_helper $chelper various display options
1551 * @param core_course_category $coursecat
1552 * @param int $depth depth of the category in the current tree
1553 * @return string
1555 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1556 $content = '';
1557 // Subcategories
1558 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1560 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1561 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1562 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1563 if ($showcoursesauto && $depth) {
1564 // this is definitely collapsed mode
1565 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1568 // Courses
1569 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1570 $courses = array();
1571 if (!$chelper->get_courses_display_option('nodisplay')) {
1572 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1574 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1575 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1576 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1577 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1580 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1583 if ($showcoursesauto) {
1584 // restore the show_courses back to AUTO
1585 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1588 return $content;
1592 * Returns HTML to display a course category as a part of a tree
1594 * This is an internal function, to display a particular category and all its contents
1595 * use {@link core_course_renderer::course_category()}
1597 * @param coursecat_helper $chelper various display options
1598 * @param core_course_category $coursecat
1599 * @param int $depth depth of this category in the current tree
1600 * @return string
1602 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1603 // open category tag
1604 $classes = array('category');
1605 if (empty($coursecat->visible)) {
1606 $classes[] = 'dimmed_category';
1608 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1609 // do not load content
1610 $categorycontent = '';
1611 $classes[] = 'notloaded';
1612 if ($coursecat->get_children_count() ||
1613 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1614 $classes[] = 'with_children';
1615 $classes[] = 'collapsed';
1617 } else {
1618 // load category content
1619 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1620 $classes[] = 'loaded';
1621 if (!empty($categorycontent)) {
1622 $classes[] = 'with_children';
1623 // Category content loaded with children.
1624 $this->categoryexpandedonload = true;
1628 // Make sure JS file to expand category content is included.
1629 $this->coursecat_include_js();
1631 $content = html_writer::start_tag('div', array(
1632 'class' => join(' ', $classes),
1633 'data-categoryid' => $coursecat->id,
1634 'data-depth' => $depth,
1635 'data-showcourses' => $chelper->get_show_courses(),
1636 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1639 // category name
1640 $categoryname = $coursecat->get_formatted_name();
1641 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1642 array('categoryid' => $coursecat->id)),
1643 $categoryname);
1644 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1645 && ($coursescount = $coursecat->get_courses_count())) {
1646 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1647 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1649 $content .= html_writer::start_tag('div', array('class' => 'info'));
1651 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname aabtn'));
1652 $content .= html_writer::end_tag('div'); // .info
1654 // add category content to the output
1655 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1657 $content .= html_writer::end_tag('div'); // .category
1659 // Return the course category tree HTML
1660 return $content;
1664 * Returns HTML to display a tree of subcategories and courses in the given category
1666 * @param coursecat_helper $chelper various display options
1667 * @param core_course_category $coursecat top category (this category's name and description will NOT be added to the tree)
1668 * @return string
1670 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1671 // Reset the category expanded flag for this course category tree first.
1672 $this->categoryexpandedonload = false;
1673 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1674 if (empty($categorycontent)) {
1675 return '';
1678 // Start content generation
1679 $content = '';
1680 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1681 $content .= html_writer::start_tag('div', $attributes);
1683 if ($coursecat->get_children_count()) {
1684 $classes = array(
1685 'collapseexpand', 'aabtn'
1688 // Check if the category content contains subcategories with children's content loaded.
1689 if ($this->categoryexpandedonload) {
1690 $classes[] = 'collapse-all';
1691 $linkname = get_string('collapseall');
1692 } else {
1693 $linkname = get_string('expandall');
1696 // Only show the collapse/expand if there are children to expand.
1697 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1698 $content .= html_writer::link('#', $linkname, array('class' => implode(' ', $classes)));
1699 $content .= html_writer::end_tag('div');
1700 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1703 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1705 $content .= html_writer::end_tag('div'); // .course_category_tree
1707 return $content;
1711 * Renders HTML to display particular course category - list of it's subcategories and courses
1713 * Invoked from /course/index.php
1715 * @param int|stdClass|core_course_category $category
1717 public function course_category($category) {
1718 global $CFG;
1719 $usertop = core_course_category::user_top();
1720 if (empty($category)) {
1721 $coursecat = $usertop;
1722 } else if (is_object($category) && $category instanceof core_course_category) {
1723 $coursecat = $category;
1724 } else {
1725 $coursecat = core_course_category::get(is_object($category) ? $category->id : $category);
1727 $site = get_site();
1728 $output = '';
1730 if ($coursecat->can_create_course() || $coursecat->has_manage_capability()) {
1731 // Add 'Manage' button if user has permissions to edit this category.
1732 $managebutton = $this->single_button(new moodle_url('/course/management.php',
1733 array('categoryid' => $coursecat->id)), get_string('managecourses'), 'get');
1734 $this->page->set_button($managebutton);
1737 if (core_course_category::is_simple_site()) {
1738 // There is only one category in the system, do not display link to it.
1739 $strfulllistofcourses = get_string('fulllistofcourses');
1740 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1741 } else if (!$coursecat->id || !$coursecat->is_uservisible()) {
1742 $strcategories = get_string('categories');
1743 $this->page->set_title("$site->shortname: $strcategories");
1744 } else {
1745 $strfulllistofcourses = get_string('fulllistofcourses');
1746 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1748 // Print the category selector
1749 $categorieslist = core_course_category::make_categories_list();
1750 if (count($categorieslist) > 1) {
1751 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1752 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1753 core_course_category::make_categories_list(), $coursecat->id, null, 'switchcategory');
1754 $select->set_label(get_string('categories').':');
1755 $output .= $this->render($select);
1756 $output .= html_writer::end_tag('div'); // .categorypicker
1760 // Print current category description
1761 $chelper = new coursecat_helper();
1762 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1763 $output .= $this->box($description, array('class' => 'generalbox info'));
1766 // Prepare parameters for courses and categories lists in the tree
1767 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1768 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1770 $coursedisplayoptions = array();
1771 $catdisplayoptions = array();
1772 $browse = optional_param('browse', null, PARAM_ALPHA);
1773 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1774 $page = optional_param('page', 0, PARAM_INT);
1775 $baseurl = new moodle_url('/course/index.php');
1776 if ($coursecat->id) {
1777 $baseurl->param('categoryid', $coursecat->id);
1779 if ($perpage != $CFG->coursesperpage) {
1780 $baseurl->param('perpage', $perpage);
1782 $coursedisplayoptions['limit'] = $perpage;
1783 $catdisplayoptions['limit'] = $perpage;
1784 if ($browse === 'courses' || !$coursecat->get_children_count()) {
1785 $coursedisplayoptions['offset'] = $page * $perpage;
1786 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1787 $catdisplayoptions['nodisplay'] = true;
1788 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1789 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1790 } else if ($browse === 'categories' || !$coursecat->get_courses_count()) {
1791 $coursedisplayoptions['nodisplay'] = true;
1792 $catdisplayoptions['offset'] = $page * $perpage;
1793 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1794 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1795 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1796 } else {
1797 // we have a category that has both subcategories and courses, display pagination separately
1798 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1799 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1801 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1802 // Add course search form.
1803 $output .= $this->course_search_form();
1805 // Display course category tree.
1806 $output .= $this->coursecat_tree($chelper, $coursecat);
1808 // Add action buttons
1809 $output .= $this->container_start('buttons');
1810 if ($coursecat->is_uservisible()) {
1811 $context = get_category_or_system_context($coursecat->id);
1812 if (has_capability('moodle/course:create', $context)) {
1813 // Print link to create a new course, for the 1st available category.
1814 if ($coursecat->id) {
1815 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1816 } else {
1817 $url = new moodle_url('/course/edit.php',
1818 array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1820 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1822 ob_start();
1823 print_course_request_buttons($context);
1824 $output .= ob_get_contents();
1825 ob_end_clean();
1827 $output .= $this->container_end();
1829 return $output;
1833 * Serves requests to /course/category.ajax.php
1835 * In this renderer implementation it may expand the category content or
1836 * course content.
1838 * @return string
1839 * @throws coding_exception
1841 public function coursecat_ajax() {
1842 global $DB, $CFG;
1844 $type = required_param('type', PARAM_INT);
1846 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1847 // This is a request for a category list of some kind.
1848 $categoryid = required_param('categoryid', PARAM_INT);
1849 $showcourses = required_param('showcourses', PARAM_INT);
1850 $depth = required_param('depth', PARAM_INT);
1852 $category = core_course_category::get($categoryid);
1854 $chelper = new coursecat_helper();
1855 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1856 $coursedisplayoptions = array(
1857 'limit' => $CFG->coursesperpage,
1858 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1860 $catdisplayoptions = array(
1861 'limit' => $CFG->coursesperpage,
1862 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1864 $chelper->set_show_courses($showcourses)->
1865 set_courses_display_options($coursedisplayoptions)->
1866 set_categories_display_options($catdisplayoptions);
1868 return $this->coursecat_category_content($chelper, $category, $depth);
1869 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1870 // This is a request for the course information.
1871 $courseid = required_param('courseid', PARAM_INT);
1873 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1875 $chelper = new coursecat_helper();
1876 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1877 return $this->coursecat_coursebox_content($chelper, $course);
1878 } else {
1879 throw new coding_exception('Invalid request type');
1884 * Renders html to display search result page
1886 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1887 * @return string
1889 public function search_courses($searchcriteria) {
1890 global $CFG;
1891 $content = '';
1892 if (!empty($searchcriteria)) {
1893 // print search results
1895 $displayoptions = array('sort' => array('displayname' => 1));
1896 // take the current page and number of results per page from query
1897 $perpage = optional_param('perpage', 0, PARAM_RAW);
1898 if ($perpage !== 'all') {
1899 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1900 $page = optional_param('page', 0, PARAM_INT);
1901 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1903 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1904 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1905 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1907 $class = 'course-search-result';
1908 foreach ($searchcriteria as $key => $value) {
1909 if (!empty($value)) {
1910 $class .= ' course-search-result-'. $key;
1913 $chelper = new coursecat_helper();
1914 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1915 set_courses_display_options($displayoptions)->
1916 set_search_criteria($searchcriteria)->
1917 set_attributes(array('class' => $class));
1919 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1920 $totalcount = core_course_category::search_courses_count($searchcriteria);
1921 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1923 if (!$totalcount) {
1924 if (!empty($searchcriteria['search'])) {
1925 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1926 } else {
1927 $content .= $this->heading(get_string('novalidcourses'));
1929 } else {
1930 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1931 $content .= $courseslist;
1934 if (!empty($searchcriteria['search'])) {
1935 // print search form only if there was a search by search string, otherwise it is confusing
1936 $content .= $this->box_start('generalbox mdl-align');
1937 $content .= $this->course_search_form($searchcriteria['search']);
1938 $content .= $this->box_end();
1940 } else {
1941 // just print search form
1942 $content .= $this->box_start('generalbox mdl-align');
1943 $content .= $this->course_search_form();
1944 $content .= $this->box_end();
1946 return $content;
1950 * Renders html to print list of courses tagged with particular tag
1952 * @param int $tagid id of the tag
1953 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1954 * are displayed on the page and the per-page limit may be bigger
1955 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1956 * to display items in the same context first
1957 * @param int $ctx context id where to search for records
1958 * @param bool $rec search in subcontexts as well
1959 * @param array $displayoptions
1960 * @return string empty string if no courses are marked with this tag or rendered list of courses
1962 public function tagged_courses($tagid, $exclusivemode = true, $ctx = 0, $rec = true, $displayoptions = null) {
1963 global $CFG;
1964 if (empty($displayoptions)) {
1965 $displayoptions = array();
1967 $showcategories = !core_course_category::is_simple_site();
1968 $displayoptions += array('limit' => $CFG->coursesperpage, 'offset' => 0);
1969 $chelper = new coursecat_helper();
1970 $searchcriteria = array('tagid' => $tagid, 'ctx' => $ctx, 'rec' => $rec);
1971 $chelper->set_show_courses($showcategories ? self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT :
1972 self::COURSECAT_SHOW_COURSES_EXPANDED)->
1973 set_search_criteria($searchcriteria)->
1974 set_courses_display_options($displayoptions)->
1975 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1976 // (we set the same css class as in search results by tagid)
1977 if ($totalcount = core_course_category::search_courses_count($searchcriteria)) {
1978 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1979 if ($exclusivemode) {
1980 return $this->coursecat_courses($chelper, $courses, $totalcount);
1981 } else {
1982 $tagfeed = new core_tag\output\tagfeed();
1983 $img = $this->output->pix_icon('i/course', '');
1984 foreach ($courses as $course) {
1985 $url = course_get_url($course);
1986 $imgwithlink = html_writer::link($url, $img);
1987 $coursename = html_writer::link($url, $course->get_formatted_name());
1988 $details = '';
1989 if ($showcategories && ($cat = core_course_category::get($course->category, IGNORE_MISSING))) {
1990 $details = get_string('category').': '.
1991 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1992 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1994 $tagfeed->add($imgwithlink, $coursename, $details);
1996 return $this->output->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($this->output));
1999 return '';
2003 * Returns HTML to display one remote course
2005 * @param stdClass $course remote course information, contains properties:
2006 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
2007 * @return string
2009 protected function frontpage_remote_course(stdClass $course) {
2010 $url = new moodle_url('/auth/mnet/jump.php', array(
2011 'hostid' => $course->hostid,
2012 'wantsurl' => '/course/view.php?id='. $course->remoteid
2015 $output = '';
2016 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
2017 $output .= html_writer::start_tag('div', array('class' => 'info'));
2018 $output .= html_writer::start_tag('h3', array('class' => 'name'));
2019 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
2020 $output .= html_writer::end_tag('h3'); // .name
2021 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
2022 $output .= html_writer::end_tag('div'); // .info
2023 $output .= html_writer::start_tag('div', array('class' => 'content'));
2024 $output .= html_writer::start_tag('div', array('class' => 'summary'));
2025 $options = new stdClass();
2026 $options->noclean = true;
2027 $options->para = false;
2028 $options->overflowdiv = true;
2029 $output .= format_text($course->summary, $course->summaryformat, $options);
2030 $output .= html_writer::end_tag('div'); // .summary
2031 $addinfo = format_string($course->hostname) . ' : '
2032 . format_string($course->cat_name) . ' : '
2033 . format_string($course->shortname);
2034 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
2035 $output .= html_writer::end_tag('div'); // .content
2036 $output .= html_writer::end_tag('div'); // .coursebox
2037 return $output;
2041 * Returns HTML to display one remote host
2043 * @param array $host host information, contains properties: name, url, count
2044 * @return string
2046 protected function frontpage_remote_host($host) {
2047 $output = '';
2048 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
2049 $output .= html_writer::start_tag('div', array('class' => 'info'));
2050 $output .= html_writer::start_tag('h3', array('class' => 'name'));
2051 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
2052 $output .= html_writer::end_tag('h3'); // .name
2053 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
2054 $output .= html_writer::end_tag('div'); // .info
2055 $output .= html_writer::start_tag('div', array('class' => 'content'));
2056 $output .= html_writer::start_tag('div', array('class' => 'summary'));
2057 $output .= $host['count'] . ' ' . get_string('courses');
2058 $output .= html_writer::end_tag('div'); // .content
2059 $output .= html_writer::end_tag('div'); // .coursebox
2060 return $output;
2064 * Returns HTML to print list of courses user is enrolled to for the frontpage
2066 * Also lists remote courses or remote hosts if MNET authorisation is used
2068 * @return string
2070 public function frontpage_my_courses() {
2071 global $USER, $CFG, $DB;
2073 if (!isloggedin() or isguestuser()) {
2074 return '';
2077 $output = '';
2078 $courses = enrol_get_my_courses('summary, summaryformat');
2079 $rhosts = array();
2080 $rcourses = array();
2081 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2082 $rcourses = get_my_remotecourses($USER->id);
2083 $rhosts = get_my_remotehosts();
2086 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2088 $chelper = new coursecat_helper();
2089 $totalcount = count($courses);
2090 if (count($courses) > $CFG->frontpagecourselimit) {
2091 // There are more enrolled courses than we can display, display link to 'My courses'.
2092 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
2093 $chelper->set_courses_display_options(array(
2094 'viewmoreurl' => new moodle_url('/my/'),
2095 'viewmoretext' => new lang_string('mycourses')
2097 } else if (core_course_category::top()->is_uservisible()) {
2098 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
2099 $chelper->set_courses_display_options(array(
2100 'viewmoreurl' => new moodle_url('/course/index.php'),
2101 'viewmoretext' => new lang_string('fulllistofcourses')
2103 $totalcount = $DB->count_records('course') - 1;
2105 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2106 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
2107 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
2109 // MNET
2110 if (!empty($rcourses)) {
2111 // at the IDP, we know of all the remote courses
2112 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2113 foreach ($rcourses as $course) {
2114 $output .= $this->frontpage_remote_course($course);
2116 $output .= html_writer::end_tag('div'); // .courses
2117 } elseif (!empty($rhosts)) {
2118 // non-IDP, we know of all the remote servers, but not courses
2119 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2120 foreach ($rhosts as $host) {
2121 $output .= $this->frontpage_remote_host($host);
2123 $output .= html_writer::end_tag('div'); // .courses
2126 return $output;
2130 * Returns HTML to print list of available courses for the frontpage
2132 * @return string
2134 public function frontpage_available_courses() {
2135 global $CFG;
2137 $chelper = new coursecat_helper();
2138 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2139 set_courses_display_options(array(
2140 'recursive' => true,
2141 'limit' => $CFG->frontpagecourselimit,
2142 'viewmoreurl' => new moodle_url('/course/index.php'),
2143 'viewmoretext' => new lang_string('fulllistofcourses')));
2145 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
2146 $courses = core_course_category::top()->get_courses($chelper->get_courses_display_options());
2147 $totalcount = core_course_category::top()->get_courses_count($chelper->get_courses_display_options());
2148 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
2149 // Print link to create a new course, for the 1st available category.
2150 return $this->add_new_course_button();
2152 return $this->coursecat_courses($chelper, $courses, $totalcount);
2156 * Returns HTML to the "add new course" button for the page
2158 * @return string
2160 public function add_new_course_button() {
2161 global $CFG;
2162 // Print link to create a new course, for the 1st available category.
2163 $output = $this->container_start('buttons');
2164 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2165 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2166 $output .= $this->container_end('buttons');
2167 return $output;
2171 * Returns HTML to print tree with course categories and courses for the frontpage
2173 * @return string
2175 public function frontpage_combo_list() {
2176 global $CFG;
2177 // TODO MDL-10965 improve.
2178 $tree = core_course_category::top();
2179 if (!$tree->get_children_count()) {
2180 return '';
2182 $chelper = new coursecat_helper();
2183 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2184 set_categories_display_options(array(
2185 'limit' => $CFG->coursesperpage,
2186 'viewmoreurl' => new moodle_url('/course/index.php',
2187 array('browse' => 'categories', 'page' => 1))
2188 ))->
2189 set_courses_display_options(array(
2190 'limit' => $CFG->coursesperpage,
2191 'viewmoreurl' => new moodle_url('/course/index.php',
2192 array('browse' => 'courses', 'page' => 1))
2193 ))->
2194 set_attributes(array('class' => 'frontpage-category-combo'));
2195 return $this->coursecat_tree($chelper, $tree);
2199 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2201 * @return string
2203 public function frontpage_categories_list() {
2204 global $CFG;
2205 // TODO MDL-10965 improve.
2206 $tree = core_course_category::top();
2207 if (!$tree->get_children_count()) {
2208 return '';
2210 $chelper = new coursecat_helper();
2211 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2212 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2213 set_categories_display_options(array(
2214 'limit' => $CFG->coursesperpage,
2215 'viewmoreurl' => new moodle_url('/course/index.php',
2216 array('browse' => 'categories', 'page' => 1))
2217 ))->
2218 set_attributes(array('class' => 'frontpage-category-names'));
2219 return $this->coursecat_tree($chelper, $tree);
2223 * Renders the activity navigation.
2225 * Defer to template.
2227 * @param \core_course\output\activity_navigation $page
2228 * @return string html for the page
2230 public function render_activity_navigation(\core_course\output\activity_navigation $page) {
2231 $data = $page->export_for_template($this->output);
2232 return $this->output->render_from_template('core_course/activity_navigation', $data);
2236 * Display waiting information about backup size during uploading backup process
2237 * @param object $backupfile the backup stored_file
2238 * @return $html string
2240 public function sendingbackupinfo($backupfile) {
2241 $sizeinfo = new stdClass();
2242 $sizeinfo->total = number_format($backupfile->get_filesize() / 1000000, 2);
2243 $html = html_writer::tag('div', get_string('sendingsize', 'hub', $sizeinfo),
2244 array('class' => 'courseuploadtextinfo'));
2245 return $html;
2249 * Hub information (logo - name - description - link)
2250 * @param object $hubinfo
2251 * @return string html code
2253 public function hubinfo($hubinfo) {
2254 $screenshothtml = html_writer::empty_tag('img',
2255 array('src' => $hubinfo['imgurl'], 'alt' => $hubinfo['name']));
2256 $hubdescription = html_writer::tag('div', $screenshothtml,
2257 array('class' => 'hubscreenshot'));
2259 $hubdescription .= html_writer::tag('a', $hubinfo['name'],
2260 array('class' => 'hublink', 'href' => $hubinfo['url'],
2261 'onclick' => 'this.target="_blank"'));
2263 $hubdescription .= html_writer::tag('div', format_text($hubinfo['description'], FORMAT_PLAIN),
2264 array('class' => 'hubdescription'));
2265 $hubdescription = html_writer::tag('div', $hubdescription, array('class' => 'hubinfo clearfix'));
2267 return $hubdescription;
2271 * Output frontpage summary text and frontpage modules (stored as section 1 in site course)
2273 * This may be disabled in settings
2275 * @return string
2277 public function frontpage_section1() {
2278 global $SITE, $USER;
2280 $output = '';
2281 $editing = $this->page->user_is_editing();
2283 if ($editing) {
2284 // Make sure section with number 1 exists.
2285 course_create_sections_if_missing($SITE, 1);
2288 $modinfo = get_fast_modinfo($SITE);
2289 $section = $modinfo->get_section_info(1);
2290 if (($section && (!empty($modinfo->sections[1]) or !empty($section->summary))) or $editing) {
2291 $output .= $this->box_start('generalbox sitetopic');
2293 // If currently moving a file then show the current clipboard.
2294 if (ismoving($SITE->id)) {
2295 $stractivityclipboard = strip_tags(get_string('activityclipboard', '', $USER->activitycopyname));
2296 $output .= '<p><font size="2">';
2297 $cancelcopyurl = new moodle_url('/course/mod.php', ['cancelcopy' => 'true', 'sesskey' => sesskey()]);
2298 $output .= "$stractivityclipboard&nbsp;&nbsp;(" . html_writer::link($cancelcopyurl, get_string('cancel')) .')';
2299 $output .= '</font></p>';
2302 $context = context_course::instance(SITEID);
2304 // If the section name is set we show it.
2305 if (trim($section->name) !== '') {
2306 $output .= $this->heading(
2307 format_string($section->name, true, array('context' => $context)),
2309 'sectionname'
2313 $summarytext = file_rewrite_pluginfile_urls($section->summary,
2314 'pluginfile.php',
2315 $context->id,
2316 'course',
2317 'section',
2318 $section->id);
2319 $summaryformatoptions = new stdClass();
2320 $summaryformatoptions->noclean = true;
2321 $summaryformatoptions->overflowdiv = true;
2323 $output .= format_text($summarytext, $section->summaryformat, $summaryformatoptions);
2325 if ($editing && has_capability('moodle/course:update', $context)) {
2326 $streditsummary = get_string('editsummary');
2327 $editsectionurl = new moodle_url('/course/editsection.php', ['id' => $section->id]);
2328 $output .= html_writer::link($editsectionurl, $this->pix_icon('t/edit', $streditsummary)) .
2329 "<br /><br />";
2332 $output .= $this->course_section_cm_list($SITE, $section);
2334 $output .= $this->course_section_add_cm_control($SITE, $section->section);
2335 $output .= $this->box_end();
2338 return $output;
2342 * Output news for the frontpage (extract from site-wide news forum)
2344 * @param stdClass $forum record from db table 'forum' that represents the site news forum
2345 * @return string
2347 protected function frontpage_news($forum) {
2348 global $CFG, $SITE, $SESSION, $USER;
2349 require_once($CFG->dirroot .'/mod/forum/lib.php');
2351 $output = '';
2353 if (isloggedin()) {
2354 $SESSION->fromdiscussion = $CFG->wwwroot;
2355 $subtext = '';
2356 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forum)) {
2357 if (!\mod_forum\subscriptions::is_forcesubscribed($forum)) {
2358 $subtext = get_string('unsubscribe', 'forum');
2360 } else {
2361 $subtext = get_string('subscribe', 'forum');
2363 $suburl = new moodle_url('/mod/forum/subscribe.php', array('id' => $forum->id, 'sesskey' => sesskey()));
2364 $output .= html_writer::tag('div', html_writer::link($suburl, $subtext), array('class' => 'subscribelink'));
2367 $coursemodule = get_coursemodule_from_instance('forum', $forum->id);
2368 $context = context_module::instance($coursemodule->id);
2370 $entityfactory = mod_forum\local\container::get_entity_factory();
2371 $forumentity = $entityfactory->get_forum_from_stdclass($forum, $context, $coursemodule, $SITE);
2373 $rendererfactory = mod_forum\local\container::get_renderer_factory();
2374 $discussionsrenderer = $rendererfactory->get_frontpage_news_discussion_list_renderer($forumentity);
2375 $cm = \cm_info::create($coursemodule);
2376 return $output . $discussionsrenderer->render($USER, $cm, null, null, 0, $SITE->newsitems);
2380 * Renders part of frontpage with a skip link (i.e. "My courses", "Site news", etc.)
2382 * @param string $skipdivid
2383 * @param string $contentsdivid
2384 * @param string $header Header of the part
2385 * @param string $contents Contents of the part
2386 * @return string
2388 protected function frontpage_part($skipdivid, $contentsdivid, $header, $contents) {
2389 if (strval($contents) === '') {
2390 return '';
2392 $output = html_writer::link('#' . $skipdivid,
2393 get_string('skipa', 'access', core_text::strtolower(strip_tags($header))),
2394 array('class' => 'skip-block skip aabtn'));
2396 // Wrap frontpage part in div container.
2397 $output .= html_writer::start_tag('div', array('id' => $contentsdivid));
2398 $output .= $this->heading($header);
2400 $output .= $contents;
2402 // End frontpage part div container.
2403 $output .= html_writer::end_tag('div');
2405 $output .= html_writer::tag('span', '', array('class' => 'skip-block-to', 'id' => $skipdivid));
2406 return $output;
2410 * Outputs contents for frontpage as configured in $CFG->frontpage or $CFG->frontpageloggedin
2412 * @return string
2414 public function frontpage() {
2415 global $CFG, $SITE;
2417 $output = '';
2419 if (isloggedin() and !isguestuser() and isset($CFG->frontpageloggedin)) {
2420 $frontpagelayout = $CFG->frontpageloggedin;
2421 } else {
2422 $frontpagelayout = $CFG->frontpage;
2425 foreach (explode(',', $frontpagelayout) as $v) {
2426 switch ($v) {
2427 // Display the main part of the front page.
2428 case FRONTPAGENEWS:
2429 if ($SITE->newsitems) {
2430 // Print forums only when needed.
2431 require_once($CFG->dirroot .'/mod/forum/lib.php');
2432 if (($newsforum = forum_get_course_forum($SITE->id, 'news')) &&
2433 ($forumcontents = $this->frontpage_news($newsforum))) {
2434 $newsforumcm = get_fast_modinfo($SITE)->instances['forum'][$newsforum->id];
2435 $output .= $this->frontpage_part('skipsitenews', 'site-news-forum',
2436 $newsforumcm->get_formatted_name(), $forumcontents);
2439 break;
2441 case FRONTPAGEENROLLEDCOURSELIST:
2442 $mycourseshtml = $this->frontpage_my_courses();
2443 if (!empty($mycourseshtml)) {
2444 $output .= $this->frontpage_part('skipmycourses', 'frontpage-course-list',
2445 get_string('mycourses'), $mycourseshtml);
2447 break;
2449 case FRONTPAGEALLCOURSELIST:
2450 $availablecourseshtml = $this->frontpage_available_courses();
2451 $output .= $this->frontpage_part('skipavailablecourses', 'frontpage-available-course-list',
2452 get_string('availablecourses'), $availablecourseshtml);
2453 break;
2455 case FRONTPAGECATEGORYNAMES:
2456 $output .= $this->frontpage_part('skipcategories', 'frontpage-category-names',
2457 get_string('categories'), $this->frontpage_categories_list());
2458 break;
2460 case FRONTPAGECATEGORYCOMBO:
2461 $output .= $this->frontpage_part('skipcourses', 'frontpage-category-combo',
2462 get_string('courses'), $this->frontpage_combo_list());
2463 break;
2465 case FRONTPAGECOURSESEARCH:
2466 $output .= $this->box($this->course_search_form('', 'short'), 'mdl-align');
2467 break;
2470 $output .= '<br />';
2473 return $output;
2478 * Class storing display options and functions to help display course category and/or courses lists
2480 * This is a wrapper for core_course_category objects that also stores display options
2481 * and functions to retrieve sorted and paginated lists of categories/courses.
2483 * If theme overrides methods in core_course_renderers that access this class
2484 * it may as well not use this class at all or extend it.
2486 * @package core
2487 * @copyright 2013 Marina Glancy
2488 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2490 class coursecat_helper {
2491 /** @var string [none, collapsed, expanded] how (if) display courses list */
2492 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2493 /** @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) */
2494 protected $subcatdepth = 1;
2495 /** @var array options to display courses list */
2496 protected $coursesdisplayoptions = array();
2497 /** @var array options to display subcategories list */
2498 protected $categoriesdisplayoptions = array();
2499 /** @var array additional HTML attributes */
2500 protected $attributes = array();
2501 /** @var array search criteria if the list is a search result */
2502 protected $searchcriteria = null;
2505 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2507 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2508 * @return coursecat_helper
2510 public function set_show_courses($showcourses) {
2511 $this->showcourses = $showcourses;
2512 // Automatically set the options to preload summary and coursecontacts for core_course_category::get_courses()
2513 // and core_course_category::search_courses().
2514 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2515 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2516 $this->coursesdisplayoptions['customfields'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED;
2517 return $this;
2521 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2523 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2525 public function get_show_courses() {
2526 return $this->showcourses;
2530 * Sets the maximum depth to expand subcategories in the tree
2532 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2534 * @param int $subcatdepth
2535 * @return coursecat_helper
2537 public function set_subcat_depth($subcatdepth) {
2538 $this->subcatdepth = $subcatdepth;
2539 return $this;
2543 * Returns the maximum depth to expand subcategories in the tree
2545 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2547 * @return int
2549 public function get_subcat_depth() {
2550 return $this->subcatdepth;
2554 * Sets options to display list of courses
2556 * Options are later submitted as argument to core_course_category::get_courses() and/or core_course_category::search_courses()
2558 * Options that core_course_category::get_courses() accept:
2559 * - recursive - return courses from subcategories as well. Use with care,
2560 * this may be a huge list!
2561 * - summary - preloads fields 'summary' and 'summaryformat'
2562 * - coursecontacts - preloads course contacts
2563 * - customfields - preloads custom fields data
2564 * - isenrolled - preloads indication whether this user is enrolled in the course
2565 * - sort - list of fields to sort. Example
2566 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2567 * will sort by idnumber asc, shortname asc and id desc.
2568 * Default: array('sortorder' => 1)
2569 * Only cached fields may be used for sorting!
2570 * - offset
2571 * - limit - maximum number of children to return, 0 or null for no limit
2573 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2575 * Also renderer can set here any additional options it wants to pass between renderer functions.
2577 * @param array $options
2578 * @return coursecat_helper
2580 public function set_courses_display_options($options) {
2581 $this->coursesdisplayoptions = $options;
2582 $this->set_show_courses($this->showcourses); // this will calculate special display options
2583 return $this;
2587 * Sets one option to display list of courses
2589 * @see coursecat_helper::set_courses_display_options()
2591 * @param string $key
2592 * @param mixed $value
2593 * @return coursecat_helper
2595 public function set_courses_display_option($key, $value) {
2596 $this->coursesdisplayoptions[$key] = $value;
2597 return $this;
2601 * Return the specified option to display list of courses
2603 * @param string $optionname option name
2604 * @param mixed $defaultvalue default value for option if it is not specified
2605 * @return mixed
2607 public function get_courses_display_option($optionname, $defaultvalue = null) {
2608 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2609 return $this->coursesdisplayoptions[$optionname];
2610 } else {
2611 return $defaultvalue;
2616 * Returns all options to display the courses
2618 * This array is usually passed to {@link core_course_category::get_courses()} or
2619 * {@link core_course_category::search_courses()}
2621 * @return array
2623 public function get_courses_display_options() {
2624 return $this->coursesdisplayoptions;
2628 * Sets options to display list of subcategories
2630 * Options 'sort', 'offset' and 'limit' are passed to core_course_category::get_children().
2631 * Any other options may be used by renderer functions
2633 * @param array $options
2634 * @return coursecat_helper
2636 public function set_categories_display_options($options) {
2637 $this->categoriesdisplayoptions = $options;
2638 return $this;
2642 * Return the specified option to display list of subcategories
2644 * @param string $optionname option name
2645 * @param mixed $defaultvalue default value for option if it is not specified
2646 * @return mixed
2648 public function get_categories_display_option($optionname, $defaultvalue = null) {
2649 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2650 return $this->categoriesdisplayoptions[$optionname];
2651 } else {
2652 return $defaultvalue;
2657 * Returns all options to display list of subcategories
2659 * This array is usually passed to {@link core_course_category::get_children()}
2661 * @return array
2663 public function get_categories_display_options() {
2664 return $this->categoriesdisplayoptions;
2668 * Sets additional general options to pass between renderer functions, usually HTML attributes
2670 * @param array $attributes
2671 * @return coursecat_helper
2673 public function set_attributes($attributes) {
2674 $this->attributes = $attributes;
2675 return $this;
2679 * Return all attributes and erases them so they are not applied again
2681 * @param string $classname adds additional class name to the beginning of $attributes['class']
2682 * @return array
2684 public function get_and_erase_attributes($classname) {
2685 $attributes = $this->attributes;
2686 $this->attributes = array();
2687 if (empty($attributes['class'])) {
2688 $attributes['class'] = '';
2690 $attributes['class'] = $classname . ' '. $attributes['class'];
2691 return $attributes;
2695 * Sets the search criteria if the course is a search result
2697 * Search string will be used to highlight terms in course name and description
2699 * @param array $searchcriteria
2700 * @return coursecat_helper
2702 public function set_search_criteria($searchcriteria) {
2703 $this->searchcriteria = $searchcriteria;
2704 return $this;
2708 * Returns formatted and filtered description of the given category
2710 * @param core_course_category $coursecat category
2711 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2712 * if context is not specified it will be added automatically
2713 * @return string|null
2715 public function get_category_formatted_description($coursecat, $options = null) {
2716 if ($coursecat->id && $coursecat->is_uservisible() && !empty($coursecat->description)) {
2717 if (!isset($coursecat->descriptionformat)) {
2718 $descriptionformat = FORMAT_MOODLE;
2719 } else {
2720 $descriptionformat = $coursecat->descriptionformat;
2722 if ($options === null) {
2723 $options = array('noclean' => true, 'overflowdiv' => true);
2724 } else {
2725 $options = (array)$options;
2727 $context = context_coursecat::instance($coursecat->id);
2728 if (!isset($options['context'])) {
2729 $options['context'] = $context;
2731 $text = file_rewrite_pluginfile_urls($coursecat->description,
2732 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2733 return format_text($text, $descriptionformat, $options);
2735 return null;
2739 * Returns given course's summary with proper embedded files urls and formatted
2741 * @param core_course_list_element $course
2742 * @param array|stdClass $options additional formatting options
2743 * @return string
2745 public function get_course_formatted_summary($course, $options = array()) {
2746 global $CFG;
2747 require_once($CFG->libdir. '/filelib.php');
2748 if (!$course->has_summary()) {
2749 return '';
2751 $options = (array)$options;
2752 $context = context_course::instance($course->id);
2753 if (!isset($options['context'])) {
2754 // TODO see MDL-38521
2755 // option 1 (current), page context - no code required
2756 // option 2, system context
2757 // $options['context'] = context_system::instance();
2758 // option 3, course context:
2759 // $options['context'] = $context;
2760 // option 4, course category context:
2761 // $options['context'] = $context->get_parent_context();
2763 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2764 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2765 if (!empty($this->searchcriteria['search'])) {
2766 $summary = highlight($this->searchcriteria['search'], $summary);
2768 return $summary;
2772 * Returns course name as it is configured to appear in courses lists formatted to course context
2774 * @param core_course_list_element $course
2775 * @param array|stdClass $options additional formatting options
2776 * @return string
2778 public function get_course_formatted_name($course, $options = array()) {
2779 $options = (array)$options;
2780 if (!isset($options['context'])) {
2781 $options['context'] = context_course::instance($course->id);
2783 $name = format_string(get_course_display_name_for_list($course), true, $options);
2784 if (!empty($this->searchcriteria['search'])) {
2785 $name = highlight($this->searchcriteria['search'], $name);
2787 return $name;