MDL-42068 Filepicker course listing use setting courselistshortname to show shortname...
[moodle.git] / course / renderer.php
blob6151757b8065dcb978b6fdd3e0d899f2741eee46
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 /**
44 * A cache of strings
45 * @var stdClass
47 protected $strings;
49 /**
50 * Override the constructor so that we can initialise the string cache
52 * @param moodle_page $page
53 * @param string $target
55 public function __construct(moodle_page $page, $target) {
56 $this->strings = new stdClass;
57 parent::__construct($page, $target);
58 $this->add_modchoosertoggle();
61 /**
62 * Adds the item in course settings navigation to toggle modchooser
64 * Theme can overwrite as an empty function to exclude it (for example if theme does not
65 * use modchooser at all)
67 protected function add_modchoosertoggle() {
68 global $CFG;
69 static $modchoosertoggleadded = false;
70 // Add the module chooser toggle to the course page
71 if ($modchoosertoggleadded || $this->page->state > moodle_page::STATE_PRINTING_HEADER ||
72 $this->page->course->id == SITEID ||
73 !$this->page->user_is_editing() ||
74 !($context = context_course::instance($this->page->course->id)) ||
75 !has_capability('moodle/course:manageactivities', $context) ||
76 !course_ajax_enabled($this->page->course) ||
77 !($coursenode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE)) ||
78 !($turneditingnode = $coursenode->get('turneditingonoff'))) {
79 // too late or we are on site page or we could not find the adjacent nodes in course settings menu
80 // or we are not allowed to edit
81 return;
83 $modchoosertoggleadded = true;
84 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
85 // We are on the course page, retain the current page params e.g. section.
86 $modchoosertoggleurl = clone($this->page->url);
87 } else {
88 // Edit on the main course page.
89 $modchoosertoggleurl = new moodle_url('/course/view.php', array('id' => $this->page->course->id,
90 'return' => $this->page->url->out_as_local_url(false)));
92 $modchoosertoggleurl->param('sesskey', sesskey());
93 if ($usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault)) {
94 $modchoosertogglestring = get_string('modchooserdisable', 'moodle');
95 $modchoosertoggleurl->param('modchooser', 'off');
96 } else {
97 $modchoosertogglestring = get_string('modchooserenable', 'moodle');
98 $modchoosertoggleurl->param('modchooser', 'on');
100 $modchoosertoggle = navigation_node::create($modchoosertogglestring, $modchoosertoggleurl, navigation_node::TYPE_SETTING, null, 'modchoosertoggle');
102 // Insert the modchoosertoggle after the settings node 'turneditingonoff' (navigation_node only has function to insert before, so we insert before and then swap).
103 $coursenode->add_node($modchoosertoggle, 'turneditingonoff');
104 $turneditingnode->remove();
105 $coursenode->add_node($turneditingnode, 'modchoosertoggle');
107 $modchoosertoggle->add_class('modchoosertoggle');
108 $modchoosertoggle->add_class('visibleifjs');
109 user_preference_allow_ajax_update('usemodchooser', PARAM_BOOL);
113 * Renders course info box.
115 * @param stdClass|course_in_list $course
116 * @return string
118 public function course_info_box(stdClass $course) {
119 $content = '';
120 $content .= $this->output->box_start('generalbox info');
121 $chelper = new coursecat_helper();
122 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
123 $content .= $this->coursecat_coursebox($chelper, $course);
124 $content .= $this->output->box_end();
125 return $content;
129 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
131 * @deprecated since 2.5
133 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
135 * @param array $ignored argument ignored
136 * @return string
138 public final function course_category_tree(array $ignored) {
139 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
140 return $this->frontpage_combo_list();
144 * Renderers a category for use with course_category_tree
146 * @deprecated since 2.5
148 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
150 * @param array $category
151 * @param int $depth
152 * @return string
154 protected final function course_category_tree_category(stdClass $category, $depth=1) {
155 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
156 return '';
160 * Build the HTML for the module chooser javascript popup
162 * @param array $modules A set of modules as returned form @see
163 * get_module_metadata
164 * @param object $course The course that will be displayed
165 * @return string The composed HTML for the module
167 public function course_modchooser($modules, $course) {
168 static $isdisplayed = false;
169 if ($isdisplayed) {
170 return '';
172 $isdisplayed = true;
174 // Add the module chooser
175 $this->page->requires->yui_module('moodle-course-modchooser',
176 'M.course.init_chooser',
177 array(array('courseid' => $course->id, 'closeButtonTitle' => get_string('close', 'editor')))
179 $this->page->requires->strings_for_js(array(
180 'addresourceoractivity',
181 'modchooserenable',
182 'modchooserdisable',
183 ), 'moodle');
185 // Add the header
186 $header = html_writer::tag('div', get_string('addresourceoractivity', 'moodle'),
187 array('class' => 'hd choosertitle'));
189 $formcontent = html_writer::start_tag('form', array('action' => new moodle_url('/course/jumpto.php'),
190 'id' => 'chooserform', 'method' => 'post'));
191 $formcontent .= html_writer::start_tag('div', array('id' => 'typeformdiv'));
192 $formcontent .= html_writer::tag('input', '', array('type' => 'hidden', 'id' => 'course',
193 'name' => 'course', 'value' => $course->id));
194 $formcontent .= html_writer::tag('input', '',
195 array('type' => 'hidden', 'class' => 'jump', 'name' => 'jump', 'value' => ''));
196 $formcontent .= html_writer::tag('input', '', array('type' => 'hidden', 'name' => 'sesskey',
197 'value' => sesskey()));
198 $formcontent .= html_writer::end_tag('div');
200 // Put everything into one tag 'options'
201 $formcontent .= html_writer::start_tag('div', array('class' => 'options'));
202 $formcontent .= html_writer::tag('div', get_string('selectmoduletoviewhelp', 'moodle'),
203 array('class' => 'instruction'));
204 // Put all options into one tag 'alloptions' to allow us to handle scrolling
205 $formcontent .= html_writer::start_tag('div', array('class' => 'alloptions'));
207 // Activities
208 $activities = array_filter($modules, create_function('$mod', 'return ($mod->archetype !== MOD_ARCHETYPE_RESOURCE && $mod->archetype !== MOD_ARCHETYPE_SYSTEM);'));
209 if (count($activities)) {
210 $formcontent .= $this->course_modchooser_title('activities');
211 $formcontent .= $this->course_modchooser_module_types($activities);
214 // Resources
215 $resources = array_filter($modules, create_function('$mod', 'return ($mod->archetype === MOD_ARCHETYPE_RESOURCE);'));
216 if (count($resources)) {
217 $formcontent .= $this->course_modchooser_title('resources');
218 $formcontent .= $this->course_modchooser_module_types($resources);
221 $formcontent .= html_writer::end_tag('div'); // modoptions
222 $formcontent .= html_writer::end_tag('div'); // types
224 $formcontent .= html_writer::start_tag('div', array('class' => 'submitbuttons'));
225 $formcontent .= html_writer::tag('input', '',
226 array('type' => 'submit', 'name' => 'submitbutton', 'class' => 'submitbutton', 'value' => get_string('add')));
227 $formcontent .= html_writer::tag('input', '',
228 array('type' => 'submit', 'name' => 'addcancel', 'class' => 'addcancel', 'value' => get_string('cancel')));
229 $formcontent .= html_writer::end_tag('div');
230 $formcontent .= html_writer::end_tag('form');
232 // Wrap the whole form in a div
233 $formcontent = html_writer::tag('div', $formcontent, array('id' => 'chooseform'));
235 // Put all of the content together
236 $content = $formcontent;
238 $content = html_writer::tag('div', $content, array('class' => 'choosercontainer'));
239 return $header . html_writer::tag('div', $content, array('class' => 'chooserdialoguebody'));
243 * Build the HTML for a specified set of modules
245 * @param array $modules A set of modules as used by the
246 * course_modchooser_module function
247 * @return string The composed HTML for the module
249 protected function course_modchooser_module_types($modules) {
250 $return = '';
251 foreach ($modules as $module) {
252 if (!isset($module->types)) {
253 $return .= $this->course_modchooser_module($module);
254 } else {
255 $return .= $this->course_modchooser_module($module, array('nonoption'));
256 foreach ($module->types as $type) {
257 $return .= $this->course_modchooser_module($type, array('option', 'subtype'));
261 return $return;
265 * Return the HTML for the specified module adding any required classes
267 * @param object $module An object containing the title, and link. An
268 * icon, and help text may optionally be specified. If the module
269 * contains subtypes in the types option, then these will also be
270 * displayed.
271 * @param array $classes Additional classes to add to the encompassing
272 * div element
273 * @return string The composed HTML for the module
275 protected function course_modchooser_module($module, $classes = array('option')) {
276 $output = '';
277 $output .= html_writer::start_tag('div', array('class' => implode(' ', $classes)));
278 $output .= html_writer::start_tag('label', array('for' => 'module_' . $module->name));
279 if (!isset($module->types)) {
280 $output .= html_writer::tag('input', '', array('type' => 'radio',
281 'name' => 'jumplink', 'id' => 'module_' . $module->name, 'value' => $module->link));
284 $output .= html_writer::start_tag('span', array('class' => 'modicon'));
285 if (isset($module->icon)) {
286 // Add an icon if we have one
287 $output .= $module->icon;
289 $output .= html_writer::end_tag('span');
291 $output .= html_writer::tag('span', $module->title, array('class' => 'typename'));
292 if (!isset($module->help)) {
293 // Add help if found
294 $module->help = get_string('nohelpforactivityorresource', 'moodle');
297 // Format the help text using markdown with the following options
298 $options = new stdClass();
299 $options->trusted = false;
300 $options->noclean = false;
301 $options->smiley = false;
302 $options->filter = false;
303 $options->para = true;
304 $options->newlines = false;
305 $options->overflowdiv = false;
306 $module->help = format_text($module->help, FORMAT_MARKDOWN, $options);
307 $output .= html_writer::tag('span', $module->help, array('class' => 'typesummary'));
308 $output .= html_writer::end_tag('label');
309 $output .= html_writer::end_tag('div');
311 return $output;
314 protected function course_modchooser_title($title, $identifier = null) {
315 $module = new stdClass();
316 $module->name = $title;
317 $module->types = array();
318 $module->title = get_string($title, $identifier);
319 $module->help = '';
320 return $this->course_modchooser_module($module, array('moduletypetitle'));
324 * Renders HTML for displaying the sequence of course module editing buttons
326 * @see course_get_cm_edit_actions()
328 * @param array $actions array of action_link or pix_icon objects
329 * @return string
331 public function course_section_cm_edit_actions($actions) {
332 $output = html_writer::start_tag('span', array('class' => 'commands'));
333 foreach ($actions as $action) {
334 if ($action instanceof renderable) {
335 $output .= $this->output->render($action);
336 } else {
337 $output .= $action;
340 $output .= html_writer::end_tag('span');
341 return $output;
345 * Renders HTML for the menus to add activities and resources to the current course
347 * Note, if theme overwrites this function and it does not use modchooser,
348 * see also {@link core_course_renderer::add_modchoosertoggle()}
350 * @param stdClass $course
351 * @param int $section relative section number (field course_sections.section)
352 * @param int $sectionreturn The section to link back to
353 * @param array $displayoptions additional display options, for example blocks add
354 * option 'inblock' => true, suggesting to display controls vertically
355 * @return string
357 function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
358 global $CFG;
360 $vertical = !empty($displayoptions['inblock']);
362 // check to see if user can add menus and there are modules to add
363 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
364 || !$this->page->user_is_editing()
365 || !($modnames = get_module_types_names()) || empty($modnames)) {
366 return '';
369 // Retrieve all modules with associated metadata
370 $modules = get_module_metadata($course, $modnames, $sectionreturn);
371 $urlparams = array('section' => $section);
373 // We'll sort resources and activities into two lists
374 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
376 foreach ($modules as $module) {
377 if (isset($module->types)) {
378 // This module has a subtype
379 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
380 $subtypes = array();
381 foreach ($module->types as $subtype) {
382 $link = $subtype->link->out(true, $urlparams);
383 $subtypes[$link] = $subtype->title;
386 // Sort module subtypes into the list
387 $activityclass = MOD_CLASS_ACTIVITY;
388 if ($module->archetype == MOD_CLASS_RESOURCE) {
389 $activityclass = MOD_CLASS_RESOURCE;
391 if (!empty($module->title)) {
392 // This grouping has a name
393 $activities[$activityclass][] = array($module->title => $subtypes);
394 } else {
395 // This grouping does not have a name
396 $activities[$activityclass] = array_merge($activities[$activityclass], $subtypes);
398 } else {
399 // This module has no subtypes
400 $activityclass = MOD_CLASS_ACTIVITY;
401 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
402 $activityclass = MOD_CLASS_RESOURCE;
403 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
404 // System modules cannot be added by user, do not add to dropdown
405 continue;
407 $link = $module->link->out(true, $urlparams);
408 $activities[$activityclass][$link] = $module->title;
412 $straddactivity = get_string('addactivity');
413 $straddresource = get_string('addresource');
414 $sectionname = get_section_name($course, $section);
415 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
416 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
418 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
420 if (!$vertical) {
421 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
424 if (!empty($activities[MOD_CLASS_RESOURCE])) {
425 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array(''=>$straddresource), "ressection$section");
426 $select->set_help_icon('resources');
427 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
428 $output .= $this->output->render($select);
431 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
432 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array(''=>$straddactivity), "section$section");
433 $select->set_help_icon('activities');
434 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
435 $output .= $this->output->render($select);
438 if (!$vertical) {
439 $output .= html_writer::end_tag('div');
442 $output .= html_writer::end_tag('div');
444 if (course_ajax_enabled($course) && $course->id == $this->page->course->id) {
445 // modchooser can be added only for the current course set on the page!
446 $straddeither = get_string('addresourceoractivity');
447 // The module chooser link
448 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
449 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
450 $icon = $this->output->pix_icon('t/add', '');
451 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
452 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
453 $modchooser.= html_writer::end_tag('div');
454 $modchooser.= html_writer::end_tag('div');
456 // Wrap the normal output in a noscript div
457 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
458 if ($usemodchooser) {
459 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
460 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
461 } else {
462 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
463 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
464 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
466 $output = $this->course_modchooser($modules, $course) . $modchooser . $output;
469 return $output;
473 * Renders html to display a course search form
475 * @param string $value default value to populate the search field
476 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
477 * @return string
479 function course_search_form($value = '', $format = 'plain') {
480 static $count = 0;
481 $formid = 'coursesearch';
482 if ((++$count) > 1) {
483 $formid .= $count;
486 switch ($format) {
487 case 'navbar' :
488 $formid = 'coursesearchnavbar';
489 $inputid = 'navsearchbox';
490 $inputsize = 20;
491 break;
492 case 'short' :
493 $inputid = 'shortsearchbox';
494 $inputsize = 12;
495 break;
496 default :
497 $inputid = 'coursesearchbox';
498 $inputsize = 30;
501 $strsearchcourses= get_string("searchcourses");
502 $searchurl = new moodle_url('/course/search.php');
504 $output = html_writer::start_tag('form', array('id' => $formid, 'action' => $searchurl, 'method' => 'get'));
505 $output .= html_writer::start_tag('fieldset', array('class' => 'coursesearchbox invisiblefieldset'));
506 $output .= html_writer::tag('label', $strsearchcourses.': ', array('for' => $inputid));
507 $output .= html_writer::empty_tag('input', array('type' => 'text', 'id' => $inputid,
508 'size' => $inputsize, 'name' => 'search', 'value' => s($value)));
509 $output .= html_writer::empty_tag('input', array('type' => 'submit',
510 'value' => get_string('go')));
511 $output .= html_writer::end_tag('fieldset');
512 $output .= html_writer::end_tag('form');
514 return $output;
518 * Renders html for completion box on course page
520 * If completion is disabled, returns empty string
521 * If completion is automatic, returns an icon of the current completion state
522 * If completion is manual, returns a form (with an icon inside) that allows user to
523 * toggle completion
525 * @param stdClass $course course object
526 * @param completion_info $completioninfo completion info for the course, it is recommended
527 * to fetch once for all modules in course/section for performance
528 * @param cm_info $mod module to show completion for
529 * @param array $displayoptions display options, not used in core
530 * @return string
532 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
533 global $CFG;
534 $output = '';
535 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
536 return $output;
538 if ($completioninfo === null) {
539 $completioninfo = new completion_info($course);
541 $completion = $completioninfo->is_enabled($mod);
542 if ($completion == COMPLETION_TRACKING_NONE) {
543 return $output;
546 $completiondata = $completioninfo->get_data($mod, true);
547 $completionicon = '';
549 if ($this->page->user_is_editing()) {
550 switch ($completion) {
551 case COMPLETION_TRACKING_MANUAL :
552 $completionicon = 'manual-enabled'; break;
553 case COMPLETION_TRACKING_AUTOMATIC :
554 $completionicon = 'auto-enabled'; break;
556 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
557 switch($completiondata->completionstate) {
558 case COMPLETION_INCOMPLETE:
559 $completionicon = 'manual-n'; break;
560 case COMPLETION_COMPLETE:
561 $completionicon = 'manual-y'; break;
563 } else { // Automatic
564 switch($completiondata->completionstate) {
565 case COMPLETION_INCOMPLETE:
566 $completionicon = 'auto-n'; break;
567 case COMPLETION_COMPLETE:
568 $completionicon = 'auto-y'; break;
569 case COMPLETION_COMPLETE_PASS:
570 $completionicon = 'auto-pass'; break;
571 case COMPLETION_COMPLETE_FAIL:
572 $completionicon = 'auto-fail'; break;
575 if ($completionicon) {
576 $formattedname = $mod->get_formatted_name();
577 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
578 if ($completion == COMPLETION_TRACKING_MANUAL && !$this->page->user_is_editing()) {
579 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
580 $newstate =
581 $completiondata->completionstate == COMPLETION_COMPLETE
582 ? COMPLETION_INCOMPLETE
583 : COMPLETION_COMPLETE;
584 // In manual mode the icon is a toggle form...
586 // If this completion state is used by the
587 // conditional activities system, we need to turn
588 // off the JS.
589 $extraclass = '';
590 if (!empty($CFG->enableavailability) &&
591 condition_info::completion_value_used_as_condition($course, $mod)) {
592 $extraclass = ' preventjs';
594 $output .= html_writer::start_tag('form', array('method' => 'post',
595 'action' => new moodle_url('/course/togglecompletion.php'),
596 'class' => 'togglecompletion'. $extraclass));
597 $output .= html_writer::start_tag('div');
598 $output .= html_writer::empty_tag('input', array(
599 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
600 $output .= html_writer::empty_tag('input', array(
601 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
602 $output .= html_writer::empty_tag('input', array(
603 'type' => 'hidden', 'name' => 'modulename', 'value' => $mod->name));
604 $output .= html_writer::empty_tag('input', array(
605 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
606 $output .= html_writer::empty_tag('input', array(
607 'type' => 'image',
608 'src' => $this->output->pix_url('i/completion-'.$completionicon),
609 'alt' => $imgalt, 'title' => $imgtitle,
610 'aria-live' => 'polite'));
611 $output .= html_writer::end_tag('div');
612 $output .= html_writer::end_tag('form');
613 } else {
614 // In auto mode, or when editing, the icon is just an image
615 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
616 array('title' => $imgalt));
617 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
618 array('class' => 'autocompletion'));
621 return $output;
625 * Checks if course module has any conditions that may make it unavailable for
626 * all or some of the students
628 * This function is internal and is only used to create CSS classes for the module name/text
630 * @param cm_info $mod
631 * @return bool
633 protected function is_cm_conditionally_hidden(cm_info $mod) {
634 global $CFG;
635 $conditionalhidden = false;
636 if (!empty($CFG->enableavailability)) {
637 $conditionalhidden = $mod->availablefrom > time() ||
638 ($mod->availableuntil && $mod->availableuntil < time()) ||
639 count($mod->conditionsgrade) > 0 ||
640 count($mod->conditionscompletion) > 0 ||
641 count($mod->conditionsfield);
643 return $conditionalhidden;
647 * Renders html to display a name with the link to the course module on a course page
649 * If module is unavailable for user but still needs to be displayed
650 * in the list, just the name is returned without a link
652 * Note, that for course modules that never have separate pages (i.e. labels)
653 * this function return an empty string
655 * @param cm_info $mod
656 * @param array $displayoptions
657 * @return string
659 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
660 global $CFG;
661 $output = '';
662 if (!$mod->uservisible &&
663 (empty($mod->showavailability) || empty($mod->availableinfo))) {
664 // nothing to be displayed to the user
665 return $output;
667 $url = $mod->get_url();
668 if (!$url) {
669 return $output;
672 //Accessibility: for files get description via icon, this is very ugly hack!
673 $instancename = $mod->get_formatted_name();
674 $altname = $mod->modfullname;
675 // Avoid unnecessary duplication: if e.g. a forum name already
676 // includes the word forum (or Forum, etc) then it is unhelpful
677 // to include that in the accessible description that is added.
678 if (false !== strpos(textlib::strtolower($instancename),
679 textlib::strtolower($altname))) {
680 $altname = '';
682 // File type after name, for alphabetic lists (screen reader).
683 if ($altname) {
684 $altname = get_accesshide(' '.$altname);
687 // For items which are hidden but available to current user
688 // ($mod->uservisible), we show those as dimmed only if the user has
689 // viewhiddenactivities, so that teachers see 'items which might not
690 // be available to some students' dimmed but students do not see 'item
691 // which is actually available to current student' dimmed.
692 $linkclasses = '';
693 $accesstext = '';
694 $textclasses = '';
695 if ($mod->uservisible) {
696 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
697 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
698 has_capability('moodle/course:viewhiddenactivities',
699 context_course::instance($mod->course));
700 if ($accessiblebutdim) {
701 $linkclasses .= ' dimmed';
702 $textclasses .= ' dimmed_text';
703 if ($conditionalhidden) {
704 $linkclasses .= ' conditionalhidden';
705 $textclasses .= ' conditionalhidden';
707 // Show accessibility note only if user can access the module himself.
708 $accesstext = get_accesshide(get_string('hiddenfromstudents').':'. $mod->modfullname);
710 } else {
711 $linkclasses .= ' dimmed';
712 $textclasses .= ' dimmed_text';
715 // Get on-click attribute value if specified and decode the onclick - it
716 // has already been encoded for display (puke).
717 $onclick = htmlspecialchars_decode($mod->get_on_click(), ENT_QUOTES);
719 $groupinglabel = '';
720 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($mod->course))) {
721 $groupings = groups_get_all_groupings($mod->course);
722 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$mod->groupingid]->name).')',
723 array('class' => 'groupinglabel '.$textclasses));
726 // Display link itself.
727 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
728 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) . $accesstext .
729 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
730 if ($mod->uservisible) {
731 $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick)) .
732 $groupinglabel;
733 } else {
734 // We may be displaying this just in order to show information
735 // about visibility, without the actual link ($mod->uservisible)
736 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses)) .
737 $groupinglabel;
739 return $output;
743 * Renders html to display the module content on the course page (i.e. text of the labels)
745 * @param cm_info $mod
746 * @param array $displayoptions
747 * @return string
749 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
750 $output = '';
751 if (!$mod->uservisible &&
752 (empty($mod->showavailability) || empty($mod->availableinfo))) {
753 // nothing to be displayed to the user
754 return $output;
756 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
757 $accesstext = '';
758 $textclasses = '';
759 if ($mod->uservisible) {
760 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
761 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
762 has_capability('moodle/course:viewhiddenactivities',
763 context_course::instance($mod->course));
764 if ($accessiblebutdim) {
765 $textclasses .= ' dimmed_text';
766 if ($conditionalhidden) {
767 $textclasses .= ' conditionalhidden';
769 // Show accessibility note only if user can access the module himself.
770 $accesstext = get_accesshide(get_string('hiddenfromstudents').':'. $mod->modfullname);
772 } else {
773 $textclasses .= ' dimmed_text';
775 if ($mod->get_url()) {
776 if ($content) {
777 // If specified, display extra content after link.
778 $output = html_writer::tag('div', $content, array('class' =>
779 trim('contentafterlink ' . $textclasses)));
781 } else {
782 // No link, so display only content.
783 $output = html_writer::tag('div', $accesstext . $content, array('class' => $textclasses));
785 return $output;
789 * Renders HTML to show course module availability information (for someone who isn't allowed
790 * to see the activity itself, or for staff)
792 * @param cm_info $mod
793 * @param array $displayoptions
794 * @return string
796 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
797 global $CFG;
798 if (!$mod->uservisible) {
799 // this is a student who is not allowed to see the module but might be allowed
800 // to see availability info (i.e. "Available from ...")
801 if (!empty($mod->showavailability) && !empty($mod->availableinfo)) {
802 $output = html_writer::tag('div', $mod->availableinfo, array('class' => 'availabilityinfo'));
804 return $output;
806 // this is a teacher who is allowed to see module but still should see the
807 // information that module is not available to all/some students
808 $modcontext = context_module::instance($mod->id);
809 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
810 if ($canviewhidden && !empty($CFG->enableavailability)) {
811 // Don't add availability information if user is not editing and activity is hidden.
812 if ($mod->visible || $this->page->user_is_editing()) {
813 $hidinfoclass = '';
814 if (!$mod->visible) {
815 $hidinfoclass = 'hide';
817 $ci = new condition_info($mod);
818 $fullinfo = $ci->get_full_information();
819 if($fullinfo) {
820 return '<div class="availabilityinfo '.$hidinfoclass.'">'.get_string($mod->showavailability
821 ? 'userrestriction_visible'
822 : 'userrestriction_hidden','condition',
823 $fullinfo).'</div>';
827 return '';
831 * Renders HTML to display one course module in a course section
833 * This includes link, content, availability, completion info and additional information
834 * that module type wants to display (i.e. number of unread forum posts)
836 * This function calls:
837 * {@link core_course_renderer::course_section_cm_name()}
838 * {@link cm_info::get_after_link()}
839 * {@link core_course_renderer::course_section_cm_text()}
840 * {@link core_course_renderer::course_section_cm_availability()}
841 * {@link core_course_renderer::course_section_cm_completion()}
842 * {@link course_get_cm_edit_actions()}
843 * {@link core_course_renderer::course_section_cm_edit_actions()}
845 * @param stdClass $course
846 * @param completion_info $completioninfo
847 * @param cm_info $mod
848 * @param int|null $sectionreturn
849 * @param array $displayoptions
850 * @return string
852 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
853 $output = '';
854 // We return empty string (because course module will not be displayed at all)
855 // if:
856 // 1) The activity is not visible to users
857 // and
858 // 2a) The 'showavailability' option is not set (if that is set,
859 // we need to display the activity so we can show
860 // availability info)
861 // or
862 // 2b) The 'availableinfo' is empty, i.e. the activity was
863 // hidden in a way that leaves no info, such as using the
864 // eye icon.
865 if (!$mod->uservisible &&
866 (empty($mod->showavailability) || empty($mod->availableinfo))) {
867 return $output;
870 $indentclasses = 'mod-indent';
871 if (!empty($mod->indent)) {
872 $indentclasses .= ' mod-indent-'.$mod->indent;
873 if ($mod->indent > 15) {
874 $indentclasses .= ' mod-indent-huge';
877 $output .= html_writer::start_tag('div', array('class' => $indentclasses));
879 // Start the div for the activity title, excluding the edit icons.
880 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
882 // Display the link to the module (or do nothing if module has no url)
883 $output .= $this->course_section_cm_name($mod, $displayoptions);
885 // Module can put text after the link (e.g. forum unread)
886 $output .= $mod->get_after_link();
888 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
889 $output .= html_writer::end_tag('div'); // .activityinstance
891 // If there is content but NO link (eg label), then display the
892 // content here (BEFORE any icons). In this case cons must be
893 // displayed after the content so that it makes more sense visually
894 // and for accessibility reasons, e.g. if you have a one-line label
895 // it should work similarly (at least in terms of ordering) to an
896 // activity.
897 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
898 $url = $mod->get_url();
899 if (empty($url)) {
900 $output .= $contentpart;
903 if ($this->page->user_is_editing()) {
904 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
905 $output .= ' '. $this->course_section_cm_edit_actions($editactions);
906 $output .= $mod->get_after_edit_icons();
909 $output .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
911 // If there is content AND a link, then display the content here
912 // (AFTER any icons). Otherwise it was displayed before
913 if (!empty($url)) {
914 $output .= $contentpart;
917 // show availability info (if module is not available)
918 $output .= $this->course_section_cm_availability($mod, $displayoptions);
920 $output .= html_writer::end_tag('div'); // $indentclasses
921 return $output;
925 * Renders HTML to display a list of course modules in a course section
926 * Also displays "move here" controls in Javascript-disabled mode
928 * This function calls {@link core_course_renderer::course_section_cm()}
930 * @param stdClass $course course object
931 * @param int|stdClass|section_info $section relative section number or section object
932 * @param int $sectionreturn section number to return to
933 * @param int $displayoptions
934 * @return void
936 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
937 global $USER;
939 $output = '';
940 $modinfo = get_fast_modinfo($course);
941 if (is_object($section)) {
942 $section = $modinfo->get_section_info($section->section);
943 } else {
944 $section = $modinfo->get_section_info($section);
946 $completioninfo = new completion_info($course);
948 // check if we are currently in the process of moving a module with JavaScript disabled
949 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
950 if ($ismoving) {
951 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
952 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
955 // Get the list of modules visible to user (excluding the module being moved if there is one)
956 $moduleshtml = array();
957 if (!empty($modinfo->sections[$section->section])) {
958 foreach ($modinfo->sections[$section->section] as $modnumber) {
959 $mod = $modinfo->cms[$modnumber];
961 if ($ismoving and $mod->id == $USER->activitycopy) {
962 // do not display moving mod
963 continue;
966 if ($modulehtml = $this->course_section_cm($course,
967 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
968 $moduleshtml[$modnumber] = $modulehtml;
973 if (!empty($moduleshtml) || $ismoving) {
975 $output .= html_writer::start_tag('ul', array('class' => 'section img-text'));
977 foreach ($moduleshtml as $modnumber => $modulehtml) {
978 if ($ismoving) {
979 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
980 $output .= html_writer::tag('li', html_writer::link($movingurl, $this->output->render($movingpix)),
981 array('class' => 'movehere', 'title' => $strmovefull));
984 $mod = $modinfo->cms[$modnumber];
985 $modclasses = 'activity '. $mod->modname. ' modtype_'.$mod->modname. ' '. $mod->get_extra_classes();
986 $output .= html_writer::start_tag('li', array('class' => $modclasses, 'id' => 'module-'. $mod->id));
987 $output .= $modulehtml;
988 $output .= html_writer::end_tag('li');
991 if ($ismoving) {
992 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
993 $output .= html_writer::tag('li', html_writer::link($movingurl, $this->output->render($movingpix)),
994 array('class' => 'movehere', 'title' => $strmovefull));
997 $output .= html_writer::end_tag('ul'); // .section
1000 return $output;
1004 * Displays a custom list of courses with paging bar if necessary
1006 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1007 * appears under the list.
1009 * If both $paginationurl and $totalcount are specified, and $totalcount is
1010 * bigger than count($courses), a paging bar is displayed above and under the
1011 * courses list.
1013 * @param array $courses array of course records (or instances of course_in_list) to show on this page
1014 * @param bool $showcategoryname whether to add category name to the course description
1015 * @param string $additionalclasses additional CSS classes to add to the div.courses
1016 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1017 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1018 * @param int $page current page number (defaults to 0 referring to the first page)
1019 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1020 * @return string
1022 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1023 global $CFG;
1024 // create instance of coursecat_helper to pass display options to function rendering courses list
1025 $chelper = new coursecat_helper();
1026 if ($showcategoryname) {
1027 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1028 } else {
1029 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1031 if ($totalcount !== null && $paginationurl !== null) {
1032 // add options to display pagination
1033 if ($perpage === null) {
1034 $perpage = $CFG->coursesperpage;
1036 $chelper->set_courses_display_options(array(
1037 'limit' => $perpage,
1038 'offset' => ((int)$page) * $perpage,
1039 'paginationurl' => $paginationurl,
1041 } else if ($paginationurl !== null) {
1042 // add options to display 'View more' link
1043 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1044 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1046 $chelper->set_attributes(array('class' => $additionalclasses));
1047 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1048 return $content;
1052 * Displays one course in the list of courses.
1054 * This is an internal function, to display an information about just one course
1055 * please use {@link core_course_renderer::course_info_box()}
1057 * @param coursecat_helper $chelper various display options
1058 * @param course_in_list|stdClass $course
1059 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1060 * depend on the course position in list - first/last/even/odd)
1061 * @return string
1063 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1064 global $CFG;
1065 if (!isset($this->strings->summary)) {
1066 $this->strings->summary = get_string('summary');
1068 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1069 return '';
1071 if ($course instanceof stdClass) {
1072 require_once($CFG->libdir. '/coursecatlib.php');
1073 $course = new course_in_list($course);
1075 $content = '';
1076 $classes = trim('coursebox clearfix '. $additionalclasses);
1077 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1078 $nametag = 'h3';
1079 } else {
1080 $classes .= ' collapsed';
1081 $nametag = 'div';
1083 $content .= html_writer::start_tag('div', array('class' => $classes)); // .coursebox
1085 $content .= html_writer::start_tag('div', array('class' => 'info'));
1087 // course name
1088 $coursename = $chelper->get_course_formatted_name($course);
1089 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', array('id' => $course->id)),
1090 $coursename, array('class' => $course->visible ? '' : 'dimmed'));
1091 $content .= html_writer::tag($nametag, $coursenamelink, array('class' => 'name'));
1093 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1094 $content .= html_writer::start_tag('div', array('class' => 'moreinfo'));
1095 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1096 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()) {
1097 $url = new moodle_url('/course/info.php', array('id' => $course->id));
1098 $image = html_writer::empty_tag('img', array('src' => $this->output->pix_url('i/info'),
1099 'alt' => $this->strings->summary));
1100 $content .= html_writer::link($url, $image, array('title' => $this->strings->summary));
1103 $content .= html_writer::end_tag('div'); // .moreinfo
1105 // print enrolmenticons
1106 if ($icons = enrol_get_course_info_icons($course)) {
1107 $content .= html_writer::start_tag('div', array('class' => 'enrolmenticons'));
1108 foreach ($icons as $pix_icon) {
1109 $content .= $this->render($pix_icon);
1111 $content .= html_writer::end_tag('div'); // .enrolmenticons
1114 $content .= html_writer::end_tag('div'); // .info
1116 $content .= html_writer::start_tag('div', array('class' => 'content'));
1117 $content .= $this->coursecat_coursebox_content($chelper, $course);
1118 $content .= html_writer::end_tag('div'); // .content
1120 $content .= html_writer::end_tag('div'); // .coursebox
1121 return $content;
1125 * Returns HTML to display course content (summary, course contacts and optionally category name)
1127 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1129 * @param coursecat_helper $chelper various display options
1130 * @param stdClass|course_in_list $course
1131 * @return string
1133 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1134 global $CFG;
1135 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1136 return '';
1138 if ($course instanceof stdClass) {
1139 require_once($CFG->libdir. '/coursecatlib.php');
1140 $course = new course_in_list($course);
1142 $content = '';
1144 // display course summary
1145 if ($course->has_summary()) {
1146 $content .= html_writer::start_tag('div', array('class' => 'summary'));
1147 $content .= $chelper->get_course_formatted_summary($course,
1148 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1149 $content .= html_writer::end_tag('div'); // .summary
1152 // display course overview files
1153 $contentimages = $contentfiles = '';
1154 foreach ($course->get_course_overviewfiles() as $file) {
1155 $isimage = $file->is_valid_image();
1156 $url = file_encode_url("$CFG->wwwroot/pluginfile.php",
1157 '/'. $file->get_contextid(). '/'. $file->get_component(). '/'.
1158 $file->get_filearea(). $file->get_filepath(). $file->get_filename(), !$isimage);
1159 if ($isimage) {
1160 $contentimages .= html_writer::tag('div',
1161 html_writer::empty_tag('img', array('src' => $url)),
1162 array('class' => 'courseimage'));
1163 } else {
1164 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1165 $filename = html_writer::tag('span', $image, array('class' => 'fp-icon')).
1166 html_writer::tag('span', $file->get_filename(), array('class' => 'fp-filename'));
1167 $contentfiles .= html_writer::tag('span',
1168 html_writer::link($url, $filename),
1169 array('class' => 'coursefile fp-filename-icon'));
1172 $content .= $contentimages. $contentfiles;
1174 // display course contacts. See course_in_list::get_course_contacts()
1175 if ($course->has_course_contacts()) {
1176 $content .= html_writer::start_tag('ul', array('class' => 'teachers'));
1177 foreach ($course->get_course_contacts() as $userid => $coursecontact) {
1178 $name = $coursecontact['rolename'].': '.
1179 html_writer::link(new moodle_url('/user/view.php',
1180 array('id' => $userid, 'course' => SITEID)),
1181 $coursecontact['username']);
1182 $content .= html_writer::tag('li', $name);
1184 $content .= html_writer::end_tag('ul'); // .teachers
1187 // display course category if necessary (for example in search results)
1188 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1189 require_once($CFG->libdir. '/coursecatlib.php');
1190 if ($cat = coursecat::get($course->category, IGNORE_MISSING)) {
1191 $content .= html_writer::start_tag('div', array('class' => 'coursecat'));
1192 $content .= get_string('category').': '.
1193 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1194 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1195 $content .= html_writer::end_tag('div'); // .coursecat
1199 return $content;
1203 * Renders the list of courses
1205 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1206 * method from outside of the class
1208 * If list of courses is specified in $courses; the argument $chelper is only used
1209 * to retrieve display options and attributes, only methods get_show_courses(),
1210 * get_courses_display_option() and get_and_erase_attributes() are called.
1212 * @param coursecat_helper $chelper various display options
1213 * @param array $courses the list of courses to display
1214 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1215 * defaulted to count($courses)
1216 * @return string
1218 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1219 global $CFG;
1220 if ($totalcount === null) {
1221 $totalcount = count($courses);
1223 if (!$totalcount) {
1224 // Courses count is cached during courses retrieval.
1225 return '';
1228 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1229 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1230 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1231 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1232 } else {
1233 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1237 // prepare content of paging bar if it is needed
1238 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1239 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1240 if ($totalcount > count($courses)) {
1241 // there are more results that can fit on one page
1242 if ($paginationurl) {
1243 // the option paginationurl was specified, display pagingbar
1244 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1245 $page = $chelper->get_courses_display_option('offset') / $perpage;
1246 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1247 $paginationurl->out(false, array('perpage' => $perpage)));
1248 if ($paginationallowall) {
1249 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1250 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1252 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1253 // the option for 'View more' link was specified, display more link
1254 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1255 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1256 array('class' => 'paging paging-morelink'));
1258 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1259 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1260 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1261 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1264 // display list of courses
1265 $attributes = $chelper->get_and_erase_attributes('courses');
1266 $content = html_writer::start_tag('div', $attributes);
1268 if (!empty($pagingbar)) {
1269 $content .= $pagingbar;
1272 $coursecount = 0;
1273 foreach ($courses as $course) {
1274 $coursecount ++;
1275 $classes = ($coursecount%2) ? 'odd' : 'even';
1276 if ($coursecount == 1) {
1277 $classes .= ' first';
1279 if ($coursecount >= count($courses)) {
1280 $classes .= ' last';
1282 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1285 if (!empty($pagingbar)) {
1286 $content .= $pagingbar;
1288 if (!empty($morelink)) {
1289 $content .= $morelink;
1292 $content .= html_writer::end_tag('div'); // .courses
1293 return $content;
1297 * Renders the list of subcategories in a category
1299 * @param coursecat_helper $chelper various display options
1300 * @param coursecat $coursecat
1301 * @param int $depth depth of the category in the current tree
1302 * @return string
1304 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1305 global $CFG;
1306 $subcategories = array();
1307 if (!$chelper->get_categories_display_option('nodisplay')) {
1308 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1310 $totalcount = $coursecat->get_children_count();
1311 if (!$totalcount) {
1312 // Note that we call get_child_categories_count() AFTER get_child_categories() to avoid extra DB requests.
1313 // Categories count is cached during children categories retrieval.
1314 return '';
1317 // prepare content of paging bar or more link if it is needed
1318 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1319 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1320 if ($totalcount > count($subcategories)) {
1321 if ($paginationurl) {
1322 // the option 'paginationurl was specified, display pagingbar
1323 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1324 $page = $chelper->get_categories_display_option('offset') / $perpage;
1325 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1326 $paginationurl->out(false, array('perpage' => $perpage)));
1327 if ($paginationallowall) {
1328 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1329 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1331 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1332 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1333 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1334 $viewmoreurl->param('categoryid', $coursecat->id);
1336 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1337 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1338 array('class' => 'paging paging-morelink'));
1340 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1341 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1342 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1343 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1346 // display list of subcategories
1347 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1349 if (!empty($pagingbar)) {
1350 $content .= $pagingbar;
1353 foreach ($subcategories as $subcategory) {
1354 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1357 if (!empty($pagingbar)) {
1358 $content .= $pagingbar;
1360 if (!empty($morelink)) {
1361 $content .= $morelink;
1364 $content .= html_writer::end_tag('div');
1365 return $content;
1369 * Returns HTML to display the subcategories and courses in the given category
1371 * This method is re-used by AJAX to expand content of not loaded category
1373 * @param coursecat_helper $chelper various display options
1374 * @param coursecat $coursecat
1375 * @param int $depth depth of the category in the current tree
1376 * @return string
1378 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1379 $content = '';
1380 // Subcategories
1381 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1383 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1384 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1385 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1386 if ($showcoursesauto && $depth) {
1387 // this is definitely collapsed mode
1388 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1391 // Courses
1392 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1393 $courses = array();
1394 if (!$chelper->get_courses_display_option('nodisplay')) {
1395 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1397 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1398 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1399 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1400 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1403 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1406 if ($showcoursesauto) {
1407 // restore the show_courses back to AUTO
1408 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1411 return $content;
1415 * Returns HTML to display a course category as a part of a tree
1417 * This is an internal function, to display a particular category and all its contents
1418 * use {@link core_course_renderer::course_category()}
1420 * @param coursecat_helper $chelper various display options
1421 * @param coursecat $coursecat
1422 * @param int $depth depth of this category in the current tree
1423 * @return string
1425 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1426 // open category tag
1427 $classes = array('category');
1428 if (empty($coursecat->visible)) {
1429 $classes[] = 'dimmed_category';
1431 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1432 // do not load content
1433 $categorycontent = '';
1434 $classes[] = 'notloaded';
1435 if ($coursecat->get_children_count() ||
1436 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1437 $classes[] = 'with_children';
1438 $classes[] = 'collapsed';
1440 } else {
1441 // load category content
1442 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1443 $classes[] = 'loaded';
1444 if (!empty($categorycontent)) {
1445 $classes[] = 'with_children';
1448 $content = html_writer::start_tag('div', array('class' => join(' ', $classes),
1449 'data-categoryid' => $coursecat->id,
1450 'data-depth' => $depth));
1452 // category name
1453 $categoryname = $coursecat->get_formatted_name();
1454 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1455 array('categoryid' => $coursecat->id)),
1456 $categoryname);
1457 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1458 && ($coursescount = $coursecat->get_courses_count())) {
1459 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1460 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1462 $content .= html_writer::start_tag('div', array('class' => 'info'));
1463 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'name'));
1464 $content .= html_writer::end_tag('div'); // .info
1466 // add category content to the output
1467 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1469 $content .= html_writer::end_tag('div'); // .category
1471 // Return the course category tree HTML
1472 return $content;
1476 * Returns HTML to display a tree of subcategories and courses in the given category
1478 * @param coursecat_helper $chelper various display options
1479 * @param coursecat $coursecat top category (this category's name and description will NOT be added to the tree)
1480 * @return string
1482 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1483 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1484 if (empty($categorycontent)) {
1485 return '';
1488 // Generate an id and the required JS call to make this a nice widget
1489 $id = html_writer::random_id('course_category_tree');
1490 $this->page->requires->js_init_call('M.util.init_toggle_class_on_click',
1491 array($id, '.category.with_children.loaded > .info .name', 'collapsed', '.category.with_children.loaded'));
1493 // Start content generation
1494 $content = '';
1495 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1496 $content .= html_writer::start_tag('div',
1497 array('id' => $id, 'data-showcourses' => $chelper->get_show_courses()) + $attributes);
1499 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1501 if ($coursecat->get_children_count() && $chelper->get_subcat_depth() != 1) {
1502 // We don't need to display "Expand all"/"Collapse all" buttons if there are no
1503 // subcategories or there is only one level of subcategories loaded
1504 // TODO if subcategories are loaded by AJAX this might still be needed!
1505 $content .= html_writer::start_tag('div', array('class' => 'controls'));
1506 $content .= html_writer::tag('div', get_string('collapseall'), array('class' => 'addtoall expandall'));
1507 $content .= html_writer::tag('div', get_string('expandall'), array('class' => 'removefromall collapseall'));
1508 $content .= html_writer::end_tag('div');
1511 $content .= html_writer::end_tag('div'); // .course_category_tree
1513 return $content;
1517 * Renders HTML to display particular course category - list of it's subcategories and courses
1519 * Invoked from /course/index.php
1521 * @param int|stdClass|coursecat $category
1523 public function course_category($category) {
1524 global $CFG;
1525 require_once($CFG->libdir. '/coursecatlib.php');
1526 $coursecat = coursecat::get(is_object($category) ? $category->id : $category);
1527 $site = get_site();
1528 $output = '';
1530 $this->page->set_button($this->course_search_form('', 'navbar'));
1531 if (!$coursecat->id) {
1532 if (can_edit_in_category()) {
1533 // add 'Manage' button instead of course search form
1534 $managebutton = $this->single_button(new moodle_url('/course/manage.php'),
1535 get_string('managecourses'), 'get');
1536 $this->page->set_button($managebutton);
1538 if (coursecat::count_all() == 1) {
1539 // There exists only one category in the system, do not display link to it
1540 $coursecat = coursecat::get_default();
1541 $strfulllistofcourses = get_string('fulllistofcourses');
1542 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1543 } else {
1544 $strcategories = get_string('categories');
1545 $this->page->set_title("$site->shortname: $strcategories");
1547 } else {
1548 $this->page->set_title("$site->shortname: ". $coursecat->get_formatted_name());
1550 // Print the category selector
1551 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1552 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1553 coursecat::make_categories_list(), $coursecat->id, null, 'switchcategory');
1554 $select->set_label(get_string('categories').':');
1555 $output .= $this->render($select);
1556 $output .= html_writer::end_tag('div'); // .categorypicker
1559 // Print current category description
1560 $chelper = new coursecat_helper();
1561 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1562 $output .= $this->box($description, array('class' => 'generalbox info'));
1565 // Prepare parameters for courses and categories lists in the tree
1566 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1567 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1569 $coursedisplayoptions = array();
1570 $catdisplayoptions = array();
1571 $browse = optional_param('browse', null, PARAM_ALPHA);
1572 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1573 $page = optional_param('page', 0, PARAM_INT);
1574 $baseurl = new moodle_url('/course/index.php');
1575 if ($coursecat->id) {
1576 $baseurl->param('categoryid', $coursecat->id);
1578 if ($perpage != $CFG->coursesperpage) {
1579 $baseurl->param('perpage', $perpage);
1581 $coursedisplayoptions['limit'] = $perpage;
1582 $catdisplayoptions['limit'] = $perpage;
1583 if ($browse === 'courses' || !$coursecat->has_children()) {
1584 $coursedisplayoptions['offset'] = $page * $perpage;
1585 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1586 $catdisplayoptions['nodisplay'] = true;
1587 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1588 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1589 } else if ($browse === 'categories' || !$coursecat->has_courses()) {
1590 $coursedisplayoptions['nodisplay'] = true;
1591 $catdisplayoptions['offset'] = $page * $perpage;
1592 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1593 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1594 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1595 } else {
1596 // we have a category that has both subcategories and courses, display pagination separately
1597 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1598 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1600 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1602 // Display course category tree
1603 $output .= $this->coursecat_tree($chelper, $coursecat);
1605 // Add course search form (if we are inside category it was already added to the navbar)
1606 if (!$coursecat->id) {
1607 $output .= $this->course_search_form();
1610 // Add action buttons
1611 $output .= $this->container_start('buttons');
1612 $context = get_category_or_system_context($coursecat->id);
1613 if (has_capability('moodle/course:create', $context)) {
1614 // Print link to create a new course, for the 1st available category.
1615 if ($coursecat->id) {
1616 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1617 } else {
1618 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1620 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1622 ob_start();
1623 if (coursecat::count_all() == 1) {
1624 print_course_request_buttons(context_system::instance());
1625 } else {
1626 print_course_request_buttons($context);
1628 $output .= ob_get_contents();
1629 ob_end_clean();
1630 $output .= $this->container_end();
1632 return $output;
1636 * Renders html to display search result page
1638 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1639 * @return string
1641 public function search_courses($searchcriteria) {
1642 global $CFG;
1643 $content = '';
1644 if (!empty($searchcriteria)) {
1645 // print search results
1646 require_once($CFG->libdir. '/coursecatlib.php');
1648 $displayoptions = array('sort' => array('displayname' => 1));
1649 // take the current page and number of results per page from query
1650 $perpage = optional_param('perpage', 0, PARAM_RAW);
1651 if ($perpage !== 'all') {
1652 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1653 $page = optional_param('page', 0, PARAM_INT);
1654 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1656 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1657 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1658 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1660 $class = 'course-search-result';
1661 foreach ($searchcriteria as $key => $value) {
1662 if (!empty($value)) {
1663 $class .= ' course-search-result-'. $key;
1666 $chelper = new coursecat_helper();
1667 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1668 set_courses_display_options($displayoptions)->
1669 set_search_criteria($searchcriteria)->
1670 set_attributes(array('class' => $class));
1672 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1673 $totalcount = coursecat::search_courses_count($searchcriteria);
1674 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1676 if (!$totalcount) {
1677 if (!empty($searchcriteria['search'])) {
1678 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1679 } else {
1680 $content .= $this->heading(get_string('novalidcourses'));
1682 } else {
1683 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1684 $content .= $courseslist;
1687 if (!empty($searchcriteria['search'])) {
1688 // print search form only if there was a search by search string, otherwise it is confusing
1689 $content .= $this->box_start('generalbox mdl-align');
1690 $content .= $this->course_search_form($searchcriteria['search']);
1691 $content .= $this->box_end();
1693 } else {
1694 // just print search form
1695 $content .= $this->box_start('generalbox mdl-align');
1696 $content .= $this->course_search_form();
1697 $content .= html_writer::tag('div', get_string("searchhelp"), array('class' => 'searchhelp'));
1698 $content .= $this->box_end();
1700 return $content;
1704 * Renders html to print list of courses tagged with particular tag
1706 * @param int $tagid id of the tag
1707 * @return string empty string if no courses are marked with this tag or rendered list of courses
1709 public function tagged_courses($tagid) {
1710 global $CFG;
1711 require_once($CFG->libdir. '/coursecatlib.php');
1712 $displayoptions = array('limit' => $CFG->coursesperpage);
1713 $displayoptions['viewmoreurl'] = new moodle_url('/course/search.php',
1714 array('tagid' => $tagid, 'page' => 1, 'perpage' => $CFG->coursesperpage));
1715 $displayoptions['viewmoretext'] = new lang_string('findmorecourses');
1716 $chelper = new coursecat_helper();
1717 $searchcriteria = array('tagid' => $tagid);
1718 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1719 set_search_criteria(array('tagid' => $tagid))->
1720 set_courses_display_options($displayoptions)->
1721 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1722 // (we set the same css class as in search results by tagid)
1723 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1724 $totalcount = coursecat::search_courses_count($searchcriteria);
1725 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1726 if ($totalcount) {
1727 require_once $CFG->dirroot.'/tag/lib.php';
1728 $heading = get_string('courses') . ' ' . get_string('taggedwith', 'tag', tag_get_name($tagid)) .': '. $totalcount;
1729 return $this->heading($heading, 3). $content;
1731 return '';
1735 * Returns HTML to display one remote course
1737 * @param stdClass $course remote course information, contains properties:
1738 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1739 * @return string
1741 protected function frontpage_remote_course(stdClass $course) {
1742 $url = new moodle_url('/auth/mnet/jump.php', array(
1743 'hostid' => $course->hostid,
1744 'wantsurl' => '/course/view.php?id='. $course->remoteid
1747 $output = '';
1748 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1749 $output .= html_writer::start_tag('div', array('class' => 'info'));
1750 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1751 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1752 $output .= html_writer::end_tag('h3'); // .name
1753 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1754 $output .= html_writer::end_tag('div'); // .info
1755 $output .= html_writer::start_tag('div', array('class' => 'content'));
1756 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1757 $options = new stdClass();
1758 $options->noclean = true;
1759 $options->para = false;
1760 $options->overflowdiv = true;
1761 $output .= format_text($course->summary, $course->summaryformat, $options);
1762 $output .= html_writer::end_tag('div'); // .summary
1763 $addinfo = format_string($course->hostname) . ' : '
1764 . format_string($course->cat_name) . ' : '
1765 . format_string($course->shortname);
1766 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1767 $output .= html_writer::end_tag('div'); // .content
1768 $output .= html_writer::end_tag('div'); // .coursebox
1769 return $output;
1773 * Returns HTML to display one remote host
1775 * @param array $host host information, contains properties: name, url, count
1776 * @return string
1778 protected function frontpage_remote_host($host) {
1779 $output = '';
1780 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1781 $output .= html_writer::start_tag('div', array('class' => 'info'));
1782 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1783 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1784 $output .= html_writer::end_tag('h3'); // .name
1785 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1786 $output .= html_writer::end_tag('div'); // .info
1787 $output .= html_writer::start_tag('div', array('class' => 'content'));
1788 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1789 $output .= $host['count'] . ' ' . get_string('courses');
1790 $output .= html_writer::end_tag('div'); // .content
1791 $output .= html_writer::end_tag('div'); // .coursebox
1792 return $output;
1796 * Returns HTML to print list of courses user is enrolled to for the frontpage
1798 * Also lists remote courses or remote hosts if MNET authorisation is used
1800 * @return string
1802 public function frontpage_my_courses() {
1803 global $USER, $CFG, $DB;
1805 if (!isloggedin() or isguestuser()) {
1806 return '';
1809 $output = '';
1810 if (!empty($CFG->navsortmycoursessort)) {
1811 // sort courses the same as in navigation menu
1812 $sortorder = 'visible DESC,'. $CFG->navsortmycoursessort.' ASC';
1813 } else {
1814 $sortorder = 'visible DESC,sortorder ASC';
1816 $courses = enrol_get_my_courses('summary, summaryformat', $sortorder);
1817 $rhosts = array();
1818 $rcourses = array();
1819 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1820 $rcourses = get_my_remotecourses($USER->id);
1821 $rhosts = get_my_remotehosts();
1824 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1826 $chelper = new coursecat_helper();
1827 if (count($courses) > $CFG->frontpagecourselimit) {
1828 // There are more enrolled courses than we can display, display link to 'My courses'.
1829 $totalcount = count($courses);
1830 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
1831 $chelper->set_courses_display_options(array(
1832 'viewmoreurl' => new moodle_url('/my/'),
1833 'viewmoretext' => new lang_string('mycourses')
1835 } else {
1836 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
1837 $chelper->set_courses_display_options(array(
1838 'viewmoreurl' => new moodle_url('/course/index.php'),
1839 'viewmoretext' => new lang_string('fulllistofcourses')
1841 $totalcount = $DB->count_records('course') - 1;
1843 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
1844 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
1845 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
1847 // MNET
1848 if (!empty($rcourses)) {
1849 // at the IDP, we know of all the remote courses
1850 $output .= html_writer::start_tag('div', array('class' => 'courses'));
1851 foreach ($rcourses as $course) {
1852 $output .= $this->frontpage_remote_course($course);
1854 $output .= html_writer::end_tag('div'); // .courses
1855 } elseif (!empty($rhosts)) {
1856 // non-IDP, we know of all the remote servers, but not courses
1857 $output .= html_writer::start_tag('div', array('class' => 'courses'));
1858 foreach ($rhosts as $host) {
1859 $output .= $this->frontpage_remote_host($host);
1861 $output .= html_writer::end_tag('div'); // .courses
1864 return $output;
1868 * Returns HTML to print list of available courses for the frontpage
1870 * @return string
1872 public function frontpage_available_courses() {
1873 global $CFG;
1874 require_once($CFG->libdir. '/coursecatlib.php');
1876 $chelper = new coursecat_helper();
1877 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
1878 set_courses_display_options(array(
1879 'recursive' => true,
1880 'limit' => $CFG->frontpagecourselimit,
1881 'viewmoreurl' => new moodle_url('/course/index.php'),
1882 'viewmoretext' => new lang_string('fulllistofcourses')));
1884 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
1885 $courses = coursecat::get(0)->get_courses($chelper->get_courses_display_options());
1886 $totalcount = coursecat::get(0)->get_courses_count($chelper->get_courses_display_options());
1887 if (!$totalcount && has_capability('moodle/course:create', context_system::instance())) {
1888 // Print link to create a new course, for the 1st available category.
1889 $output = $this->container_start('buttons');
1890 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1891 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1892 $output .= $this->container_end('buttons');
1893 return $output;
1895 return $this->coursecat_courses($chelper, $courses, $totalcount);
1899 * Returns HTML to print tree with course categories and courses for the frontpage
1901 * @return string
1903 public function frontpage_combo_list() {
1904 global $CFG;
1905 require_once($CFG->libdir. '/coursecatlib.php');
1906 $chelper = new coursecat_helper();
1907 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
1908 set_categories_display_options(array(
1909 'limit' => $CFG->coursesperpage,
1910 'viewmoreurl' => new moodle_url('/course/index.php',
1911 array('browse' => 'categories', 'page' => 1))
1912 ))->
1913 set_courses_display_options(array(
1914 'limit' => $CFG->coursesperpage,
1915 'viewmoreurl' => new moodle_url('/course/index.php',
1916 array('browse' => 'courses', 'page' => 1))
1917 ))->
1918 set_attributes(array('class' => 'frontpage-category-combo'));
1919 return $this->coursecat_tree($chelper, coursecat::get(0));
1923 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
1925 * @return string
1927 public function frontpage_categories_list() {
1928 global $CFG;
1929 require_once($CFG->libdir. '/coursecatlib.php');
1930 $chelper = new coursecat_helper();
1931 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
1932 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
1933 set_categories_display_options(array(
1934 'limit' => $CFG->coursesperpage,
1935 'viewmoreurl' => new moodle_url('/course/index.php',
1936 array('browse' => 'categories', 'page' => 1))
1937 ))->
1938 set_attributes(array('class' => 'frontpage-category-names'));
1939 return $this->coursecat_tree($chelper, coursecat::get(0));
1944 * Class storing display options and functions to help display course category and/or courses lists
1946 * This is a wrapper for coursecat objects that also stores display options
1947 * and functions to retrieve sorted and paginated lists of categories/courses.
1949 * If theme overrides methods in core_course_renderers that access this class
1950 * it may as well not use this class at all or extend it.
1952 * @package core
1953 * @copyright 2013 Marina Glancy
1954 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1956 class coursecat_helper {
1957 /** @var string [none, collapsed, expanded] how (if) display courses list */
1958 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
1959 /** @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) */
1960 protected $subcatdepth = 1;
1961 /** @var array options to display courses list */
1962 protected $coursesdisplayoptions = array();
1963 /** @var array options to display subcategories list */
1964 protected $categoriesdisplayoptions = array();
1965 /** @var array additional HTML attributes */
1966 protected $attributes = array();
1967 /** @var array search criteria if the list is a search result */
1968 protected $searchcriteria = null;
1971 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
1973 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
1974 * @return coursecat_helper
1976 public function set_show_courses($showcourses) {
1977 $this->showcourses = $showcourses;
1978 // Automatically set the options to preload summary and coursecontacts for coursecat::get_courses() and coursecat::search_courses()
1979 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
1980 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
1981 return $this;
1985 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
1987 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
1989 public function get_show_courses() {
1990 return $this->showcourses;
1994 * Sets the maximum depth to expand subcategories in the tree
1996 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
1998 * @param int $subcatdepth
1999 * @return coursecat_helper
2001 public function set_subcat_depth($subcatdepth) {
2002 $this->subcatdepth = $subcatdepth;
2003 return $this;
2007 * Returns the maximum depth to expand subcategories in the tree
2009 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2011 * @return int
2013 public function get_subcat_depth() {
2014 return $this->subcatdepth;
2018 * Sets options to display list of courses
2020 * Options are later submitted as argument to coursecat::get_courses() and/or coursecat::search_courses()
2022 * Options that coursecat::get_courses() accept:
2023 * - recursive - return courses from subcategories as well. Use with care,
2024 * this may be a huge list!
2025 * - summary - preloads fields 'summary' and 'summaryformat'
2026 * - coursecontacts - preloads course contacts
2027 * - isenrolled - preloads indication whether this user is enrolled in the course
2028 * - sort - list of fields to sort. Example
2029 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2030 * will sort by idnumber asc, shortname asc and id desc.
2031 * Default: array('sortorder' => 1)
2032 * Only cached fields may be used for sorting!
2033 * - offset
2034 * - limit - maximum number of children to return, 0 or null for no limit
2036 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2038 * Also renderer can set here any additional options it wants to pass between renderer functions.
2040 * @param array $options
2041 * @return coursecat_helper
2043 public function set_courses_display_options($options) {
2044 $this->coursesdisplayoptions = $options;
2045 $this->set_show_courses($this->showcourses); // this will calculate special display options
2046 return $this;
2050 * Sets one option to display list of courses
2052 * @see coursecat_helper::set_courses_display_options()
2054 * @param string $key
2055 * @param mixed $value
2056 * @return coursecat_helper
2058 public function set_courses_display_option($key, $value) {
2059 $this->coursesdisplayoptions[$key] = $value;
2060 return $this;
2064 * Return the specified option to display list of courses
2066 * @param string $optionname option name
2067 * @param mixed $defaultvalue default value for option if it is not specified
2068 * @return mixed
2070 public function get_courses_display_option($optionname, $defaultvalue = null) {
2071 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2072 return $this->coursesdisplayoptions[$optionname];
2073 } else {
2074 return $defaultvalue;
2079 * Returns all options to display the courses
2081 * This array is usually passed to {@link coursecat::get_courses()} or
2082 * {@link coursecat::search_courses()}
2084 * @return array
2086 public function get_courses_display_options() {
2087 return $this->coursesdisplayoptions;
2091 * Sets options to display list of subcategories
2093 * Options 'sort', 'offset' and 'limit' are passed to coursecat::get_children().
2094 * Any other options may be used by renderer functions
2096 * @param array $options
2097 * @return coursecat_helper
2099 public function set_categories_display_options($options) {
2100 $this->categoriesdisplayoptions = $options;
2101 return $this;
2105 * Return the specified option to display list of subcategories
2107 * @param string $optionname option name
2108 * @param mixed $defaultvalue default value for option if it is not specified
2109 * @return mixed
2111 public function get_categories_display_option($optionname, $defaultvalue = null) {
2112 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2113 return $this->categoriesdisplayoptions[$optionname];
2114 } else {
2115 return $defaultvalue;
2120 * Returns all options to display list of subcategories
2122 * This array is usually passed to {@link coursecat::get_children()}
2124 * @return array
2126 public function get_categories_display_options() {
2127 return $this->categoriesdisplayoptions;
2131 * Sets additional general options to pass between renderer functions, usually HTML attributes
2133 * @param array $attributes
2134 * @return coursecat_helper
2136 public function set_attributes($attributes) {
2137 $this->attributes = $attributes;
2138 return $this;
2142 * Return all attributes and erases them so they are not applied again
2144 * @param string $classname adds additional class name to the beginning of $attributes['class']
2145 * @return array
2147 public function get_and_erase_attributes($classname) {
2148 $attributes = $this->attributes;
2149 $this->attributes = array();
2150 if (empty($attributes['class'])) {
2151 $attributes['class'] = '';
2153 $attributes['class'] = $classname . ' '. $attributes['class'];
2154 return $attributes;
2158 * Sets the search criteria if the course is a search result
2160 * Search string will be used to highlight terms in course name and description
2162 * @param array $searchcriteria
2163 * @return coursecat_helper
2165 public function set_search_criteria($searchcriteria) {
2166 $this->searchcriteria = $searchcriteria;
2167 return $this;
2171 * Returns formatted and filtered description of the given category
2173 * @param coursecat $coursecat category
2174 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2175 * if context is not specified it will be added automatically
2176 * @return string|null
2178 public function get_category_formatted_description($coursecat, $options = null) {
2179 if ($coursecat->id && !empty($coursecat->description)) {
2180 if (!isset($coursecat->descriptionformat)) {
2181 $descriptionformat = FORMAT_MOODLE;
2182 } else {
2183 $descriptionformat = $coursecat->descriptionformat;
2185 if ($options === null) {
2186 $options = array('noclean' => true, 'overflowdiv' => true);
2187 } else {
2188 $options = (array)$options;
2190 $context = context_coursecat::instance($coursecat->id);
2191 if (!isset($options['context'])) {
2192 $options['context'] = $context;
2194 $text = file_rewrite_pluginfile_urls($coursecat->description,
2195 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2196 return format_text($text, $descriptionformat, $options);
2198 return null;
2202 * Returns given course's summary with proper embedded files urls and formatted
2204 * @param course_in_list $course
2205 * @param array|stdClass $options additional formatting options
2206 * @return string
2208 public function get_course_formatted_summary($course, $options = array()) {
2209 global $CFG;
2210 require_once($CFG->libdir. '/filelib.php');
2211 if (!$course->has_summary()) {
2212 return '';
2214 $options = (array)$options;
2215 $context = context_course::instance($course->id);
2216 if (!isset($options['context'])) {
2217 // TODO see MDL-38521
2218 // option 1 (current), page context - no code required
2219 // option 2, system context
2220 // $options['context'] = context_system::instance();
2221 // option 3, course context:
2222 // $options['context'] = $context;
2223 // option 4, course category context:
2224 // $options['context'] = $context->get_parent_context();
2226 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2227 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2228 if (!empty($this->searchcriteria['search'])) {
2229 $summary = highlight($this->searchcriteria['search'], $summary);
2231 return $summary;
2235 * Returns course name as it is configured to appear in courses lists formatted to course context
2237 * @param course_in_list $course
2238 * @param array|stdClass $options additional formatting options
2239 * @return string
2241 public function get_course_formatted_name($course, $options = array()) {
2242 $options = (array)$options;
2243 if (!isset($options['context'])) {
2244 $options['context'] = context_course::instance($course->id);
2246 $name = format_string(get_course_display_name_for_list($course), true, $options);
2247 if (!empty($this->searchcriteria['search'])) {
2248 $name = highlight($this->searchcriteria['search'], $name);
2250 return $name;