MDL-56110 forms: debug message for php 7.1 compat
[moodle.git] / course / renderer.php
blob96d1690b79a5df8d27bc22653e8c5b55dfe6b6c2
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 * Override the constructor so that we can initialise the string cache
55 * @param moodle_page $page
56 * @param string $target
58 public function __construct(moodle_page $page, $target) {
59 $this->strings = new stdClass;
60 parent::__construct($page, $target);
63 /**
64 * Adds the item in course settings navigation to toggle modchooser
66 * Theme can overwrite as an empty function to exclude it (for example if theme does not
67 * use modchooser at all)
69 * @deprecated since 3.2
71 protected function add_modchoosertoggle() {
72 debugging('core_course_renderer::add_modchoosertoggle() is deprecated.', DEBUG_DEVELOPER);
74 global $CFG;
76 // Only needs to be done once per page.
77 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchoosertoggle')) {
78 return;
81 if ($this->page->state > moodle_page::STATE_PRINTING_HEADER ||
82 $this->page->course->id == SITEID ||
83 !$this->page->user_is_editing() ||
84 !($context = context_course::instance($this->page->course->id)) ||
85 !has_capability('moodle/course:manageactivities', $context) ||
86 !course_ajax_enabled($this->page->course) ||
87 !($coursenode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE)) ||
88 !($turneditingnode = $coursenode->get('turneditingonoff'))) {
89 // Too late, or we are on site page, or we could not find the
90 // adjacent nodes in course settings menu, or we are not allowed to edit.
91 return;
94 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
95 // We are on the course page, retain the current page params e.g. section.
96 $modchoosertoggleurl = clone($this->page->url);
97 } else {
98 // Edit on the main course page.
99 $modchoosertoggleurl = new moodle_url('/course/view.php', array('id' => $this->page->course->id,
100 'return' => $this->page->url->out_as_local_url(false)));
102 $modchoosertoggleurl->param('sesskey', sesskey());
103 if ($usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault)) {
104 $modchoosertogglestring = get_string('modchooserdisable', 'moodle');
105 $modchoosertoggleurl->param('modchooser', 'off');
106 } else {
107 $modchoosertogglestring = get_string('modchooserenable', 'moodle');
108 $modchoosertoggleurl->param('modchooser', 'on');
110 $modchoosertoggle = navigation_node::create($modchoosertogglestring, $modchoosertoggleurl, navigation_node::TYPE_SETTING, null, 'modchoosertoggle');
112 // Insert the modchoosertoggle after the settings node 'turneditingonoff' (navigation_node only has function to insert before, so we insert before and then swap).
113 $coursenode->add_node($modchoosertoggle, 'turneditingonoff');
114 $turneditingnode->remove();
115 $coursenode->add_node($turneditingnode, 'modchoosertoggle');
117 $modchoosertoggle->add_class('modchoosertoggle');
118 $modchoosertoggle->add_class('visibleifjs');
119 user_preference_allow_ajax_update('usemodchooser', PARAM_BOOL);
123 * Renders course info box.
125 * @param stdClass|course_in_list $course
126 * @return string
128 public function course_info_box(stdClass $course) {
129 $content = '';
130 $content .= $this->output->box_start('generalbox info');
131 $chelper = new coursecat_helper();
132 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
133 $content .= $this->coursecat_coursebox($chelper, $course);
134 $content .= $this->output->box_end();
135 return $content;
139 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
141 * @deprecated since 2.5
143 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
145 * @param array $ignored argument ignored
146 * @return string
148 public final function course_category_tree(array $ignored) {
149 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
150 return $this->frontpage_combo_list();
154 * Renderers a category for use with course_category_tree
156 * @deprecated since 2.5
158 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
160 * @param array $category
161 * @param int $depth
162 * @return string
164 protected final function course_category_tree_category(stdClass $category, $depth=1) {
165 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
166 return '';
170 * Render a modchooser.
172 * @param renderable $modchooser The chooser.
173 * @return string
175 public function render_modchooser(renderable $modchooser) {
176 return $this->render_from_template('core_course/modchooser', $modchooser->export_for_template($this));
180 * Build the HTML for the module chooser javascript popup
182 * @param array $modules A set of modules as returned form @see
183 * get_module_metadata
184 * @param object $course The course that will be displayed
185 * @return string The composed HTML for the module
187 public function course_modchooser($modules, $course) {
188 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchooser')) {
189 return '';
191 $modchooser = new \core_course\output\modchooser($course, $modules);
192 return $this->render($modchooser);
196 * Build the HTML for a specified set of modules
198 * @param array $modules A set of modules as used by the
199 * course_modchooser_module function
200 * @return string The composed HTML for the module
202 protected function course_modchooser_module_types($modules) {
203 debugging('Method core_course_renderer::course_modchooser_module_types() is deprecated, ' .
204 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
205 return '';
209 * Return the HTML for the specified module adding any required classes
211 * @param object $module An object containing the title, and link. An
212 * icon, and help text may optionally be specified. If the module
213 * contains subtypes in the types option, then these will also be
214 * displayed.
215 * @param array $classes Additional classes to add to the encompassing
216 * div element
217 * @return string The composed HTML for the module
219 protected function course_modchooser_module($module, $classes = array('option')) {
220 debugging('Method core_course_renderer::course_modchooser_module() is deprecated, ' .
221 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
222 return '';
225 protected function course_modchooser_title($title, $identifier = null) {
226 debugging('Method core_course_renderer::course_modchooser_title() is deprecated, ' .
227 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
228 return '';
232 * Renders HTML for displaying the sequence of course module editing buttons
234 * @see course_get_cm_edit_actions()
236 * @param action_link[] $actions Array of action_link objects
237 * @param cm_info $mod The module we are displaying actions for.
238 * @param array $displayoptions additional display options:
239 * ownerselector => A JS/CSS selector that can be used to find an cm node.
240 * If specified the owning node will be given the class 'action-menu-shown' when the action
241 * menu is being displayed.
242 * constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
243 * the action menu to when it is being displayed.
244 * donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
245 * @return string
247 public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
248 global $CFG;
250 if (empty($actions)) {
251 return '';
254 if (isset($displayoptions['ownerselector'])) {
255 $ownerselector = $displayoptions['ownerselector'];
256 } else if ($mod) {
257 $ownerselector = '#module-'.$mod->id;
258 } else {
259 debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
260 $ownerselector = 'li.activity';
263 if (isset($displayoptions['constraintselector'])) {
264 $constraint = $displayoptions['constraintselector'];
265 } else {
266 $constraint = '.course-content';
269 $menu = new action_menu();
270 $menu->set_owner_selector($ownerselector);
271 $menu->set_constraint($constraint);
272 $menu->set_alignment(action_menu::TR, action_menu::BR);
273 $menu->set_menu_trigger(get_string('edit'));
275 foreach ($actions as $action) {
276 if ($action instanceof action_menu_link) {
277 $action->add_class('cm-edit-action');
279 $menu->add($action);
281 $menu->attributes['class'] .= ' section-cm-edit-actions commands';
283 // Prioritise the menu ahead of all other actions.
284 $menu->prioritise = true;
286 return $this->render($menu);
290 * Renders HTML for the menus to add activities and resources to the current course
292 * @param stdClass $course
293 * @param int $section relative section number (field course_sections.section)
294 * @param int $sectionreturn The section to link back to
295 * @param array $displayoptions additional display options, for example blocks add
296 * option 'inblock' => true, suggesting to display controls vertically
297 * @return string
299 function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
300 global $CFG;
302 $vertical = !empty($displayoptions['inblock']);
304 // check to see if user can add menus and there are modules to add
305 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
306 || !$this->page->user_is_editing()
307 || !($modnames = get_module_types_names()) || empty($modnames)) {
308 return '';
311 // Retrieve all modules with associated metadata
312 $modules = get_module_metadata($course, $modnames, $sectionreturn);
313 $urlparams = array('section' => $section);
315 // We'll sort resources and activities into two lists
316 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
318 foreach ($modules as $module) {
319 $activityclass = MOD_CLASS_ACTIVITY;
320 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
321 $activityclass = MOD_CLASS_RESOURCE;
322 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
323 // System modules cannot be added by user, do not add to dropdown.
324 continue;
326 $link = $module->link->out(true, $urlparams);
327 $activities[$activityclass][$link] = $module->title;
330 $straddactivity = get_string('addactivity');
331 $straddresource = get_string('addresource');
332 $sectionname = get_section_name($course, $section);
333 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
334 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
336 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
338 if (!$vertical) {
339 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
342 if (!empty($activities[MOD_CLASS_RESOURCE])) {
343 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array(''=>$straddresource), "ressection$section");
344 $select->set_help_icon('resources');
345 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
346 $output .= $this->output->render($select);
349 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
350 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array(''=>$straddactivity), "section$section");
351 $select->set_help_icon('activities');
352 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
353 $output .= $this->output->render($select);
356 if (!$vertical) {
357 $output .= html_writer::end_tag('div');
360 $output .= html_writer::end_tag('div');
362 if (course_ajax_enabled($course) && $course->id == $this->page->course->id) {
363 // modchooser can be added only for the current course set on the page!
364 $straddeither = get_string('addresourceoractivity');
365 // The module chooser link
366 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
367 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
368 $icon = $this->output->pix_icon('t/add', '');
369 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
370 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
371 $modchooser.= html_writer::end_tag('div');
372 $modchooser.= html_writer::end_tag('div');
374 // Wrap the normal output in a noscript div
375 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
376 if ($usemodchooser) {
377 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
378 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
379 } else {
380 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
381 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
382 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
384 $output = $this->course_modchooser($modules, $course) . $modchooser . $output;
387 return $output;
391 * Renders html to display a course search form
393 * @param string $value default value to populate the search field
394 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
395 * @return string
397 function course_search_form($value = '', $format = 'plain') {
398 static $count = 0;
399 $formid = 'coursesearch';
400 if ((++$count) > 1) {
401 $formid .= $count;
404 switch ($format) {
405 case 'navbar' :
406 $formid = 'coursesearchnavbar';
407 $inputid = 'navsearchbox';
408 $inputsize = 20;
409 break;
410 case 'short' :
411 $inputid = 'shortsearchbox';
412 $inputsize = 12;
413 break;
414 default :
415 $inputid = 'coursesearchbox';
416 $inputsize = 30;
419 $strsearchcourses= get_string("searchcourses");
420 $searchurl = new moodle_url('/course/search.php');
422 $output = html_writer::start_tag('form', array('id' => $formid, 'action' => $searchurl, 'method' => 'get'));
423 $output .= html_writer::start_tag('fieldset', array('class' => 'coursesearchbox invisiblefieldset'));
424 $output .= html_writer::tag('label', $strsearchcourses.': ', array('for' => $inputid));
425 $output .= html_writer::empty_tag('input', array('type' => 'text', 'id' => $inputid,
426 'size' => $inputsize, 'name' => 'search', 'value' => s($value)));
427 $output .= html_writer::empty_tag('input', array('type' => 'submit',
428 'value' => get_string('go')));
429 $output .= html_writer::end_tag('fieldset');
430 $output .= html_writer::end_tag('form');
432 return $output;
436 * Renders html for completion box on course page
438 * If completion is disabled, returns empty string
439 * If completion is automatic, returns an icon of the current completion state
440 * If completion is manual, returns a form (with an icon inside) that allows user to
441 * toggle completion
443 * @param stdClass $course course object
444 * @param completion_info $completioninfo completion info for the course, it is recommended
445 * to fetch once for all modules in course/section for performance
446 * @param cm_info $mod module to show completion for
447 * @param array $displayoptions display options, not used in core
448 * @return string
450 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
451 global $CFG;
452 $output = '';
453 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
454 return $output;
456 if ($completioninfo === null) {
457 $completioninfo = new completion_info($course);
459 $completion = $completioninfo->is_enabled($mod);
460 if ($completion == COMPLETION_TRACKING_NONE) {
461 if ($this->page->user_is_editing()) {
462 $output .= html_writer::span('&nbsp;', 'filler');
464 return $output;
467 $completiondata = $completioninfo->get_data($mod, true);
468 $completionicon = '';
470 if ($this->page->user_is_editing()) {
471 switch ($completion) {
472 case COMPLETION_TRACKING_MANUAL :
473 $completionicon = 'manual-enabled'; break;
474 case COMPLETION_TRACKING_AUTOMATIC :
475 $completionicon = 'auto-enabled'; break;
477 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
478 switch($completiondata->completionstate) {
479 case COMPLETION_INCOMPLETE:
480 $completionicon = 'manual-n'; break;
481 case COMPLETION_COMPLETE:
482 $completionicon = 'manual-y'; break;
484 } else { // Automatic
485 switch($completiondata->completionstate) {
486 case COMPLETION_INCOMPLETE:
487 $completionicon = 'auto-n'; break;
488 case COMPLETION_COMPLETE:
489 $completionicon = 'auto-y'; break;
490 case COMPLETION_COMPLETE_PASS:
491 $completionicon = 'auto-pass'; break;
492 case COMPLETION_COMPLETE_FAIL:
493 $completionicon = 'auto-fail'; break;
496 if ($completionicon) {
497 $formattedname = $mod->get_formatted_name();
498 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
500 if ($this->page->user_is_editing()) {
501 // When editing, the icon is just an image.
502 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
503 array('title' => $imgalt, 'class' => 'iconsmall'));
504 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
505 array('class' => 'autocompletion'));
506 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
507 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
508 $newstate =
509 $completiondata->completionstate == COMPLETION_COMPLETE
510 ? COMPLETION_INCOMPLETE
511 : COMPLETION_COMPLETE;
512 // In manual mode the icon is a toggle form...
514 // If this completion state is used by the
515 // conditional activities system, we need to turn
516 // off the JS.
517 $extraclass = '';
518 if (!empty($CFG->enableavailability) &&
519 core_availability\info::completion_value_used($course, $mod->id)) {
520 $extraclass = ' preventjs';
522 $output .= html_writer::start_tag('form', array('method' => 'post',
523 'action' => new moodle_url('/course/togglecompletion.php'),
524 'class' => 'togglecompletion'. $extraclass));
525 $output .= html_writer::start_tag('div');
526 $output .= html_writer::empty_tag('input', array(
527 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
528 $output .= html_writer::empty_tag('input', array(
529 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
530 $output .= html_writer::empty_tag('input', array(
531 'type' => 'hidden', 'name' => 'modulename', 'value' => $mod->name));
532 $output .= html_writer::empty_tag('input', array(
533 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
534 $output .= html_writer::empty_tag('input', array(
535 'type' => 'image',
536 'src' => $this->output->pix_url('i/completion-'.$completionicon),
537 'alt' => $imgalt, 'title' => $imgtitle,
538 'aria-live' => 'polite'));
539 $output .= html_writer::end_tag('div');
540 $output .= html_writer::end_tag('form');
541 } else {
542 // In auto mode, the icon is just an image.
543 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
544 array('title' => $imgalt));
545 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
546 array('class' => 'autocompletion'));
549 return $output;
553 * Checks if course module has any conditions that may make it unavailable for
554 * all or some of the students
556 * This function is internal and is only used to create CSS classes for the module name/text
558 * @param cm_info $mod
559 * @return bool
561 protected function is_cm_conditionally_hidden(cm_info $mod) {
562 global $CFG;
563 $conditionalhidden = false;
564 if (!empty($CFG->enableavailability)) {
565 $info = new \core_availability\info_module($mod);
566 $conditionalhidden = !$info->is_available_for_all();
568 return $conditionalhidden;
572 * Renders html to display a name with the link to the course module on a course page
574 * If module is unavailable for user but still needs to be displayed
575 * in the list, just the name is returned without a link
577 * Note, that for course modules that never have separate pages (i.e. labels)
578 * this function return an empty string
580 * @param cm_info $mod
581 * @param array $displayoptions
582 * @return string
584 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
585 if ((!$mod->uservisible && empty($mod->availableinfo)) || !$mod->url) {
586 // Nothing to be displayed to the user.
587 return '';
590 // Render element that allows to edit activity name inline. It calls {@link course_section_cm_name_title()}
591 // to get the display title of the activity.
592 $tmpl = new \core_course\output\course_module_name($mod, $this->page->user_is_editing(), $displayoptions);
593 return $this->output->render_from_template('core/inplace_editable', $tmpl->export_for_template($this->output));
597 * Renders html to display a name with the link to the course module on a course page
599 * If module is unavailable for user but still needs to be displayed
600 * in the list, just the name is returned without a link
602 * Note, that for course modules that never have separate pages (i.e. labels)
603 * this function return an empty string
605 * @param cm_info $mod
606 * @param array $displayoptions
607 * @return string
609 public function course_section_cm_name_title(cm_info $mod, $displayoptions = array()) {
610 $output = '';
611 if (!$mod->uservisible && empty($mod->availableinfo)) {
612 // Nothing to be displayed to the user.
613 return $output;
615 $url = $mod->url;
616 if (!$url) {
617 return $output;
620 //Accessibility: for files get description via icon, this is very ugly hack!
621 $instancename = $mod->get_formatted_name();
622 $altname = $mod->modfullname;
623 // Avoid unnecessary duplication: if e.g. a forum name already
624 // includes the word forum (or Forum, etc) then it is unhelpful
625 // to include that in the accessible description that is added.
626 if (false !== strpos(core_text::strtolower($instancename),
627 core_text::strtolower($altname))) {
628 $altname = '';
630 // File type after name, for alphabetic lists (screen reader).
631 if ($altname) {
632 $altname = get_accesshide(' '.$altname);
635 // For items which are hidden but available to current user
636 // ($mod->uservisible), we show those as dimmed only if the user has
637 // viewhiddenactivities, so that teachers see 'items which might not
638 // be available to some students' dimmed but students do not see 'item
639 // which is actually available to current student' dimmed.
640 $linkclasses = '';
641 $accesstext = '';
642 $textclasses = '';
643 if ($mod->uservisible) {
644 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
645 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
646 has_capability('moodle/course:viewhiddenactivities', $mod->context);
647 if ($accessiblebutdim) {
648 $linkclasses .= ' dimmed';
649 $textclasses .= ' dimmed_text';
650 if ($conditionalhidden) {
651 $linkclasses .= ' conditionalhidden';
652 $textclasses .= ' conditionalhidden';
654 // Show accessibility note only if user can access the module himself.
655 $accesstext = get_accesshide(get_string('hiddenfromstudents').':'. $mod->modfullname);
657 } else {
658 $linkclasses .= ' dimmed';
659 $textclasses .= ' dimmed_text';
662 // Get on-click attribute value if specified and decode the onclick - it
663 // has already been encoded for display (puke).
664 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
666 $groupinglabel = $mod->get_grouping_label($textclasses);
668 // Display link itself.
669 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
670 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) . $accesstext .
671 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
672 if ($mod->uservisible) {
673 $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick)) .
674 $groupinglabel;
675 } else {
676 // We may be displaying this just in order to show information
677 // about visibility, without the actual link ($mod->uservisible)
678 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses)) .
679 $groupinglabel;
681 return $output;
685 * Renders html to display the module content on the course page (i.e. text of the labels)
687 * @param cm_info $mod
688 * @param array $displayoptions
689 * @return string
691 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
692 $output = '';
693 if (!$mod->uservisible && empty($mod->availableinfo)) {
694 // nothing to be displayed to the user
695 return $output;
697 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
698 $accesstext = '';
699 $textclasses = '';
700 if ($mod->uservisible) {
701 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
702 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
703 has_capability('moodle/course:viewhiddenactivities', $mod->context);
704 if ($accessiblebutdim) {
705 $textclasses .= ' dimmed_text';
706 if ($conditionalhidden) {
707 $textclasses .= ' conditionalhidden';
709 // Show accessibility note only if user can access the module himself.
710 $accesstext = get_accesshide(get_string('hiddenfromstudents').':'. $mod->modfullname);
712 } else {
713 $textclasses .= ' dimmed_text';
715 if ($mod->url) {
716 if ($content) {
717 // If specified, display extra content after link.
718 $output = html_writer::tag('div', $content, array('class' =>
719 trim('contentafterlink ' . $textclasses)));
721 } else {
722 $groupinglabel = $mod->get_grouping_label($textclasses);
724 // No link, so display only content.
725 $output = html_writer::tag('div', $accesstext . $content . $groupinglabel,
726 array('class' => 'contentwithoutlink ' . $textclasses));
728 return $output;
732 * Renders HTML to show course module availability information (for someone who isn't allowed
733 * to see the activity itself, or for staff)
735 * @param cm_info $mod
736 * @param array $displayoptions
737 * @return string
739 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
740 global $CFG;
741 if (!$mod->uservisible) {
742 // this is a student who is not allowed to see the module but might be allowed
743 // to see availability info (i.e. "Available from ...")
744 if (!empty($mod->availableinfo)) {
745 $formattedinfo = \core_availability\info::format_info(
746 $mod->availableinfo, $mod->get_course());
747 $output = html_writer::tag('div', $formattedinfo, array('class' => 'availabilityinfo'));
749 return $output;
751 // this is a teacher who is allowed to see module but still should see the
752 // information that module is not available to all/some students
753 $modcontext = context_module::instance($mod->id);
754 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
755 if ($canviewhidden && !empty($CFG->enableavailability)) {
756 // Don't add availability information if user is not editing and activity is hidden.
757 if ($mod->visible || $this->page->user_is_editing()) {
758 $hidinfoclass = '';
759 if (!$mod->visible) {
760 $hidinfoclass = 'hide';
762 $ci = new \core_availability\info_module($mod);
763 $fullinfo = $ci->get_full_information();
764 if ($fullinfo) {
765 $formattedinfo = \core_availability\info::format_info(
766 $fullinfo, $mod->get_course());
767 return html_writer::div($formattedinfo, 'availabilityinfo ' . $hidinfoclass);
771 return '';
775 * Renders HTML to display one course module for display within a section.
777 * This function calls:
778 * {@link core_course_renderer::course_section_cm()}
780 * @param stdClass $course
781 * @param completion_info $completioninfo
782 * @param cm_info $mod
783 * @param int|null $sectionreturn
784 * @param array $displayoptions
785 * @return String
787 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
788 $output = '';
789 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
790 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
791 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
793 return $output;
797 * Renders HTML to display one course module in a course section
799 * This includes link, content, availability, completion info and additional information
800 * that module type wants to display (i.e. number of unread forum posts)
802 * This function calls:
803 * {@link core_course_renderer::course_section_cm_name()}
804 * {@link core_course_renderer::course_section_cm_text()}
805 * {@link core_course_renderer::course_section_cm_availability()}
806 * {@link core_course_renderer::course_section_cm_completion()}
807 * {@link course_get_cm_edit_actions()}
808 * {@link core_course_renderer::course_section_cm_edit_actions()}
810 * @param stdClass $course
811 * @param completion_info $completioninfo
812 * @param cm_info $mod
813 * @param int|null $sectionreturn
814 * @param array $displayoptions
815 * @return string
817 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
818 $output = '';
819 // We return empty string (because course module will not be displayed at all)
820 // if:
821 // 1) The activity is not visible to users
822 // and
823 // 2) The 'availableinfo' is empty, i.e. the activity was
824 // hidden in a way that leaves no info, such as using the
825 // eye icon.
826 if (!$mod->uservisible && empty($mod->availableinfo)) {
827 return $output;
830 $indentclasses = 'mod-indent';
831 if (!empty($mod->indent)) {
832 $indentclasses .= ' mod-indent-'.$mod->indent;
833 if ($mod->indent > 15) {
834 $indentclasses .= ' mod-indent-huge';
838 $output .= html_writer::start_tag('div');
840 if ($this->page->user_is_editing()) {
841 $output .= course_get_cm_move($mod, $sectionreturn);
844 $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer'));
846 // This div is used to indent the content.
847 $output .= html_writer::div('', $indentclasses);
849 // Start a wrapper for the actual content to keep the indentation consistent
850 $output .= html_writer::start_tag('div');
852 // Display the link to the module (or do nothing if module has no url)
853 $cmname = $this->course_section_cm_name($mod, $displayoptions);
855 if (!empty($cmname)) {
856 // Start the div for the activity title, excluding the edit icons.
857 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
858 $output .= $cmname;
861 // Module can put text after the link (e.g. forum unread)
862 $output .= $mod->afterlink;
864 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
865 $output .= html_writer::end_tag('div'); // .activityinstance
868 // If there is content but NO link (eg label), then display the
869 // content here (BEFORE any icons). In this case cons must be
870 // displayed after the content so that it makes more sense visually
871 // and for accessibility reasons, e.g. if you have a one-line label
872 // it should work similarly (at least in terms of ordering) to an
873 // activity.
874 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
875 $url = $mod->url;
876 if (empty($url)) {
877 $output .= $contentpart;
880 $modicons = '';
881 if ($this->page->user_is_editing()) {
882 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
883 $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
884 $modicons .= $mod->afterediticons;
887 $modicons .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
889 if (!empty($modicons)) {
890 $output .= html_writer::span($modicons, 'actions');
893 // If there is content AND a link, then display the content here
894 // (AFTER any icons). Otherwise it was displayed before
895 if (!empty($url)) {
896 $output .= $contentpart;
899 // show availability info (if module is not available)
900 $output .= $this->course_section_cm_availability($mod, $displayoptions);
902 $output .= html_writer::end_tag('div'); // $indentclasses
904 // End of indentation div.
905 $output .= html_writer::end_tag('div');
907 $output .= html_writer::end_tag('div');
908 return $output;
912 * Renders HTML to display a list of course modules in a course section
913 * Also displays "move here" controls in Javascript-disabled mode
915 * This function calls {@link core_course_renderer::course_section_cm()}
917 * @param stdClass $course course object
918 * @param int|stdClass|section_info $section relative section number or section object
919 * @param int $sectionreturn section number to return to
920 * @param int $displayoptions
921 * @return void
923 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
924 global $USER;
926 $output = '';
927 $modinfo = get_fast_modinfo($course);
928 if (is_object($section)) {
929 $section = $modinfo->get_section_info($section->section);
930 } else {
931 $section = $modinfo->get_section_info($section);
933 $completioninfo = new completion_info($course);
935 // check if we are currently in the process of moving a module with JavaScript disabled
936 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
937 if ($ismoving) {
938 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
939 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
942 // Get the list of modules visible to user (excluding the module being moved if there is one)
943 $moduleshtml = array();
944 if (!empty($modinfo->sections[$section->section])) {
945 foreach ($modinfo->sections[$section->section] as $modnumber) {
946 $mod = $modinfo->cms[$modnumber];
948 if ($ismoving and $mod->id == $USER->activitycopy) {
949 // do not display moving mod
950 continue;
953 if ($modulehtml = $this->course_section_cm_list_item($course,
954 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
955 $moduleshtml[$modnumber] = $modulehtml;
960 $sectionoutput = '';
961 if (!empty($moduleshtml) || $ismoving) {
962 foreach ($moduleshtml as $modnumber => $modulehtml) {
963 if ($ismoving) {
964 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
965 $sectionoutput .= html_writer::tag('li',
966 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
967 array('class' => 'movehere'));
970 $sectionoutput .= $modulehtml;
973 if ($ismoving) {
974 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
975 $sectionoutput .= html_writer::tag('li',
976 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
977 array('class' => 'movehere'));
981 // Always output the section module list.
982 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
984 return $output;
988 * Displays a custom list of courses with paging bar if necessary
990 * If $paginationurl is specified but $totalcount is not, the link 'View more'
991 * appears under the list.
993 * If both $paginationurl and $totalcount are specified, and $totalcount is
994 * bigger than count($courses), a paging bar is displayed above and under the
995 * courses list.
997 * @param array $courses array of course records (or instances of course_in_list) to show on this page
998 * @param bool $showcategoryname whether to add category name to the course description
999 * @param string $additionalclasses additional CSS classes to add to the div.courses
1000 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1001 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1002 * @param int $page current page number (defaults to 0 referring to the first page)
1003 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1004 * @return string
1006 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1007 global $CFG;
1008 // create instance of coursecat_helper to pass display options to function rendering courses list
1009 $chelper = new coursecat_helper();
1010 if ($showcategoryname) {
1011 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1012 } else {
1013 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1015 if ($totalcount !== null && $paginationurl !== null) {
1016 // add options to display pagination
1017 if ($perpage === null) {
1018 $perpage = $CFG->coursesperpage;
1020 $chelper->set_courses_display_options(array(
1021 'limit' => $perpage,
1022 'offset' => ((int)$page) * $perpage,
1023 'paginationurl' => $paginationurl,
1025 } else if ($paginationurl !== null) {
1026 // add options to display 'View more' link
1027 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1028 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1030 $chelper->set_attributes(array('class' => $additionalclasses));
1031 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1032 return $content;
1036 * Displays one course in the list of courses.
1038 * This is an internal function, to display an information about just one course
1039 * please use {@link core_course_renderer::course_info_box()}
1041 * @param coursecat_helper $chelper various display options
1042 * @param course_in_list|stdClass $course
1043 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1044 * depend on the course position in list - first/last/even/odd)
1045 * @return string
1047 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1048 global $CFG;
1049 if (!isset($this->strings->summary)) {
1050 $this->strings->summary = get_string('summary');
1052 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1053 return '';
1055 if ($course instanceof stdClass) {
1056 require_once($CFG->libdir. '/coursecatlib.php');
1057 $course = new course_in_list($course);
1059 $content = '';
1060 $classes = trim('coursebox clearfix '. $additionalclasses);
1061 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1062 $nametag = 'h3';
1063 } else {
1064 $classes .= ' collapsed';
1065 $nametag = 'div';
1068 // .coursebox
1069 $content .= html_writer::start_tag('div', array(
1070 'class' => $classes,
1071 'data-courseid' => $course->id,
1072 'data-type' => self::COURSECAT_TYPE_COURSE,
1075 $content .= html_writer::start_tag('div', array('class' => 'info'));
1077 // course name
1078 $coursename = $chelper->get_course_formatted_name($course);
1079 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', array('id' => $course->id)),
1080 $coursename, array('class' => $course->visible ? '' : 'dimmed'));
1081 $content .= html_writer::tag($nametag, $coursenamelink, array('class' => 'coursename'));
1082 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1083 $content .= html_writer::start_tag('div', array('class' => 'moreinfo'));
1084 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1085 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()) {
1086 $url = new moodle_url('/course/info.php', array('id' => $course->id));
1087 $image = html_writer::empty_tag('img', array('src' => $this->output->pix_url('i/info'),
1088 'alt' => $this->strings->summary));
1089 $content .= html_writer::link($url, $image, array('title' => $this->strings->summary));
1090 // Make sure JS file to expand course content is included.
1091 $this->coursecat_include_js();
1094 $content .= html_writer::end_tag('div'); // .moreinfo
1096 // print enrolmenticons
1097 if ($icons = enrol_get_course_info_icons($course)) {
1098 $content .= html_writer::start_tag('div', array('class' => 'enrolmenticons'));
1099 foreach ($icons as $pix_icon) {
1100 $content .= $this->render($pix_icon);
1102 $content .= html_writer::end_tag('div'); // .enrolmenticons
1105 $content .= html_writer::end_tag('div'); // .info
1107 $content .= html_writer::start_tag('div', array('class' => 'content'));
1108 $content .= $this->coursecat_coursebox_content($chelper, $course);
1109 $content .= html_writer::end_tag('div'); // .content
1111 $content .= html_writer::end_tag('div'); // .coursebox
1112 return $content;
1116 * Returns HTML to display course content (summary, course contacts and optionally category name)
1118 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1120 * @param coursecat_helper $chelper various display options
1121 * @param stdClass|course_in_list $course
1122 * @return string
1124 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1125 global $CFG;
1126 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1127 return '';
1129 if ($course instanceof stdClass) {
1130 require_once($CFG->libdir. '/coursecatlib.php');
1131 $course = new course_in_list($course);
1133 $content = '';
1135 // display course summary
1136 if ($course->has_summary()) {
1137 $content .= html_writer::start_tag('div', array('class' => 'summary'));
1138 $content .= $chelper->get_course_formatted_summary($course,
1139 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1140 $content .= html_writer::end_tag('div'); // .summary
1143 // display course overview files
1144 $contentimages = $contentfiles = '';
1145 foreach ($course->get_course_overviewfiles() as $file) {
1146 $isimage = $file->is_valid_image();
1147 $url = file_encode_url("$CFG->wwwroot/pluginfile.php",
1148 '/'. $file->get_contextid(). '/'. $file->get_component(). '/'.
1149 $file->get_filearea(). $file->get_filepath(). $file->get_filename(), !$isimage);
1150 if ($isimage) {
1151 $contentimages .= html_writer::tag('div',
1152 html_writer::empty_tag('img', array('src' => $url)),
1153 array('class' => 'courseimage'));
1154 } else {
1155 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1156 $filename = html_writer::tag('span', $image, array('class' => 'fp-icon')).
1157 html_writer::tag('span', $file->get_filename(), array('class' => 'fp-filename'));
1158 $contentfiles .= html_writer::tag('span',
1159 html_writer::link($url, $filename),
1160 array('class' => 'coursefile fp-filename-icon'));
1163 $content .= $contentimages. $contentfiles;
1165 // display course contacts. See course_in_list::get_course_contacts()
1166 if ($course->has_course_contacts()) {
1167 $content .= html_writer::start_tag('ul', array('class' => 'teachers'));
1168 foreach ($course->get_course_contacts() as $userid => $coursecontact) {
1169 $name = $coursecontact['rolename'].': '.
1170 html_writer::link(new moodle_url('/user/view.php',
1171 array('id' => $userid, 'course' => SITEID)),
1172 $coursecontact['username']);
1173 $content .= html_writer::tag('li', $name);
1175 $content .= html_writer::end_tag('ul'); // .teachers
1178 // display course category if necessary (for example in search results)
1179 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1180 require_once($CFG->libdir. '/coursecatlib.php');
1181 if ($cat = coursecat::get($course->category, IGNORE_MISSING)) {
1182 $content .= html_writer::start_tag('div', array('class' => 'coursecat'));
1183 $content .= get_string('category').': '.
1184 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1185 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1186 $content .= html_writer::end_tag('div'); // .coursecat
1190 return $content;
1194 * Renders the list of courses
1196 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1197 * method from outside of the class
1199 * If list of courses is specified in $courses; the argument $chelper is only used
1200 * to retrieve display options and attributes, only methods get_show_courses(),
1201 * get_courses_display_option() and get_and_erase_attributes() are called.
1203 * @param coursecat_helper $chelper various display options
1204 * @param array $courses the list of courses to display
1205 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1206 * defaulted to count($courses)
1207 * @return string
1209 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1210 global $CFG;
1211 if ($totalcount === null) {
1212 $totalcount = count($courses);
1214 if (!$totalcount) {
1215 // Courses count is cached during courses retrieval.
1216 return '';
1219 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1220 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1221 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1222 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1223 } else {
1224 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1228 // prepare content of paging bar if it is needed
1229 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1230 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1231 if ($totalcount > count($courses)) {
1232 // there are more results that can fit on one page
1233 if ($paginationurl) {
1234 // the option paginationurl was specified, display pagingbar
1235 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1236 $page = $chelper->get_courses_display_option('offset') / $perpage;
1237 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1238 $paginationurl->out(false, array('perpage' => $perpage)));
1239 if ($paginationallowall) {
1240 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1241 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1243 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1244 // the option for 'View more' link was specified, display more link
1245 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1246 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1247 array('class' => 'paging paging-morelink'));
1249 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1250 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1251 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1252 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1255 // display list of courses
1256 $attributes = $chelper->get_and_erase_attributes('courses');
1257 $content = html_writer::start_tag('div', $attributes);
1259 if (!empty($pagingbar)) {
1260 $content .= $pagingbar;
1263 $coursecount = 0;
1264 foreach ($courses as $course) {
1265 $coursecount ++;
1266 $classes = ($coursecount%2) ? 'odd' : 'even';
1267 if ($coursecount == 1) {
1268 $classes .= ' first';
1270 if ($coursecount >= count($courses)) {
1271 $classes .= ' last';
1273 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1276 if (!empty($pagingbar)) {
1277 $content .= $pagingbar;
1279 if (!empty($morelink)) {
1280 $content .= $morelink;
1283 $content .= html_writer::end_tag('div'); // .courses
1284 return $content;
1288 * Renders the list of subcategories in a category
1290 * @param coursecat_helper $chelper various display options
1291 * @param coursecat $coursecat
1292 * @param int $depth depth of the category in the current tree
1293 * @return string
1295 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1296 global $CFG;
1297 $subcategories = array();
1298 if (!$chelper->get_categories_display_option('nodisplay')) {
1299 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1301 $totalcount = $coursecat->get_children_count();
1302 if (!$totalcount) {
1303 // Note that we call coursecat::get_children_count() AFTER coursecat::get_children() to avoid extra DB requests.
1304 // Categories count is cached during children categories retrieval.
1305 return '';
1308 // prepare content of paging bar or more link if it is needed
1309 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1310 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1311 if ($totalcount > count($subcategories)) {
1312 if ($paginationurl) {
1313 // the option 'paginationurl was specified, display pagingbar
1314 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1315 $page = $chelper->get_categories_display_option('offset') / $perpage;
1316 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1317 $paginationurl->out(false, array('perpage' => $perpage)));
1318 if ($paginationallowall) {
1319 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1320 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1322 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1323 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1324 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1325 $viewmoreurl->param('categoryid', $coursecat->id);
1327 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1328 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1329 array('class' => 'paging paging-morelink'));
1331 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1332 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1333 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1334 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1337 // display list of subcategories
1338 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1340 if (!empty($pagingbar)) {
1341 $content .= $pagingbar;
1344 foreach ($subcategories as $subcategory) {
1345 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1348 if (!empty($pagingbar)) {
1349 $content .= $pagingbar;
1351 if (!empty($morelink)) {
1352 $content .= $morelink;
1355 $content .= html_writer::end_tag('div');
1356 return $content;
1360 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1362 protected function coursecat_include_js() {
1363 if (!$this->page->requires->should_create_one_time_item_now('core_course_categoryexpanderjsinit')) {
1364 return;
1367 // We must only load this module once.
1368 $this->page->requires->yui_module('moodle-course-categoryexpander',
1369 'Y.Moodle.course.categoryexpander.init');
1373 * Returns HTML to display the subcategories and courses in the given category
1375 * This method is re-used by AJAX to expand content of not loaded category
1377 * @param coursecat_helper $chelper various display options
1378 * @param coursecat $coursecat
1379 * @param int $depth depth of the category in the current tree
1380 * @return string
1382 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1383 $content = '';
1384 // Subcategories
1385 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1387 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1388 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1389 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1390 if ($showcoursesauto && $depth) {
1391 // this is definitely collapsed mode
1392 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1395 // Courses
1396 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1397 $courses = array();
1398 if (!$chelper->get_courses_display_option('nodisplay')) {
1399 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1401 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1402 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1403 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1404 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1407 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1410 if ($showcoursesauto) {
1411 // restore the show_courses back to AUTO
1412 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1415 return $content;
1419 * Returns HTML to display a course category as a part of a tree
1421 * This is an internal function, to display a particular category and all its contents
1422 * use {@link core_course_renderer::course_category()}
1424 * @param coursecat_helper $chelper various display options
1425 * @param coursecat $coursecat
1426 * @param int $depth depth of this category in the current tree
1427 * @return string
1429 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1430 // open category tag
1431 $classes = array('category');
1432 if (empty($coursecat->visible)) {
1433 $classes[] = 'dimmed_category';
1435 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1436 // do not load content
1437 $categorycontent = '';
1438 $classes[] = 'notloaded';
1439 if ($coursecat->get_children_count() ||
1440 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1441 $classes[] = 'with_children';
1442 $classes[] = 'collapsed';
1444 } else {
1445 // load category content
1446 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1447 $classes[] = 'loaded';
1448 if (!empty($categorycontent)) {
1449 $classes[] = 'with_children';
1453 // Make sure JS file to expand category content is included.
1454 $this->coursecat_include_js();
1456 $content = html_writer::start_tag('div', array(
1457 'class' => join(' ', $classes),
1458 'data-categoryid' => $coursecat->id,
1459 'data-depth' => $depth,
1460 'data-showcourses' => $chelper->get_show_courses(),
1461 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1464 // category name
1465 $categoryname = $coursecat->get_formatted_name();
1466 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1467 array('categoryid' => $coursecat->id)),
1468 $categoryname);
1469 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1470 && ($coursescount = $coursecat->get_courses_count())) {
1471 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1472 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1474 $content .= html_writer::start_tag('div', array('class' => 'info'));
1476 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname'));
1477 $content .= html_writer::end_tag('div'); // .info
1479 // add category content to the output
1480 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1482 $content .= html_writer::end_tag('div'); // .category
1484 // Return the course category tree HTML
1485 return $content;
1489 * Returns HTML to display a tree of subcategories and courses in the given category
1491 * @param coursecat_helper $chelper various display options
1492 * @param coursecat $coursecat top category (this category's name and description will NOT be added to the tree)
1493 * @return string
1495 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1496 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1497 if (empty($categorycontent)) {
1498 return '';
1501 // Start content generation
1502 $content = '';
1503 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1504 $content .= html_writer::start_tag('div', $attributes);
1506 if ($coursecat->get_children_count()) {
1507 $classes = array(
1508 'collapseexpand',
1509 'collapse-all',
1511 if ($chelper->get_subcat_depth() == 1) {
1512 $classes[] = 'disabled';
1514 // Only show the collapse/expand if there are children to expand.
1515 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1516 $content .= html_writer::link('#', get_string('collapseall'),
1517 array('class' => implode(' ', $classes)));
1518 $content .= html_writer::end_tag('div');
1519 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1522 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1524 $content .= html_writer::end_tag('div'); // .course_category_tree
1526 return $content;
1530 * Renders HTML to display particular course category - list of it's subcategories and courses
1532 * Invoked from /course/index.php
1534 * @param int|stdClass|coursecat $category
1536 public function course_category($category) {
1537 global $CFG;
1538 require_once($CFG->libdir. '/coursecatlib.php');
1539 $coursecat = coursecat::get(is_object($category) ? $category->id : $category);
1540 $site = get_site();
1541 $output = '';
1543 if (can_edit_in_category($coursecat->id)) {
1544 // Add 'Manage' button if user has permissions to edit this category.
1545 $managebutton = $this->single_button(new moodle_url('/course/management.php',
1546 array('categoryid' => $coursecat->id)), get_string('managecourses'), 'get');
1547 $this->page->set_button($managebutton);
1549 if (!$coursecat->id) {
1550 if (coursecat::count_all() == 1) {
1551 // There exists only one category in the system, do not display link to it
1552 $coursecat = coursecat::get_default();
1553 $strfulllistofcourses = get_string('fulllistofcourses');
1554 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1555 } else {
1556 $strcategories = get_string('categories');
1557 $this->page->set_title("$site->shortname: $strcategories");
1559 } else {
1560 $this->page->set_title("$site->shortname: ". $coursecat->get_formatted_name());
1562 // Print the category selector
1563 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1564 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1565 coursecat::make_categories_list(), $coursecat->id, null, 'switchcategory');
1566 $select->set_label(get_string('categories').':');
1567 $output .= $this->render($select);
1568 $output .= html_writer::end_tag('div'); // .categorypicker
1571 // Print current category description
1572 $chelper = new coursecat_helper();
1573 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1574 $output .= $this->box($description, array('class' => 'generalbox info'));
1577 // Prepare parameters for courses and categories lists in the tree
1578 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1579 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1581 $coursedisplayoptions = array();
1582 $catdisplayoptions = array();
1583 $browse = optional_param('browse', null, PARAM_ALPHA);
1584 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1585 $page = optional_param('page', 0, PARAM_INT);
1586 $baseurl = new moodle_url('/course/index.php');
1587 if ($coursecat->id) {
1588 $baseurl->param('categoryid', $coursecat->id);
1590 if ($perpage != $CFG->coursesperpage) {
1591 $baseurl->param('perpage', $perpage);
1593 $coursedisplayoptions['limit'] = $perpage;
1594 $catdisplayoptions['limit'] = $perpage;
1595 if ($browse === 'courses' || !$coursecat->has_children()) {
1596 $coursedisplayoptions['offset'] = $page * $perpage;
1597 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1598 $catdisplayoptions['nodisplay'] = true;
1599 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1600 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1601 } else if ($browse === 'categories' || !$coursecat->has_courses()) {
1602 $coursedisplayoptions['nodisplay'] = true;
1603 $catdisplayoptions['offset'] = $page * $perpage;
1604 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1605 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1606 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1607 } else {
1608 // we have a category that has both subcategories and courses, display pagination separately
1609 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1610 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1612 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1613 // Add course search form.
1614 $output .= $this->course_search_form();
1616 // Display course category tree.
1617 $output .= $this->coursecat_tree($chelper, $coursecat);
1619 // Add action buttons
1620 $output .= $this->container_start('buttons');
1621 $context = get_category_or_system_context($coursecat->id);
1622 if (has_capability('moodle/course:create', $context)) {
1623 // Print link to create a new course, for the 1st available category.
1624 if ($coursecat->id) {
1625 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1626 } else {
1627 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1629 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1631 ob_start();
1632 if (coursecat::count_all() == 1) {
1633 print_course_request_buttons(context_system::instance());
1634 } else {
1635 print_course_request_buttons($context);
1637 $output .= ob_get_contents();
1638 ob_end_clean();
1639 $output .= $this->container_end();
1641 return $output;
1645 * Serves requests to /course/category.ajax.php
1647 * In this renderer implementation it may expand the category content or
1648 * course content.
1650 * @return string
1651 * @throws coding_exception
1653 public function coursecat_ajax() {
1654 global $DB, $CFG;
1655 require_once($CFG->libdir. '/coursecatlib.php');
1657 $type = required_param('type', PARAM_INT);
1659 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1660 // This is a request for a category list of some kind.
1661 $categoryid = required_param('categoryid', PARAM_INT);
1662 $showcourses = required_param('showcourses', PARAM_INT);
1663 $depth = required_param('depth', PARAM_INT);
1665 $category = coursecat::get($categoryid);
1667 $chelper = new coursecat_helper();
1668 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1669 $coursedisplayoptions = array(
1670 'limit' => $CFG->coursesperpage,
1671 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1673 $catdisplayoptions = array(
1674 'limit' => $CFG->coursesperpage,
1675 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1677 $chelper->set_show_courses($showcourses)->
1678 set_courses_display_options($coursedisplayoptions)->
1679 set_categories_display_options($catdisplayoptions);
1681 return $this->coursecat_category_content($chelper, $category, $depth);
1682 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1683 // This is a request for the course information.
1684 $courseid = required_param('courseid', PARAM_INT);
1686 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1688 $chelper = new coursecat_helper();
1689 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1690 return $this->coursecat_coursebox_content($chelper, $course);
1691 } else {
1692 throw new coding_exception('Invalid request type');
1697 * Renders html to display search result page
1699 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1700 * @return string
1702 public function search_courses($searchcriteria) {
1703 global $CFG;
1704 $content = '';
1705 if (!empty($searchcriteria)) {
1706 // print search results
1707 require_once($CFG->libdir. '/coursecatlib.php');
1709 $displayoptions = array('sort' => array('displayname' => 1));
1710 // take the current page and number of results per page from query
1711 $perpage = optional_param('perpage', 0, PARAM_RAW);
1712 if ($perpage !== 'all') {
1713 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1714 $page = optional_param('page', 0, PARAM_INT);
1715 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1717 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1718 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1719 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1721 $class = 'course-search-result';
1722 foreach ($searchcriteria as $key => $value) {
1723 if (!empty($value)) {
1724 $class .= ' course-search-result-'. $key;
1727 $chelper = new coursecat_helper();
1728 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1729 set_courses_display_options($displayoptions)->
1730 set_search_criteria($searchcriteria)->
1731 set_attributes(array('class' => $class));
1733 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1734 $totalcount = coursecat::search_courses_count($searchcriteria);
1735 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1737 if (!$totalcount) {
1738 if (!empty($searchcriteria['search'])) {
1739 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1740 } else {
1741 $content .= $this->heading(get_string('novalidcourses'));
1743 } else {
1744 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1745 $content .= $courseslist;
1748 if (!empty($searchcriteria['search'])) {
1749 // print search form only if there was a search by search string, otherwise it is confusing
1750 $content .= $this->box_start('generalbox mdl-align');
1751 $content .= $this->course_search_form($searchcriteria['search']);
1752 $content .= $this->box_end();
1754 } else {
1755 // just print search form
1756 $content .= $this->box_start('generalbox mdl-align');
1757 $content .= $this->course_search_form();
1758 $content .= html_writer::tag('div', get_string("searchhelp"), array('class' => 'searchhelp'));
1759 $content .= $this->box_end();
1761 return $content;
1765 * Renders html to print list of courses tagged with particular tag
1767 * @param int $tagid id of the tag
1768 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1769 * are displayed on the page and the per-page limit may be bigger
1770 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1771 * to display items in the same context first
1772 * @param int $ctx context id where to search for records
1773 * @param bool $rec search in subcontexts as well
1774 * @param array $displayoptions
1775 * @return string empty string if no courses are marked with this tag or rendered list of courses
1777 public function tagged_courses($tagid, $exclusivemode = true, $ctx = 0, $rec = true, $displayoptions = null) {
1778 global $CFG;
1779 require_once($CFG->libdir . '/coursecatlib.php');
1780 if (empty($displayoptions)) {
1781 $displayoptions = array();
1783 $showcategories = coursecat::count_all() > 1;
1784 $displayoptions += array('limit' => $CFG->coursesperpage, 'offset' => 0);
1785 $chelper = new coursecat_helper();
1786 $searchcriteria = array('tagid' => $tagid, 'ctx' => $ctx, 'rec' => $rec);
1787 $chelper->set_show_courses($showcategories ? self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT :
1788 self::COURSECAT_SHOW_COURSES_EXPANDED)->
1789 set_search_criteria($searchcriteria)->
1790 set_courses_display_options($displayoptions)->
1791 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1792 // (we set the same css class as in search results by tagid)
1793 if ($totalcount = coursecat::search_courses_count($searchcriteria)) {
1794 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1795 if ($exclusivemode) {
1796 return $this->coursecat_courses($chelper, $courses, $totalcount);
1797 } else {
1798 $tagfeed = new core_tag\output\tagfeed();
1799 $img = $this->output->pix_icon('i/course', '');
1800 foreach ($courses as $course) {
1801 $url = course_get_url($course);
1802 $imgwithlink = html_writer::link($url, $img);
1803 $coursename = html_writer::link($url, $course->get_formatted_name());
1804 $details = '';
1805 if ($showcategories && ($cat = coursecat::get($course->category, IGNORE_MISSING))) {
1806 $details = get_string('category').': '.
1807 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1808 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1810 $tagfeed->add($imgwithlink, $coursename, $details);
1812 return $this->output->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($this->output));
1815 return '';
1819 * Returns HTML to display one remote course
1821 * @param stdClass $course remote course information, contains properties:
1822 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1823 * @return string
1825 protected function frontpage_remote_course(stdClass $course) {
1826 $url = new moodle_url('/auth/mnet/jump.php', array(
1827 'hostid' => $course->hostid,
1828 'wantsurl' => '/course/view.php?id='. $course->remoteid
1831 $output = '';
1832 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1833 $output .= html_writer::start_tag('div', array('class' => 'info'));
1834 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1835 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1836 $output .= html_writer::end_tag('h3'); // .name
1837 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1838 $output .= html_writer::end_tag('div'); // .info
1839 $output .= html_writer::start_tag('div', array('class' => 'content'));
1840 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1841 $options = new stdClass();
1842 $options->noclean = true;
1843 $options->para = false;
1844 $options->overflowdiv = true;
1845 $output .= format_text($course->summary, $course->summaryformat, $options);
1846 $output .= html_writer::end_tag('div'); // .summary
1847 $addinfo = format_string($course->hostname) . ' : '
1848 . format_string($course->cat_name) . ' : '
1849 . format_string($course->shortname);
1850 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1851 $output .= html_writer::end_tag('div'); // .content
1852 $output .= html_writer::end_tag('div'); // .coursebox
1853 return $output;
1857 * Returns HTML to display one remote host
1859 * @param array $host host information, contains properties: name, url, count
1860 * @return string
1862 protected function frontpage_remote_host($host) {
1863 $output = '';
1864 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1865 $output .= html_writer::start_tag('div', array('class' => 'info'));
1866 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1867 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1868 $output .= html_writer::end_tag('h3'); // .name
1869 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1870 $output .= html_writer::end_tag('div'); // .info
1871 $output .= html_writer::start_tag('div', array('class' => 'content'));
1872 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1873 $output .= $host['count'] . ' ' . get_string('courses');
1874 $output .= html_writer::end_tag('div'); // .content
1875 $output .= html_writer::end_tag('div'); // .coursebox
1876 return $output;
1880 * Returns HTML to print list of courses user is enrolled to for the frontpage
1882 * Also lists remote courses or remote hosts if MNET authorisation is used
1884 * @return string
1886 public function frontpage_my_courses() {
1887 global $USER, $CFG, $DB;
1889 if (!isloggedin() or isguestuser()) {
1890 return '';
1893 $output = '';
1894 if (!empty($CFG->navsortmycoursessort)) {
1895 // sort courses the same as in navigation menu
1896 $sortorder = 'visible DESC,'. $CFG->navsortmycoursessort.' ASC';
1897 } else {
1898 $sortorder = 'visible DESC,sortorder ASC';
1900 $courses = enrol_get_my_courses('summary, summaryformat', $sortorder);
1901 $rhosts = array();
1902 $rcourses = array();
1903 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1904 $rcourses = get_my_remotecourses($USER->id);
1905 $rhosts = get_my_remotehosts();
1908 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1910 $chelper = new coursecat_helper();
1911 if (count($courses) > $CFG->frontpagecourselimit) {
1912 // There are more enrolled courses than we can display, display link to 'My courses'.
1913 $totalcount = count($courses);
1914 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
1915 $chelper->set_courses_display_options(array(
1916 'viewmoreurl' => new moodle_url('/my/'),
1917 'viewmoretext' => new lang_string('mycourses')
1919 } else {
1920 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
1921 $chelper->set_courses_display_options(array(
1922 'viewmoreurl' => new moodle_url('/course/index.php'),
1923 'viewmoretext' => new lang_string('fulllistofcourses')
1925 $totalcount = $DB->count_records('course') - 1;
1927 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
1928 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
1929 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
1931 // MNET
1932 if (!empty($rcourses)) {
1933 // at the IDP, we know of all the remote courses
1934 $output .= html_writer::start_tag('div', array('class' => 'courses'));
1935 foreach ($rcourses as $course) {
1936 $output .= $this->frontpage_remote_course($course);
1938 $output .= html_writer::end_tag('div'); // .courses
1939 } elseif (!empty($rhosts)) {
1940 // non-IDP, we know of all the remote servers, but not courses
1941 $output .= html_writer::start_tag('div', array('class' => 'courses'));
1942 foreach ($rhosts as $host) {
1943 $output .= $this->frontpage_remote_host($host);
1945 $output .= html_writer::end_tag('div'); // .courses
1948 return $output;
1952 * Returns HTML to print list of available courses for the frontpage
1954 * @return string
1956 public function frontpage_available_courses() {
1957 global $CFG;
1958 require_once($CFG->libdir. '/coursecatlib.php');
1960 $chelper = new coursecat_helper();
1961 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
1962 set_courses_display_options(array(
1963 'recursive' => true,
1964 'limit' => $CFG->frontpagecourselimit,
1965 'viewmoreurl' => new moodle_url('/course/index.php'),
1966 'viewmoretext' => new lang_string('fulllistofcourses')));
1968 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
1969 $courses = coursecat::get(0)->get_courses($chelper->get_courses_display_options());
1970 $totalcount = coursecat::get(0)->get_courses_count($chelper->get_courses_display_options());
1971 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
1972 // Print link to create a new course, for the 1st available category.
1973 return $this->add_new_course_button();
1975 return $this->coursecat_courses($chelper, $courses, $totalcount);
1979 * Returns HTML to the "add new course" button for the page
1981 * @return string
1983 public function add_new_course_button() {
1984 global $CFG;
1985 // Print link to create a new course, for the 1st available category.
1986 $output = $this->container_start('buttons');
1987 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1988 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1989 $output .= $this->container_end('buttons');
1990 return $output;
1994 * Returns HTML to print tree with course categories and courses for the frontpage
1996 * @return string
1998 public function frontpage_combo_list() {
1999 global $CFG;
2000 require_once($CFG->libdir. '/coursecatlib.php');
2001 $chelper = new coursecat_helper();
2002 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2003 set_categories_display_options(array(
2004 'limit' => $CFG->coursesperpage,
2005 'viewmoreurl' => new moodle_url('/course/index.php',
2006 array('browse' => 'categories', 'page' => 1))
2007 ))->
2008 set_courses_display_options(array(
2009 'limit' => $CFG->coursesperpage,
2010 'viewmoreurl' => new moodle_url('/course/index.php',
2011 array('browse' => 'courses', 'page' => 1))
2012 ))->
2013 set_attributes(array('class' => 'frontpage-category-combo'));
2014 return $this->coursecat_tree($chelper, coursecat::get(0));
2018 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2020 * @return string
2022 public function frontpage_categories_list() {
2023 global $CFG;
2024 require_once($CFG->libdir. '/coursecatlib.php');
2025 $chelper = new coursecat_helper();
2026 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2027 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2028 set_categories_display_options(array(
2029 'limit' => $CFG->coursesperpage,
2030 'viewmoreurl' => new moodle_url('/course/index.php',
2031 array('browse' => 'categories', 'page' => 1))
2032 ))->
2033 set_attributes(array('class' => 'frontpage-category-names'));
2034 return $this->coursecat_tree($chelper, coursecat::get(0));
2040 * Class storing display options and functions to help display course category and/or courses lists
2042 * This is a wrapper for coursecat objects that also stores display options
2043 * and functions to retrieve sorted and paginated lists of categories/courses.
2045 * If theme overrides methods in core_course_renderers that access this class
2046 * it may as well not use this class at all or extend it.
2048 * @package core
2049 * @copyright 2013 Marina Glancy
2050 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2052 class coursecat_helper {
2053 /** @var string [none, collapsed, expanded] how (if) display courses list */
2054 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2055 /** @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) */
2056 protected $subcatdepth = 1;
2057 /** @var array options to display courses list */
2058 protected $coursesdisplayoptions = array();
2059 /** @var array options to display subcategories list */
2060 protected $categoriesdisplayoptions = array();
2061 /** @var array additional HTML attributes */
2062 protected $attributes = array();
2063 /** @var array search criteria if the list is a search result */
2064 protected $searchcriteria = null;
2067 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2069 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2070 * @return coursecat_helper
2072 public function set_show_courses($showcourses) {
2073 $this->showcourses = $showcourses;
2074 // Automatically set the options to preload summary and coursecontacts for coursecat::get_courses() and coursecat::search_courses()
2075 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2076 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2077 return $this;
2081 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2083 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2085 public function get_show_courses() {
2086 return $this->showcourses;
2090 * Sets the maximum depth to expand subcategories in the tree
2092 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2094 * @param int $subcatdepth
2095 * @return coursecat_helper
2097 public function set_subcat_depth($subcatdepth) {
2098 $this->subcatdepth = $subcatdepth;
2099 return $this;
2103 * Returns the maximum depth to expand subcategories in the tree
2105 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2107 * @return int
2109 public function get_subcat_depth() {
2110 return $this->subcatdepth;
2114 * Sets options to display list of courses
2116 * Options are later submitted as argument to coursecat::get_courses() and/or coursecat::search_courses()
2118 * Options that coursecat::get_courses() accept:
2119 * - recursive - return courses from subcategories as well. Use with care,
2120 * this may be a huge list!
2121 * - summary - preloads fields 'summary' and 'summaryformat'
2122 * - coursecontacts - preloads course contacts
2123 * - isenrolled - preloads indication whether this user is enrolled in the course
2124 * - sort - list of fields to sort. Example
2125 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2126 * will sort by idnumber asc, shortname asc and id desc.
2127 * Default: array('sortorder' => 1)
2128 * Only cached fields may be used for sorting!
2129 * - offset
2130 * - limit - maximum number of children to return, 0 or null for no limit
2132 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2134 * Also renderer can set here any additional options it wants to pass between renderer functions.
2136 * @param array $options
2137 * @return coursecat_helper
2139 public function set_courses_display_options($options) {
2140 $this->coursesdisplayoptions = $options;
2141 $this->set_show_courses($this->showcourses); // this will calculate special display options
2142 return $this;
2146 * Sets one option to display list of courses
2148 * @see coursecat_helper::set_courses_display_options()
2150 * @param string $key
2151 * @param mixed $value
2152 * @return coursecat_helper
2154 public function set_courses_display_option($key, $value) {
2155 $this->coursesdisplayoptions[$key] = $value;
2156 return $this;
2160 * Return the specified option to display list of courses
2162 * @param string $optionname option name
2163 * @param mixed $defaultvalue default value for option if it is not specified
2164 * @return mixed
2166 public function get_courses_display_option($optionname, $defaultvalue = null) {
2167 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2168 return $this->coursesdisplayoptions[$optionname];
2169 } else {
2170 return $defaultvalue;
2175 * Returns all options to display the courses
2177 * This array is usually passed to {@link coursecat::get_courses()} or
2178 * {@link coursecat::search_courses()}
2180 * @return array
2182 public function get_courses_display_options() {
2183 return $this->coursesdisplayoptions;
2187 * Sets options to display list of subcategories
2189 * Options 'sort', 'offset' and 'limit' are passed to coursecat::get_children().
2190 * Any other options may be used by renderer functions
2192 * @param array $options
2193 * @return coursecat_helper
2195 public function set_categories_display_options($options) {
2196 $this->categoriesdisplayoptions = $options;
2197 return $this;
2201 * Return the specified option to display list of subcategories
2203 * @param string $optionname option name
2204 * @param mixed $defaultvalue default value for option if it is not specified
2205 * @return mixed
2207 public function get_categories_display_option($optionname, $defaultvalue = null) {
2208 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2209 return $this->categoriesdisplayoptions[$optionname];
2210 } else {
2211 return $defaultvalue;
2216 * Returns all options to display list of subcategories
2218 * This array is usually passed to {@link coursecat::get_children()}
2220 * @return array
2222 public function get_categories_display_options() {
2223 return $this->categoriesdisplayoptions;
2227 * Sets additional general options to pass between renderer functions, usually HTML attributes
2229 * @param array $attributes
2230 * @return coursecat_helper
2232 public function set_attributes($attributes) {
2233 $this->attributes = $attributes;
2234 return $this;
2238 * Return all attributes and erases them so they are not applied again
2240 * @param string $classname adds additional class name to the beginning of $attributes['class']
2241 * @return array
2243 public function get_and_erase_attributes($classname) {
2244 $attributes = $this->attributes;
2245 $this->attributes = array();
2246 if (empty($attributes['class'])) {
2247 $attributes['class'] = '';
2249 $attributes['class'] = $classname . ' '. $attributes['class'];
2250 return $attributes;
2254 * Sets the search criteria if the course is a search result
2256 * Search string will be used to highlight terms in course name and description
2258 * @param array $searchcriteria
2259 * @return coursecat_helper
2261 public function set_search_criteria($searchcriteria) {
2262 $this->searchcriteria = $searchcriteria;
2263 return $this;
2267 * Returns formatted and filtered description of the given category
2269 * @param coursecat $coursecat category
2270 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2271 * if context is not specified it will be added automatically
2272 * @return string|null
2274 public function get_category_formatted_description($coursecat, $options = null) {
2275 if ($coursecat->id && !empty($coursecat->description)) {
2276 if (!isset($coursecat->descriptionformat)) {
2277 $descriptionformat = FORMAT_MOODLE;
2278 } else {
2279 $descriptionformat = $coursecat->descriptionformat;
2281 if ($options === null) {
2282 $options = array('noclean' => true, 'overflowdiv' => true);
2283 } else {
2284 $options = (array)$options;
2286 $context = context_coursecat::instance($coursecat->id);
2287 if (!isset($options['context'])) {
2288 $options['context'] = $context;
2290 $text = file_rewrite_pluginfile_urls($coursecat->description,
2291 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2292 return format_text($text, $descriptionformat, $options);
2294 return null;
2298 * Returns given course's summary with proper embedded files urls and formatted
2300 * @param course_in_list $course
2301 * @param array|stdClass $options additional formatting options
2302 * @return string
2304 public function get_course_formatted_summary($course, $options = array()) {
2305 global $CFG;
2306 require_once($CFG->libdir. '/filelib.php');
2307 if (!$course->has_summary()) {
2308 return '';
2310 $options = (array)$options;
2311 $context = context_course::instance($course->id);
2312 if (!isset($options['context'])) {
2313 // TODO see MDL-38521
2314 // option 1 (current), page context - no code required
2315 // option 2, system context
2316 // $options['context'] = context_system::instance();
2317 // option 3, course context:
2318 // $options['context'] = $context;
2319 // option 4, course category context:
2320 // $options['context'] = $context->get_parent_context();
2322 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2323 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2324 if (!empty($this->searchcriteria['search'])) {
2325 $summary = highlight($this->searchcriteria['search'], $summary);
2327 return $summary;
2331 * Returns course name as it is configured to appear in courses lists formatted to course context
2333 * @param course_in_list $course
2334 * @param array|stdClass $options additional formatting options
2335 * @return string
2337 public function get_course_formatted_name($course, $options = array()) {
2338 $options = (array)$options;
2339 if (!isset($options['context'])) {
2340 $options['context'] = context_course::instance($course->id);
2342 $name = format_string(get_course_display_name_for_list($course), true, $options);
2343 if (!empty($this->searchcriteria['search'])) {
2344 $name = highlight($this->searchcriteria['search'], $name);
2346 return $name;