MDL-65060 core_message: Group_message_message_content selector
[moodle.git] / course / renderer.php
blob9d1439c7ad8bc8b3282eab609fc745ece1f243a7
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Renderer for use with the course section and all the goodness that falls
20 * within it.
22 * This renderer should contain methods useful to courses, and categories.
24 * @package moodlecore
25 * @copyright 2010 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 /**
30 * The core course renderer
32 * Can be retrieved with the following:
33 * $renderer = $PAGE->get_renderer('core','course');
35 class core_course_renderer extends plugin_renderer_base {
36 const COURSECAT_SHOW_COURSES_NONE = 0; /* do not show courses at all */
37 const COURSECAT_SHOW_COURSES_COUNT = 5; /* do not show courses but show number of courses next to category name */
38 const COURSECAT_SHOW_COURSES_COLLAPSED = 10;
39 const COURSECAT_SHOW_COURSES_AUTO = 15; /* will choose between collapsed and expanded automatically */
40 const COURSECAT_SHOW_COURSES_EXPANDED = 20;
41 const COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT = 30;
43 const COURSECAT_TYPE_CATEGORY = 0;
44 const COURSECAT_TYPE_COURSE = 1;
46 /**
47 * A cache of strings
48 * @var stdClass
50 protected $strings;
52 /**
53 * Whether a category content is being initially rendered with children. This is mainly used by the
54 * core_course_renderer::corsecat_tree() to render the appropriate action for the Expand/Collapse all link on
55 * page load.
56 * @var bool
58 protected $categoryexpandedonload = false;
60 /**
61 * Override the constructor so that we can initialise the string cache
63 * @param moodle_page $page
64 * @param string $target
66 public function __construct(moodle_page $page, $target) {
67 $this->strings = new stdClass;
68 parent::__construct($page, $target);
71 /**
72 * @deprecated since 3.2
74 protected function add_modchoosertoggle() {
75 throw new coding_exception('core_course_renderer::add_modchoosertoggle() can not be used anymore.');
78 /**
79 * Renders course info box.
81 * @param stdClass $course
82 * @return string
84 public function course_info_box(stdClass $course) {
85 $content = '';
86 $content .= $this->output->box_start('generalbox info');
87 $chelper = new coursecat_helper();
88 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
89 $content .= $this->coursecat_coursebox($chelper, $course);
90 $content .= $this->output->box_end();
91 return $content;
94 /**
95 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
97 * @deprecated since 2.5
99 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
101 * @param array $ignored argument ignored
102 * @return string
104 public final function course_category_tree(array $ignored) {
105 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
106 return $this->frontpage_combo_list();
110 * Renderers a category for use with course_category_tree
112 * @deprecated since 2.5
114 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
116 * @param array $category
117 * @param int $depth
118 * @return string
120 protected final function course_category_tree_category(stdClass $category, $depth=1) {
121 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
122 return '';
126 * Render a modchooser.
128 * @param renderable $modchooser The chooser.
129 * @return string
131 public function render_modchooser(renderable $modchooser) {
132 return $this->render_from_template('core_course/modchooser', $modchooser->export_for_template($this));
136 * Build the HTML for the module chooser javascript popup
138 * @param array $modules A set of modules as returned form @see
139 * get_module_metadata
140 * @param object $course The course that will be displayed
141 * @return string The composed HTML for the module
143 public function course_modchooser($modules, $course) {
144 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchooser')) {
145 return '';
147 $modchooser = new \core_course\output\modchooser($course, $modules);
148 return $this->render($modchooser);
152 * Build the HTML for a specified set of modules
154 * @param array $modules A set of modules as used by the
155 * course_modchooser_module function
156 * @return string The composed HTML for the module
158 protected function course_modchooser_module_types($modules) {
159 debugging('Method core_course_renderer::course_modchooser_module_types() is deprecated, ' .
160 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
161 return '';
165 * Return the HTML for the specified module adding any required classes
167 * @param object $module An object containing the title, and link. An
168 * icon, and help text may optionally be specified. If the module
169 * contains subtypes in the types option, then these will also be
170 * displayed.
171 * @param array $classes Additional classes to add to the encompassing
172 * div element
173 * @return string The composed HTML for the module
175 protected function course_modchooser_module($module, $classes = array('option')) {
176 debugging('Method core_course_renderer::course_modchooser_module() is deprecated, ' .
177 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
178 return '';
181 protected function course_modchooser_title($title, $identifier = null) {
182 debugging('Method core_course_renderer::course_modchooser_title() is deprecated, ' .
183 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
184 return '';
188 * Renders HTML for displaying the sequence of course module editing buttons
190 * @see course_get_cm_edit_actions()
192 * @param action_link[] $actions Array of action_link objects
193 * @param cm_info $mod The module we are displaying actions for.
194 * @param array $displayoptions additional display options:
195 * ownerselector => A JS/CSS selector that can be used to find an cm node.
196 * If specified the owning node will be given the class 'action-menu-shown' when the action
197 * menu is being displayed.
198 * constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
199 * the action menu to when it is being displayed.
200 * donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
201 * @return string
203 public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
204 global $CFG;
206 if (empty($actions)) {
207 return '';
210 if (isset($displayoptions['ownerselector'])) {
211 $ownerselector = $displayoptions['ownerselector'];
212 } else if ($mod) {
213 $ownerselector = '#module-'.$mod->id;
214 } else {
215 debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
216 $ownerselector = 'li.activity';
219 if (isset($displayoptions['constraintselector'])) {
220 $constraint = $displayoptions['constraintselector'];
221 } else {
222 $constraint = '.course-content';
225 $menu = new action_menu();
226 $menu->set_owner_selector($ownerselector);
227 $menu->set_constraint($constraint);
228 $menu->set_alignment(action_menu::TR, action_menu::BR);
229 $menu->set_menu_trigger(get_string('edit'));
231 foreach ($actions as $action) {
232 if ($action instanceof action_menu_link) {
233 $action->add_class('cm-edit-action');
235 $menu->add($action);
237 $menu->attributes['class'] .= ' section-cm-edit-actions commands';
239 // Prioritise the menu ahead of all other actions.
240 $menu->prioritise = true;
242 return $this->render($menu);
246 * Renders HTML for the menus to add activities and resources to the current course
248 * @param stdClass $course
249 * @param int $section relative section number (field course_sections.section)
250 * @param int $sectionreturn The section to link back to
251 * @param array $displayoptions additional display options, for example blocks add
252 * option 'inblock' => true, suggesting to display controls vertically
253 * @return string
255 function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
256 global $CFG;
258 $vertical = !empty($displayoptions['inblock']);
260 // check to see if user can add menus and there are modules to add
261 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
262 || !$this->page->user_is_editing()
263 || !($modnames = get_module_types_names()) || empty($modnames)) {
264 return '';
267 // Retrieve all modules with associated metadata
268 $modules = get_module_metadata($course, $modnames, $sectionreturn);
269 $urlparams = array('section' => $section);
271 // We'll sort resources and activities into two lists
272 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
274 foreach ($modules as $module) {
275 $activityclass = MOD_CLASS_ACTIVITY;
276 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
277 $activityclass = MOD_CLASS_RESOURCE;
278 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
279 // System modules cannot be added by user, do not add to dropdown.
280 continue;
282 $link = $module->link->out(true, $urlparams);
283 $activities[$activityclass][$link] = $module->title;
286 $straddactivity = get_string('addactivity');
287 $straddresource = get_string('addresource');
288 $sectionname = get_section_name($course, $section);
289 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
290 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
292 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
294 if (!$vertical) {
295 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
298 if (!empty($activities[MOD_CLASS_RESOURCE])) {
299 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array(''=>$straddresource), "ressection$section");
300 $select->set_help_icon('resources');
301 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
302 $output .= $this->output->render($select);
305 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
306 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array(''=>$straddactivity), "section$section");
307 $select->set_help_icon('activities');
308 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
309 $output .= $this->output->render($select);
312 if (!$vertical) {
313 $output .= html_writer::end_tag('div');
316 $output .= html_writer::end_tag('div');
318 if (course_ajax_enabled($course) && $course->id == $this->page->course->id) {
319 // modchooser can be added only for the current course set on the page!
320 $straddeither = get_string('addresourceoractivity');
321 // The module chooser link
322 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
323 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
324 $icon = $this->output->pix_icon('t/add', '');
325 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
326 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
327 $modchooser.= html_writer::end_tag('div');
328 $modchooser.= html_writer::end_tag('div');
330 // Wrap the normal output in a noscript div
331 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
332 if ($usemodchooser) {
333 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
334 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
335 } else {
336 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
337 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
338 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
340 $output = $this->course_modchooser($modules, $course) . $modchooser . $output;
343 return $output;
347 * Renders html to display a course search form.
349 * @param string $value default value to populate the search field
350 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
351 * @return string
353 public function course_search_form($value = '', $format = 'plain') {
354 static $count = 0;
355 $formid = 'coursesearch';
356 if ((++$count) > 1) {
357 $formid .= $count;
360 switch ($format) {
361 case 'navbar' :
362 $formid = 'coursesearchnavbar';
363 $inputid = 'navsearchbox';
364 $inputsize = 20;
365 break;
366 case 'short' :
367 $inputid = 'shortsearchbox';
368 $inputsize = 12;
369 break;
370 default :
371 $inputid = 'coursesearchbox';
372 $inputsize = 30;
375 $data = (object) [
376 'searchurl' => (new moodle_url('/course/search.php'))->out(false),
377 'id' => $formid,
378 'inputid' => $inputid,
379 'inputsize' => $inputsize,
380 'value' => $value
382 if ($format != 'navbar') {
383 $helpicon = new \help_icon('coursesearch', 'core');
384 $data->helpicon = $helpicon->export_for_template($this);
387 return $this->render_from_template('core_course/course_search_form', $data);
391 * Renders html for completion box on course page
393 * If completion is disabled, returns empty string
394 * If completion is automatic, returns an icon of the current completion state
395 * If completion is manual, returns a form (with an icon inside) that allows user to
396 * toggle completion
398 * @param stdClass $course course object
399 * @param completion_info $completioninfo completion info for the course, it is recommended
400 * to fetch once for all modules in course/section for performance
401 * @param cm_info $mod module to show completion for
402 * @param array $displayoptions display options, not used in core
403 * @return string
405 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
406 global $CFG, $DB, $USER;
407 $output = '';
409 $istrackeduser = $completioninfo->is_tracked_user($USER->id);
410 $isediting = $this->page->user_is_editing();
412 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
413 return $output;
415 if ($completioninfo === null) {
416 $completioninfo = new completion_info($course);
418 $completion = $completioninfo->is_enabled($mod);
420 if ($completion == COMPLETION_TRACKING_NONE) {
421 if ($isediting) {
422 $output .= html_writer::span('&nbsp;', 'filler');
424 return $output;
427 $completionicon = '';
429 if ($isediting || !$istrackeduser) {
430 switch ($completion) {
431 case COMPLETION_TRACKING_MANUAL :
432 $completionicon = 'manual-enabled'; break;
433 case COMPLETION_TRACKING_AUTOMATIC :
434 $completionicon = 'auto-enabled'; break;
436 } else {
437 $completiondata = $completioninfo->get_data($mod, true);
438 if ($completion == COMPLETION_TRACKING_MANUAL) {
439 switch($completiondata->completionstate) {
440 case COMPLETION_INCOMPLETE:
441 $completionicon = 'manual-n' . ($completiondata->overrideby ? '-override' : '');
442 break;
443 case COMPLETION_COMPLETE:
444 $completionicon = 'manual-y' . ($completiondata->overrideby ? '-override' : '');
445 break;
447 } else { // Automatic
448 switch($completiondata->completionstate) {
449 case COMPLETION_INCOMPLETE:
450 $completionicon = 'auto-n' . ($completiondata->overrideby ? '-override' : '');
451 break;
452 case COMPLETION_COMPLETE:
453 $completionicon = 'auto-y' . ($completiondata->overrideby ? '-override' : '');
454 break;
455 case COMPLETION_COMPLETE_PASS:
456 $completionicon = 'auto-pass'; break;
457 case COMPLETION_COMPLETE_FAIL:
458 $completionicon = 'auto-fail'; break;
462 if ($completionicon) {
463 $formattedname = html_entity_decode($mod->get_formatted_name(), ENT_QUOTES, 'UTF-8');
464 if (!$isediting && $istrackeduser && $completiondata->overrideby) {
465 $args = new stdClass();
466 $args->modname = $formattedname;
467 $overridebyuser = \core_user::get_user($completiondata->overrideby, '*', MUST_EXIST);
468 $args->overrideuser = fullname($overridebyuser);
469 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $args);
470 } else {
471 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
474 if ($isediting || !$istrackeduser || !has_capability('moodle/course:togglecompletion', $mod->context)) {
475 // When editing, the icon is just an image.
476 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
477 array('title' => $imgalt, 'class' => 'iconsmall'));
478 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
479 array('class' => 'autocompletion'));
480 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
481 $newstate =
482 $completiondata->completionstate == COMPLETION_COMPLETE
483 ? COMPLETION_INCOMPLETE
484 : COMPLETION_COMPLETE;
485 // In manual mode the icon is a toggle form...
487 // If this completion state is used by the
488 // conditional activities system, we need to turn
489 // off the JS.
490 $extraclass = '';
491 if (!empty($CFG->enableavailability) &&
492 core_availability\info::completion_value_used($course, $mod->id)) {
493 $extraclass = ' preventjs';
495 $output .= html_writer::start_tag('form', array('method' => 'post',
496 'action' => new moodle_url('/course/togglecompletion.php'),
497 'class' => 'togglecompletion'. $extraclass));
498 $output .= html_writer::start_tag('div');
499 $output .= html_writer::empty_tag('input', array(
500 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
501 $output .= html_writer::empty_tag('input', array(
502 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
503 $output .= html_writer::empty_tag('input', array(
504 'type' => 'hidden', 'name' => 'modulename', 'value' => $formattedname));
505 $output .= html_writer::empty_tag('input', array(
506 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
507 $output .= html_writer::tag('button',
508 $this->output->pix_icon('i/completion-' . $completionicon, $imgalt),
509 array('class' => 'btn btn-link', 'aria-live' => 'assertive'));
510 $output .= html_writer::end_tag('div');
511 $output .= html_writer::end_tag('form');
512 } else {
513 // In auto mode, the icon is just an image.
514 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
515 array('title' => $imgalt));
516 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
517 array('class' => 'autocompletion'));
520 return $output;
524 * Checks if course module has any conditions that may make it unavailable for
525 * all or some of the students
527 * This function is internal and is only used to create CSS classes for the module name/text
529 * @param cm_info $mod
530 * @return bool
532 protected function is_cm_conditionally_hidden(cm_info $mod) {
533 global $CFG;
534 $conditionalhidden = false;
535 if (!empty($CFG->enableavailability)) {
536 $info = new \core_availability\info_module($mod);
537 $conditionalhidden = !$info->is_available_for_all();
539 return $conditionalhidden;
543 * Renders html to display a name with the link to the course module on a course page
545 * If module is unavailable for user but still needs to be displayed
546 * in the list, just the name is returned without a link
548 * Note, that for course modules that never have separate pages (i.e. labels)
549 * this function return an empty string
551 * @param cm_info $mod
552 * @param array $displayoptions
553 * @return string
555 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
556 if (!$mod->is_visible_on_course_page() || !$mod->url) {
557 // Nothing to be displayed to the user.
558 return '';
561 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
562 $groupinglabel = $mod->get_grouping_label($textclasses);
564 // Render element that allows to edit activity name inline. It calls {@link course_section_cm_name_title()}
565 // to get the display title of the activity.
566 $tmpl = new \core_course\output\course_module_name($mod, $this->page->user_is_editing(), $displayoptions);
567 return $this->output->render_from_template('core/inplace_editable', $tmpl->export_for_template($this->output)) .
568 $groupinglabel;
572 * Returns the CSS classes for the activity name/content
574 * For items which are hidden, unavailable or stealth but should be displayed
575 * to current user ($mod->is_visible_on_course_page()), we show those as dimmed.
576 * Students will also see as dimmed activities names that are not yet available
577 * but should still be displayed (without link) with availability info.
579 * @param cm_info $mod
580 * @return array array of two elements ($linkclasses, $textclasses)
582 protected function course_section_cm_classes(cm_info $mod) {
583 $linkclasses = '';
584 $textclasses = '';
585 if ($mod->uservisible) {
586 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
587 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
588 has_capability('moodle/course:viewhiddenactivities', $mod->context);
589 if ($accessiblebutdim) {
590 $linkclasses .= ' dimmed';
591 $textclasses .= ' dimmed_text';
592 if ($conditionalhidden) {
593 $linkclasses .= ' conditionalhidden';
594 $textclasses .= ' conditionalhidden';
597 if ($mod->is_stealth()) {
598 // Stealth activity is the one that is not visible on course page.
599 // It still may be displayed to the users who can manage it.
600 $linkclasses .= ' stealth';
601 $textclasses .= ' stealth';
603 } else {
604 $linkclasses .= ' dimmed';
605 $textclasses .= ' dimmed dimmed_text';
607 return array($linkclasses, $textclasses);
611 * Renders html to display a name with the link to the course module on a course page
613 * If module is unavailable for user but still needs to be displayed
614 * in the list, just the name is returned without a link
616 * Note, that for course modules that never have separate pages (i.e. labels)
617 * this function return an empty string
619 * @param cm_info $mod
620 * @param array $displayoptions
621 * @return string
623 public function course_section_cm_name_title(cm_info $mod, $displayoptions = array()) {
624 $output = '';
625 $url = $mod->url;
626 if (!$mod->is_visible_on_course_page() || !$url) {
627 // Nothing to be displayed to the user.
628 return $output;
631 //Accessibility: for files get description via icon, this is very ugly hack!
632 $instancename = $mod->get_formatted_name();
633 $altname = $mod->modfullname;
634 // Avoid unnecessary duplication: if e.g. a forum name already
635 // includes the word forum (or Forum, etc) then it is unhelpful
636 // to include that in the accessible description that is added.
637 if (false !== strpos(core_text::strtolower($instancename),
638 core_text::strtolower($altname))) {
639 $altname = '';
641 // File type after name, for alphabetic lists (screen reader).
642 if ($altname) {
643 $altname = get_accesshide(' '.$altname);
646 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
648 // Get on-click attribute value if specified and decode the onclick - it
649 // has already been encoded for display (puke).
650 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
652 // Display link itself.
653 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
654 'class' => 'iconlarge activityicon', 'alt' => '', 'role' => 'presentation', 'aria-hidden' => 'true')) .
655 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
656 if ($mod->uservisible) {
657 $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick));
658 } else {
659 // We may be displaying this just in order to show information
660 // about visibility, without the actual link ($mod->is_visible_on_course_page()).
661 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses));
663 return $output;
667 * Renders html to display the module content on the course page (i.e. text of the labels)
669 * @param cm_info $mod
670 * @param array $displayoptions
671 * @return string
673 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
674 $output = '';
675 if (!$mod->is_visible_on_course_page()) {
676 // nothing to be displayed to the user
677 return $output;
679 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
680 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
681 if ($mod->url && $mod->uservisible) {
682 if ($content) {
683 // If specified, display extra content after link.
684 $output = html_writer::tag('div', $content, array('class' =>
685 trim('contentafterlink ' . $textclasses)));
687 } else {
688 $groupinglabel = $mod->get_grouping_label($textclasses);
690 // No link, so display only content.
691 $output = html_writer::tag('div', $content . $groupinglabel,
692 array('class' => 'contentwithoutlink ' . $textclasses));
694 return $output;
698 * Displays availability info for a course section or course module
700 * @param string $text
701 * @param string $additionalclasses
702 * @return string
704 public function availability_info($text, $additionalclasses = '') {
706 $data = ['text' => $text, 'classes' => $additionalclasses];
707 $additionalclasses = array_filter(explode(' ', $additionalclasses));
709 if (in_array('ishidden', $additionalclasses)) {
710 $data['ishidden'] = 1;
712 } else if (in_array('isstealth', $additionalclasses)) {
713 $data['isstealth'] = 1;
715 } else if (in_array('isrestricted', $additionalclasses)) {
716 $data['isrestricted'] = 1;
718 if (in_array('isfullinfo', $additionalclasses)) {
719 $data['isfullinfo'] = 1;
723 return $this->render_from_template('core/availability_info', $data);
727 * Renders HTML to show course module availability information (for someone who isn't allowed
728 * to see the activity itself, or for staff)
730 * @param cm_info $mod
731 * @param array $displayoptions
732 * @return string
734 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
735 global $CFG;
736 $output = '';
737 if (!$mod->is_visible_on_course_page()) {
738 return $output;
740 if (!$mod->uservisible) {
741 // this is a student who is not allowed to see the module but might be allowed
742 // to see availability info (i.e. "Available from ...")
743 if (!empty($mod->availableinfo)) {
744 $formattedinfo = \core_availability\info::format_info(
745 $mod->availableinfo, $mod->get_course());
746 $output = $this->availability_info($formattedinfo, 'isrestricted');
748 return $output;
750 // this is a teacher who is allowed to see module but still should see the
751 // information that module is not available to all/some students
752 $modcontext = context_module::instance($mod->id);
753 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
754 if ($canviewhidden && !$mod->visible) {
755 // This module is hidden but current user has capability to see it.
756 // Do not display the availability info if the whole section is hidden.
757 if ($mod->get_section_info()->visible) {
758 $output .= $this->availability_info(get_string('hiddenfromstudents'), 'ishidden');
760 } else if ($mod->is_stealth()) {
761 // This module is available but is normally not displayed on the course page
762 // (this user can see it because they can manage it).
763 $output .= $this->availability_info(get_string('hiddenoncoursepage'), 'isstealth');
765 if ($canviewhidden && !empty($CFG->enableavailability)) {
766 // Display information about conditional availability.
767 // Don't add availability information if user is not editing and activity is hidden.
768 if ($mod->visible || $this->page->user_is_editing()) {
769 $hidinfoclass = 'isrestricted isfullinfo';
770 if (!$mod->visible) {
771 $hidinfoclass .= ' hide';
773 $ci = new \core_availability\info_module($mod);
774 $fullinfo = $ci->get_full_information();
775 if ($fullinfo) {
776 $formattedinfo = \core_availability\info::format_info(
777 $fullinfo, $mod->get_course());
778 $output .= $this->availability_info($formattedinfo, $hidinfoclass);
782 return $output;
786 * Renders HTML to display one course module for display within a section.
788 * This function calls:
789 * {@link core_course_renderer::course_section_cm()}
791 * @param stdClass $course
792 * @param completion_info $completioninfo
793 * @param cm_info $mod
794 * @param int|null $sectionreturn
795 * @param array $displayoptions
796 * @return String
798 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
799 $output = '';
800 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
801 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
802 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
804 return $output;
808 * Renders HTML to display one course module in a course section
810 * This includes link, content, availability, completion info and additional information
811 * that module type wants to display (i.e. number of unread forum posts)
813 * This function calls:
814 * {@link core_course_renderer::course_section_cm_name()}
815 * {@link core_course_renderer::course_section_cm_text()}
816 * {@link core_course_renderer::course_section_cm_availability()}
817 * {@link core_course_renderer::course_section_cm_completion()}
818 * {@link course_get_cm_edit_actions()}
819 * {@link core_course_renderer::course_section_cm_edit_actions()}
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($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
829 $output = '';
830 // We return empty string (because course module will not be displayed at all)
831 // if:
832 // 1) The activity is not visible to users
833 // and
834 // 2) The 'availableinfo' is empty, i.e. the activity was
835 // hidden in a way that leaves no info, such as using the
836 // eye icon.
837 if (!$mod->is_visible_on_course_page()) {
838 return $output;
841 $indentclasses = 'mod-indent';
842 if (!empty($mod->indent)) {
843 $indentclasses .= ' mod-indent-'.$mod->indent;
844 if ($mod->indent > 15) {
845 $indentclasses .= ' mod-indent-huge';
849 $output .= html_writer::start_tag('div');
851 if ($this->page->user_is_editing()) {
852 $output .= course_get_cm_move($mod, $sectionreturn);
855 $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer'));
857 // This div is used to indent the content.
858 $output .= html_writer::div('', $indentclasses);
860 // Start a wrapper for the actual content to keep the indentation consistent
861 $output .= html_writer::start_tag('div');
863 // Display the link to the module (or do nothing if module has no url)
864 $cmname = $this->course_section_cm_name($mod, $displayoptions);
866 if (!empty($cmname)) {
867 // Start the div for the activity title, excluding the edit icons.
868 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
869 $output .= $cmname;
872 // Module can put text after the link (e.g. forum unread)
873 $output .= $mod->afterlink;
875 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
876 $output .= html_writer::end_tag('div'); // .activityinstance
879 // If there is content but NO link (eg label), then display the
880 // content here (BEFORE any icons). In this case cons must be
881 // displayed after the content so that it makes more sense visually
882 // and for accessibility reasons, e.g. if you have a one-line label
883 // it should work similarly (at least in terms of ordering) to an
884 // activity.
885 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
886 $url = $mod->url;
887 if (empty($url)) {
888 $output .= $contentpart;
891 $modicons = '';
892 if ($this->page->user_is_editing()) {
893 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
894 $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
895 $modicons .= $mod->afterediticons;
898 $modicons .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
900 if (!empty($modicons)) {
901 $output .= html_writer::span($modicons, 'actions');
904 // Show availability info (if module is not available).
905 $output .= $this->course_section_cm_availability($mod, $displayoptions);
907 // If there is content AND a link, then display the content here
908 // (AFTER any icons). Otherwise it was displayed before
909 if (!empty($url)) {
910 $output .= $contentpart;
913 $output .= html_writer::end_tag('div'); // $indentclasses
915 // End of indentation div.
916 $output .= html_writer::end_tag('div');
918 $output .= html_writer::end_tag('div');
919 return $output;
923 * Message displayed to the user when they try to access unavailable activity following URL
925 * This method is a very simplified version of {@link course_section_cm()} to be part of the error
926 * notification only. It also does not check if module is visible on course page or not.
928 * The message will be displayed inside notification!
930 * @param cm_info $cm
931 * @return string
933 public function course_section_cm_unavailable_error_message(cm_info $cm) {
934 if ($cm->uservisible) {
935 return null;
937 if (!$cm->availableinfo) {
938 return get_string('activityiscurrentlyhidden');
941 $altname = get_accesshide(' ' . $cm->modfullname);
942 $name = html_writer::empty_tag('img', array('src' => $cm->get_icon_url(),
943 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
944 html_writer::tag('span', ' '.$cm->get_formatted_name() . $altname, array('class' => 'instancename'));
945 $formattedinfo = \core_availability\info::format_info($cm->availableinfo, $cm->get_course());
946 return html_writer::div($name, 'activityinstance-error') .
947 html_writer::div($formattedinfo, 'availabilityinfo-error');
951 * Renders HTML to display a list of course modules in a course section
952 * Also displays "move here" controls in Javascript-disabled mode
954 * This function calls {@link core_course_renderer::course_section_cm()}
956 * @param stdClass $course course object
957 * @param int|stdClass|section_info $section relative section number or section object
958 * @param int $sectionreturn section number to return to
959 * @param int $displayoptions
960 * @return void
962 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
963 global $USER;
965 $output = '';
966 $modinfo = get_fast_modinfo($course);
967 if (is_object($section)) {
968 $section = $modinfo->get_section_info($section->section);
969 } else {
970 $section = $modinfo->get_section_info($section);
972 $completioninfo = new completion_info($course);
974 // check if we are currently in the process of moving a module with JavaScript disabled
975 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
976 if ($ismoving) {
977 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
978 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
981 // Get the list of modules visible to user (excluding the module being moved if there is one)
982 $moduleshtml = array();
983 if (!empty($modinfo->sections[$section->section])) {
984 foreach ($modinfo->sections[$section->section] as $modnumber) {
985 $mod = $modinfo->cms[$modnumber];
987 if ($ismoving and $mod->id == $USER->activitycopy) {
988 // do not display moving mod
989 continue;
992 if ($modulehtml = $this->course_section_cm_list_item($course,
993 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
994 $moduleshtml[$modnumber] = $modulehtml;
999 $sectionoutput = '';
1000 if (!empty($moduleshtml) || $ismoving) {
1001 foreach ($moduleshtml as $modnumber => $modulehtml) {
1002 if ($ismoving) {
1003 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
1004 $sectionoutput .= html_writer::tag('li',
1005 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1006 array('class' => 'movehere'));
1009 $sectionoutput .= $modulehtml;
1012 if ($ismoving) {
1013 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1014 $sectionoutput .= html_writer::tag('li',
1015 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1016 array('class' => 'movehere'));
1020 // Always output the section module list.
1021 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1023 return $output;
1027 * Displays a custom list of courses with paging bar if necessary
1029 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1030 * appears under the list.
1032 * If both $paginationurl and $totalcount are specified, and $totalcount is
1033 * bigger than count($courses), a paging bar is displayed above and under the
1034 * courses list.
1036 * @param array $courses array of course records (or instances of core_course_list_element) to show on this page
1037 * @param bool $showcategoryname whether to add category name to the course description
1038 * @param string $additionalclasses additional CSS classes to add to the div.courses
1039 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1040 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1041 * @param int $page current page number (defaults to 0 referring to the first page)
1042 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1043 * @return string
1045 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1046 global $CFG;
1047 // create instance of coursecat_helper to pass display options to function rendering courses list
1048 $chelper = new coursecat_helper();
1049 if ($showcategoryname) {
1050 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1051 } else {
1052 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1054 if ($totalcount !== null && $paginationurl !== null) {
1055 // add options to display pagination
1056 if ($perpage === null) {
1057 $perpage = $CFG->coursesperpage;
1059 $chelper->set_courses_display_options(array(
1060 'limit' => $perpage,
1061 'offset' => ((int)$page) * $perpage,
1062 'paginationurl' => $paginationurl,
1064 } else if ($paginationurl !== null) {
1065 // add options to display 'View more' link
1066 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1067 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1069 $chelper->set_attributes(array('class' => $additionalclasses));
1070 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1071 return $content;
1075 * Displays one course in the list of courses.
1077 * This is an internal function, to display an information about just one course
1078 * please use {@link core_course_renderer::course_info_box()}
1080 * @param coursecat_helper $chelper various display options
1081 * @param core_course_list_element|stdClass $course
1082 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1083 * depend on the course position in list - first/last/even/odd)
1084 * @return string
1086 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1087 if (!isset($this->strings->summary)) {
1088 $this->strings->summary = get_string('summary');
1090 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1091 return '';
1093 if ($course instanceof stdClass) {
1094 $course = new core_course_list_element($course);
1096 $content = '';
1097 $classes = trim('coursebox clearfix '. $additionalclasses);
1098 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1099 $nametag = 'h3';
1100 } else {
1101 $classes .= ' collapsed';
1102 $nametag = 'div';
1105 // .coursebox
1106 $content .= html_writer::start_tag('div', array(
1107 'class' => $classes,
1108 'data-courseid' => $course->id,
1109 'data-type' => self::COURSECAT_TYPE_COURSE,
1112 $content .= html_writer::start_tag('div', array('class' => 'info'));
1114 // course name
1115 $coursename = $chelper->get_course_formatted_name($course);
1116 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', array('id' => $course->id)),
1117 $coursename, array('class' => $course->visible ? '' : 'dimmed'));
1118 $content .= html_writer::tag($nametag, $coursenamelink, array('class' => 'coursename'));
1119 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1120 $content .= html_writer::start_tag('div', array('class' => 'moreinfo'));
1121 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1122 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()
1123 || $course->has_custom_fields()) {
1124 $url = new moodle_url('/course/info.php', array('id' => $course->id));
1125 $image = $this->output->pix_icon('i/info', $this->strings->summary);
1126 $content .= html_writer::link($url, $image, array('title' => $this->strings->summary));
1127 // Make sure JS file to expand course content is included.
1128 $this->coursecat_include_js();
1131 $content .= html_writer::end_tag('div'); // .moreinfo
1133 // print enrolmenticons
1134 if ($icons = enrol_get_course_info_icons($course)) {
1135 $content .= html_writer::start_tag('div', array('class' => 'enrolmenticons'));
1136 foreach ($icons as $pix_icon) {
1137 $content .= $this->render($pix_icon);
1139 $content .= html_writer::end_tag('div'); // .enrolmenticons
1142 $content .= html_writer::end_tag('div'); // .info
1144 $content .= html_writer::start_tag('div', array('class' => 'content'));
1145 $content .= $this->coursecat_coursebox_content($chelper, $course);
1146 $content .= html_writer::end_tag('div'); // .content
1148 $content .= html_writer::end_tag('div'); // .coursebox
1149 return $content;
1153 * Returns HTML to display course content (summary, course contacts and optionally category name)
1155 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1157 * @param coursecat_helper $chelper various display options
1158 * @param stdClass|core_course_list_element $course
1159 * @return string
1161 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1162 global $CFG;
1163 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1164 return '';
1166 if ($course instanceof stdClass) {
1167 $course = new core_course_list_element($course);
1169 $content = '';
1171 // display course summary
1172 if ($course->has_summary()) {
1173 $content .= html_writer::start_tag('div', array('class' => 'summary'));
1174 $content .= $chelper->get_course_formatted_summary($course,
1175 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1176 $content .= html_writer::end_tag('div'); // .summary
1179 // display course overview files
1180 $contentimages = $contentfiles = '';
1181 foreach ($course->get_course_overviewfiles() as $file) {
1182 $isimage = $file->is_valid_image();
1183 $url = file_encode_url("$CFG->wwwroot/pluginfile.php",
1184 '/'. $file->get_contextid(). '/'. $file->get_component(). '/'.
1185 $file->get_filearea(). $file->get_filepath(). $file->get_filename(), !$isimage);
1186 if ($isimage) {
1187 $contentimages .= html_writer::tag('div',
1188 html_writer::empty_tag('img', array('src' => $url)),
1189 array('class' => 'courseimage'));
1190 } else {
1191 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1192 $filename = html_writer::tag('span', $image, array('class' => 'fp-icon')).
1193 html_writer::tag('span', $file->get_filename(), array('class' => 'fp-filename'));
1194 $contentfiles .= html_writer::tag('span',
1195 html_writer::link($url, $filename),
1196 array('class' => 'coursefile fp-filename-icon'));
1199 $content .= $contentimages. $contentfiles;
1201 // Display course contacts. See core_course_list_element::get_course_contacts().
1202 if ($course->has_course_contacts()) {
1203 $content .= html_writer::start_tag('ul', array('class' => 'teachers'));
1204 foreach ($course->get_course_contacts() as $coursecontact) {
1205 $rolenames = array_map(function ($role) {
1206 return $role->displayname;
1207 }, $coursecontact['roles']);
1208 $name = implode(", ", $rolenames).': '.
1209 html_writer::link(new moodle_url('/user/view.php',
1210 array('id' => $coursecontact['user']->id, 'course' => SITEID)),
1211 $coursecontact['username']);
1212 $content .= html_writer::tag('li', $name);
1214 $content .= html_writer::end_tag('ul'); // .teachers
1217 // display course category if necessary (for example in search results)
1218 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1219 if ($cat = core_course_category::get($course->category, IGNORE_MISSING)) {
1220 $content .= html_writer::start_tag('div', array('class' => 'coursecat'));
1221 $content .= get_string('category').': '.
1222 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1223 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1224 $content .= html_writer::end_tag('div'); // .coursecat
1228 // Display custom fields.
1229 if ($course->has_custom_fields()) {
1230 $handler = core_course\customfield\course_handler::create();
1231 $customfields = $handler->display_custom_fields_data($course->get_custom_fields());
1232 $content .= \html_writer::tag('div', $customfields, ['class' => 'customfields-container']);
1235 return $content;
1239 * Renders the list of courses
1241 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1242 * method from outside of the class
1244 * If list of courses is specified in $courses; the argument $chelper is only used
1245 * to retrieve display options and attributes, only methods get_show_courses(),
1246 * get_courses_display_option() and get_and_erase_attributes() are called.
1248 * @param coursecat_helper $chelper various display options
1249 * @param array $courses the list of courses to display
1250 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1251 * defaulted to count($courses)
1252 * @return string
1254 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1255 global $CFG;
1256 if ($totalcount === null) {
1257 $totalcount = count($courses);
1259 if (!$totalcount) {
1260 // Courses count is cached during courses retrieval.
1261 return '';
1264 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1265 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1266 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1267 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1268 } else {
1269 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1273 // prepare content of paging bar if it is needed
1274 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1275 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1276 if ($totalcount > count($courses)) {
1277 // there are more results that can fit on one page
1278 if ($paginationurl) {
1279 // the option paginationurl was specified, display pagingbar
1280 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1281 $page = $chelper->get_courses_display_option('offset') / $perpage;
1282 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1283 $paginationurl->out(false, array('perpage' => $perpage)));
1284 if ($paginationallowall) {
1285 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1286 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1288 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1289 // the option for 'View more' link was specified, display more link
1290 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1291 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1292 array('class' => 'paging paging-morelink'));
1294 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1295 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1296 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1297 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1300 // display list of courses
1301 $attributes = $chelper->get_and_erase_attributes('courses');
1302 $content = html_writer::start_tag('div', $attributes);
1304 if (!empty($pagingbar)) {
1305 $content .= $pagingbar;
1308 $coursecount = 0;
1309 foreach ($courses as $course) {
1310 $coursecount ++;
1311 $classes = ($coursecount%2) ? 'odd' : 'even';
1312 if ($coursecount == 1) {
1313 $classes .= ' first';
1315 if ($coursecount >= count($courses)) {
1316 $classes .= ' last';
1318 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1321 if (!empty($pagingbar)) {
1322 $content .= $pagingbar;
1324 if (!empty($morelink)) {
1325 $content .= $morelink;
1328 $content .= html_writer::end_tag('div'); // .courses
1329 return $content;
1333 * Renders the list of subcategories in a category
1335 * @param coursecat_helper $chelper various display options
1336 * @param core_course_category $coursecat
1337 * @param int $depth depth of the category in the current tree
1338 * @return string
1340 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1341 global $CFG;
1342 $subcategories = array();
1343 if (!$chelper->get_categories_display_option('nodisplay')) {
1344 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1346 $totalcount = $coursecat->get_children_count();
1347 if (!$totalcount) {
1348 // Note that we call core_course_category::get_children_count() AFTER core_course_category::get_children()
1349 // to avoid extra DB requests.
1350 // Categories count is cached during children categories retrieval.
1351 return '';
1354 // prepare content of paging bar or more link if it is needed
1355 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1356 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1357 if ($totalcount > count($subcategories)) {
1358 if ($paginationurl) {
1359 // the option 'paginationurl was specified, display pagingbar
1360 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1361 $page = $chelper->get_categories_display_option('offset') / $perpage;
1362 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1363 $paginationurl->out(false, array('perpage' => $perpage)));
1364 if ($paginationallowall) {
1365 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1366 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1368 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1369 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1370 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1371 $viewmoreurl->param('categoryid', $coursecat->id);
1373 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1374 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1375 array('class' => 'paging paging-morelink'));
1377 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1378 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1379 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1380 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1383 // display list of subcategories
1384 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1386 if (!empty($pagingbar)) {
1387 $content .= $pagingbar;
1390 foreach ($subcategories as $subcategory) {
1391 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1394 if (!empty($pagingbar)) {
1395 $content .= $pagingbar;
1397 if (!empty($morelink)) {
1398 $content .= $morelink;
1401 $content .= html_writer::end_tag('div');
1402 return $content;
1406 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1408 protected function coursecat_include_js() {
1409 if (!$this->page->requires->should_create_one_time_item_now('core_course_categoryexpanderjsinit')) {
1410 return;
1413 // We must only load this module once.
1414 $this->page->requires->yui_module('moodle-course-categoryexpander',
1415 'Y.Moodle.course.categoryexpander.init');
1419 * Returns HTML to display the subcategories and courses in the given category
1421 * This method is re-used by AJAX to expand content of not loaded category
1423 * @param coursecat_helper $chelper various display options
1424 * @param core_course_category $coursecat
1425 * @param int $depth depth of the category in the current tree
1426 * @return string
1428 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1429 $content = '';
1430 // Subcategories
1431 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1433 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1434 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1435 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1436 if ($showcoursesauto && $depth) {
1437 // this is definitely collapsed mode
1438 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1441 // Courses
1442 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1443 $courses = array();
1444 if (!$chelper->get_courses_display_option('nodisplay')) {
1445 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1447 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1448 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1449 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1450 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1453 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1456 if ($showcoursesauto) {
1457 // restore the show_courses back to AUTO
1458 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1461 return $content;
1465 * Returns HTML to display a course category as a part of a tree
1467 * This is an internal function, to display a particular category and all its contents
1468 * use {@link core_course_renderer::course_category()}
1470 * @param coursecat_helper $chelper various display options
1471 * @param core_course_category $coursecat
1472 * @param int $depth depth of this category in the current tree
1473 * @return string
1475 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1476 // open category tag
1477 $classes = array('category');
1478 if (empty($coursecat->visible)) {
1479 $classes[] = 'dimmed_category';
1481 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1482 // do not load content
1483 $categorycontent = '';
1484 $classes[] = 'notloaded';
1485 if ($coursecat->get_children_count() ||
1486 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1487 $classes[] = 'with_children';
1488 $classes[] = 'collapsed';
1490 } else {
1491 // load category content
1492 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1493 $classes[] = 'loaded';
1494 if (!empty($categorycontent)) {
1495 $classes[] = 'with_children';
1496 // Category content loaded with children.
1497 $this->categoryexpandedonload = true;
1501 // Make sure JS file to expand category content is included.
1502 $this->coursecat_include_js();
1504 $content = html_writer::start_tag('div', array(
1505 'class' => join(' ', $classes),
1506 'data-categoryid' => $coursecat->id,
1507 'data-depth' => $depth,
1508 'data-showcourses' => $chelper->get_show_courses(),
1509 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1512 // category name
1513 $categoryname = $coursecat->get_formatted_name();
1514 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1515 array('categoryid' => $coursecat->id)),
1516 $categoryname);
1517 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1518 && ($coursescount = $coursecat->get_courses_count())) {
1519 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1520 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1522 $content .= html_writer::start_tag('div', array('class' => 'info'));
1524 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname'));
1525 $content .= html_writer::end_tag('div'); // .info
1527 // add category content to the output
1528 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1530 $content .= html_writer::end_tag('div'); // .category
1532 // Return the course category tree HTML
1533 return $content;
1537 * Returns HTML to display a tree of subcategories and courses in the given category
1539 * @param coursecat_helper $chelper various display options
1540 * @param core_course_category $coursecat top category (this category's name and description will NOT be added to the tree)
1541 * @return string
1543 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1544 // Reset the category expanded flag for this course category tree first.
1545 $this->categoryexpandedonload = false;
1546 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1547 if (empty($categorycontent)) {
1548 return '';
1551 // Start content generation
1552 $content = '';
1553 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1554 $content .= html_writer::start_tag('div', $attributes);
1556 if ($coursecat->get_children_count()) {
1557 $classes = array(
1558 'collapseexpand',
1561 // Check if the category content contains subcategories with children's content loaded.
1562 if ($this->categoryexpandedonload) {
1563 $classes[] = 'collapse-all';
1564 $linkname = get_string('collapseall');
1565 } else {
1566 $linkname = get_string('expandall');
1569 // Only show the collapse/expand if there are children to expand.
1570 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1571 $content .= html_writer::link('#', $linkname, array('class' => implode(' ', $classes)));
1572 $content .= html_writer::end_tag('div');
1573 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1576 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1578 $content .= html_writer::end_tag('div'); // .course_category_tree
1580 return $content;
1584 * Renders HTML to display particular course category - list of it's subcategories and courses
1586 * Invoked from /course/index.php
1588 * @param int|stdClass|core_course_category $category
1590 public function course_category($category) {
1591 global $CFG;
1592 $usertop = core_course_category::user_top();
1593 if (empty($category)) {
1594 $coursecat = $usertop;
1595 } else if (is_object($category) && $category instanceof core_course_category) {
1596 $coursecat = $category;
1597 } else {
1598 $coursecat = core_course_category::get(is_object($category) ? $category->id : $category);
1600 $site = get_site();
1601 $output = '';
1603 if ($coursecat->can_create_course() || $coursecat->has_manage_capability()) {
1604 // Add 'Manage' button if user has permissions to edit this category.
1605 $managebutton = $this->single_button(new moodle_url('/course/management.php',
1606 array('categoryid' => $coursecat->id)), get_string('managecourses'), 'get');
1607 $this->page->set_button($managebutton);
1610 if (core_course_category::is_simple_site()) {
1611 // There is only one category in the system, do not display link to it.
1612 $strfulllistofcourses = get_string('fulllistofcourses');
1613 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1614 } else if (!$coursecat->id || !$coursecat->is_uservisible()) {
1615 $strcategories = get_string('categories');
1616 $this->page->set_title("$site->shortname: $strcategories");
1617 } else {
1618 $strfulllistofcourses = get_string('fulllistofcourses');
1619 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1621 // Print the category selector
1622 $categorieslist = core_course_category::make_categories_list();
1623 if (count($categorieslist) > 1) {
1624 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1625 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1626 core_course_category::make_categories_list(), $coursecat->id, null, 'switchcategory');
1627 $select->set_label(get_string('categories').':');
1628 $output .= $this->render($select);
1629 $output .= html_writer::end_tag('div'); // .categorypicker
1633 // Print current category description
1634 $chelper = new coursecat_helper();
1635 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1636 $output .= $this->box($description, array('class' => 'generalbox info'));
1639 // Prepare parameters for courses and categories lists in the tree
1640 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1641 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1643 $coursedisplayoptions = array();
1644 $catdisplayoptions = array();
1645 $browse = optional_param('browse', null, PARAM_ALPHA);
1646 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1647 $page = optional_param('page', 0, PARAM_INT);
1648 $baseurl = new moodle_url('/course/index.php');
1649 if ($coursecat->id) {
1650 $baseurl->param('categoryid', $coursecat->id);
1652 if ($perpage != $CFG->coursesperpage) {
1653 $baseurl->param('perpage', $perpage);
1655 $coursedisplayoptions['limit'] = $perpage;
1656 $catdisplayoptions['limit'] = $perpage;
1657 if ($browse === 'courses' || !$coursecat->get_children_count()) {
1658 $coursedisplayoptions['offset'] = $page * $perpage;
1659 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1660 $catdisplayoptions['nodisplay'] = true;
1661 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1662 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1663 } else if ($browse === 'categories' || !$coursecat->get_courses_count()) {
1664 $coursedisplayoptions['nodisplay'] = true;
1665 $catdisplayoptions['offset'] = $page * $perpage;
1666 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1667 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1668 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1669 } else {
1670 // we have a category that has both subcategories and courses, display pagination separately
1671 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1672 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1674 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1675 // Add course search form.
1676 $output .= $this->course_search_form();
1678 // Display course category tree.
1679 $output .= $this->coursecat_tree($chelper, $coursecat);
1681 // Add action buttons
1682 $output .= $this->container_start('buttons');
1683 if ($coursecat->is_uservisible()) {
1684 $context = get_category_or_system_context($coursecat->id);
1685 if (has_capability('moodle/course:create', $context)) {
1686 // Print link to create a new course, for the 1st available category.
1687 if ($coursecat->id) {
1688 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1689 } else {
1690 $url = new moodle_url('/course/edit.php',
1691 array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1693 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1695 ob_start();
1696 print_course_request_buttons($context);
1697 $output .= ob_get_contents();
1698 ob_end_clean();
1700 $output .= $this->container_end();
1702 return $output;
1706 * Serves requests to /course/category.ajax.php
1708 * In this renderer implementation it may expand the category content or
1709 * course content.
1711 * @return string
1712 * @throws coding_exception
1714 public function coursecat_ajax() {
1715 global $DB, $CFG;
1717 $type = required_param('type', PARAM_INT);
1719 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1720 // This is a request for a category list of some kind.
1721 $categoryid = required_param('categoryid', PARAM_INT);
1722 $showcourses = required_param('showcourses', PARAM_INT);
1723 $depth = required_param('depth', PARAM_INT);
1725 $category = core_course_category::get($categoryid);
1727 $chelper = new coursecat_helper();
1728 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1729 $coursedisplayoptions = array(
1730 'limit' => $CFG->coursesperpage,
1731 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1733 $catdisplayoptions = array(
1734 'limit' => $CFG->coursesperpage,
1735 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1737 $chelper->set_show_courses($showcourses)->
1738 set_courses_display_options($coursedisplayoptions)->
1739 set_categories_display_options($catdisplayoptions);
1741 return $this->coursecat_category_content($chelper, $category, $depth);
1742 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1743 // This is a request for the course information.
1744 $courseid = required_param('courseid', PARAM_INT);
1746 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1748 $chelper = new coursecat_helper();
1749 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1750 return $this->coursecat_coursebox_content($chelper, $course);
1751 } else {
1752 throw new coding_exception('Invalid request type');
1757 * Renders html to display search result page
1759 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1760 * @return string
1762 public function search_courses($searchcriteria) {
1763 global $CFG;
1764 $content = '';
1765 if (!empty($searchcriteria)) {
1766 // print search results
1768 $displayoptions = array('sort' => array('displayname' => 1));
1769 // take the current page and number of results per page from query
1770 $perpage = optional_param('perpage', 0, PARAM_RAW);
1771 if ($perpage !== 'all') {
1772 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1773 $page = optional_param('page', 0, PARAM_INT);
1774 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1776 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1777 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1778 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1780 $class = 'course-search-result';
1781 foreach ($searchcriteria as $key => $value) {
1782 if (!empty($value)) {
1783 $class .= ' course-search-result-'. $key;
1786 $chelper = new coursecat_helper();
1787 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1788 set_courses_display_options($displayoptions)->
1789 set_search_criteria($searchcriteria)->
1790 set_attributes(array('class' => $class));
1792 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1793 $totalcount = core_course_category::search_courses_count($searchcriteria);
1794 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1796 if (!$totalcount) {
1797 if (!empty($searchcriteria['search'])) {
1798 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1799 } else {
1800 $content .= $this->heading(get_string('novalidcourses'));
1802 } else {
1803 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1804 $content .= $courseslist;
1807 if (!empty($searchcriteria['search'])) {
1808 // print search form only if there was a search by search string, otherwise it is confusing
1809 $content .= $this->box_start('generalbox mdl-align');
1810 $content .= $this->course_search_form($searchcriteria['search']);
1811 $content .= $this->box_end();
1813 } else {
1814 // just print search form
1815 $content .= $this->box_start('generalbox mdl-align');
1816 $content .= $this->course_search_form();
1817 $content .= $this->box_end();
1819 return $content;
1823 * Renders html to print list of courses tagged with particular tag
1825 * @param int $tagid id of the tag
1826 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1827 * are displayed on the page and the per-page limit may be bigger
1828 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1829 * to display items in the same context first
1830 * @param int $ctx context id where to search for records
1831 * @param bool $rec search in subcontexts as well
1832 * @param array $displayoptions
1833 * @return string empty string if no courses are marked with this tag or rendered list of courses
1835 public function tagged_courses($tagid, $exclusivemode = true, $ctx = 0, $rec = true, $displayoptions = null) {
1836 global $CFG;
1837 if (empty($displayoptions)) {
1838 $displayoptions = array();
1840 $showcategories = !core_course_category::is_simple_site();
1841 $displayoptions += array('limit' => $CFG->coursesperpage, 'offset' => 0);
1842 $chelper = new coursecat_helper();
1843 $searchcriteria = array('tagid' => $tagid, 'ctx' => $ctx, 'rec' => $rec);
1844 $chelper->set_show_courses($showcategories ? self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT :
1845 self::COURSECAT_SHOW_COURSES_EXPANDED)->
1846 set_search_criteria($searchcriteria)->
1847 set_courses_display_options($displayoptions)->
1848 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1849 // (we set the same css class as in search results by tagid)
1850 if ($totalcount = core_course_category::search_courses_count($searchcriteria)) {
1851 $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
1852 if ($exclusivemode) {
1853 return $this->coursecat_courses($chelper, $courses, $totalcount);
1854 } else {
1855 $tagfeed = new core_tag\output\tagfeed();
1856 $img = $this->output->pix_icon('i/course', '');
1857 foreach ($courses as $course) {
1858 $url = course_get_url($course);
1859 $imgwithlink = html_writer::link($url, $img);
1860 $coursename = html_writer::link($url, $course->get_formatted_name());
1861 $details = '';
1862 if ($showcategories && ($cat = core_course_category::get($course->category, IGNORE_MISSING))) {
1863 $details = get_string('category').': '.
1864 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1865 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1867 $tagfeed->add($imgwithlink, $coursename, $details);
1869 return $this->output->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($this->output));
1872 return '';
1876 * Returns HTML to display one remote course
1878 * @param stdClass $course remote course information, contains properties:
1879 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1880 * @return string
1882 protected function frontpage_remote_course(stdClass $course) {
1883 $url = new moodle_url('/auth/mnet/jump.php', array(
1884 'hostid' => $course->hostid,
1885 'wantsurl' => '/course/view.php?id='. $course->remoteid
1888 $output = '';
1889 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1890 $output .= html_writer::start_tag('div', array('class' => 'info'));
1891 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1892 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1893 $output .= html_writer::end_tag('h3'); // .name
1894 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1895 $output .= html_writer::end_tag('div'); // .info
1896 $output .= html_writer::start_tag('div', array('class' => 'content'));
1897 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1898 $options = new stdClass();
1899 $options->noclean = true;
1900 $options->para = false;
1901 $options->overflowdiv = true;
1902 $output .= format_text($course->summary, $course->summaryformat, $options);
1903 $output .= html_writer::end_tag('div'); // .summary
1904 $addinfo = format_string($course->hostname) . ' : '
1905 . format_string($course->cat_name) . ' : '
1906 . format_string($course->shortname);
1907 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1908 $output .= html_writer::end_tag('div'); // .content
1909 $output .= html_writer::end_tag('div'); // .coursebox
1910 return $output;
1914 * Returns HTML to display one remote host
1916 * @param array $host host information, contains properties: name, url, count
1917 * @return string
1919 protected function frontpage_remote_host($host) {
1920 $output = '';
1921 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1922 $output .= html_writer::start_tag('div', array('class' => 'info'));
1923 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1924 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1925 $output .= html_writer::end_tag('h3'); // .name
1926 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1927 $output .= html_writer::end_tag('div'); // .info
1928 $output .= html_writer::start_tag('div', array('class' => 'content'));
1929 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1930 $output .= $host['count'] . ' ' . get_string('courses');
1931 $output .= html_writer::end_tag('div'); // .content
1932 $output .= html_writer::end_tag('div'); // .coursebox
1933 return $output;
1937 * Returns HTML to print list of courses user is enrolled to for the frontpage
1939 * Also lists remote courses or remote hosts if MNET authorisation is used
1941 * @return string
1943 public function frontpage_my_courses() {
1944 global $USER, $CFG, $DB;
1946 if (!isloggedin() or isguestuser()) {
1947 return '';
1950 $output = '';
1951 $courses = enrol_get_my_courses('summary, summaryformat');
1952 $rhosts = array();
1953 $rcourses = array();
1954 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1955 $rcourses = get_my_remotecourses($USER->id);
1956 $rhosts = get_my_remotehosts();
1959 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1961 $chelper = new coursecat_helper();
1962 $totalcount = count($courses);
1963 if (count($courses) > $CFG->frontpagecourselimit) {
1964 // There are more enrolled courses than we can display, display link to 'My courses'.
1965 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
1966 $chelper->set_courses_display_options(array(
1967 'viewmoreurl' => new moodle_url('/my/'),
1968 'viewmoretext' => new lang_string('mycourses')
1970 } else if (core_course_category::top()->is_uservisible()) {
1971 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
1972 $chelper->set_courses_display_options(array(
1973 'viewmoreurl' => new moodle_url('/course/index.php'),
1974 'viewmoretext' => new lang_string('fulllistofcourses')
1976 $totalcount = $DB->count_records('course') - 1;
1978 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
1979 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
1980 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
1982 // MNET
1983 if (!empty($rcourses)) {
1984 // at the IDP, we know of all the remote courses
1985 $output .= html_writer::start_tag('div', array('class' => 'courses'));
1986 foreach ($rcourses as $course) {
1987 $output .= $this->frontpage_remote_course($course);
1989 $output .= html_writer::end_tag('div'); // .courses
1990 } elseif (!empty($rhosts)) {
1991 // non-IDP, we know of all the remote servers, but not courses
1992 $output .= html_writer::start_tag('div', array('class' => 'courses'));
1993 foreach ($rhosts as $host) {
1994 $output .= $this->frontpage_remote_host($host);
1996 $output .= html_writer::end_tag('div'); // .courses
1999 return $output;
2003 * Returns HTML to print list of available courses for the frontpage
2005 * @return string
2007 public function frontpage_available_courses() {
2008 global $CFG;
2010 $chelper = new coursecat_helper();
2011 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2012 set_courses_display_options(array(
2013 'recursive' => true,
2014 'limit' => $CFG->frontpagecourselimit,
2015 'viewmoreurl' => new moodle_url('/course/index.php'),
2016 'viewmoretext' => new lang_string('fulllistofcourses')));
2018 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
2019 $courses = core_course_category::top()->get_courses($chelper->get_courses_display_options());
2020 $totalcount = core_course_category::top()->get_courses_count($chelper->get_courses_display_options());
2021 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
2022 // Print link to create a new course, for the 1st available category.
2023 return $this->add_new_course_button();
2025 return $this->coursecat_courses($chelper, $courses, $totalcount);
2029 * Returns HTML to the "add new course" button for the page
2031 * @return string
2033 public function add_new_course_button() {
2034 global $CFG;
2035 // Print link to create a new course, for the 1st available category.
2036 $output = $this->container_start('buttons');
2037 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2038 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2039 $output .= $this->container_end('buttons');
2040 return $output;
2044 * Returns HTML to print tree with course categories and courses for the frontpage
2046 * @return string
2048 public function frontpage_combo_list() {
2049 global $CFG;
2050 // TODO MDL-10965 improve.
2051 $tree = core_course_category::top();
2052 if (!$tree->get_children_count()) {
2053 return '';
2055 $chelper = new coursecat_helper();
2056 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2057 set_categories_display_options(array(
2058 'limit' => $CFG->coursesperpage,
2059 'viewmoreurl' => new moodle_url('/course/index.php',
2060 array('browse' => 'categories', 'page' => 1))
2061 ))->
2062 set_courses_display_options(array(
2063 'limit' => $CFG->coursesperpage,
2064 'viewmoreurl' => new moodle_url('/course/index.php',
2065 array('browse' => 'courses', 'page' => 1))
2066 ))->
2067 set_attributes(array('class' => 'frontpage-category-combo'));
2068 return $this->coursecat_tree($chelper, $tree);
2072 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2074 * @return string
2076 public function frontpage_categories_list() {
2077 global $CFG;
2078 // TODO MDL-10965 improve.
2079 $tree = core_course_category::top();
2080 if (!$tree->get_children_count()) {
2081 return '';
2083 $chelper = new coursecat_helper();
2084 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2085 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2086 set_categories_display_options(array(
2087 'limit' => $CFG->coursesperpage,
2088 'viewmoreurl' => new moodle_url('/course/index.php',
2089 array('browse' => 'categories', 'page' => 1))
2090 ))->
2091 set_attributes(array('class' => 'frontpage-category-names'));
2092 return $this->coursecat_tree($chelper, $tree);
2096 * Renders the activity navigation.
2098 * Defer to template.
2100 * @param \core_course\output\activity_navigation $page
2101 * @return string html for the page
2103 public function render_activity_navigation(\core_course\output\activity_navigation $page) {
2104 $data = $page->export_for_template($this->output);
2105 return $this->output->render_from_template('core_course/activity_navigation', $data);
2109 * Display the selector to advertise or publish a course
2110 * @param int $courseid
2112 public function publicationselector($courseid) {
2113 $text = '';
2115 $advertiseurl = new moodle_url("/course/publish/metadata.php",
2116 array('sesskey' => sesskey(), 'id' => $courseid, 'advertise' => true));
2117 $advertisebutton = new single_button($advertiseurl, get_string('advertise', 'hub'));
2118 $text .= $this->output->render($advertisebutton);
2119 $text .= html_writer::tag('div', get_string('advertisepublication_help', 'hub'),
2120 array('class' => 'publishhelp'));
2122 $text .= html_writer::empty_tag('br'); // TODO Delete.
2124 $uploadurl = new moodle_url("/course/publish/metadata.php",
2125 array('sesskey' => sesskey(), 'id' => $courseid, 'share' => true));
2126 $uploadbutton = new single_button($uploadurl, get_string('share', 'hub'));
2127 $text .= $this->output->render($uploadbutton);
2128 $text .= html_writer::tag('div', get_string('sharepublication_help', 'hub'),
2129 array('class' => 'publishhelp'));
2131 return $text;
2135 * Display the listing of hub where a course is registered on
2136 * @param int $courseid
2137 * @param array $publications
2139 public function registeredonhublisting($courseid, $publications) {
2140 global $CFG;
2141 $table = new html_table();
2142 $table->head = array(get_string('type', 'hub'),
2143 get_string('date'), get_string('status', 'hub'), get_string('operation', 'hub'));
2144 $table->size = array('20%', '30%', '%20', '%25');
2146 $brtag = html_writer::empty_tag('br');
2148 foreach ($publications as $publication) {
2150 $params = array('id' => $publication->courseid, 'publicationid' => $publication->id);
2151 $cancelurl = new moodle_url("/course/publish/index.php", $params);
2152 $cancelbutton = new single_button($cancelurl, get_string('removefromhub', 'hub'));
2153 $cancelbutton->class = 'centeredbutton';
2154 $cancelbuttonhtml = $this->output->render($cancelbutton);
2156 if ($publication->enrollable) {
2157 $params = array('sesskey' => sesskey(), 'id' => $publication->courseid, 'publicationid' => $publication->id);
2158 $updateurl = new moodle_url("/course/publish/metadata.php", $params);
2159 $updatebutton = new single_button($updateurl, get_string('update', 'hub'));
2160 $updatebutton->class = 'centeredbutton';
2161 $updatebuttonhtml = $this->output->render($updatebutton);
2163 $operations = $updatebuttonhtml . $brtag . $cancelbuttonhtml;
2164 } else {
2165 $operations = $cancelbuttonhtml;
2168 // If the publication check time if bigger than May 2010, it has been checked.
2169 if ($publication->timechecked > 1273127954) {
2170 if ($publication->status == 0) {
2171 $status = get_string('statusunpublished', 'hub');
2172 } else {
2173 $status = get_string('statuspublished', 'hub');
2174 if (!empty($publication->link)) {
2175 $status = html_writer::link($publication->link, $status);
2179 $status .= $brtag . html_writer::tag('a', get_string('updatestatus', 'hub'),
2180 array('href' => $CFG->wwwroot . '/course/publish/index.php?id='
2181 . $courseid . "&updatestatusid=" . $publication->id
2182 . "&sesskey=" . sesskey())) .
2183 $brtag . get_string('lasttimechecked', 'hub') . ": "
2184 . format_time(time() - $publication->timechecked);
2185 } else {
2186 $status = get_string('neverchecked', 'hub') . $brtag
2187 . html_writer::tag('a', get_string('updatestatus', 'hub'),
2188 array('href' => $CFG->wwwroot . '/course/publish/index.php?id='
2189 . $courseid . "&updatestatusid=" . $publication->id
2190 . "&sesskey=" . sesskey()));
2192 // Add button cells.
2193 $cells = array($publication->enrollable ?
2194 get_string('advertised', 'hub') : get_string('shared', 'hub'),
2195 userdate($publication->timepublished,
2196 get_string('strftimedatetimeshort')), $status, $operations);
2197 $row = new html_table_row($cells);
2198 $table->data[] = $row;
2201 $contenthtml = html_writer::table($table);
2203 return $contenthtml;
2207 * Display unpublishing confirmation page
2208 * @param stdClass $publication
2209 * $publication->courseshortname
2210 * $publication->courseid
2211 * $publication->hubname
2212 * $publication->huburl
2213 * $publication->id
2215 public function confirmunpublishing($publication) {
2216 $optionsyes = array('sesskey' => sesskey(), 'id' => $publication->courseid,
2217 'hubcourseid' => $publication->hubcourseid,
2218 'cancel' => true, 'publicationid' => $publication->id, 'confirm' => true);
2219 $optionsno = array('sesskey' => sesskey(), 'id' => $publication->courseid);
2220 $publication->hubname = html_writer::tag('a', 'Moodle.net',
2221 array('href' => HUB_MOODLEORGHUBURL));
2222 $formcontinue = new single_button(new moodle_url("/course/publish/index.php",
2223 $optionsyes), get_string('unpublish', 'hub'), 'post');
2224 $formcancel = new single_button(new moodle_url("/course/publish/index.php",
2225 $optionsno), get_string('cancel'), 'get');
2226 return $this->output->confirm(get_string('unpublishconfirmation', 'hub', $publication),
2227 $formcontinue, $formcancel);
2231 * Display waiting information about backup size during uploading backup process
2232 * @param object $backupfile the backup stored_file
2233 * @return $html string
2235 public function sendingbackupinfo($backupfile) {
2236 $sizeinfo = new stdClass();
2237 $sizeinfo->total = number_format($backupfile->get_filesize() / 1000000, 2);
2238 $html = html_writer::tag('div', get_string('sendingsize', 'hub', $sizeinfo),
2239 array('class' => 'courseuploadtextinfo'));
2240 return $html;
2244 * Display upload successfull message and a button to the publish index page
2245 * @param int $id the course id
2246 * @return $html string
2248 public function sentbackupinfo($id) {
2249 $html = html_writer::tag('div', get_string('sent', 'hub'),
2250 array('class' => 'courseuploadtextinfo'));
2251 $publishindexurl = new moodle_url('/course/publish/index.php',
2252 array('sesskey' => sesskey(), 'id' => $id,
2253 'published' => true));
2254 $continue = $this->output->render(
2255 new single_button($publishindexurl, get_string('continue')));
2256 $html .= html_writer::tag('div', $continue, array('class' => 'sharecoursecontinue'));
2257 return $html;
2261 * Hub information (logo - name - description - link)
2262 * @param object $hubinfo
2263 * @return string html code
2265 public function hubinfo($hubinfo) {
2266 $screenshothtml = html_writer::empty_tag('img',
2267 array('src' => $hubinfo['imgurl'], 'alt' => $hubinfo['name']));
2268 $hubdescription = html_writer::tag('div', $screenshothtml,
2269 array('class' => 'hubscreenshot'));
2271 $hubdescription .= html_writer::tag('a', $hubinfo['name'],
2272 array('class' => 'hublink', 'href' => $hubinfo['url'],
2273 'onclick' => 'this.target="_blank"'));
2275 $hubdescription .= html_writer::tag('div', format_text($hubinfo['description'], FORMAT_PLAIN),
2276 array('class' => 'hubdescription'));
2277 $hubdescription = html_writer::tag('div', $hubdescription, array('class' => 'hubinfo clearfix'));
2279 return $hubdescription;
2283 * Output frontpage summary text and frontpage modules (stored as section 1 in site course)
2285 * This may be disabled in settings
2287 * @return string
2289 public function frontpage_section1() {
2290 global $SITE, $USER;
2292 $output = '';
2293 $editing = $this->page->user_is_editing();
2295 if ($editing) {
2296 // Make sure section with number 1 exists.
2297 course_create_sections_if_missing($SITE, 1);
2300 $modinfo = get_fast_modinfo($SITE);
2301 $section = $modinfo->get_section_info(1);
2302 if (($section && (!empty($modinfo->sections[1]) or !empty($section->summary))) or $editing) {
2303 $output .= $this->box_start('generalbox sitetopic');
2305 // If currently moving a file then show the current clipboard.
2306 if (ismoving($SITE->id)) {
2307 $stractivityclipboard = strip_tags(get_string('activityclipboard', '', $USER->activitycopyname));
2308 $output .= '<p><font size="2">';
2309 $cancelcopyurl = new moodle_url('/course/mod.php', ['cancelcopy' => 'true', 'sesskey' => sesskey()]);
2310 $output .= "$stractivityclipboard&nbsp;&nbsp;(" . html_writer::link($cancelcopyurl, get_string('cancel')) .')';
2311 $output .= '</font></p>';
2314 $context = context_course::instance(SITEID);
2316 // If the section name is set we show it.
2317 if (trim($section->name) !== '') {
2318 $output .= $this->heading(
2319 format_string($section->name, true, array('context' => $context)),
2321 'sectionname'
2325 $summarytext = file_rewrite_pluginfile_urls($section->summary,
2326 'pluginfile.php',
2327 $context->id,
2328 'course',
2329 'section',
2330 $section->id);
2331 $summaryformatoptions = new stdClass();
2332 $summaryformatoptions->noclean = true;
2333 $summaryformatoptions->overflowdiv = true;
2335 $output .= format_text($summarytext, $section->summaryformat, $summaryformatoptions);
2337 if ($editing && has_capability('moodle/course:update', $context)) {
2338 $streditsummary = get_string('editsummary');
2339 $editsectionurl = new moodle_url('/course/editsection.php', ['id' => $section->id]);
2340 $output .= html_writer::link($editsectionurl, $this->pix_icon('t/edit', $streditsummary)) .
2341 "<br /><br />";
2344 $output .= $this->course_section_cm_list($SITE, $section);
2346 $output .= $this->course_section_add_cm_control($SITE, $section->section);
2347 $output .= $this->box_end();
2350 return $output;
2354 * Output news for the frontpage (extract from site-wide news forum)
2356 * @param stdClass $forum record from db table 'forum' that represents the site news forum
2357 * @return string
2359 protected function frontpage_news($forum) {
2360 global $CFG, $SITE, $SESSION, $USER;
2361 require_once($CFG->dirroot .'/mod/forum/lib.php');
2363 $output = '';
2365 if (isloggedin()) {
2366 $SESSION->fromdiscussion = $CFG->wwwroot;
2367 $subtext = '';
2368 if (\mod_forum\subscriptions::is_subscribed($USER->id, $forum)) {
2369 if (!\mod_forum\subscriptions::is_forcesubscribed($forum)) {
2370 $subtext = get_string('unsubscribe', 'forum');
2372 } else {
2373 $subtext = get_string('subscribe', 'forum');
2375 $suburl = new moodle_url('/mod/forum/subscribe.php', array('id' => $forum->id, 'sesskey' => sesskey()));
2376 $output .= html_writer::tag('div', html_writer::link($suburl, $subtext), array('class' => 'subscribelink'));
2379 $coursemodule = get_coursemodule_from_instance('forum', $forum->id);
2380 $context = context_module::instance($coursemodule->id);
2382 $entityfactory = mod_forum\local\container::get_entity_factory();
2383 $forumentity = $entityfactory->get_forum_from_stdclass($forum, $context, $coursemodule, $SITE);
2385 $rendererfactory = mod_forum\local\container::get_renderer_factory();
2386 $discussionsrenderer = $rendererfactory->get_frontpage_news_discussion_list_renderer($forumentity);
2387 $cm = \cm_info::create($coursemodule);
2388 return $output . $discussionsrenderer->render($USER, $cm, null, null, 0, $SITE->newsitems);
2392 * Renders part of frontpage with a skip link (i.e. "My courses", "Site news", etc.)
2394 * @param string $skipdivid
2395 * @param string $contentsdivid
2396 * @param string $header Header of the part
2397 * @param string $contents Contents of the part
2398 * @return string
2400 protected function frontpage_part($skipdivid, $contentsdivid, $header, $contents) {
2401 if (strval($contents) === '') {
2402 return '';
2404 $output = html_writer::link('#' . $skipdivid,
2405 get_string('skipa', 'access', core_text::strtolower(strip_tags($header))),
2406 array('class' => 'skip-block skip'));
2408 // Wrap frontpage part in div container.
2409 $output .= html_writer::start_tag('div', array('id' => $contentsdivid));
2410 $output .= $this->heading($header);
2412 $output .= $contents;
2414 // End frontpage part div container.
2415 $output .= html_writer::end_tag('div');
2417 $output .= html_writer::tag('span', '', array('class' => 'skip-block-to', 'id' => $skipdivid));
2418 return $output;
2422 * Outputs contents for frontpage as configured in $CFG->frontpage or $CFG->frontpageloggedin
2424 * @return string
2426 public function frontpage() {
2427 global $CFG, $SITE;
2429 $output = '';
2431 if (isloggedin() and !isguestuser() and isset($CFG->frontpageloggedin)) {
2432 $frontpagelayout = $CFG->frontpageloggedin;
2433 } else {
2434 $frontpagelayout = $CFG->frontpage;
2437 foreach (explode(',', $frontpagelayout) as $v) {
2438 switch ($v) {
2439 // Display the main part of the front page.
2440 case FRONTPAGENEWS:
2441 if ($SITE->newsitems) {
2442 // Print forums only when needed.
2443 require_once($CFG->dirroot .'/mod/forum/lib.php');
2444 if (($newsforum = forum_get_course_forum($SITE->id, 'news')) &&
2445 ($forumcontents = $this->frontpage_news($newsforum))) {
2446 $newsforumcm = get_fast_modinfo($SITE)->instances['forum'][$newsforum->id];
2447 $output .= $this->frontpage_part('skipsitenews', 'site-news-forum',
2448 $newsforumcm->get_formatted_name(), $forumcontents);
2451 break;
2453 case FRONTPAGEENROLLEDCOURSELIST:
2454 $mycourseshtml = $this->frontpage_my_courses();
2455 if (!empty($mycourseshtml)) {
2456 $output .= $this->frontpage_part('skipmycourses', 'frontpage-course-list',
2457 get_string('mycourses'), $mycourseshtml);
2459 break;
2461 case FRONTPAGEALLCOURSELIST:
2462 $availablecourseshtml = $this->frontpage_available_courses();
2463 $output .= $this->frontpage_part('skipavailablecourses', 'frontpage-available-course-list',
2464 get_string('availablecourses'), $availablecourseshtml);
2465 break;
2467 case FRONTPAGECATEGORYNAMES:
2468 $output .= $this->frontpage_part('skipcategories', 'frontpage-category-names',
2469 get_string('categories'), $this->frontpage_categories_list());
2470 break;
2472 case FRONTPAGECATEGORYCOMBO:
2473 $output .= $this->frontpage_part('skipcourses', 'frontpage-category-combo',
2474 get_string('courses'), $this->frontpage_combo_list());
2475 break;
2477 case FRONTPAGECOURSESEARCH:
2478 $output .= $this->box($this->course_search_form('', 'short'), 'mdl-align');
2479 break;
2482 $output .= '<br />';
2485 return $output;
2490 * Class storing display options and functions to help display course category and/or courses lists
2492 * This is a wrapper for core_course_category objects that also stores display options
2493 * and functions to retrieve sorted and paginated lists of categories/courses.
2495 * If theme overrides methods in core_course_renderers that access this class
2496 * it may as well not use this class at all or extend it.
2498 * @package core
2499 * @copyright 2013 Marina Glancy
2500 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2502 class coursecat_helper {
2503 /** @var string [none, collapsed, expanded] how (if) display courses list */
2504 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2505 /** @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) */
2506 protected $subcatdepth = 1;
2507 /** @var array options to display courses list */
2508 protected $coursesdisplayoptions = array();
2509 /** @var array options to display subcategories list */
2510 protected $categoriesdisplayoptions = array();
2511 /** @var array additional HTML attributes */
2512 protected $attributes = array();
2513 /** @var array search criteria if the list is a search result */
2514 protected $searchcriteria = null;
2517 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2519 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2520 * @return coursecat_helper
2522 public function set_show_courses($showcourses) {
2523 $this->showcourses = $showcourses;
2524 // Automatically set the options to preload summary and coursecontacts for core_course_category::get_courses()
2525 // and core_course_category::search_courses().
2526 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2527 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2528 $this->coursesdisplayoptions['customfields'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED;
2529 return $this;
2533 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2535 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2537 public function get_show_courses() {
2538 return $this->showcourses;
2542 * Sets the maximum depth to expand subcategories in the tree
2544 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2546 * @param int $subcatdepth
2547 * @return coursecat_helper
2549 public function set_subcat_depth($subcatdepth) {
2550 $this->subcatdepth = $subcatdepth;
2551 return $this;
2555 * Returns the maximum depth to expand subcategories in the tree
2557 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2559 * @return int
2561 public function get_subcat_depth() {
2562 return $this->subcatdepth;
2566 * Sets options to display list of courses
2568 * Options are later submitted as argument to core_course_category::get_courses() and/or core_course_category::search_courses()
2570 * Options that core_course_category::get_courses() accept:
2571 * - recursive - return courses from subcategories as well. Use with care,
2572 * this may be a huge list!
2573 * - summary - preloads fields 'summary' and 'summaryformat'
2574 * - coursecontacts - preloads course contacts
2575 * - customfields - preloads custom fields data
2576 * - isenrolled - preloads indication whether this user is enrolled in the course
2577 * - sort - list of fields to sort. Example
2578 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2579 * will sort by idnumber asc, shortname asc and id desc.
2580 * Default: array('sortorder' => 1)
2581 * Only cached fields may be used for sorting!
2582 * - offset
2583 * - limit - maximum number of children to return, 0 or null for no limit
2585 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2587 * Also renderer can set here any additional options it wants to pass between renderer functions.
2589 * @param array $options
2590 * @return coursecat_helper
2592 public function set_courses_display_options($options) {
2593 $this->coursesdisplayoptions = $options;
2594 $this->set_show_courses($this->showcourses); // this will calculate special display options
2595 return $this;
2599 * Sets one option to display list of courses
2601 * @see coursecat_helper::set_courses_display_options()
2603 * @param string $key
2604 * @param mixed $value
2605 * @return coursecat_helper
2607 public function set_courses_display_option($key, $value) {
2608 $this->coursesdisplayoptions[$key] = $value;
2609 return $this;
2613 * Return the specified option to display list of courses
2615 * @param string $optionname option name
2616 * @param mixed $defaultvalue default value for option if it is not specified
2617 * @return mixed
2619 public function get_courses_display_option($optionname, $defaultvalue = null) {
2620 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2621 return $this->coursesdisplayoptions[$optionname];
2622 } else {
2623 return $defaultvalue;
2628 * Returns all options to display the courses
2630 * This array is usually passed to {@link core_course_category::get_courses()} or
2631 * {@link core_course_category::search_courses()}
2633 * @return array
2635 public function get_courses_display_options() {
2636 return $this->coursesdisplayoptions;
2640 * Sets options to display list of subcategories
2642 * Options 'sort', 'offset' and 'limit' are passed to core_course_category::get_children().
2643 * Any other options may be used by renderer functions
2645 * @param array $options
2646 * @return coursecat_helper
2648 public function set_categories_display_options($options) {
2649 $this->categoriesdisplayoptions = $options;
2650 return $this;
2654 * Return the specified option to display list of subcategories
2656 * @param string $optionname option name
2657 * @param mixed $defaultvalue default value for option if it is not specified
2658 * @return mixed
2660 public function get_categories_display_option($optionname, $defaultvalue = null) {
2661 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2662 return $this->categoriesdisplayoptions[$optionname];
2663 } else {
2664 return $defaultvalue;
2669 * Returns all options to display list of subcategories
2671 * This array is usually passed to {@link core_course_category::get_children()}
2673 * @return array
2675 public function get_categories_display_options() {
2676 return $this->categoriesdisplayoptions;
2680 * Sets additional general options to pass between renderer functions, usually HTML attributes
2682 * @param array $attributes
2683 * @return coursecat_helper
2685 public function set_attributes($attributes) {
2686 $this->attributes = $attributes;
2687 return $this;
2691 * Return all attributes and erases them so they are not applied again
2693 * @param string $classname adds additional class name to the beginning of $attributes['class']
2694 * @return array
2696 public function get_and_erase_attributes($classname) {
2697 $attributes = $this->attributes;
2698 $this->attributes = array();
2699 if (empty($attributes['class'])) {
2700 $attributes['class'] = '';
2702 $attributes['class'] = $classname . ' '. $attributes['class'];
2703 return $attributes;
2707 * Sets the search criteria if the course is a search result
2709 * Search string will be used to highlight terms in course name and description
2711 * @param array $searchcriteria
2712 * @return coursecat_helper
2714 public function set_search_criteria($searchcriteria) {
2715 $this->searchcriteria = $searchcriteria;
2716 return $this;
2720 * Returns formatted and filtered description of the given category
2722 * @param core_course_category $coursecat category
2723 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2724 * if context is not specified it will be added automatically
2725 * @return string|null
2727 public function get_category_formatted_description($coursecat, $options = null) {
2728 if ($coursecat->id && $coursecat->is_uservisible() && !empty($coursecat->description)) {
2729 if (!isset($coursecat->descriptionformat)) {
2730 $descriptionformat = FORMAT_MOODLE;
2731 } else {
2732 $descriptionformat = $coursecat->descriptionformat;
2734 if ($options === null) {
2735 $options = array('noclean' => true, 'overflowdiv' => true);
2736 } else {
2737 $options = (array)$options;
2739 $context = context_coursecat::instance($coursecat->id);
2740 if (!isset($options['context'])) {
2741 $options['context'] = $context;
2743 $text = file_rewrite_pluginfile_urls($coursecat->description,
2744 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2745 return format_text($text, $descriptionformat, $options);
2747 return null;
2751 * Returns given course's summary with proper embedded files urls and formatted
2753 * @param core_course_list_element $course
2754 * @param array|stdClass $options additional formatting options
2755 * @return string
2757 public function get_course_formatted_summary($course, $options = array()) {
2758 global $CFG;
2759 require_once($CFG->libdir. '/filelib.php');
2760 if (!$course->has_summary()) {
2761 return '';
2763 $options = (array)$options;
2764 $context = context_course::instance($course->id);
2765 if (!isset($options['context'])) {
2766 // TODO see MDL-38521
2767 // option 1 (current), page context - no code required
2768 // option 2, system context
2769 // $options['context'] = context_system::instance();
2770 // option 3, course context:
2771 // $options['context'] = $context;
2772 // option 4, course category context:
2773 // $options['context'] = $context->get_parent_context();
2775 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2776 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2777 if (!empty($this->searchcriteria['search'])) {
2778 $summary = highlight($this->searchcriteria['search'], $summary);
2780 return $summary;
2784 * Returns course name as it is configured to appear in courses lists formatted to course context
2786 * @param core_course_list_element $course
2787 * @param array|stdClass $options additional formatting options
2788 * @return string
2790 public function get_course_formatted_name($course, $options = array()) {
2791 $options = (array)$options;
2792 if (!isset($options['context'])) {
2793 $options['context'] = context_course::instance($course->id);
2795 $name = format_string(get_course_display_name_for_list($course), true, $options);
2796 if (!empty($this->searchcriteria['search'])) {
2797 $name = highlight($this->searchcriteria['search'], $name);
2799 return $name;