Merge branch 'MDL-69583-310' of git://github.com/ferranrecio/moodle into MOODLE_310_S...
[moodle.git] / course / renderer.php
blob89b7e0c7566cdd1d6086d017477f45eb03542aca
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Renderer for use with the course section and all the goodness that falls
20 * within it.
22 * This renderer should contain methods useful to courses, and categories.
24 * @package moodlecore
25 * @copyright 2010 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 /**
30 * The core course renderer
32 * Can be retrieved with the following:
33 * $renderer = $PAGE->get_renderer('core','course');
35 class core_course_renderer extends plugin_renderer_base {
36 const COURSECAT_SHOW_COURSES_NONE = 0; /* do not show courses at all */
37 const COURSECAT_SHOW_COURSES_COUNT = 5; /* do not show courses but show number of courses next to category name */
38 const COURSECAT_SHOW_COURSES_COLLAPSED = 10;
39 const COURSECAT_SHOW_COURSES_AUTO = 15; /* will choose between collapsed and expanded automatically */
40 const COURSECAT_SHOW_COURSES_EXPANDED = 20;
41 const COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT = 30;
43 const COURSECAT_TYPE_CATEGORY = 0;
44 const COURSECAT_TYPE_COURSE = 1;
46 /**
47 * A cache of strings
48 * @var stdClass
50 protected $strings;
52 /**
53 * Whether a category content is being initially rendered with children. This is mainly used by the
54 * core_course_renderer::corsecat_tree() to render the appropriate action for the Expand/Collapse all link on
55 * page load.
56 * @var bool
58 protected $categoryexpandedonload = false;
60 /**
61 * Override the constructor so that we can initialise the string cache
63 * @param moodle_page $page
64 * @param string $target
66 public function __construct(moodle_page $page, $target) {
67 $this->strings = new stdClass;
68 parent::__construct($page, $target);
71 /**
72 * @deprecated since 3.2
74 protected function add_modchoosertoggle() {
75 throw new coding_exception('core_course_renderer::add_modchoosertoggle() can not be used anymore.');
78 /**
79 * Renders course info box.
81 * @param stdClass $course
82 * @return string
84 public function course_info_box(stdClass $course) {
85 $content = '';
86 $content .= $this->output->box_start('generalbox info');
87 $chelper = new coursecat_helper();
88 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
89 $content .= $this->coursecat_coursebox($chelper, $course);
90 $content .= $this->output->box_end();
91 return $content;
94 /**
95 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
97 * @deprecated since 2.5
99 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
101 * @param array $ignored argument ignored
102 * @return string
104 public final function course_category_tree(array $ignored) {
105 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
106 return $this->frontpage_combo_list();
110 * Renderers a category for use with course_category_tree
112 * @deprecated since 2.5
114 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
116 * @param array $category
117 * @param int $depth
118 * @return string
120 protected final function course_category_tree_category(stdClass $category, $depth=1) {
121 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
122 return '';
126 * Render a modchooser.
128 * @param renderable $modchooser The chooser.
129 * @return string
131 public function render_modchooser(renderable $modchooser) {
132 return $this->render_from_template('core_course/modchooser', $modchooser->export_for_template($this));
136 * Build the HTML for the module chooser javascript popup
138 * @param array $modules A set of modules as returned form @see
139 * get_module_metadata
140 * @param object $course The course that will be displayed
141 * @return string The composed HTML for the module
143 public function course_modchooser($modules, $course) {
144 debugging('course_modchooser() is deprecated. Please use course_activitychooser() instead.', DEBUG_DEVELOPER);
146 return $this->course_activitychooser($course->id);
150 * Build the HTML for the module chooser javascript popup.
152 * @param int $courseid The course id to fetch modules for.
153 * @return string
155 public function course_activitychooser($courseid) {
157 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchooser')) {
158 return '';
161 // Build an object of config settings that we can then hook into in the Activity Chooser.
162 $chooserconfig = (object) [
163 'tabmode' => get_config('core', 'activitychoosertabmode'),
165 $this->page->requires->js_call_amd('core_course/activitychooser', 'init', [$courseid, $chooserconfig]);
167 return '';
171 * Build the HTML for a specified set of modules
173 * @param array $modules A set of modules as used by the
174 * course_modchooser_module function
175 * @return string The composed HTML for the module
177 protected function course_modchooser_module_types($modules) {
178 debugging('Method core_course_renderer::course_modchooser_module_types() is deprecated, ' .
179 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
180 return '';
184 * Return the HTML for the specified module adding any required classes
186 * @param object $module An object containing the title, and link. An
187 * icon, and help text may optionally be specified. If the module
188 * contains subtypes in the types option, then these will also be
189 * displayed.
190 * @param array $classes Additional classes to add to the encompassing
191 * div element
192 * @return string The composed HTML for the module
194 protected function course_modchooser_module($module, $classes = array('option')) {
195 debugging('Method core_course_renderer::course_modchooser_module() is deprecated, ' .
196 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
197 return '';
200 protected function course_modchooser_title($title, $identifier = null) {
201 debugging('Method core_course_renderer::course_modchooser_title() is deprecated, ' .
202 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
203 return '';
207 * Renders HTML for displaying the sequence of course module editing buttons
209 * @see course_get_cm_edit_actions()
211 * @param action_link[] $actions Array of action_link objects
212 * @param cm_info $mod The module we are displaying actions for.
213 * @param array $displayoptions additional display options:
214 * ownerselector => A JS/CSS selector that can be used to find an cm node.
215 * If specified the owning node will be given the class 'action-menu-shown' when the action
216 * menu is being displayed.
217 * constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
218 * the action menu to when it is being displayed.
219 * donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
220 * @return string
222 public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
223 global $CFG;
225 if (empty($actions)) {
226 return '';
229 if (isset($displayoptions['ownerselector'])) {
230 $ownerselector = $displayoptions['ownerselector'];
231 } else if ($mod) {
232 $ownerselector = '#module-'.$mod->id;
233 } else {
234 debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
235 $ownerselector = 'li.activity';
238 if (isset($displayoptions['constraintselector'])) {
239 $constraint = $displayoptions['constraintselector'];
240 } else {
241 $constraint = '.course-content';
244 $menu = new action_menu();
245 $menu->set_owner_selector($ownerselector);
246 $menu->set_constraint($constraint);
247 $menu->set_alignment(action_menu::TR, action_menu::BR);
248 $menu->set_menu_trigger(get_string('edit'));
250 foreach ($actions as $action) {
251 if ($action instanceof action_menu_link) {
252 $action->add_class('cm-edit-action');
254 $menu->add($action);
256 $menu->attributes['class'] .= ' section-cm-edit-actions commands';
258 // Prioritise the menu ahead of all other actions.
259 $menu->prioritise = true;
261 return $this->render($menu);
265 * Renders HTML for the menus to add activities and resources to the current course
267 * @param stdClass $course
268 * @param int $section relative section number (field course_sections.section)
269 * @param int $sectionreturn The section to link back to
270 * @param array $displayoptions additional display options, for example blocks add
271 * option 'inblock' => true, suggesting to display controls vertically
272 * @return string
274 function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
275 global $CFG, $USER;
277 // The returned control HTML can be one of the following:
278 // - Only the non-ajax control (select menus of activities and resources) with a noscript fallback for non js clients.
279 // - Only the ajax control (the link which when clicked produces the activity chooser modal). No noscript fallback.
280 // - [Behat only]: The non-ajax control and optionally the ajax control (depending on site settings). If included, the link
281 // takes priority and the non-ajax control is wrapped in a <noscript>.
282 // Behat requires the third case because some features run with JS, some do not. We must include the noscript fallback.
283 $behatsite = defined('BEHAT_SITE_RUNNING');
284 $nonajaxcontrol = '';
285 $ajaxcontrol = '';
286 $courseajaxenabled = course_ajax_enabled($course);
287 $userchooserenabled = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
289 // Decide what combination of controls to output:
290 // During behat runs, both controls can be used in conjunction to provide non-js fallback.
291 // During normal use only one control or the other will be output. No non-js fallback is needed.
292 $rendernonajaxcontrol = $behatsite || !$courseajaxenabled || !$userchooserenabled || $course->id != $this->page->course->id;
293 $renderajaxcontrol = $courseajaxenabled && $userchooserenabled && $course->id == $this->page->course->id;
295 // The non-ajax control, which includes an entirely non-js (<noscript>) fallback too.
296 if ($rendernonajaxcontrol) {
297 $vertical = !empty($displayoptions['inblock']);
299 // Check to see if user can add menus.
300 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
301 || !$this->page->user_is_editing()) {
302 return '';
305 // Retrieve all modules with associated metadata.
306 $contentitemservice = \core_course\local\factory\content_item_service_factory::get_content_item_service();
307 $urlparams = ['section' => $section];
308 if (!is_null($sectionreturn)) {
309 $urlparams['sr'] = $sectionreturn;
311 $modules = $contentitemservice->get_content_items_for_user_in_course($USER, $course, $urlparams);
313 // Return if there are no content items to add.
314 if (empty($modules)) {
315 return '';
318 // We'll sort resources and activities into two lists.
319 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
321 foreach ($modules as $module) {
322 $activityclass = MOD_CLASS_ACTIVITY;
323 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
324 $activityclass = MOD_CLASS_RESOURCE;
325 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
326 // System modules cannot be added by user, do not add to dropdown.
327 continue;
329 $link = $module->link;
330 $activities[$activityclass][$link] = $module->title;
333 $straddactivity = get_string('addactivity');
334 $straddresource = get_string('addresource');
335 $sectionname = get_section_name($course, $section);
336 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
337 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
339 $nonajaxcontrol = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-'
340 . $section));
342 if (!$vertical) {
343 $nonajaxcontrol .= html_writer::start_tag('div', array('class' => 'horizontal'));
346 if (!empty($activities[MOD_CLASS_RESOURCE])) {
347 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array('' => $straddresource), "ressection$section");
348 $select->set_help_icon('resources');
349 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
350 $nonajaxcontrol .= $this->output->render($select);
353 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
354 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array('' => $straddactivity), "section$section");
355 $select->set_help_icon('activities');
356 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
357 $nonajaxcontrol .= $this->output->render($select);
360 if (!$vertical) {
361 $nonajaxcontrol .= html_writer::end_tag('div');
364 $nonajaxcontrol .= html_writer::end_tag('div');
367 // The ajax control - the 'Add an activity or resource' link.
368 if ($renderajaxcontrol) {
369 // The module chooser link.
370 $straddeither = get_string('addresourceoractivity');
371 $ajaxcontrol = html_writer::start_tag('div', array('class' => 'mdl-right'));
372 $ajaxcontrol .= html_writer::start_tag('div', array('class' => 'section-modchooser'));
373 $icon = $this->output->pix_icon('t/add', '');
374 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
375 $ajaxcontrol .= html_writer::tag('button', $icon . $span, [
376 'class' => 'section-modchooser-link btn btn-link',
377 'data-action' => 'open-chooser',
378 'data-sectionid' => $section,
379 'data-sectionreturnid' => $sectionreturn,
382 $ajaxcontrol .= html_writer::end_tag('div');
383 $ajaxcontrol .= html_writer::end_tag('div');
385 // Load the JS for the modal.
386 $this->course_activitychooser($course->id);
389 // Behat only: If both controls are being included in the HTML,
390 // show the link by default and only fall back to the selects if js is disabled.
391 if ($behatsite && $renderajaxcontrol) {
392 $nonajaxcontrol = html_writer::tag('div', $nonajaxcontrol, array('class' => 'hiddenifjs addresourcedropdown'));
393 $ajaxcontrol = html_writer::tag('div', $ajaxcontrol, array('class' => 'visibleifjs addresourcemodchooser'));
396 // If behat is running, we should have the non-ajax control + the ajax control.
397 // Otherwise, we'll have one or the other.
398 return $ajaxcontrol . $nonajaxcontrol;
402 * Renders html to display a course search form
404 * @param string $value default value to populate the search field
405 * @return string
407 public function course_search_form($value = '') {
409 $data = [
410 'action' => \core_search\manager::get_course_search_url(),
411 'btnclass' => 'btn-primary',
412 'inputname' => 'q',
413 'searchstring' => get_string('searchcourses'),
414 'hiddenfields' => (object) ['name' => 'areaids', 'value' => 'core_course-course'],
415 'query' => $value
417 return $this->render_from_template('core/search_input', $data);
421 * Renders html for completion box on course page
423 * If completion is disabled, returns empty string
424 * If completion is automatic, returns an icon of the current completion state
425 * If completion is manual, returns a form (with an icon inside) that allows user to
426 * toggle completion
428 * @param stdClass $course course object
429 * @param completion_info $completioninfo completion info for the course, it is recommended
430 * to fetch once for all modules in course/section for performance
431 * @param cm_info $mod module to show completion for
432 * @param array $displayoptions display options, not used in core
433 * @return string
435 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
436 global $CFG, $DB, $USER;
437 $output = '';
439 $istrackeduser = $completioninfo->is_tracked_user($USER->id);
440 $isediting = $this->page->user_is_editing();
442 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
443 return $output;
445 if ($completioninfo === null) {
446 $completioninfo = new completion_info($course);
448 $completion = $completioninfo->is_enabled($mod);
450 if ($completion == COMPLETION_TRACKING_NONE) {
451 if ($isediting) {
452 $output .= html_writer::span('&nbsp;', 'filler');
454 return $output;
457 $completionicon = '';
459 if ($isediting || !$istrackeduser) {
460 switch ($completion) {
461 case COMPLETION_TRACKING_MANUAL :
462 $completionicon = 'manual-enabled'; break;
463 case COMPLETION_TRACKING_AUTOMATIC :
464 $completionicon = 'auto-enabled'; break;
466 } else {
467 $completiondata = $completioninfo->get_data($mod, true);
468 if ($completion == COMPLETION_TRACKING_MANUAL) {
469 switch($completiondata->completionstate) {
470 case COMPLETION_INCOMPLETE:
471 $completionicon = 'manual-n' . ($completiondata->overrideby ? '-override' : '');
472 break;
473 case COMPLETION_COMPLETE:
474 $completionicon = 'manual-y' . ($completiondata->overrideby ? '-override' : '');
475 break;
477 } else { // Automatic
478 switch($completiondata->completionstate) {
479 case COMPLETION_INCOMPLETE:
480 $completionicon = 'auto-n' . ($completiondata->overrideby ? '-override' : '');
481 break;
482 case COMPLETION_COMPLETE:
483 $completionicon = 'auto-y' . ($completiondata->overrideby ? '-override' : '');
484 break;
485 case COMPLETION_COMPLETE_PASS:
486 $completionicon = 'auto-pass'; break;
487 case COMPLETION_COMPLETE_FAIL:
488 $completionicon = 'auto-fail'; break;
492 if ($completionicon) {
493 $formattedname = html_entity_decode($mod->get_formatted_name(), ENT_QUOTES, 'UTF-8');
494 if (!$isediting && $istrackeduser && $completiondata->overrideby) {
495 $args = new stdClass();
496 $args->modname = $formattedname;
497 $overridebyuser = \core_user::get_user($completiondata->overrideby, '*', MUST_EXIST);
498 $args->overrideuser = fullname($overridebyuser);
499 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $args);
500 } else {
501 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
504 if ($isediting || !$istrackeduser || !has_capability('moodle/course:togglecompletion', $mod->context)) {
505 // When editing, the icon is just an image.
506 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
507 array('title' => $imgalt, 'class' => 'iconsmall'));
508 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
509 array('class' => 'autocompletion'));
510 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
511 $newstate =
512 $completiondata->completionstate == COMPLETION_COMPLETE
513 ? COMPLETION_INCOMPLETE
514 : COMPLETION_COMPLETE;
515 // In manual mode the icon is a toggle form...
517 // If this completion state is used by the
518 // conditional activities system, we need to turn
519 // off the JS.
520 $extraclass = '';
521 if (!empty($CFG->enableavailability) &&
522 core_availability\info::completion_value_used($course, $mod->id)) {
523 $extraclass = ' preventjs';
525 $output .= html_writer::start_tag('form', array('method' => 'post',
526 'action' => new moodle_url('/course/togglecompletion.php'),
527 'class' => 'togglecompletion'. $extraclass));
528 $output .= html_writer::start_tag('div');
529 $output .= html_writer::empty_tag('input', array(
530 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
531 $output .= html_writer::empty_tag('input', array(
532 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
533 $output .= html_writer::empty_tag('input', array(
534 'type' => 'hidden', 'name' => 'modulename', 'value' => $formattedname));
535 $output .= html_writer::empty_tag('input', array(
536 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
537 $output .= html_writer::tag('button',
538 $this->output->pix_icon('i/completion-' . $completionicon, $imgalt),
539 array('class' => 'btn btn-link', 'aria-live' => 'assertive'));
540 $output .= html_writer::end_tag('div');
541 $output .= html_writer::end_tag('form');
542 } else {
543 // In auto mode, the icon is just an image.
544 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
545 array('title' => $imgalt));
546 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
547 array('class' => 'autocompletion'));
550 return $output;
554 * Checks if course module has any conditions that may make it unavailable for
555 * all or some of the students
557 * This function is internal and is only used to create CSS classes for the module name/text
559 * @param cm_info $mod
560 * @return bool
562 protected function is_cm_conditionally_hidden(cm_info $mod) {
563 global $CFG;
564 $conditionalhidden = false;
565 if (!empty($CFG->enableavailability)) {
566 $info = new \core_availability\info_module($mod);
567 $conditionalhidden = !$info->is_available_for_all();
569 return $conditionalhidden;
573 * Renders html to display a name with the link to the course module on a course page
575 * If module is unavailable for user but still needs to be displayed
576 * in the list, just the name is returned without a link
578 * Note, that for course modules that never have separate pages (i.e. labels)
579 * this function return an empty string
581 * @param cm_info $mod
582 * @param array $displayoptions
583 * @return string
585 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
586 if (!$mod->is_visible_on_course_page() || !$mod->url) {
587 // Nothing to be displayed to the user.
588 return '';
591 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
592 $groupinglabel = $mod->get_grouping_label($textclasses);
594 // Render element that allows to edit activity name inline. It calls {@link course_section_cm_name_title()}
595 // to get the display title of the activity.
596 $tmpl = new \core_course\output\course_module_name($mod, $this->page->user_is_editing(), $displayoptions);
597 return $this->output->render_from_template('core/inplace_editable', $tmpl->export_for_template($this->output)) .
598 $groupinglabel;
602 * Returns the CSS classes for the activity name/content
604 * For items which are hidden, unavailable or stealth but should be displayed
605 * to current user ($mod->is_visible_on_course_page()), we show those as dimmed.
606 * Students will also see as dimmed activities names that are not yet available
607 * but should still be displayed (without link) with availability info.
609 * @param cm_info $mod
610 * @return array array of two elements ($linkclasses, $textclasses)
612 protected function course_section_cm_classes(cm_info $mod) {
613 $linkclasses = '';
614 $textclasses = '';
615 if ($mod->uservisible) {
616 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
617 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
618 has_capability('moodle/course:viewhiddenactivities', $mod->context);
619 if ($accessiblebutdim) {
620 $linkclasses .= ' dimmed';
621 $textclasses .= ' dimmed_text';
622 if ($conditionalhidden) {
623 $linkclasses .= ' conditionalhidden';
624 $textclasses .= ' conditionalhidden';
627 if ($mod->is_stealth()) {
628 // Stealth activity is the one that is not visible on course page.
629 // It still may be displayed to the users who can manage it.
630 $linkclasses .= ' stealth';
631 $textclasses .= ' stealth';
633 } else {
634 $linkclasses .= ' dimmed';
635 $textclasses .= ' dimmed dimmed_text';
637 return array($linkclasses, $textclasses);
641 * Renders html to display a name with the link to the course module on a course page
643 * If module is unavailable for user but still needs to be displayed
644 * in the list, just the name is returned without a link
646 * Note, that for course modules that never have separate pages (i.e. labels)
647 * this function return an empty string
649 * @param cm_info $mod
650 * @param array $displayoptions
651 * @return string
653 public function course_section_cm_name_title(cm_info $mod, $displayoptions = array()) {
654 $output = '';
655 $url = $mod->url;
656 if (!$mod->is_visible_on_course_page() || !$url) {
657 // Nothing to be displayed to the user.
658 return $output;
661 //Accessibility: for files get description via icon, this is very ugly hack!
662 $instancename = $mod->get_formatted_name();
663 $altname = $mod->modfullname;
664 // Avoid unnecessary duplication: if e.g. a forum name already
665 // includes the word forum (or Forum, etc) then it is unhelpful
666 // to include that in the accessible description that is added.
667 if (false !== strpos(core_text::strtolower($instancename),
668 core_text::strtolower($altname))) {
669 $altname = '';
671 // File type after name, for alphabetic lists (screen reader).
672 if ($altname) {
673 $altname = get_accesshide(' '.$altname);
676 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
678 // Get on-click attribute value if specified and decode the onclick - it
679 // has already been encoded for display (puke).
680 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
682 // Display link itself.
683 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
684 'class' => 'iconlarge activityicon', 'alt' => '', 'role' => 'presentation', 'aria-hidden' => 'true')) .
685 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
686 if ($mod->uservisible) {
687 $output .= html_writer::link($url, $activitylink, array('class' => 'aalink' . $linkclasses, 'onclick' => $onclick));
688 } else {
689 // We may be displaying this just in order to show information
690 // about visibility, without the actual link ($mod->is_visible_on_course_page()).
691 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses));
693 return $output;
697 * Renders html to display the module content on the course page (i.e. text of the labels)
699 * @param cm_info $mod
700 * @param array $displayoptions
701 * @return string
703 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
704 $output = '';
705 if (!$mod->is_visible_on_course_page()) {
706 // nothing to be displayed to the user
707 return $output;
709 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
710 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
711 if ($mod->url && $mod->uservisible) {
712 if ($content) {
713 // If specified, display extra content after link.
714 $output = html_writer::tag('div', $content, array('class' =>
715 trim('contentafterlink ' . $textclasses)));
717 } else {
718 $groupinglabel = $mod->get_grouping_label($textclasses);
720 // No link, so display only content.
721 $output = html_writer::tag('div', $content . $groupinglabel,
722 array('class' => 'contentwithoutlink ' . $textclasses));
724 return $output;
728 * Displays availability info for a course section or course module
730 * @param string $text
731 * @param string $additionalclasses
732 * @return string
734 public function availability_info($text, $additionalclasses = '') {
736 $data = ['text' => $text, 'classes' => $additionalclasses];
737 $additionalclasses = array_filter(explode(' ', $additionalclasses));
739 if (in_array('ishidden', $additionalclasses)) {
740 $data['ishidden'] = 1;
742 } else if (in_array('isstealth', $additionalclasses)) {
743 $data['isstealth'] = 1;
745 } else if (in_array('isrestricted', $additionalclasses)) {
746 $data['isrestricted'] = 1;
748 if (in_array('isfullinfo', $additionalclasses)) {
749 $data['isfullinfo'] = 1;
753 return $this->render_from_template('core/availability_info', $data);
757 * Renders HTML to show course module availability information (for someone who isn't allowed
758 * to see the activity itself, or for staff)
760 * @param cm_info $mod
761 * @param array $displayoptions
762 * @return string
764 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
765 global $CFG;
766 $output = '';
767 if (!$mod->is_visible_on_course_page()) {
768 return $output;
770 if (!$mod->uservisible) {
771 // this is a student who is not allowed to see the module but might be allowed
772 // to see availability info (i.e. "Available from ...")
773 if (!empty($mod->availableinfo)) {
774 $formattedinfo = \core_availability\info::format_info(
775 $mod->availableinfo, $mod->get_course());
776 $output = $this->availability_info($formattedinfo, 'isrestricted');
778 return $output;
780 // this is a teacher who is allowed to see module but still should see the
781 // information that module is not available to all/some students
782 $modcontext = context_module::instance($mod->id);
783 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
784 if ($canviewhidden && !$mod->visible) {
785 // This module is hidden but current user has capability to see it.
786 // Do not display the availability info if the whole section is hidden.
787 if ($mod->get_section_info()->visible) {
788 $output .= $this->availability_info(get_string('hiddenfromstudents'), 'ishidden');
790 } else if ($mod->is_stealth()) {
791 // This module is available but is normally not displayed on the course page
792 // (this user can see it because they can manage it).
793 $output .= $this->availability_info(get_string('hiddenoncoursepage'), 'isstealth');
795 if ($canviewhidden && !empty($CFG->enableavailability)) {
796 // Display information about conditional availability.
797 // Don't add availability information if user is not editing and activity is hidden.
798 if ($mod->visible || $this->page->user_is_editing()) {
799 $hidinfoclass = 'isrestricted isfullinfo';
800 if (!$mod->visible) {
801 $hidinfoclass .= ' hide';
803 $ci = new \core_availability\info_module($mod);
804 $fullinfo = $ci->get_full_information();
805 if ($fullinfo) {
806 $formattedinfo = \core_availability\info::format_info(
807 $fullinfo, $mod->get_course());
808 $output .= $this->availability_info($formattedinfo, $hidinfoclass);
812 return $output;
816 * Renders HTML to display one course module for display within a section.
818 * This function calls:
819 * {@link core_course_renderer::course_section_cm()}
821 * @param stdClass $course
822 * @param completion_info $completioninfo
823 * @param cm_info $mod
824 * @param int|null $sectionreturn
825 * @param array $displayoptions
826 * @return String
828 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
829 $output = '';
830 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
831 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
832 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
834 return $output;
838 * Renders HTML to display one course module in a course section
840 * This includes link, content, availability, completion info and additional information
841 * that module type wants to display (i.e. number of unread forum posts)
843 * This function calls:
844 * {@link core_course_renderer::course_section_cm_name()}
845 * {@link core_course_renderer::course_section_cm_text()}
846 * {@link core_course_renderer::course_section_cm_availability()}
847 * {@link core_course_renderer::course_section_cm_completion()}
848 * {@link course_get_cm_edit_actions()}
849 * {@link core_course_renderer::course_section_cm_edit_actions()}
851 * @param stdClass $course
852 * @param completion_info $completioninfo
853 * @param cm_info $mod
854 * @param int|null $sectionreturn
855 * @param array $displayoptions
856 * @return string
858 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
859 $output = '';
860 // We return empty string (because course module will not be displayed at all)
861 // if:
862 // 1) The activity is not visible to users
863 // and
864 // 2) The 'availableinfo' is empty, i.e. the activity was
865 // hidden in a way that leaves no info, such as using the
866 // eye icon.
867 if (!$mod->is_visible_on_course_page()) {
868 return $output;
871 $indentclasses = 'mod-indent';
872 if (!empty($mod->indent)) {
873 $indentclasses .= ' mod-indent-'.$mod->indent;
874 if ($mod->indent > 15) {
875 $indentclasses .= ' mod-indent-huge';
879 $output .= html_writer::start_tag('div');
881 if ($this->page->user_is_editing()) {
882 $output .= course_get_cm_move($mod, $sectionreturn);
885 $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer w-100'));
887 // This div is used to indent the content.
888 $output .= html_writer::div('', $indentclasses);
890 // Start a wrapper for the actual content to keep the indentation consistent
891 $output .= html_writer::start_tag('div');
893 // Display the link to the module (or do nothing if module has no url)
894 $cmname = $this->course_section_cm_name($mod, $displayoptions);
896 if (!empty($cmname)) {
897 // Start the div for the activity title, excluding the edit icons.
898 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
899 $output .= $cmname;
902 // Module can put text after the link (e.g. forum unread)
903 $output .= $mod->afterlink;
905 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
906 $output .= html_writer::end_tag('div'); // .activityinstance
909 // If there is content but NO link (eg label), then display the
910 // content here (BEFORE any icons). In this case cons must be
911 // displayed after the content so that it makes more sense visually
912 // and for accessibility reasons, e.g. if you have a one-line label
913 // it should work similarly (at least in terms of ordering) to an
914 // activity.
915 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
916 $url = $mod->url;
917 if (empty($url)) {
918 $output .= $contentpart;
921 $modicons = '';
922 if ($this->page->user_is_editing()) {
923 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
924 $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
925 $modicons .= $mod->afterediticons;
928 $modicons .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
930 if (!empty($modicons)) {
931 $output .= html_writer::div($modicons, 'actions');
934 // Show availability info (if module is not available).
935 $output .= $this->course_section_cm_availability($mod, $displayoptions);
937 // If there is content AND a link, then display the content here
938 // (AFTER any icons). Otherwise it was displayed before
939 if (!empty($url)) {
940 $output .= $contentpart;
943 $output .= html_writer::end_tag('div'); // $indentclasses
945 // End of indentation div.
946 $output .= html_writer::end_tag('div');
948 $output .= html_writer::end_tag('div');
949 return $output;
953 * Message displayed to the user when they try to access unavailable activity following URL
955 * This method is a very simplified version of {@link course_section_cm()} to be part of the error
956 * notification only. It also does not check if module is visible on course page or not.
958 * The message will be displayed inside notification!
960 * @param cm_info $cm
961 * @return string
963 public function course_section_cm_unavailable_error_message(cm_info $cm) {
964 if ($cm->uservisible) {
965 return null;
967 if (!$cm->availableinfo) {
968 return get_string('activityiscurrentlyhidden');
971 $altname = get_accesshide(' ' . $cm->modfullname);
972 $name = html_writer::empty_tag('img', array('src' => $cm->get_icon_url(),
973 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
974 html_writer::tag('span', ' '.$cm->get_formatted_name() . $altname, array('class' => 'instancename'));
975 $formattedinfo = \core_availability\info::format_info($cm->availableinfo, $cm->get_course());
976 return html_writer::div($name, 'activityinstance-error') .
977 html_writer::div($formattedinfo, 'availabilityinfo-error');
981 * Renders HTML to display a list of course modules in a course section
982 * Also displays "move here" controls in Javascript-disabled mode
984 * This function calls {@link core_course_renderer::course_section_cm()}
986 * @param stdClass $course course object
987 * @param int|stdClass|section_info $section relative section number or section object
988 * @param int $sectionreturn section number to return to
989 * @param int $displayoptions
990 * @return void
992 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
993 global $USER;
995 $output = '';
996 $modinfo = get_fast_modinfo($course);
997 if (is_object($section)) {
998 $section = $modinfo->get_section_info($section->section);
999 } else {
1000 $section = $modinfo->get_section_info($section);
1002 $completioninfo = new completion_info($course);
1004 // check if we are currently in the process of moving a module with JavaScript disabled
1005 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
1006 if ($ismoving) {
1007 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
1008 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1011 // Get the list of modules visible to user (excluding the module being moved if there is one)
1012 $moduleshtml = array();
1013 if (!empty($modinfo->sections[$section->section])) {
1014 foreach ($modinfo->sections[$section->section] as $modnumber) {
1015 $mod = $modinfo->cms[$modnumber];
1017 if ($ismoving and $mod->id == $USER->activitycopy) {
1018 // do not display moving mod
1019 continue;
1022 if ($modulehtml = $this->course_section_cm_list_item($course,
1023 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
1024 $moduleshtml[$modnumber] = $modulehtml;
1029 $sectionoutput = '';
1030 if (!empty($moduleshtml) || $ismoving) {
1031 foreach ($moduleshtml as $modnumber => $modulehtml) {
1032 if ($ismoving) {
1033 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
1034 $sectionoutput .= html_writer::tag('li',
1035 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1036 array('class' => 'movehere'));
1039 $sectionoutput .= $modulehtml;
1042 if ($ismoving) {
1043 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1044 $sectionoutput .= html_writer::tag('li',
1045 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1046 array('class' => 'movehere'));
1050 // Always output the section module list.
1051 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1053 return $output;
1057 * Displays a custom list of courses with paging bar if necessary
1059 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1060 * appears under the list.
1062 * If both $paginationurl and $totalcount are specified, and $totalcount is
1063 * bigger than count($courses), a paging bar is displayed above and under the
1064 * courses list.
1066 * @param array $courses array of course records (or instances of core_course_list_element) to show on this page
1067 * @param bool $showcategoryname whether to add category name to the course description
1068 * @param string $additionalclasses additional CSS classes to add to the div.courses
1069 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1070 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1071 * @param int $page current page number (defaults to 0 referring to the first page)
1072 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1073 * @return string
1075 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1076 global $CFG;
1077 // create instance of coursecat_helper to pass display options to function rendering courses list
1078 $chelper = new coursecat_helper();
1079 if ($showcategoryname) {
1080 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1081 } else {
1082 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1084 if ($totalcount !== null && $paginationurl !== null) {
1085 // add options to display pagination
1086 if ($perpage === null) {
1087 $perpage = $CFG->coursesperpage;
1089 $chelper->set_courses_display_options(array(
1090 'limit' => $perpage,
1091 'offset' => ((int)$page) * $perpage,
1092 'paginationurl' => $paginationurl,
1094 } else if ($paginationurl !== null) {
1095 // add options to display 'View more' link
1096 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1097 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1099 $chelper->set_attributes(array('class' => $additionalclasses));
1100 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1101 return $content;
1105 * Returns HTML to display course name.
1107 * @param coursecat_helper $chelper
1108 * @param core_course_list_element $course
1109 * @return string
1111 protected function course_name(coursecat_helper $chelper, core_course_list_element $course): string {
1112 $content = '';
1113 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1114 $nametag = 'h3';
1115 } else {
1116 $nametag = 'div';
1118 $coursename = $chelper->get_course_formatted_name($course);
1119 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', ['id' => $course->id]),
1120 $coursename, ['class' => $course->visible ? 'aalink' : 'aalink dimmed']);
1121 $content .= html_writer::tag($nametag, $coursenamelink, ['class' => 'coursename']);
1122 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1123 $content .= html_writer::start_tag('div', ['class' => 'moreinfo']);
1124 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1125 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()
1126 || $course->has_custom_fields()) {
1127 $url = new moodle_url('/course/info.php', ['id' => $course->id]);
1128 $image = $this->output->pix_icon('i/info', $this->strings->summary);
1129 $content .= html_writer::link($url, $image, ['title' => $this->strings->summary]);
1130 // Make sure JS file to expand course content is included.
1131 $this->coursecat_include_js();
1134 $content .= html_writer::end_tag('div');
1135 return $content;
1139 * Returns HTML to display course enrolment icons.
1141 * @param core_course_list_element $course
1142 * @return string
1144 protected function course_enrolment_icons(core_course_list_element $course): string {
1145 $content = '';
1146 if ($icons = enrol_get_course_info_icons($course)) {
1147 $content .= html_writer::start_tag('div', ['class' => 'enrolmenticons']);
1148 foreach ($icons as $icon) {
1149 $content .= $this->render($icon);
1151 $content .= html_writer::end_tag('div');
1153 return $content;
1157 * Displays one course in the list of courses.
1159 * This is an internal function, to display an information about just one course
1160 * please use {@link core_course_renderer::course_info_box()}
1162 * @param coursecat_helper $chelper various display options
1163 * @param core_course_list_element|stdClass $course
1164 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1165 * depend on the course position in list - first/last/even/odd)
1166 * @return string
1168 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1169 if (!isset($this->strings->summary)) {
1170 $this->strings->summary = get_string('summary');
1172 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1173 return '';
1175 if ($course instanceof stdClass) {
1176 $course = new core_course_list_element($course);
1178 $content = '';
1179 $classes = trim('coursebox clearfix '. $additionalclasses);
1180 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1181 $classes .= ' collapsed';
1184 // .coursebox
1185 $content .= html_writer::start_tag('div', array(
1186 'class' => $classes,
1187 'data-courseid' => $course->id,
1188 'data-type' => self::COURSECAT_TYPE_COURSE,
1191 $content .= html_writer::start_tag('div', array('class' => 'info'));
1192 $content .= $this->course_name($chelper, $course);
1193 $content .= $this->course_enrolment_icons($course);
1194 $content .= html_writer::end_tag('div');
1196 $content .= html_writer::start_tag('div', array('class' => 'content'));
1197 $content .= $this->coursecat_coursebox_content($chelper, $course);
1198 $content .= html_writer::end_tag('div');
1200 $content .= html_writer::end_tag('div'); // .coursebox
1201 return $content;
1205 * Returns HTML to display course summary.
1207 * @param coursecat_helper $chelper
1208 * @param core_course_list_element $course
1209 * @return string
1211 protected function course_summary(coursecat_helper $chelper, core_course_list_element $course): string {
1212 $content = '';
1213 if ($course->has_summary()) {
1214 $content .= html_writer::start_tag('div', ['class' => 'summary']);
1215 $content .= $chelper->get_course_formatted_summary($course,
1216 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1217 $content .= html_writer::end_tag('div');
1219 return $content;
1223 * Returns HTML to display course contacts.
1225 * @param core_course_list_element $course
1226 * @return string
1228 protected function course_contacts(core_course_list_element $course) {
1229 $content = '';
1230 if ($course->has_course_contacts()) {
1231 $content .= html_writer::start_tag('ul', ['class' => 'teachers']);
1232 foreach ($course->get_course_contacts() as $coursecontact) {
1233 $rolenames = array_map(function ($role) {
1234 return $role->displayname;
1235 }, $coursecontact['roles']);
1236 $name = implode(", ", $rolenames).': '.
1237 html_writer::link(new moodle_url('/user/view.php',
1238 ['id' => $coursecontact['user']->id, 'course' => SITEID]),
1239 $coursecontact['username']);
1240 $content .= html_writer::tag('li', $name);
1242 $content .= html_writer::end_tag('ul');
1244 return $content;
1248 * Returns HTML to display course overview files.
1250 * @param core_course_list_element $course
1251 * @return string
1253 protected function course_overview_files(core_course_list_element $course): string {
1254 global $CFG;
1256 $contentimages = $contentfiles = '';
1257 foreach ($course->get_course_overviewfiles() as $file) {
1258 $isimage = $file->is_valid_image();
1259 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php",
1260 '/' . $file->get_contextid() . '/' . $file->get_component() . '/' .
1261 $file->get_filearea() . $file->get_filepath() . $file->get_filename(), !$isimage);
1262 if ($isimage) {
1263 $contentimages .= html_writer::tag('div',
1264 html_writer::empty_tag('img', ['src' => $url]),
1265 ['class' => 'courseimage']);
1266 } else {
1267 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1268 $filename = html_writer::tag('span', $image, ['class' => 'fp-icon']).
1269 html_writer::tag('span', $file->get_filename(), ['class' => 'fp-filename']);
1270 $contentfiles .= html_writer::tag('span',
1271 html_writer::link($url, $filename),
1272 ['class' => 'coursefile fp-filename-icon']);
1275 return $contentimages . $contentfiles;
1279 * Returns HTML to display course category name.
1281 * @param coursecat_helper $chelper
1282 * @param core_course_list_element $course
1283 * @return string
1285 protected function course_category_name(coursecat_helper $chelper, core_course_list_element $course): string {
1286 $content = '';
1287 // Display course category if necessary (for example in search results).
1288 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1289 if ($cat = core_course_category::get($course->category, IGNORE_MISSING)) {
1290 $content .= html_writer::start_tag('div', ['class' => 'coursecat']);
1291 $content .= get_string('category').': '.
1292 html_writer::link(new moodle_url('/course/index.php', ['categoryid' => $cat->id]),
1293 $cat->get_formatted_name(), ['class' => $cat->visible ? '' : 'dimmed']);
1294 $content .= html_writer::end_tag('div');
1297 return $content;
1301 * Returns HTML to display course custom fields.
1303 * @param core_course_list_element $course
1304 * @return string
1306 protected function course_custom_fields(core_course_list_element $course): string {
1307 $content = '';
1308 if ($course->has_custom_fields()) {
1309 $handler = core_course\customfield\course_handler::create();
1310 $customfields = $handler->display_custom_fields_data($course->get_custom_fields());
1311 $content .= \html_writer::tag('div', $customfields, ['class' => 'customfields-container']);
1313 return $content;
1317 * Returns HTML to display course content (summary, course contacts and optionally category name)
1319 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1321 * @param coursecat_helper $chelper various display options
1322 * @param stdClass|core_course_list_element $course
1323 * @return string
1325 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1326 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1327 return '';
1329 if ($course instanceof stdClass) {
1330 $course = new core_course_list_element($course);
1332 $content = $this->course_summary($chelper, $course);
1333 $content .= $this->course_overview_files($course);
1334 $content .= $this->course_contacts($course);
1335 $content .= $this->course_category_name($chelper, $course);
1336 $content .= $this->course_custom_fields($course);
1337 return $content;
1341 * Renders the list of courses
1343 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1344 * method from outside of the class
1346 * If list of courses is specified in $courses; the argument $chelper is only used
1347 * to retrieve display options and attributes, only methods get_show_courses(),
1348 * get_courses_display_option() and get_and_erase_attributes() are called.
1350 * @param coursecat_helper $chelper various display options
1351 * @param array $courses the list of courses to display
1352 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1353 * defaulted to count($courses)
1354 * @return string
1356 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1357 global $CFG;
1358 if ($totalcount === null) {
1359 $totalcount = count($courses);
1361 if (!$totalcount) {
1362 // Courses count is cached during courses retrieval.
1363 return '';
1366 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1367 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1368 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1369 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1370 } else {
1371 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1375 // prepare content of paging bar if it is needed
1376 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1377 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1378 if ($totalcount > count($courses)) {
1379 // there are more results that can fit on one page
1380 if ($paginationurl) {
1381 // the option paginationurl was specified, display pagingbar
1382 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1383 $page = $chelper->get_courses_display_option('offset') / $perpage;
1384 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1385 $paginationurl->out(false, array('perpage' => $perpage)));
1386 if ($paginationallowall) {
1387 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1388 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1390 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1391 // the option for 'View more' link was specified, display more link
1392 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1393 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1394 array('class' => 'paging paging-morelink'));
1396 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1397 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1398 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1399 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1402 // display list of courses
1403 $attributes = $chelper->get_and_erase_attributes('courses');
1404 $content = html_writer::start_tag('div', $attributes);
1406 if (!empty($pagingbar)) {
1407 $content .= $pagingbar;
1410 $coursecount = 0;
1411 foreach ($courses as $course) {
1412 $coursecount ++;
1413 $classes = ($coursecount%2) ? 'odd' : 'even';
1414 if ($coursecount == 1) {
1415 $classes .= ' first';
1417 if ($coursecount >= count($courses)) {
1418 $classes .= ' last';
1420 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1423 if (!empty($pagingbar)) {
1424 $content .= $pagingbar;
1426 if (!empty($morelink)) {
1427 $content .= $morelink;
1430 $content .= html_writer::end_tag('div'); // .courses
1431 return $content;
1435 * Renders the list of subcategories in a category
1437 * @param coursecat_helper $chelper various display options
1438 * @param core_course_category $coursecat
1439 * @param int $depth depth of the category in the current tree
1440 * @return string
1442 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1443 global $CFG;
1444 $subcategories = array();
1445 if (!$chelper->get_categories_display_option('nodisplay')) {
1446 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1448 $totalcount = $coursecat->get_children_count();
1449 if (!$totalcount) {
1450 // Note that we call core_course_category::get_children_count() AFTER core_course_category::get_children()
1451 // to avoid extra DB requests.
1452 // Categories count is cached during children categories retrieval.
1453 return '';
1456 // prepare content of paging bar or more link if it is needed
1457 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1458 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1459 if ($totalcount > count($subcategories)) {
1460 if ($paginationurl) {
1461 // the option 'paginationurl was specified, display pagingbar
1462 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1463 $page = $chelper->get_categories_display_option('offset') / $perpage;
1464 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1465 $paginationurl->out(false, array('perpage' => $perpage)));
1466 if ($paginationallowall) {
1467 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1468 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1470 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1471 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1472 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1473 $viewmoreurl->param('categoryid', $coursecat->id);
1475 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1476 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1477 array('class' => 'paging paging-morelink'));
1479 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1480 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1481 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1482 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1485 // display list of subcategories
1486 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1488 if (!empty($pagingbar)) {
1489 $content .= $pagingbar;
1492 foreach ($subcategories as $subcategory) {
1493 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1496 if (!empty($pagingbar)) {
1497 $content .= $pagingbar;
1499 if (!empty($morelink)) {
1500 $content .= $morelink;
1503 $content .= html_writer::end_tag('div');
1504 return $content;
1508 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1510 protected function coursecat_include_js() {
1511 if (!$this->page->requires->should_create_one_time_item_now('core_course_categoryexpanderjsinit')) {
1512 return;
1515 // We must only load this module once.
1516 $this->page->requires->yui_module('moodle-course-categoryexpander',
1517 'Y.Moodle.course.categoryexpander.init');
1521 * Returns HTML to display the subcategories and courses in the given category
1523 * This method is re-used by AJAX to expand content of not loaded category
1525 * @param coursecat_helper $chelper various display options
1526 * @param core_course_category $coursecat
1527 * @param int $depth depth of the category in the current tree
1528 * @return string
1530 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1531 $content = '';
1532 // Subcategories
1533 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1535 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1536 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1537 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1538 if ($showcoursesauto && $depth) {
1539 // this is definitely collapsed mode
1540 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1543 // Courses
1544 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1545 $courses = array();
1546 if (!$chelper->get_courses_display_option('nodisplay')) {
1547 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1549 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1550 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1551 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1552 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1555 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1558 if ($showcoursesauto) {
1559 // restore the show_courses back to AUTO
1560 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1563 return $content;
1567 * Returns HTML to display a course category as a part of a tree
1569 * This is an internal function, to display a particular category and all its contents
1570 * use {@link core_course_renderer::course_category()}
1572 * @param coursecat_helper $chelper various display options
1573 * @param core_course_category $coursecat
1574 * @param int $depth depth of this category in the current tree
1575 * @return string
1577 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1578 // open category tag
1579 $classes = array('category');
1580 if (empty($coursecat->visible)) {
1581 $classes[] = 'dimmed_category';
1583 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1584 // do not load content
1585 $categorycontent = '';
1586 $classes[] = 'notloaded';
1587 if ($coursecat->get_children_count() ||
1588 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1589 $classes[] = 'with_children';
1590 $classes[] = 'collapsed';
1592 } else {
1593 // load category content
1594 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1595 $classes[] = 'loaded';
1596 if (!empty($categorycontent)) {
1597 $classes[] = 'with_children';
1598 // Category content loaded with children.
1599 $this->categoryexpandedonload = true;
1603 // Make sure JS file to expand category content is included.
1604 $this->coursecat_include_js();
1606 $content = html_writer::start_tag('div', array(
1607 'class' => join(' ', $classes),
1608 'data-categoryid' => $coursecat->id,
1609 'data-depth' => $depth,
1610 'data-showcourses' => $chelper->get_show_courses(),
1611 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1614 // category name
1615 $categoryname = $coursecat->get_formatted_name();
1616 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1617 array('categoryid' => $coursecat->id)),
1618 $categoryname);
1619 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1620 && ($coursescount = $coursecat->get_courses_count())) {
1621 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1622 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1624 $content .= html_writer::start_tag('div', array('class' => 'info'));
1626 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname aabtn'));
1627 $content .= html_writer::end_tag('div'); // .info
1629 // add category content to the output
1630 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1632 $content .= html_writer::end_tag('div'); // .category
1634 // Return the course category tree HTML
1635 return $content;
1639 * Returns HTML to display a tree of subcategories and courses in the given category
1641 * @param coursecat_helper $chelper various display options
1642 * @param core_course_category $coursecat top category (this category's name and description will NOT be added to the tree)
1643 * @return string
1645 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1646 // Reset the category expanded flag for this course category tree first.
1647 $this->categoryexpandedonload = false;
1648 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1649 if (empty($categorycontent)) {
1650 return '';
1653 // Start content generation
1654 $content = '';
1655 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1656 $content .= html_writer::start_tag('div', $attributes);
1658 if ($coursecat->get_children_count()) {
1659 $classes = array(
1660 'collapseexpand', 'aabtn'
1663 // Check if the category content contains subcategories with children's content loaded.
1664 if ($this->categoryexpandedonload) {
1665 $classes[] = 'collapse-all';
1666 $linkname = get_string('collapseall');
1667 } else {
1668 $linkname = get_string('expandall');
1671 // Only show the collapse/expand if there are children to expand.
1672 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1673 $content .= html_writer::link('#', $linkname, array('class' => implode(' ', $classes)));
1674 $content .= html_writer::end_tag('div');
1675 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1678 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1680 $content .= html_writer::end_tag('div'); // .course_category_tree
1682 return $content;
1686 * Renders HTML to display particular course category - list of it's subcategories and courses
1688 * Invoked from /course/index.php
1690 * @param int|stdClass|core_course_category $category
1692 public function course_category($category) {
1693 global $CFG;
1694 $usertop = core_course_category::user_top();
1695 if (empty($category)) {
1696 $coursecat = $usertop;
1697 } else if (is_object($category) && $category instanceof core_course_category) {
1698 $coursecat = $category;
1699 } else {
1700 $coursecat = core_course_category::get(is_object($category) ? $category->id : $category);
1702 $site = get_site();
1703 $output = '';
1705 if ($coursecat->can_create_course() || $coursecat->has_manage_capability()) {
1706 // Add 'Manage' button if user has permissions to edit this category.
1707 $managebutton = $this->single_button(new moodle_url('/course/management.php',
1708 array('categoryid' => $coursecat->id)), get_string('managecourses'), 'get');
1709 $this->page->set_button($managebutton);
1712 if (core_course_category::is_simple_site()) {
1713 // There is only one category in the system, do not display link to it.
1714 $strfulllistofcourses = get_string('fulllistofcourses');
1715 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1716 } else if (!$coursecat->id || !$coursecat->is_uservisible()) {
1717 $strcategories = get_string('categories');
1718 $this->page->set_title("$site->shortname: $strcategories");
1719 } else {
1720 $strfulllistofcourses = get_string('fulllistofcourses');
1721 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1723 // Print the category selector
1724 $categorieslist = core_course_category::make_categories_list();
1725 if (count($categorieslist) > 1) {
1726 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1727 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1728 core_course_category::make_categories_list(), $coursecat->id, null, 'switchcategory');
1729 $select->set_label(get_string('categories').':');
1730 $output .= $this->render($select);
1731 $output .= html_writer::end_tag('div'); // .categorypicker
1735 // Print current category description
1736 $chelper = new coursecat_helper();
1737 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1738 $output .= $this->box($description, array('class' => 'generalbox info'));
1741 // Prepare parameters for courses and categories lists in the tree
1742 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1743 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1745 $coursedisplayoptions = array();
1746 $catdisplayoptions = array();
1747 $browse = optional_param('browse', null, PARAM_ALPHA);
1748 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1749 $page = optional_param('page', 0, PARAM_INT);
1750 $baseurl = new moodle_url('/course/index.php');
1751 if ($coursecat->id) {
1752 $baseurl->param('categoryid', $coursecat->id);
1754 if ($perpage != $CFG->coursesperpage) {
1755 $baseurl->param('perpage', $perpage);
1757 $coursedisplayoptions['limit'] = $perpage;
1758 $catdisplayoptions['limit'] = $perpage;
1759 if ($browse === 'courses' || !$coursecat->get_children_count()) {
1760 $coursedisplayoptions['offset'] = $page * $perpage;
1761 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1762 $catdisplayoptions['nodisplay'] = true;
1763 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1764 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1765 } else if ($browse === 'categories' || !$coursecat->get_courses_count()) {
1766 $coursedisplayoptions['nodisplay'] = true;
1767 $catdisplayoptions['offset'] = $page * $perpage;
1768 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1769 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1770 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1771 } else {
1772 // we have a category that has both subcategories and courses, display pagination separately
1773 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1774 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1776 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1777 // Add course search form.
1778 $output .= $this->course_search_form();
1780 // Display course category tree.
1781 $output .= $this->coursecat_tree($chelper, $coursecat);
1783 // Add action buttons
1784 $output .= $this->container_start('buttons');
1785 if ($coursecat->is_uservisible()) {
1786 $context = get_category_or_system_context($coursecat->id);
1787 if (has_capability('moodle/course:create', $context)) {
1788 // Print link to create a new course, for the 1st available category.
1789 if ($coursecat->id) {
1790 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1791 } else {
1792 $url = new moodle_url('/course/edit.php',
1793 array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1795 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1797 ob_start();
1798 print_course_request_buttons($context);
1799 $output .= ob_get_contents();
1800 ob_end_clean();
1802 $output .= $this->container_end();
1804 return $output;
1808 * Serves requests to /course/category.ajax.php
1810 * In this renderer implementation it may expand the category content or
1811 * course content.
1813 * @return string
1814 * @throws coding_exception
1816 public function coursecat_ajax() {
1817 global $DB, $CFG;
1819 $type = required_param('type', PARAM_INT);
1821 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1822 // This is a request for a category list of some kind.
1823 $categoryid = required_param('categoryid', PARAM_INT);
1824 $showcourses = required_param('showcourses', PARAM_INT);
1825 $depth = required_param('depth', PARAM_INT);
1827 $category = core_course_category::get($categoryid);
1829 $chelper = new coursecat_helper();
1830 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1831 $coursedisplayoptions = array(
1832 'limit' => $CFG->coursesperpage,
1833 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1835 $catdisplayoptions = array(
1836 'limit' => $CFG->coursesperpage,
1837 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1839 $chelper->set_show_courses($showcourses)->
1840 set_courses_display_options($coursedisplayoptions)->
1841 set_categories_display_options($catdisplayoptions);
1843 return $this->coursecat_category_content($chelper, $category, $depth);
1844 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1845 // This is a request for the course information.
1846 $courseid = required_param('courseid', PARAM_INT);
1848 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1850 $chelper = new coursecat_helper();
1851 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1852 return $this->coursecat_coursebox_content($chelper, $course);
1853 } else {
1854 throw new coding_exception('Invalid request type');
1859 * Renders html to display search result page
1861 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1862 * @return string
1864 public function search_courses($searchcriteria) {
1865 global $CFG;
1866 $content = '';
1868 $search = '';
1869 if (!empty($searchcriteria['search'])) {
1870 $search = $searchcriteria['search'];
1872 $content .= $this->course_search_form($search);
1874 if (!empty($searchcriteria)) {
1875 // print search results
1877 $displayoptions = array('sort' => array('displayname' => 1));
1878 // take the current page and number of results per page from query
1879 $perpage = optional_param('perpage', 0, PARAM_RAW);
1880 if ($perpage !== 'all') {
1881 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1882 $page = optional_param('page', 0, PARAM_INT);
1883 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1885 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1886 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1887 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1889 $class = 'course-search-result';
1890 foreach ($searchcriteria as $key => $value) {
1891 if (!empty($value)) {
1892 $class .= ' course-search-result-'. $key;
1895 $chelper = new coursecat_helper();
1896 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1897 set_courses_display_options($displayoptions)->
1898 set_search_criteria($searchcriteria)->
1899 set_attributes(array('class' => $class));
1901 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1902 $totalcount = core_course_category::search_courses_count($searchcriteria);
1903 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1905 if (!$totalcount) {
1906 if (!empty($searchcriteria['search'])) {
1907 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1908 } else {
1909 $content .= $this->heading(get_string('novalidcourses'));
1911 } else {
1912 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1913 $content .= $courseslist;
1916 return $content;
1920 * Renders html to print list of courses tagged with particular tag
1922 * @param int $tagid id of the tag
1923 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1924 * are displayed on the page and the per-page limit may be bigger
1925 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1926 * to display items in the same context first
1927 * @param int $ctx context id where to search for records
1928 * @param bool $rec search in subcontexts as well
1929 * @param array $displayoptions
1930 * @return string empty string if no courses are marked with this tag or rendered list of courses
1932 public function tagged_courses($tagid, $exclusivemode = true, $ctx = 0, $rec = true, $displayoptions = null) {
1933 global $CFG;
1934 if (empty($displayoptions)) {
1935 $displayoptions = array();
1937 $showcategories = !core_course_category::is_simple_site();
1938 $displayoptions += array('limit' => $CFG->coursesperpage, 'offset' => 0);
1939 $chelper = new coursecat_helper();
1940 $searchcriteria = array('tagid' => $tagid, 'ctx' => $ctx, 'rec' => $rec);
1941 $chelper->set_show_courses($showcategories ? self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT :
1942 self::COURSECAT_SHOW_COURSES_EXPANDED)->
1943 set_search_criteria($searchcriteria)->
1944 set_courses_display_options($displayoptions)->
1945 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1946 // (we set the same css class as in search results by tagid)
1947 if ($totalcount = core_course_category::search_courses_count($searchcriteria)) {
1948 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1949 if ($exclusivemode) {
1950 return $this->coursecat_courses($chelper, $courses, $totalcount);
1951 } else {
1952 $tagfeed = new core_tag\output\tagfeed();
1953 $img = $this->output->pix_icon('i/course', '');
1954 foreach ($courses as $course) {
1955 $url = course_get_url($course);
1956 $imgwithlink = html_writer::link($url, $img);
1957 $coursename = html_writer::link($url, $course->get_formatted_name());
1958 $details = '';
1959 if ($showcategories && ($cat = core_course_category::get($course->category, IGNORE_MISSING))) {
1960 $details = get_string('category').': '.
1961 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1962 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1964 $tagfeed->add($imgwithlink, $coursename, $details);
1966 return $this->output->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($this->output));
1969 return '';
1973 * Returns HTML to display one remote course
1975 * @param stdClass $course remote course information, contains properties:
1976 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1977 * @return string
1979 protected function frontpage_remote_course(stdClass $course) {
1980 $url = new moodle_url('/auth/mnet/jump.php', array(
1981 'hostid' => $course->hostid,
1982 'wantsurl' => '/course/view.php?id='. $course->remoteid
1985 $output = '';
1986 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1987 $output .= html_writer::start_tag('div', array('class' => 'info'));
1988 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1989 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1990 $output .= html_writer::end_tag('h3'); // .name
1991 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1992 $output .= html_writer::end_tag('div'); // .info
1993 $output .= html_writer::start_tag('div', array('class' => 'content'));
1994 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1995 $options = new stdClass();
1996 $options->noclean = true;
1997 $options->para = false;
1998 $options->overflowdiv = true;
1999 $output .= format_text($course->summary, $course->summaryformat, $options);
2000 $output .= html_writer::end_tag('div'); // .summary
2001 $addinfo = format_string($course->hostname) . ' : '
2002 . format_string($course->cat_name) . ' : '
2003 . format_string($course->shortname);
2004 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
2005 $output .= html_writer::end_tag('div'); // .content
2006 $output .= html_writer::end_tag('div'); // .coursebox
2007 return $output;
2011 * Returns HTML to display one remote host
2013 * @param array $host host information, contains properties: name, url, count
2014 * @return string
2016 protected function frontpage_remote_host($host) {
2017 $output = '';
2018 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
2019 $output .= html_writer::start_tag('div', array('class' => 'info'));
2020 $output .= html_writer::start_tag('h3', array('class' => 'name'));
2021 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
2022 $output .= html_writer::end_tag('h3'); // .name
2023 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
2024 $output .= html_writer::end_tag('div'); // .info
2025 $output .= html_writer::start_tag('div', array('class' => 'content'));
2026 $output .= html_writer::start_tag('div', array('class' => 'summary'));
2027 $output .= $host['count'] . ' ' . get_string('courses');
2028 $output .= html_writer::end_tag('div'); // .content
2029 $output .= html_writer::end_tag('div'); // .coursebox
2030 return $output;
2034 * Returns HTML to print list of courses user is enrolled to for the frontpage
2036 * Also lists remote courses or remote hosts if MNET authorisation is used
2038 * @return string
2040 public function frontpage_my_courses() {
2041 global $USER, $CFG, $DB;
2043 if (!isloggedin() or isguestuser()) {
2044 return '';
2047 $output = '';
2048 $courses = enrol_get_my_courses('summary, summaryformat');
2049 $rhosts = array();
2050 $rcourses = array();
2051 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2052 $rcourses = get_my_remotecourses($USER->id);
2053 $rhosts = get_my_remotehosts();
2056 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2058 $chelper = new coursecat_helper();
2059 $totalcount = count($courses);
2060 if (count($courses) > $CFG->frontpagecourselimit) {
2061 // There are more enrolled courses than we can display, display link to 'My courses'.
2062 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
2063 $chelper->set_courses_display_options(array(
2064 'viewmoreurl' => new moodle_url('/my/'),
2065 'viewmoretext' => new lang_string('mycourses')
2067 } else if (core_course_category::top()->is_uservisible()) {
2068 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
2069 $chelper->set_courses_display_options(array(
2070 'viewmoreurl' => new moodle_url('/course/index.php'),
2071 'viewmoretext' => new lang_string('fulllistofcourses')
2073 $totalcount = $DB->count_records('course') - 1;
2075 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2076 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
2077 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
2079 // MNET
2080 if (!empty($rcourses)) {
2081 // at the IDP, we know of all the remote courses
2082 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2083 foreach ($rcourses as $course) {
2084 $output .= $this->frontpage_remote_course($course);
2086 $output .= html_writer::end_tag('div'); // .courses
2087 } elseif (!empty($rhosts)) {
2088 // non-IDP, we know of all the remote servers, but not courses
2089 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2090 foreach ($rhosts as $host) {
2091 $output .= $this->frontpage_remote_host($host);
2093 $output .= html_writer::end_tag('div'); // .courses
2096 return $output;
2100 * Returns HTML to print list of available courses for the frontpage
2102 * @return string
2104 public function frontpage_available_courses() {
2105 global $CFG;
2107 $chelper = new coursecat_helper();
2108 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2109 set_courses_display_options(array(
2110 'recursive' => true,
2111 'limit' => $CFG->frontpagecourselimit,
2112 'viewmoreurl' => new moodle_url('/course/index.php'),
2113 'viewmoretext' => new lang_string('fulllistofcourses')));
2115 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
2116 $courses = core_course_category::top()->get_courses($chelper->get_courses_display_options());
2117 $totalcount = core_course_category::top()->get_courses_count($chelper->get_courses_display_options());
2118 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
2119 // Print link to create a new course, for the 1st available category.
2120 return $this->add_new_course_button();
2122 return $this->coursecat_courses($chelper, $courses, $totalcount);
2126 * Returns HTML to the "add new course" button for the page
2128 * @return string
2130 public function add_new_course_button() {
2131 global $CFG;
2132 // Print link to create a new course, for the 1st available category.
2133 $output = $this->container_start('buttons');
2134 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2135 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2136 $output .= $this->container_end('buttons');
2137 return $output;
2141 * Returns HTML to print tree with course categories and courses for the frontpage
2143 * @return string
2145 public function frontpage_combo_list() {
2146 global $CFG;
2147 // TODO MDL-10965 improve.
2148 $tree = core_course_category::top();
2149 if (!$tree->get_children_count()) {
2150 return '';
2152 $chelper = new coursecat_helper();
2153 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2154 set_categories_display_options(array(
2155 'limit' => $CFG->coursesperpage,
2156 'viewmoreurl' => new moodle_url('/course/index.php',
2157 array('browse' => 'categories', 'page' => 1))
2158 ))->
2159 set_courses_display_options(array(
2160 'limit' => $CFG->coursesperpage,
2161 'viewmoreurl' => new moodle_url('/course/index.php',
2162 array('browse' => 'courses', 'page' => 1))
2163 ))->
2164 set_attributes(array('class' => 'frontpage-category-combo'));
2165 return $this->coursecat_tree($chelper, $tree);
2169 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2171 * @return string
2173 public function frontpage_categories_list() {
2174 global $CFG;
2175 // TODO MDL-10965 improve.
2176 $tree = core_course_category::top();
2177 if (!$tree->get_children_count()) {
2178 return '';
2180 $chelper = new coursecat_helper();
2181 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2182 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2183 set_categories_display_options(array(
2184 'limit' => $CFG->coursesperpage,
2185 'viewmoreurl' => new moodle_url('/course/index.php',
2186 array('browse' => 'categories', 'page' => 1))
2187 ))->
2188 set_attributes(array('class' => 'frontpage-category-names'));
2189 return $this->coursecat_tree($chelper, $tree);
2193 * Renders the activity navigation.
2195 * Defer to template.
2197 * @param \core_course\output\activity_navigation $page
2198 * @return string html for the page
2200 public function render_activity_navigation(\core_course\output\activity_navigation $page) {
2201 $data = $page->export_for_template($this->output);
2202 return $this->output->render_from_template('core_course/activity_navigation', $data);
2206 * Display waiting information about backup size during uploading backup process
2207 * @param object $backupfile the backup stored_file
2208 * @return $html string
2210 public function sendingbackupinfo($backupfile) {
2211 $sizeinfo = new stdClass();
2212 $sizeinfo->total = number_format($backupfile->get_filesize() / 1000000, 2);
2213 $html = html_writer::tag('div', get_string('sendingsize', 'hub', $sizeinfo),
2214 array('class' => 'courseuploadtextinfo'));
2215 return $html;
2219 * Hub information (logo - name - description - link)
2220 * @param object $hubinfo
2221 * @return string html code
2223 public function hubinfo($hubinfo) {
2224 $screenshothtml = html_writer::empty_tag('img',
2225 array('src' => $hubinfo['imgurl'], 'alt' => $hubinfo['name']));
2226 $hubdescription = html_writer::tag('div', $screenshothtml,
2227 array('class' => 'hubscreenshot'));
2229 $hubdescription .= html_writer::tag('a', $hubinfo['name'],
2230 array('class' => 'hublink', 'href' => $hubinfo['url'],
2231 'onclick' => 'this.target="_blank"'));
2233 $hubdescription .= html_writer::tag('div', format_text($hubinfo['description'], FORMAT_PLAIN),
2234 array('class' => 'hubdescription'));
2235 $hubdescription = html_writer::tag('div', $hubdescription, array('class' => 'hubinfo clearfix'));
2237 return $hubdescription;
2241 * Output frontpage summary text and frontpage modules (stored as section 1 in site course)
2243 * This may be disabled in settings
2245 * @return string
2247 public function frontpage_section1() {
2248 global $SITE, $USER;
2250 $output = '';
2251 $editing = $this->page->user_is_editing();
2253 if ($editing) {
2254 // Make sure section with number 1 exists.
2255 course_create_sections_if_missing($SITE, 1);
2258 $modinfo = get_fast_modinfo($SITE);
2259 $section = $modinfo->get_section_info(1);
2260 if (($section && (!empty($modinfo->sections[1]) or !empty($section->summary))) or $editing) {
2261 $output .= $this->box_start('generalbox sitetopic');
2263 // If currently moving a file then show the current clipboard.
2264 if (ismoving($SITE->id)) {
2265 $stractivityclipboard = strip_tags(get_string('activityclipboard', '', $USER->activitycopyname));
2266 $output .= '<p><font size="2">';
2267 $cancelcopyurl = new moodle_url('/course/mod.php', ['cancelcopy' => 'true', 'sesskey' => sesskey()]);
2268 $output .= "$stractivityclipboard&nbsp;&nbsp;(" . html_writer::link($cancelcopyurl, get_string('cancel')) .')';
2269 $output .= '</font></p>';
2272 $context = context_course::instance(SITEID);
2274 // If the section name is set we show it.
2275 if (trim($section->name) !== '') {
2276 $output .= $this->heading(
2277 format_string($section->name, true, array('context' => $context)),
2279 'sectionname'
2283 $summarytext = file_rewrite_pluginfile_urls($section->summary,
2284 'pluginfile.php',
2285 $context->id,
2286 'course',
2287 'section',
2288 $section->id);
2289 $summaryformatoptions = new stdClass();
2290 $summaryformatoptions->noclean = true;
2291 $summaryformatoptions->overflowdiv = true;
2293 $output .= format_text($summarytext, $section->summaryformat, $summaryformatoptions);
2295 if ($editing && has_capability('moodle/course:update', $context)) {
2296 $streditsummary = get_string('editsummary');
2297 $editsectionurl = new moodle_url('/course/editsection.php', ['id' => $section->id]);
2298 $output .= html_writer::link($editsectionurl, $this->pix_icon('t/edit', $streditsummary)) .
2299 "<br /><br />";
2302 $output .= $this->course_section_cm_list($SITE, $section);
2304 $output .= $this->course_section_add_cm_control($SITE, $section->section);
2305 $output .= $this->box_end();
2308 return $output;
2312 * Output news for the frontpage (extract from site-wide news forum)
2314 * @param stdClass $forum record from db table 'forum' that represents the site news forum
2315 * @return string
2317 protected function frontpage_news($forum) {
2318 global $CFG, $SITE, $SESSION, $USER;
2319 require_once($CFG->dirroot .'/mod/forum/lib.php');
2321 $output = '';
2323 if (isloggedin()) {
2324 $SESSION->fromdiscussion = $CFG->wwwroot;
2325 $subtext = '';
2326 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forum)) {
2327 if (!\mod_forum\subscriptions::is_forcesubscribed($forum)) {
2328 $subtext = get_string('unsubscribe', 'forum');
2330 } else {
2331 $subtext = get_string('subscribe', 'forum');
2333 $suburl = new moodle_url('/mod/forum/subscribe.php', array('id' => $forum->id, 'sesskey' => sesskey()));
2334 $output .= html_writer::tag('div', html_writer::link($suburl, $subtext), array('class' => 'subscribelink'));
2337 $coursemodule = get_coursemodule_from_instance('forum', $forum->id);
2338 $context = context_module::instance($coursemodule->id);
2340 $entityfactory = mod_forum\local\container::get_entity_factory();
2341 $forumentity = $entityfactory->get_forum_from_stdclass($forum, $context, $coursemodule, $SITE);
2343 $rendererfactory = mod_forum\local\container::get_renderer_factory();
2344 $discussionsrenderer = $rendererfactory->get_frontpage_news_discussion_list_renderer($forumentity);
2345 $cm = \cm_info::create($coursemodule);
2346 return $output . $discussionsrenderer->render($USER, $cm, null, null, 0, $SITE->newsitems);
2350 * Renders part of frontpage with a skip link (i.e. "My courses", "Site news", etc.)
2352 * @param string $skipdivid
2353 * @param string $contentsdivid
2354 * @param string $header Header of the part
2355 * @param string $contents Contents of the part
2356 * @return string
2358 protected function frontpage_part($skipdivid, $contentsdivid, $header, $contents) {
2359 if (strval($contents) === '') {
2360 return '';
2362 $output = html_writer::link('#' . $skipdivid,
2363 get_string('skipa', 'access', core_text::strtolower(strip_tags($header))),
2364 array('class' => 'skip-block skip aabtn'));
2366 // Wrap frontpage part in div container.
2367 $output .= html_writer::start_tag('div', array('id' => $contentsdivid));
2368 $output .= $this->heading($header);
2370 $output .= $contents;
2372 // End frontpage part div container.
2373 $output .= html_writer::end_tag('div');
2375 $output .= html_writer::tag('span', '', array('class' => 'skip-block-to', 'id' => $skipdivid));
2376 return $output;
2380 * Outputs contents for frontpage as configured in $CFG->frontpage or $CFG->frontpageloggedin
2382 * @return string
2384 public function frontpage() {
2385 global $CFG, $SITE;
2387 $output = '';
2389 if (isloggedin() and !isguestuser() and isset($CFG->frontpageloggedin)) {
2390 $frontpagelayout = $CFG->frontpageloggedin;
2391 } else {
2392 $frontpagelayout = $CFG->frontpage;
2395 foreach (explode(',', $frontpagelayout) as $v) {
2396 switch ($v) {
2397 // Display the main part of the front page.
2398 case FRONTPAGENEWS:
2399 if ($SITE->newsitems) {
2400 // Print forums only when needed.
2401 require_once($CFG->dirroot .'/mod/forum/lib.php');
2402 if (($newsforum = forum_get_course_forum($SITE->id, 'news')) &&
2403 ($forumcontents = $this->frontpage_news($newsforum))) {
2404 $newsforumcm = get_fast_modinfo($SITE)->instances['forum'][$newsforum->id];
2405 $output .= $this->frontpage_part('skipsitenews', 'site-news-forum',
2406 $newsforumcm->get_formatted_name(), $forumcontents);
2409 break;
2411 case FRONTPAGEENROLLEDCOURSELIST:
2412 $mycourseshtml = $this->frontpage_my_courses();
2413 if (!empty($mycourseshtml)) {
2414 $output .= $this->frontpage_part('skipmycourses', 'frontpage-course-list',
2415 get_string('mycourses'), $mycourseshtml);
2417 break;
2419 case FRONTPAGEALLCOURSELIST:
2420 $availablecourseshtml = $this->frontpage_available_courses();
2421 $output .= $this->frontpage_part('skipavailablecourses', 'frontpage-available-course-list',
2422 get_string('availablecourses'), $availablecourseshtml);
2423 break;
2425 case FRONTPAGECATEGORYNAMES:
2426 $output .= $this->frontpage_part('skipcategories', 'frontpage-category-names',
2427 get_string('categories'), $this->frontpage_categories_list());
2428 break;
2430 case FRONTPAGECATEGORYCOMBO:
2431 $output .= $this->frontpage_part('skipcourses', 'frontpage-category-combo',
2432 get_string('courses'), $this->frontpage_combo_list());
2433 break;
2435 case FRONTPAGECOURSESEARCH:
2436 $output .= $this->box($this->course_search_form(''), 'd-flex justify-content-center');
2437 break;
2440 $output .= '<br />';
2443 return $output;
2448 * Class storing display options and functions to help display course category and/or courses lists
2450 * This is a wrapper for core_course_category objects that also stores display options
2451 * and functions to retrieve sorted and paginated lists of categories/courses.
2453 * If theme overrides methods in core_course_renderers that access this class
2454 * it may as well not use this class at all or extend it.
2456 * @package core
2457 * @copyright 2013 Marina Glancy
2458 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2460 class coursecat_helper {
2461 /** @var string [none, collapsed, expanded] how (if) display courses list */
2462 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2463 /** @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) */
2464 protected $subcatdepth = 1;
2465 /** @var array options to display courses list */
2466 protected $coursesdisplayoptions = array();
2467 /** @var array options to display subcategories list */
2468 protected $categoriesdisplayoptions = array();
2469 /** @var array additional HTML attributes */
2470 protected $attributes = array();
2471 /** @var array search criteria if the list is a search result */
2472 protected $searchcriteria = null;
2475 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2477 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2478 * @return coursecat_helper
2480 public function set_show_courses($showcourses) {
2481 $this->showcourses = $showcourses;
2482 // Automatically set the options to preload summary and coursecontacts for core_course_category::get_courses()
2483 // and core_course_category::search_courses().
2484 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2485 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2486 $this->coursesdisplayoptions['customfields'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED;
2487 return $this;
2491 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2493 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2495 public function get_show_courses() {
2496 return $this->showcourses;
2500 * Sets the maximum depth to expand subcategories in the tree
2502 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2504 * @param int $subcatdepth
2505 * @return coursecat_helper
2507 public function set_subcat_depth($subcatdepth) {
2508 $this->subcatdepth = $subcatdepth;
2509 return $this;
2513 * Returns the maximum depth to expand subcategories in the tree
2515 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2517 * @return int
2519 public function get_subcat_depth() {
2520 return $this->subcatdepth;
2524 * Sets options to display list of courses
2526 * Options are later submitted as argument to core_course_category::get_courses() and/or core_course_category::search_courses()
2528 * Options that core_course_category::get_courses() accept:
2529 * - recursive - return courses from subcategories as well. Use with care,
2530 * this may be a huge list!
2531 * - summary - preloads fields 'summary' and 'summaryformat'
2532 * - coursecontacts - preloads course contacts
2533 * - customfields - preloads custom fields data
2534 * - isenrolled - preloads indication whether this user is enrolled in the course
2535 * - sort - list of fields to sort. Example
2536 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2537 * will sort by idnumber asc, shortname asc and id desc.
2538 * Default: array('sortorder' => 1)
2539 * Only cached fields may be used for sorting!
2540 * - offset
2541 * - limit - maximum number of children to return, 0 or null for no limit
2543 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2545 * Also renderer can set here any additional options it wants to pass between renderer functions.
2547 * @param array $options
2548 * @return coursecat_helper
2550 public function set_courses_display_options($options) {
2551 $this->coursesdisplayoptions = $options;
2552 $this->set_show_courses($this->showcourses); // this will calculate special display options
2553 return $this;
2557 * Sets one option to display list of courses
2559 * @see coursecat_helper::set_courses_display_options()
2561 * @param string $key
2562 * @param mixed $value
2563 * @return coursecat_helper
2565 public function set_courses_display_option($key, $value) {
2566 $this->coursesdisplayoptions[$key] = $value;
2567 return $this;
2571 * Return the specified option to display list of courses
2573 * @param string $optionname option name
2574 * @param mixed $defaultvalue default value for option if it is not specified
2575 * @return mixed
2577 public function get_courses_display_option($optionname, $defaultvalue = null) {
2578 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2579 return $this->coursesdisplayoptions[$optionname];
2580 } else {
2581 return $defaultvalue;
2586 * Returns all options to display the courses
2588 * This array is usually passed to {@link core_course_category::get_courses()} or
2589 * {@link core_course_category::search_courses()}
2591 * @return array
2593 public function get_courses_display_options() {
2594 return $this->coursesdisplayoptions;
2598 * Sets options to display list of subcategories
2600 * Options 'sort', 'offset' and 'limit' are passed to core_course_category::get_children().
2601 * Any other options may be used by renderer functions
2603 * @param array $options
2604 * @return coursecat_helper
2606 public function set_categories_display_options($options) {
2607 $this->categoriesdisplayoptions = $options;
2608 return $this;
2612 * Return the specified option to display list of subcategories
2614 * @param string $optionname option name
2615 * @param mixed $defaultvalue default value for option if it is not specified
2616 * @return mixed
2618 public function get_categories_display_option($optionname, $defaultvalue = null) {
2619 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2620 return $this->categoriesdisplayoptions[$optionname];
2621 } else {
2622 return $defaultvalue;
2627 * Returns all options to display list of subcategories
2629 * This array is usually passed to {@link core_course_category::get_children()}
2631 * @return array
2633 public function get_categories_display_options() {
2634 return $this->categoriesdisplayoptions;
2638 * Sets additional general options to pass between renderer functions, usually HTML attributes
2640 * @param array $attributes
2641 * @return coursecat_helper
2643 public function set_attributes($attributes) {
2644 $this->attributes = $attributes;
2645 return $this;
2649 * Return all attributes and erases them so they are not applied again
2651 * @param string $classname adds additional class name to the beginning of $attributes['class']
2652 * @return array
2654 public function get_and_erase_attributes($classname) {
2655 $attributes = $this->attributes;
2656 $this->attributes = array();
2657 if (empty($attributes['class'])) {
2658 $attributes['class'] = '';
2660 $attributes['class'] = $classname . ' '. $attributes['class'];
2661 return $attributes;
2665 * Sets the search criteria if the course is a search result
2667 * Search string will be used to highlight terms in course name and description
2669 * @param array $searchcriteria
2670 * @return coursecat_helper
2672 public function set_search_criteria($searchcriteria) {
2673 $this->searchcriteria = $searchcriteria;
2674 return $this;
2678 * Returns formatted and filtered description of the given category
2680 * @param core_course_category $coursecat category
2681 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2682 * if context is not specified it will be added automatically
2683 * @return string|null
2685 public function get_category_formatted_description($coursecat, $options = null) {
2686 if ($coursecat->id && $coursecat->is_uservisible() && !empty($coursecat->description)) {
2687 if (!isset($coursecat->descriptionformat)) {
2688 $descriptionformat = FORMAT_MOODLE;
2689 } else {
2690 $descriptionformat = $coursecat->descriptionformat;
2692 if ($options === null) {
2693 $options = array('noclean' => true, 'overflowdiv' => true);
2694 } else {
2695 $options = (array)$options;
2697 $context = context_coursecat::instance($coursecat->id);
2698 if (!isset($options['context'])) {
2699 $options['context'] = $context;
2701 $text = file_rewrite_pluginfile_urls($coursecat->description,
2702 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2703 return format_text($text, $descriptionformat, $options);
2705 return null;
2709 * Returns given course's summary with proper embedded files urls and formatted
2711 * @param core_course_list_element $course
2712 * @param array|stdClass $options additional formatting options
2713 * @return string
2715 public function get_course_formatted_summary($course, $options = array()) {
2716 global $CFG;
2717 require_once($CFG->libdir. '/filelib.php');
2718 if (!$course->has_summary()) {
2719 return '';
2721 $options = (array)$options;
2722 $context = context_course::instance($course->id);
2723 if (!isset($options['context'])) {
2724 // TODO see MDL-38521
2725 // option 1 (current), page context - no code required
2726 // option 2, system context
2727 // $options['context'] = context_system::instance();
2728 // option 3, course context:
2729 // $options['context'] = $context;
2730 // option 4, course category context:
2731 // $options['context'] = $context->get_parent_context();
2733 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2734 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2735 if (!empty($this->searchcriteria['search'])) {
2736 $summary = highlight($this->searchcriteria['search'], $summary);
2738 return $summary;
2742 * Returns course name as it is configured to appear in courses lists formatted to course context
2744 * @param core_course_list_element $course
2745 * @param array|stdClass $options additional formatting options
2746 * @return string
2748 public function get_course_formatted_name($course, $options = array()) {
2749 $options = (array)$options;
2750 if (!isset($options['context'])) {
2751 $options['context'] = context_course::instance($course->id);
2753 $name = format_string(get_course_display_name_for_list($course), true, $options);
2754 if (!empty($this->searchcriteria['search'])) {
2755 $name = highlight($this->searchcriteria['search'], $name);
2757 return $name;