MDL-40205 theme: fixed overflow of block headers
[moodle.git] / course / renderer.php
blobeb6ab4ae776154f1fe787520c802c038a274836f
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);
61 $this->add_modchoosertoggle();
64 /**
65 * Adds the item in course settings navigation to toggle modchooser
67 * Theme can overwrite as an empty function to exclude it (for example if theme does not
68 * use modchooser at all)
70 protected function add_modchoosertoggle() {
71 global $CFG;
72 static $modchoosertoggleadded = false;
73 // Add the module chooser toggle to the course page
74 if ($modchoosertoggleadded || $this->page->state > moodle_page::STATE_PRINTING_HEADER ||
75 $this->page->course->id == SITEID ||
76 !$this->page->user_is_editing() ||
77 !($context = context_course::instance($this->page->course->id)) ||
78 !has_capability('moodle/course:manageactivities', $context) ||
79 !course_ajax_enabled($this->page->course) ||
80 !($coursenode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE)) ||
81 !($turneditingnode = $coursenode->get('turneditingonoff'))) {
82 // too late or we are on site page or we could not find the adjacent nodes in course settings menu
83 // or we are not allowed to edit
84 return;
86 $modchoosertoggleadded = true;
87 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
88 // We are on the course page, retain the current page params e.g. section.
89 $modchoosertoggleurl = clone($this->page->url);
90 } else {
91 // Edit on the main course page.
92 $modchoosertoggleurl = new moodle_url('/course/view.php', array('id' => $this->page->course->id,
93 'return' => $this->page->url->out_as_local_url(false)));
95 $modchoosertoggleurl->param('sesskey', sesskey());
96 if ($usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault)) {
97 $modchoosertogglestring = get_string('modchooserdisable', 'moodle');
98 $modchoosertoggleurl->param('modchooser', 'off');
99 } else {
100 $modchoosertogglestring = get_string('modchooserenable', 'moodle');
101 $modchoosertoggleurl->param('modchooser', 'on');
103 $modchoosertoggle = navigation_node::create($modchoosertogglestring, $modchoosertoggleurl, navigation_node::TYPE_SETTING, null, 'modchoosertoggle');
105 // Insert the modchoosertoggle after the settings node 'turneditingonoff' (navigation_node only has function to insert before, so we insert before and then swap).
106 $coursenode->add_node($modchoosertoggle, 'turneditingonoff');
107 $turneditingnode->remove();
108 $coursenode->add_node($turneditingnode, 'modchoosertoggle');
110 $modchoosertoggle->add_class('modchoosertoggle');
111 $modchoosertoggle->add_class('visibleifjs');
112 user_preference_allow_ajax_update('usemodchooser', PARAM_BOOL);
116 * Renders course info box.
118 * @param stdClass|course_in_list $course
119 * @return string
121 public function course_info_box(stdClass $course) {
122 $content = '';
123 $content .= $this->output->box_start('generalbox info');
124 $chelper = new coursecat_helper();
125 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
126 $content .= $this->coursecat_coursebox($chelper, $course);
127 $content .= $this->output->box_end();
128 return $content;
132 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
134 * @deprecated since 2.5
136 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
138 * @param array $ignored argument ignored
139 * @return string
141 public final function course_category_tree(array $ignored) {
142 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
143 return $this->frontpage_combo_list();
147 * Renderers a category for use with course_category_tree
149 * @deprecated since 2.5
151 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
153 * @param array $category
154 * @param int $depth
155 * @return string
157 protected final function course_category_tree_category(stdClass $category, $depth=1) {
158 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
159 return '';
163 * Build the HTML for the module chooser javascript popup
165 * @param array $modules A set of modules as returned form @see
166 * get_module_metadata
167 * @param object $course The course that will be displayed
168 * @return string The composed HTML for the module
170 public function course_modchooser($modules, $course) {
171 static $isdisplayed = false;
172 if ($isdisplayed) {
173 return '';
175 $isdisplayed = true;
177 // Add the module chooser
178 $this->page->requires->yui_module('moodle-course-modchooser',
179 'M.course.init_chooser',
180 array(array('courseid' => $course->id, 'closeButtonTitle' => get_string('close', 'editor')))
182 $this->page->requires->strings_for_js(array(
183 'addresourceoractivity',
184 'modchooserenable',
185 'modchooserdisable',
186 ), 'moodle');
188 // Add the header
189 $header = html_writer::tag('div', get_string('addresourceoractivity', 'moodle'),
190 array('class' => 'hd choosertitle'));
192 $formcontent = html_writer::start_tag('form', array('action' => new moodle_url('/course/jumpto.php'),
193 'id' => 'chooserform', 'method' => 'post'));
194 $formcontent .= html_writer::start_tag('div', array('id' => 'typeformdiv'));
195 $formcontent .= html_writer::tag('input', '', array('type' => 'hidden', 'id' => 'course',
196 'name' => 'course', 'value' => $course->id));
197 $formcontent .= html_writer::tag('input', '', array('type' => 'hidden', 'name' => 'sesskey',
198 'value' => sesskey()));
199 $formcontent .= html_writer::end_tag('div');
201 // Put everything into one tag 'options'
202 $formcontent .= html_writer::start_tag('div', array('class' => 'options'));
203 $formcontent .= html_writer::tag('div', get_string('selectmoduletoviewhelp', 'moodle'),
204 array('class' => 'instruction'));
205 // Put all options into one tag 'alloptions' to allow us to handle scrolling
206 $formcontent .= html_writer::start_tag('div', array('class' => 'alloptions'));
208 // Activities
209 $activities = array_filter($modules, create_function('$mod', 'return ($mod->archetype !== MOD_ARCHETYPE_RESOURCE && $mod->archetype !== MOD_ARCHETYPE_SYSTEM);'));
210 if (count($activities)) {
211 $formcontent .= $this->course_modchooser_title('activities');
212 $formcontent .= $this->course_modchooser_module_types($activities);
215 // Resources
216 $resources = array_filter($modules, create_function('$mod', 'return ($mod->archetype === MOD_ARCHETYPE_RESOURCE);'));
217 if (count($resources)) {
218 $formcontent .= $this->course_modchooser_title('resources');
219 $formcontent .= $this->course_modchooser_module_types($resources);
222 $formcontent .= html_writer::end_tag('div'); // modoptions
223 $formcontent .= html_writer::end_tag('div'); // types
225 $formcontent .= html_writer::start_tag('div', array('class' => 'submitbuttons'));
226 $formcontent .= html_writer::tag('input', '',
227 array('type' => 'submit', 'name' => 'submitbutton', 'class' => 'submitbutton', 'value' => get_string('add')));
228 $formcontent .= html_writer::tag('input', '',
229 array('type' => 'submit', 'name' => 'addcancel', 'class' => 'addcancel', 'value' => get_string('cancel')));
230 $formcontent .= html_writer::end_tag('div');
231 $formcontent .= html_writer::end_tag('form');
233 // Wrap the whole form in a div
234 $formcontent = html_writer::tag('div', $formcontent, array('id' => 'chooseform'));
236 // Put all of the content together
237 $content = $formcontent;
239 $content = html_writer::tag('div', $content, array('class' => 'choosercontainer'));
240 return $header . html_writer::tag('div', $content, array('class' => 'chooserdialoguebody'));
244 * Build the HTML for a specified set of modules
246 * @param array $modules A set of modules as used by the
247 * course_modchooser_module function
248 * @return string The composed HTML for the module
250 protected function course_modchooser_module_types($modules) {
251 $return = '';
252 foreach ($modules as $module) {
253 if (!isset($module->types)) {
254 $return .= $this->course_modchooser_module($module);
255 } else {
256 $return .= $this->course_modchooser_module($module, array('nonoption'));
257 foreach ($module->types as $type) {
258 $return .= $this->course_modchooser_module($type, array('option', 'subtype'));
262 return $return;
266 * Return the HTML for the specified module adding any required classes
268 * @param object $module An object containing the title, and link. An
269 * icon, and help text may optionally be specified. If the module
270 * contains subtypes in the types option, then these will also be
271 * displayed.
272 * @param array $classes Additional classes to add to the encompassing
273 * div element
274 * @return string The composed HTML for the module
276 protected function course_modchooser_module($module, $classes = array('option')) {
277 $output = '';
278 $output .= html_writer::start_tag('div', array('class' => implode(' ', $classes)));
279 $output .= html_writer::start_tag('label', array('for' => 'module_' . $module->name));
280 if (!isset($module->types)) {
281 $output .= html_writer::tag('input', '', array('type' => 'radio',
282 'name' => 'jumplink', 'id' => 'module_' . $module->name, 'value' => $module->link));
285 $output .= html_writer::start_tag('span', array('class' => 'modicon'));
286 if (isset($module->icon)) {
287 // Add an icon if we have one
288 $output .= $module->icon;
290 $output .= html_writer::end_tag('span');
292 $output .= html_writer::tag('span', $module->title, array('class' => 'typename'));
293 if (!isset($module->help)) {
294 // Add help if found
295 $module->help = get_string('nohelpforactivityorresource', 'moodle');
298 // Format the help text using markdown with the following options
299 $options = new stdClass();
300 $options->trusted = false;
301 $options->noclean = false;
302 $options->smiley = false;
303 $options->filter = false;
304 $options->para = true;
305 $options->newlines = false;
306 $options->overflowdiv = false;
307 $module->help = format_text($module->help, FORMAT_MARKDOWN, $options);
308 $output .= html_writer::tag('span', $module->help, array('class' => 'typesummary'));
309 $output .= html_writer::end_tag('label');
310 $output .= html_writer::end_tag('div');
312 return $output;
315 protected function course_modchooser_title($title, $identifier = null) {
316 $module = new stdClass();
317 $module->name = $title;
318 $module->types = array();
319 $module->title = get_string($title, $identifier);
320 $module->help = '';
321 return $this->course_modchooser_module($module, array('moduletypetitle'));
325 * Renders HTML for displaying the sequence of course module editing buttons
327 * @see course_get_cm_edit_actions()
329 * @param action_link[] $actions Array of action_link objects
330 * @param cm_info $mod The module we are displaying actions for.
331 * @param array $displayoptions additional display options:
332 * ownerselector => A JS/CSS selector that can be used to find an cm node.
333 * If specified the owning node will be given the class 'action-menu-shown' when the action
334 * menu is being displayed.
335 * constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
336 * the action menu to when it is being displayed.
337 * donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
338 * @return string
340 public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
341 global $CFG;
343 if (empty($actions)) {
344 return '';
347 if (isset($displayoptions['ownerselector'])) {
348 $ownerselector = $displayoptions['ownerselector'];
349 } else if ($mod) {
350 $ownerselector = '#module-'.$mod->id;
351 } else {
352 debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
353 $ownerselector = 'li.activity';
356 if (isset($displayoptions['constraintselector'])) {
357 $constraint = $displayoptions['constraintselector'];
358 } else {
359 $constraint = '.course-content';
362 $menu = new action_menu();
363 $menu->set_owner_selector($ownerselector);
364 $menu->set_constraint($constraint);
365 $menu->set_alignment(action_menu::TR, action_menu::BR);
366 $menu->set_menu_trigger(get_string('edit'));
367 if (isset($CFG->modeditingmenu) && !$CFG->modeditingmenu || !empty($displayoptions['donotenhance'])) {
368 $menu->do_not_enhance();
370 // Swap the left/right icons.
371 // Normally we have have right, then left but this does not
372 // make sense when modactionmenu is disabled.
373 $moveright = null;
374 $_actions = array();
375 foreach ($actions as $key => $value) {
376 if ($key === 'moveright') {
378 // Save moveright for later.
379 $moveright = $value;
380 } else if ($moveright) {
382 // This assumes that the order was moveright, moveleft.
383 // If we have a moveright, then we should place it immediately after the current value.
384 $_actions[$key] = $value;
385 $_actions['moveright'] = $moveright;
387 // Clear the value to prevent it being used multiple times.
388 $moveright = null;
389 } else {
391 $_actions[$key] = $value;
394 $actions = $_actions;
395 unset($_actions);
397 foreach ($actions as $action) {
398 if ($action instanceof action_menu_link) {
399 $action->add_class('cm-edit-action');
401 $menu->add($action);
403 $menu->attributes['class'] .= ' section-cm-edit-actions commands';
405 // Prioritise the menu ahead of all other actions.
406 $menu->prioritise = true;
408 return $this->render($menu);
412 * Renders HTML for the menus to add activities and resources to the current course
414 * Note, if theme overwrites this function and it does not use modchooser,
415 * see also {@link core_course_renderer::add_modchoosertoggle()}
417 * @param stdClass $course
418 * @param int $section relative section number (field course_sections.section)
419 * @param int $sectionreturn The section to link back to
420 * @param array $displayoptions additional display options, for example blocks add
421 * option 'inblock' => true, suggesting to display controls vertically
422 * @return string
424 function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
425 global $CFG;
427 $vertical = !empty($displayoptions['inblock']);
429 // check to see if user can add menus and there are modules to add
430 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
431 || !$this->page->user_is_editing()
432 || !($modnames = get_module_types_names()) || empty($modnames)) {
433 return '';
436 // Retrieve all modules with associated metadata
437 $modules = get_module_metadata($course, $modnames, $sectionreturn);
438 $urlparams = array('section' => $section);
440 // We'll sort resources and activities into two lists
441 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
443 foreach ($modules as $module) {
444 if (isset($module->types)) {
445 // This module has a subtype
446 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
447 $subtypes = array();
448 foreach ($module->types as $subtype) {
449 $link = $subtype->link->out(true, $urlparams);
450 $subtypes[$link] = $subtype->title;
453 // Sort module subtypes into the list
454 $activityclass = MOD_CLASS_ACTIVITY;
455 if ($module->archetype == MOD_CLASS_RESOURCE) {
456 $activityclass = MOD_CLASS_RESOURCE;
458 if (!empty($module->title)) {
459 // This grouping has a name
460 $activities[$activityclass][] = array($module->title => $subtypes);
461 } else {
462 // This grouping does not have a name
463 $activities[$activityclass] = array_merge($activities[$activityclass], $subtypes);
465 } else {
466 // This module has no subtypes
467 $activityclass = MOD_CLASS_ACTIVITY;
468 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
469 $activityclass = MOD_CLASS_RESOURCE;
470 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
471 // System modules cannot be added by user, do not add to dropdown
472 continue;
474 $link = $module->link->out(true, $urlparams);
475 $activities[$activityclass][$link] = $module->title;
479 $straddactivity = get_string('addactivity');
480 $straddresource = get_string('addresource');
481 $sectionname = get_section_name($course, $section);
482 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
483 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
485 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
487 if (!$vertical) {
488 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
491 if (!empty($activities[MOD_CLASS_RESOURCE])) {
492 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array(''=>$straddresource), "ressection$section");
493 $select->set_help_icon('resources');
494 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
495 $output .= $this->output->render($select);
498 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
499 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array(''=>$straddactivity), "section$section");
500 $select->set_help_icon('activities');
501 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
502 $output .= $this->output->render($select);
505 if (!$vertical) {
506 $output .= html_writer::end_tag('div');
509 $output .= html_writer::end_tag('div');
511 if (course_ajax_enabled($course) && $course->id == $this->page->course->id) {
512 // modchooser can be added only for the current course set on the page!
513 $straddeither = get_string('addresourceoractivity');
514 // The module chooser link
515 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
516 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
517 $icon = $this->output->pix_icon('t/add', '');
518 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
519 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
520 $modchooser.= html_writer::end_tag('div');
521 $modchooser.= html_writer::end_tag('div');
523 // Wrap the normal output in a noscript div
524 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
525 if ($usemodchooser) {
526 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
527 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
528 } else {
529 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
530 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
531 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
533 $output = $this->course_modchooser($modules, $course) . $modchooser . $output;
536 return $output;
540 * Renders html to display a course search form
542 * @param string $value default value to populate the search field
543 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
544 * @return string
546 function course_search_form($value = '', $format = 'plain') {
547 static $count = 0;
548 $formid = 'coursesearch';
549 if ((++$count) > 1) {
550 $formid .= $count;
553 switch ($format) {
554 case 'navbar' :
555 $formid = 'coursesearchnavbar';
556 $inputid = 'navsearchbox';
557 $inputsize = 20;
558 break;
559 case 'short' :
560 $inputid = 'shortsearchbox';
561 $inputsize = 12;
562 break;
563 default :
564 $inputid = 'coursesearchbox';
565 $inputsize = 30;
568 $strsearchcourses= get_string("searchcourses");
569 $searchurl = new moodle_url('/course/search.php');
571 $output = html_writer::start_tag('form', array('id' => $formid, 'action' => $searchurl, 'method' => 'get'));
572 $output .= html_writer::start_tag('fieldset', array('class' => 'coursesearchbox invisiblefieldset'));
573 $output .= html_writer::tag('label', $strsearchcourses.': ', array('for' => $inputid));
574 $output .= html_writer::empty_tag('input', array('type' => 'text', 'id' => $inputid,
575 'size' => $inputsize, 'name' => 'search', 'value' => s($value)));
576 $output .= html_writer::empty_tag('input', array('type' => 'submit',
577 'value' => get_string('go')));
578 $output .= html_writer::end_tag('fieldset');
579 $output .= html_writer::end_tag('form');
581 return $output;
585 * Renders html for completion box on course page
587 * If completion is disabled, returns empty string
588 * If completion is automatic, returns an icon of the current completion state
589 * If completion is manual, returns a form (with an icon inside) that allows user to
590 * toggle completion
592 * @param stdClass $course course object
593 * @param completion_info $completioninfo completion info for the course, it is recommended
594 * to fetch once for all modules in course/section for performance
595 * @param cm_info $mod module to show completion for
596 * @param array $displayoptions display options, not used in core
597 * @return string
599 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
600 global $CFG;
601 $output = '';
602 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
603 return $output;
605 if ($completioninfo === null) {
606 $completioninfo = new completion_info($course);
608 $completion = $completioninfo->is_enabled($mod);
609 if ($completion == COMPLETION_TRACKING_NONE) {
610 if ($this->page->user_is_editing()) {
611 $output .= html_writer::span('&nbsp;', 'filler');
613 return $output;
616 $completiondata = $completioninfo->get_data($mod, true);
617 $completionicon = '';
619 if ($this->page->user_is_editing()) {
620 switch ($completion) {
621 case COMPLETION_TRACKING_MANUAL :
622 $completionicon = 'manual-enabled'; break;
623 case COMPLETION_TRACKING_AUTOMATIC :
624 $completionicon = 'auto-enabled'; break;
626 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
627 switch($completiondata->completionstate) {
628 case COMPLETION_INCOMPLETE:
629 $completionicon = 'manual-n'; break;
630 case COMPLETION_COMPLETE:
631 $completionicon = 'manual-y'; break;
633 } else { // Automatic
634 switch($completiondata->completionstate) {
635 case COMPLETION_INCOMPLETE:
636 $completionicon = 'auto-n'; break;
637 case COMPLETION_COMPLETE:
638 $completionicon = 'auto-y'; break;
639 case COMPLETION_COMPLETE_PASS:
640 $completionicon = 'auto-pass'; break;
641 case COMPLETION_COMPLETE_FAIL:
642 $completionicon = 'auto-fail'; break;
645 if ($completionicon) {
646 $formattedname = $mod->get_formatted_name();
647 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
649 if ($this->page->user_is_editing()) {
650 // When editing, the icon is just an image.
651 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
652 array('title' => $imgalt, 'class' => 'iconsmall'));
653 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
654 array('class' => 'autocompletion'));
655 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
656 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
657 $newstate =
658 $completiondata->completionstate == COMPLETION_COMPLETE
659 ? COMPLETION_INCOMPLETE
660 : COMPLETION_COMPLETE;
661 // In manual mode the icon is a toggle form...
663 // If this completion state is used by the
664 // conditional activities system, we need to turn
665 // off the JS.
666 $extraclass = '';
667 if (!empty($CFG->enableavailability) &&
668 condition_info::completion_value_used_as_condition($course, $mod)) {
669 $extraclass = ' preventjs';
671 $output .= html_writer::start_tag('form', array('method' => 'post',
672 'action' => new moodle_url('/course/togglecompletion.php'),
673 'class' => 'togglecompletion'. $extraclass));
674 $output .= html_writer::start_tag('div');
675 $output .= html_writer::empty_tag('input', array(
676 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
677 $output .= html_writer::empty_tag('input', array(
678 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
679 $output .= html_writer::empty_tag('input', array(
680 'type' => 'hidden', 'name' => 'modulename', 'value' => $mod->name));
681 $output .= html_writer::empty_tag('input', array(
682 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
683 $output .= html_writer::empty_tag('input', array(
684 'type' => 'image',
685 'src' => $this->output->pix_url('i/completion-'.$completionicon),
686 'alt' => $imgalt, 'title' => $imgtitle,
687 'aria-live' => 'polite'));
688 $output .= html_writer::end_tag('div');
689 $output .= html_writer::end_tag('form');
690 } else {
691 // In auto mode, the icon is just an image.
692 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
693 array('title' => $imgalt));
694 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
695 array('class' => 'autocompletion'));
698 return $output;
702 * Checks if course module has any conditions that may make it unavailable for
703 * all or some of the students
705 * This function is internal and is only used to create CSS classes for the module name/text
707 * @param cm_info $mod
708 * @return bool
710 protected function is_cm_conditionally_hidden(cm_info $mod) {
711 global $CFG;
712 $conditionalhidden = false;
713 if (!empty($CFG->enableavailability)) {
714 $conditionalhidden = $mod->availablefrom > time() ||
715 ($mod->availableuntil && $mod->availableuntil < time()) ||
716 count($mod->conditionsgrade) > 0 ||
717 count($mod->conditionscompletion) > 0 ||
718 count($mod->conditionsfield);
720 return $conditionalhidden;
724 * Renders html to display a name with the link to the course module on a course page
726 * If module is unavailable for user but still needs to be displayed
727 * in the list, just the name is returned without a link
729 * Note, that for course modules that never have separate pages (i.e. labels)
730 * this function return an empty string
732 * @param cm_info $mod
733 * @param array $displayoptions
734 * @return string
736 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
737 global $CFG;
738 $output = '';
739 if (!$mod->uservisible &&
740 (empty($mod->showavailability) || empty($mod->availableinfo))) {
741 // nothing to be displayed to the user
742 return $output;
744 $url = $mod->url;
745 if (!$url) {
746 return $output;
749 //Accessibility: for files get description via icon, this is very ugly hack!
750 $instancename = $mod->get_formatted_name();
751 $altname = $mod->modfullname;
752 // Avoid unnecessary duplication: if e.g. a forum name already
753 // includes the word forum (or Forum, etc) then it is unhelpful
754 // to include that in the accessible description that is added.
755 if (false !== strpos(core_text::strtolower($instancename),
756 core_text::strtolower($altname))) {
757 $altname = '';
759 // File type after name, for alphabetic lists (screen reader).
760 if ($altname) {
761 $altname = get_accesshide(' '.$altname);
764 // For items which are hidden but available to current user
765 // ($mod->uservisible), we show those as dimmed only if the user has
766 // viewhiddenactivities, so that teachers see 'items which might not
767 // be available to some students' dimmed but students do not see 'item
768 // which is actually available to current student' dimmed.
769 $linkclasses = '';
770 $accesstext = '';
771 $textclasses = '';
772 if ($mod->uservisible) {
773 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
774 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
775 has_capability('moodle/course:viewhiddenactivities',
776 context_course::instance($mod->course));
777 if ($accessiblebutdim) {
778 $linkclasses .= ' dimmed';
779 $textclasses .= ' dimmed_text';
780 if ($conditionalhidden) {
781 $linkclasses .= ' conditionalhidden';
782 $textclasses .= ' conditionalhidden';
784 // Show accessibility note only if user can access the module himself.
785 $accesstext = get_accesshide(get_string('hiddenfromstudents').':'. $mod->modfullname);
787 } else {
788 $linkclasses .= ' dimmed';
789 $textclasses .= ' dimmed_text';
792 // Get on-click attribute value if specified and decode the onclick - it
793 // has already been encoded for display (puke).
794 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
796 $groupinglabel = '';
797 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($mod->course))) {
798 $groupings = groups_get_all_groupings($mod->course);
799 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$mod->groupingid]->name).')',
800 array('class' => 'groupinglabel '.$textclasses));
803 // Display link itself.
804 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
805 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) . $accesstext .
806 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
807 if ($mod->uservisible) {
808 $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick)) .
809 $groupinglabel;
810 } else {
811 // We may be displaying this just in order to show information
812 // about visibility, without the actual link ($mod->uservisible)
813 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses)) .
814 $groupinglabel;
816 return $output;
820 * Renders html to display the module content on the course page (i.e. text of the labels)
822 * @param cm_info $mod
823 * @param array $displayoptions
824 * @return string
826 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
827 $output = '';
828 if (!$mod->uservisible &&
829 (empty($mod->showavailability) || empty($mod->availableinfo))) {
830 // nothing to be displayed to the user
831 return $output;
833 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
834 $accesstext = '';
835 $textclasses = '';
836 if ($mod->uservisible) {
837 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
838 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
839 has_capability('moodle/course:viewhiddenactivities',
840 context_course::instance($mod->course));
841 if ($accessiblebutdim) {
842 $textclasses .= ' dimmed_text';
843 if ($conditionalhidden) {
844 $textclasses .= ' conditionalhidden';
846 // Show accessibility note only if user can access the module himself.
847 $accesstext = get_accesshide(get_string('hiddenfromstudents').':'. $mod->modfullname);
849 } else {
850 $textclasses .= ' dimmed_text';
852 if ($mod->url) {
853 if ($content) {
854 // If specified, display extra content after link.
855 $output = html_writer::tag('div', $content, array('class' =>
856 trim('contentafterlink ' . $textclasses)));
858 } else {
859 // No link, so display only content.
860 $output = html_writer::tag('div', $accesstext . $content,
861 array('class' => 'contentwithoutlink ' . $textclasses));
863 return $output;
867 * Renders HTML to show course module availability information (for someone who isn't allowed
868 * to see the activity itself, or for staff)
870 * @param cm_info $mod
871 * @param array $displayoptions
872 * @return string
874 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
875 global $CFG;
876 if (!$mod->uservisible) {
877 // this is a student who is not allowed to see the module but might be allowed
878 // to see availability info (i.e. "Available from ...")
879 if (!empty($mod->showavailability) && !empty($mod->availableinfo)) {
880 $output = html_writer::tag('div', $mod->availableinfo, array('class' => 'availabilityinfo'));
882 return $output;
884 // this is a teacher who is allowed to see module but still should see the
885 // information that module is not available to all/some students
886 $modcontext = context_module::instance($mod->id);
887 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
888 if ($canviewhidden && !empty($CFG->enableavailability)) {
889 // Don't add availability information if user is not editing and activity is hidden.
890 if ($mod->visible || $this->page->user_is_editing()) {
891 $hidinfoclass = '';
892 if (!$mod->visible) {
893 $hidinfoclass = 'hide';
895 $ci = new condition_info($mod);
896 $fullinfo = $ci->get_full_information();
897 if($fullinfo) {
898 return '<div class="availabilityinfo '.$hidinfoclass.'">'.get_string($mod->showavailability
899 ? 'userrestriction_visible'
900 : 'userrestriction_hidden','condition',
901 $fullinfo).'</div>';
905 return '';
909 * Renders HTML to display one course module for display within a section.
911 * This function calls:
912 * {@link core_course_renderer::course_section_cm()}
914 * @param stdClass $course
915 * @param completion_info $completioninfo
916 * @param cm_info $mod
917 * @param int|null $sectionreturn
918 * @param array $displayoptions
919 * @return String
921 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
922 $output = '';
923 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
924 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
925 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
927 return $output;
931 * Renders HTML to display one course module in a course section
933 * This includes link, content, availability, completion info and additional information
934 * that module type wants to display (i.e. number of unread forum posts)
936 * This function calls:
937 * {@link core_course_renderer::course_section_cm_name()}
938 * {@link core_course_renderer::course_section_cm_text()}
939 * {@link core_course_renderer::course_section_cm_availability()}
940 * {@link core_course_renderer::course_section_cm_completion()}
941 * {@link course_get_cm_edit_actions()}
942 * {@link core_course_renderer::course_section_cm_edit_actions()}
944 * @param stdClass $course
945 * @param completion_info $completioninfo
946 * @param cm_info $mod
947 * @param int|null $sectionreturn
948 * @param array $displayoptions
949 * @return string
951 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
952 $output = '';
953 // We return empty string (because course module will not be displayed at all)
954 // if:
955 // 1) The activity is not visible to users
956 // and
957 // 2a) The 'showavailability' option is not set (if that is set,
958 // we need to display the activity so we can show
959 // availability info)
960 // or
961 // 2b) The 'availableinfo' is empty, i.e. the activity was
962 // hidden in a way that leaves no info, such as using the
963 // eye icon.
964 if (!$mod->uservisible &&
965 (empty($mod->showavailability) || empty($mod->availableinfo))) {
966 return $output;
969 $indentclasses = 'mod-indent';
970 if (!empty($mod->indent)) {
971 $indentclasses .= ' mod-indent-'.$mod->indent;
972 if ($mod->indent > 15) {
973 $indentclasses .= ' mod-indent-huge';
977 $output .= html_writer::start_tag('div');
979 if ($this->page->user_is_editing()) {
980 $output .= course_get_cm_move($mod, $sectionreturn);
983 $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer'));
985 // This div is used to indent the content.
986 $output .= html_writer::div('', $indentclasses);
988 // Start a wrapper for the actual content to keep the indentation consistent
989 $output .= html_writer::start_tag('div');
991 // Display the link to the module (or do nothing if module has no url)
992 $cmname = $this->course_section_cm_name($mod, $displayoptions);
994 if (!empty($cmname)) {
995 // Start the div for the activity title, excluding the edit icons.
996 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
997 $output .= $cmname;
1000 if ($this->page->user_is_editing()) {
1001 $output .= ' ' . course_get_cm_rename_action($mod, $sectionreturn);
1004 // Module can put text after the link (e.g. forum unread)
1005 $output .= $mod->afterlink;
1007 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
1008 $output .= html_writer::end_tag('div'); // .activityinstance
1011 // If there is content but NO link (eg label), then display the
1012 // content here (BEFORE any icons). In this case cons must be
1013 // displayed after the content so that it makes more sense visually
1014 // and for accessibility reasons, e.g. if you have a one-line label
1015 // it should work similarly (at least in terms of ordering) to an
1016 // activity.
1017 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
1018 $url = $mod->url;
1019 if (empty($url)) {
1020 $output .= $contentpart;
1023 $modicons = '';
1024 if ($this->page->user_is_editing()) {
1025 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
1026 $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
1027 $modicons .= $mod->afterediticons;
1030 $modicons .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
1032 if (!empty($modicons)) {
1033 $output .= html_writer::span($modicons, 'actions');
1036 // If there is content AND a link, then display the content here
1037 // (AFTER any icons). Otherwise it was displayed before
1038 if (!empty($url)) {
1039 $output .= $contentpart;
1042 // show availability info (if module is not available)
1043 $output .= $this->course_section_cm_availability($mod, $displayoptions);
1045 $output .= html_writer::end_tag('div'); // $indentclasses
1047 // End of indentation div.
1048 $output .= html_writer::end_tag('div');
1050 $output .= html_writer::end_tag('div');
1051 return $output;
1055 * Renders HTML to display a list of course modules in a course section
1056 * Also displays "move here" controls in Javascript-disabled mode
1058 * This function calls {@link core_course_renderer::course_section_cm()}
1060 * @param stdClass $course course object
1061 * @param int|stdClass|section_info $section relative section number or section object
1062 * @param int $sectionreturn section number to return to
1063 * @param int $displayoptions
1064 * @return void
1066 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
1067 global $USER;
1069 $output = '';
1070 $modinfo = get_fast_modinfo($course);
1071 if (is_object($section)) {
1072 $section = $modinfo->get_section_info($section->section);
1073 } else {
1074 $section = $modinfo->get_section_info($section);
1076 $completioninfo = new completion_info($course);
1078 // check if we are currently in the process of moving a module with JavaScript disabled
1079 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
1080 if ($ismoving) {
1081 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
1082 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1085 // Get the list of modules visible to user (excluding the module being moved if there is one)
1086 $moduleshtml = array();
1087 if (!empty($modinfo->sections[$section->section])) {
1088 foreach ($modinfo->sections[$section->section] as $modnumber) {
1089 $mod = $modinfo->cms[$modnumber];
1091 if ($ismoving and $mod->id == $USER->activitycopy) {
1092 // do not display moving mod
1093 continue;
1096 if ($modulehtml = $this->course_section_cm_list_item($course,
1097 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
1098 $moduleshtml[$modnumber] = $modulehtml;
1103 $sectionoutput = '';
1104 if (!empty($moduleshtml) || $ismoving) {
1105 foreach ($moduleshtml as $modnumber => $modulehtml) {
1106 if ($ismoving) {
1107 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
1108 $sectionoutput .= html_writer::tag('li', html_writer::link($movingurl, $this->output->render($movingpix)),
1109 array('class' => 'movehere', 'title' => $strmovefull));
1112 $sectionoutput .= $modulehtml;
1115 if ($ismoving) {
1116 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1117 $sectionoutput .= html_writer::tag('li', html_writer::link($movingurl, $this->output->render($movingpix)),
1118 array('class' => 'movehere', 'title' => $strmovefull));
1122 // Always output the section module list.
1123 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1125 return $output;
1129 * Displays a custom list of courses with paging bar if necessary
1131 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1132 * appears under the list.
1134 * If both $paginationurl and $totalcount are specified, and $totalcount is
1135 * bigger than count($courses), a paging bar is displayed above and under the
1136 * courses list.
1138 * @param array $courses array of course records (or instances of course_in_list) to show on this page
1139 * @param bool $showcategoryname whether to add category name to the course description
1140 * @param string $additionalclasses additional CSS classes to add to the div.courses
1141 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1142 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1143 * @param int $page current page number (defaults to 0 referring to the first page)
1144 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1145 * @return string
1147 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1148 global $CFG;
1149 // create instance of coursecat_helper to pass display options to function rendering courses list
1150 $chelper = new coursecat_helper();
1151 if ($showcategoryname) {
1152 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1153 } else {
1154 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1156 if ($totalcount !== null && $paginationurl !== null) {
1157 // add options to display pagination
1158 if ($perpage === null) {
1159 $perpage = $CFG->coursesperpage;
1161 $chelper->set_courses_display_options(array(
1162 'limit' => $perpage,
1163 'offset' => ((int)$page) * $perpage,
1164 'paginationurl' => $paginationurl,
1166 } else if ($paginationurl !== null) {
1167 // add options to display 'View more' link
1168 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1169 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1171 $chelper->set_attributes(array('class' => $additionalclasses));
1172 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1173 return $content;
1177 * Displays one course in the list of courses.
1179 * This is an internal function, to display an information about just one course
1180 * please use {@link core_course_renderer::course_info_box()}
1182 * @param coursecat_helper $chelper various display options
1183 * @param course_in_list|stdClass $course
1184 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1185 * depend on the course position in list - first/last/even/odd)
1186 * @return string
1188 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1189 global $CFG;
1190 if (!isset($this->strings->summary)) {
1191 $this->strings->summary = get_string('summary');
1193 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1194 return '';
1196 if ($course instanceof stdClass) {
1197 require_once($CFG->libdir. '/coursecatlib.php');
1198 $course = new course_in_list($course);
1200 $content = '';
1201 $classes = trim('coursebox clearfix '. $additionalclasses);
1202 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1203 $nametag = 'h3';
1204 } else {
1205 $classes .= ' collapsed';
1206 $nametag = 'div';
1209 // .coursebox
1210 $content .= html_writer::start_tag('div', array(
1211 'class' => $classes,
1212 'data-courseid' => $course->id,
1213 'data-type' => self::COURSECAT_TYPE_COURSE,
1216 $content .= html_writer::start_tag('div', array('class' => 'info'));
1218 // course name
1219 $coursename = $chelper->get_course_formatted_name($course);
1220 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', array('id' => $course->id)),
1221 $coursename, array('class' => $course->visible ? '' : 'dimmed'));
1222 $content .= html_writer::tag($nametag, $coursenamelink, array('class' => 'coursename'));
1223 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1224 $content .= html_writer::start_tag('div', array('class' => 'moreinfo'));
1225 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1226 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()) {
1227 $url = new moodle_url('/course/info.php', array('id' => $course->id));
1228 $image = html_writer::empty_tag('img', array('src' => $this->output->pix_url('i/info'),
1229 'alt' => $this->strings->summary));
1230 $content .= html_writer::link($url, $image, array('title' => $this->strings->summary));
1231 // Make sure JS file to expand course content is included.
1232 $this->coursecat_include_js();
1235 $content .= html_writer::end_tag('div'); // .moreinfo
1237 // print enrolmenticons
1238 if ($icons = enrol_get_course_info_icons($course)) {
1239 $content .= html_writer::start_tag('div', array('class' => 'enrolmenticons'));
1240 foreach ($icons as $pix_icon) {
1241 $content .= $this->render($pix_icon);
1243 $content .= html_writer::end_tag('div'); // .enrolmenticons
1246 $content .= html_writer::end_tag('div'); // .info
1248 $content .= html_writer::start_tag('div', array('class' => 'content'));
1249 $content .= $this->coursecat_coursebox_content($chelper, $course);
1250 $content .= html_writer::end_tag('div'); // .content
1252 $content .= html_writer::end_tag('div'); // .coursebox
1253 return $content;
1257 * Returns HTML to display course content (summary, course contacts and optionally category name)
1259 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1261 * @param coursecat_helper $chelper various display options
1262 * @param stdClass|course_in_list $course
1263 * @return string
1265 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1266 global $CFG;
1267 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1268 return '';
1270 if ($course instanceof stdClass) {
1271 require_once($CFG->libdir. '/coursecatlib.php');
1272 $course = new course_in_list($course);
1274 $content = '';
1276 // display course summary
1277 if ($course->has_summary()) {
1278 $content .= html_writer::start_tag('div', array('class' => 'summary'));
1279 $content .= $chelper->get_course_formatted_summary($course,
1280 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1281 $content .= html_writer::end_tag('div'); // .summary
1284 // display course overview files
1285 $contentimages = $contentfiles = '';
1286 foreach ($course->get_course_overviewfiles() as $file) {
1287 $isimage = $file->is_valid_image();
1288 $url = file_encode_url("$CFG->wwwroot/pluginfile.php",
1289 '/'. $file->get_contextid(). '/'. $file->get_component(). '/'.
1290 $file->get_filearea(). $file->get_filepath(). $file->get_filename(), !$isimage);
1291 if ($isimage) {
1292 $contentimages .= html_writer::tag('div',
1293 html_writer::empty_tag('img', array('src' => $url)),
1294 array('class' => 'courseimage'));
1295 } else {
1296 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1297 $filename = html_writer::tag('span', $image, array('class' => 'fp-icon')).
1298 html_writer::tag('span', $file->get_filename(), array('class' => 'fp-filename'));
1299 $contentfiles .= html_writer::tag('span',
1300 html_writer::link($url, $filename),
1301 array('class' => 'coursefile fp-filename-icon'));
1304 $content .= $contentimages. $contentfiles;
1306 // display course contacts. See course_in_list::get_course_contacts()
1307 if ($course->has_course_contacts()) {
1308 $content .= html_writer::start_tag('ul', array('class' => 'teachers'));
1309 foreach ($course->get_course_contacts() as $userid => $coursecontact) {
1310 $name = $coursecontact['rolename'].': '.
1311 html_writer::link(new moodle_url('/user/view.php',
1312 array('id' => $userid, 'course' => SITEID)),
1313 $coursecontact['username']);
1314 $content .= html_writer::tag('li', $name);
1316 $content .= html_writer::end_tag('ul'); // .teachers
1319 // display course category if necessary (for example in search results)
1320 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1321 require_once($CFG->libdir. '/coursecatlib.php');
1322 if ($cat = coursecat::get($course->category, IGNORE_MISSING)) {
1323 $content .= html_writer::start_tag('div', array('class' => 'coursecat'));
1324 $content .= get_string('category').': '.
1325 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1326 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1327 $content .= html_writer::end_tag('div'); // .coursecat
1331 return $content;
1335 * Renders the list of courses
1337 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1338 * method from outside of the class
1340 * If list of courses is specified in $courses; the argument $chelper is only used
1341 * to retrieve display options and attributes, only methods get_show_courses(),
1342 * get_courses_display_option() and get_and_erase_attributes() are called.
1344 * @param coursecat_helper $chelper various display options
1345 * @param array $courses the list of courses to display
1346 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1347 * defaulted to count($courses)
1348 * @return string
1350 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1351 global $CFG;
1352 if ($totalcount === null) {
1353 $totalcount = count($courses);
1355 if (!$totalcount) {
1356 // Courses count is cached during courses retrieval.
1357 return '';
1360 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1361 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1362 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1363 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1364 } else {
1365 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1369 // prepare content of paging bar if it is needed
1370 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1371 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1372 if ($totalcount > count($courses)) {
1373 // there are more results that can fit on one page
1374 if ($paginationurl) {
1375 // the option paginationurl was specified, display pagingbar
1376 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1377 $page = $chelper->get_courses_display_option('offset') / $perpage;
1378 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1379 $paginationurl->out(false, array('perpage' => $perpage)));
1380 if ($paginationallowall) {
1381 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1382 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1384 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1385 // the option for 'View more' link was specified, display more link
1386 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1387 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1388 array('class' => 'paging paging-morelink'));
1390 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1391 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1392 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1393 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1396 // display list of courses
1397 $attributes = $chelper->get_and_erase_attributes('courses');
1398 $content = html_writer::start_tag('div', $attributes);
1400 if (!empty($pagingbar)) {
1401 $content .= $pagingbar;
1404 $coursecount = 0;
1405 foreach ($courses as $course) {
1406 $coursecount ++;
1407 $classes = ($coursecount%2) ? 'odd' : 'even';
1408 if ($coursecount == 1) {
1409 $classes .= ' first';
1411 if ($coursecount >= count($courses)) {
1412 $classes .= ' last';
1414 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1417 if (!empty($pagingbar)) {
1418 $content .= $pagingbar;
1420 if (!empty($morelink)) {
1421 $content .= $morelink;
1424 $content .= html_writer::end_tag('div'); // .courses
1425 return $content;
1429 * Renders the list of subcategories in a category
1431 * @param coursecat_helper $chelper various display options
1432 * @param coursecat $coursecat
1433 * @param int $depth depth of the category in the current tree
1434 * @return string
1436 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1437 global $CFG;
1438 $subcategories = array();
1439 if (!$chelper->get_categories_display_option('nodisplay')) {
1440 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1442 $totalcount = $coursecat->get_children_count();
1443 if (!$totalcount) {
1444 // Note that we call get_child_categories_count() AFTER get_child_categories() to avoid extra DB requests.
1445 // Categories count is cached during children categories retrieval.
1446 return '';
1449 // prepare content of paging bar or more link if it is needed
1450 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1451 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1452 if ($totalcount > count($subcategories)) {
1453 if ($paginationurl) {
1454 // the option 'paginationurl was specified, display pagingbar
1455 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1456 $page = $chelper->get_categories_display_option('offset') / $perpage;
1457 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1458 $paginationurl->out(false, array('perpage' => $perpage)));
1459 if ($paginationallowall) {
1460 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1461 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1463 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1464 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1465 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1466 $viewmoreurl->param('categoryid', $coursecat->id);
1468 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1469 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1470 array('class' => 'paging paging-morelink'));
1472 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1473 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1474 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1475 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1478 // display list of subcategories
1479 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1481 if (!empty($pagingbar)) {
1482 $content .= $pagingbar;
1485 foreach ($subcategories as $subcategory) {
1486 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1489 if (!empty($pagingbar)) {
1490 $content .= $pagingbar;
1492 if (!empty($morelink)) {
1493 $content .= $morelink;
1496 $content .= html_writer::end_tag('div');
1497 return $content;
1501 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1503 protected function coursecat_include_js() {
1504 global $CFG;
1505 static $jsloaded = false;
1506 if (!$jsloaded && $CFG->enableajax) {
1507 // We must only load this module once.
1508 $this->page->requires->yui_module('moodle-course-categoryexpander',
1509 'Y.Moodle.course.categoryexpander.init');
1510 $jsloaded = true;
1515 * Returns HTML to display the subcategories and courses in the given category
1517 * This method is re-used by AJAX to expand content of not loaded category
1519 * @param coursecat_helper $chelper various display options
1520 * @param coursecat $coursecat
1521 * @param int $depth depth of the category in the current tree
1522 * @return string
1524 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1525 $content = '';
1526 // Subcategories
1527 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1529 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1530 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1531 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1532 if ($showcoursesauto && $depth) {
1533 // this is definitely collapsed mode
1534 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1537 // Courses
1538 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1539 $courses = array();
1540 if (!$chelper->get_courses_display_option('nodisplay')) {
1541 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1543 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1544 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1545 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1546 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1549 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1552 if ($showcoursesauto) {
1553 // restore the show_courses back to AUTO
1554 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1557 return $content;
1561 * Returns HTML to display a course category as a part of a tree
1563 * This is an internal function, to display a particular category and all its contents
1564 * use {@link core_course_renderer::course_category()}
1566 * @param coursecat_helper $chelper various display options
1567 * @param coursecat $coursecat
1568 * @param int $depth depth of this category in the current tree
1569 * @return string
1571 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1572 // open category tag
1573 $classes = array('category');
1574 if (empty($coursecat->visible)) {
1575 $classes[] = 'dimmed_category';
1577 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1578 // do not load content
1579 $categorycontent = '';
1580 $classes[] = 'notloaded';
1581 if ($coursecat->get_children_count() ||
1582 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1583 $classes[] = 'with_children';
1584 $classes[] = 'collapsed';
1586 // Make sure JS file to expand category content is included.
1587 $this->coursecat_include_js();
1588 } else {
1589 // load category content
1590 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1591 $classes[] = 'loaded';
1592 if (!empty($categorycontent)) {
1593 $classes[] = 'with_children';
1596 $content = html_writer::start_tag('div', array(
1597 'class' => join(' ', $classes),
1598 'data-categoryid' => $coursecat->id,
1599 'data-depth' => $depth,
1600 'data-showcourses' => $chelper->get_show_courses(),
1601 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1604 // category name
1605 $categoryname = $coursecat->get_formatted_name();
1606 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1607 array('categoryid' => $coursecat->id)),
1608 $categoryname);
1609 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1610 && ($coursescount = $coursecat->get_courses_count())) {
1611 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1612 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1614 $content .= html_writer::start_tag('div', array('class' => 'info'));
1616 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname'));
1617 $content .= html_writer::end_tag('div'); // .info
1619 // add category content to the output
1620 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1622 $content .= html_writer::end_tag('div'); // .category
1624 // Return the course category tree HTML
1625 return $content;
1629 * Returns HTML to display a tree of subcategories and courses in the given category
1631 * @param coursecat_helper $chelper various display options
1632 * @param coursecat $coursecat top category (this category's name and description will NOT be added to the tree)
1633 * @return string
1635 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1636 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1637 if (empty($categorycontent)) {
1638 return '';
1641 // Start content generation
1642 $content = '';
1643 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1644 $content .= html_writer::start_tag('div', $attributes);
1646 if ($coursecat->get_children_count()) {
1647 $classes = array(
1648 'collapseexpand',
1649 'collapse-all',
1651 if ($chelper->get_subcat_depth() == 1) {
1652 $classes[] = 'disabled';
1654 // Only show the collapse/expand if there are children to expand.
1655 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1656 $content .= html_writer::link('#', get_string('collapseall'),
1657 array('class' => implode(' ', $classes)));
1658 $content .= html_writer::end_tag('div');
1659 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1662 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1664 $content .= html_writer::end_tag('div'); // .course_category_tree
1666 return $content;
1670 * Renders HTML to display particular course category - list of it's subcategories and courses
1672 * Invoked from /course/index.php
1674 * @param int|stdClass|coursecat $category
1676 public function course_category($category) {
1677 global $CFG;
1678 require_once($CFG->libdir. '/coursecatlib.php');
1679 $coursecat = coursecat::get(is_object($category) ? $category->id : $category);
1680 $site = get_site();
1681 $output = '';
1683 $this->page->set_button($this->course_search_form('', 'navbar'));
1684 if (!$coursecat->id) {
1685 if (can_edit_in_category()) {
1686 // add 'Manage' button instead of course search form
1687 $managebutton = $this->single_button(new moodle_url('/course/management.php'), get_string('managecourses'), 'get');
1688 $this->page->set_button($managebutton);
1690 if (coursecat::count_all() == 1) {
1691 // There exists only one category in the system, do not display link to it
1692 $coursecat = coursecat::get_default();
1693 $strfulllistofcourses = get_string('fulllistofcourses');
1694 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1695 } else {
1696 $strcategories = get_string('categories');
1697 $this->page->set_title("$site->shortname: $strcategories");
1699 } else {
1700 $this->page->set_title("$site->shortname: ". $coursecat->get_formatted_name());
1702 // Print the category selector
1703 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1704 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1705 coursecat::make_categories_list(), $coursecat->id, null, 'switchcategory');
1706 $select->set_label(get_string('categories').':');
1707 $output .= $this->render($select);
1708 $output .= html_writer::end_tag('div'); // .categorypicker
1711 // Print current category description
1712 $chelper = new coursecat_helper();
1713 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1714 $output .= $this->box($description, array('class' => 'generalbox info'));
1717 // Prepare parameters for courses and categories lists in the tree
1718 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1719 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1721 $coursedisplayoptions = array();
1722 $catdisplayoptions = array();
1723 $browse = optional_param('browse', null, PARAM_ALPHA);
1724 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1725 $page = optional_param('page', 0, PARAM_INT);
1726 $baseurl = new moodle_url('/course/index.php');
1727 if ($coursecat->id) {
1728 $baseurl->param('categoryid', $coursecat->id);
1730 if ($perpage != $CFG->coursesperpage) {
1731 $baseurl->param('perpage', $perpage);
1733 $coursedisplayoptions['limit'] = $perpage;
1734 $catdisplayoptions['limit'] = $perpage;
1735 if ($browse === 'courses' || !$coursecat->has_children()) {
1736 $coursedisplayoptions['offset'] = $page * $perpage;
1737 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1738 $catdisplayoptions['nodisplay'] = true;
1739 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1740 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1741 } else if ($browse === 'categories' || !$coursecat->has_courses()) {
1742 $coursedisplayoptions['nodisplay'] = true;
1743 $catdisplayoptions['offset'] = $page * $perpage;
1744 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1745 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1746 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1747 } else {
1748 // we have a category that has both subcategories and courses, display pagination separately
1749 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1750 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1752 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1754 // Display course category tree
1755 $output .= $this->coursecat_tree($chelper, $coursecat);
1757 // Add course search form (if we are inside category it was already added to the navbar)
1758 if (!$coursecat->id) {
1759 $output .= $this->course_search_form();
1762 // Add action buttons
1763 $output .= $this->container_start('buttons');
1764 $context = get_category_or_system_context($coursecat->id);
1765 if (has_capability('moodle/course:create', $context)) {
1766 // Print link to create a new course, for the 1st available category.
1767 if ($coursecat->id) {
1768 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1769 } else {
1770 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1772 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1774 ob_start();
1775 if (coursecat::count_all() == 1) {
1776 print_course_request_buttons(context_system::instance());
1777 } else {
1778 print_course_request_buttons($context);
1780 $output .= ob_get_contents();
1781 ob_end_clean();
1782 $output .= $this->container_end();
1784 return $output;
1788 * Serves requests to /course/category.ajax.php
1790 * In this renderer implementation it may expand the category content or
1791 * course content.
1793 * @return string
1794 * @throws coding_exception
1796 public function coursecat_ajax() {
1797 global $DB, $CFG;
1798 require_once($CFG->libdir. '/coursecatlib.php');
1800 $type = required_param('type', PARAM_INT);
1802 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1803 // This is a request for a category list of some kind.
1804 $categoryid = required_param('categoryid', PARAM_INT);
1805 $showcourses = required_param('showcourses', PARAM_INT);
1806 $depth = required_param('depth', PARAM_INT);
1808 $category = coursecat::get($categoryid);
1810 $chelper = new coursecat_helper();
1811 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1812 $coursedisplayoptions = array(
1813 'limit' => $CFG->coursesperpage,
1814 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1816 $catdisplayoptions = array(
1817 'limit' => $CFG->coursesperpage,
1818 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1820 $chelper->set_show_courses($showcourses)->
1821 set_courses_display_options($coursedisplayoptions)->
1822 set_categories_display_options($catdisplayoptions);
1824 return $this->coursecat_category_content($chelper, $category, $depth);
1825 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1826 // This is a request for the course information.
1827 $courseid = required_param('courseid', PARAM_INT);
1829 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1831 $chelper = new coursecat_helper();
1832 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1833 return $this->coursecat_coursebox_content($chelper, $course);
1834 } else {
1835 throw new coding_exception('Invalid request type');
1840 * Renders html to display search result page
1842 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1843 * @return string
1845 public function search_courses($searchcriteria) {
1846 global $CFG;
1847 $content = '';
1848 if (!empty($searchcriteria)) {
1849 // print search results
1850 require_once($CFG->libdir. '/coursecatlib.php');
1852 $displayoptions = array('sort' => array('displayname' => 1));
1853 // take the current page and number of results per page from query
1854 $perpage = optional_param('perpage', 0, PARAM_RAW);
1855 if ($perpage !== 'all') {
1856 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1857 $page = optional_param('page', 0, PARAM_INT);
1858 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1860 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1861 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1862 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1864 $class = 'course-search-result';
1865 foreach ($searchcriteria as $key => $value) {
1866 if (!empty($value)) {
1867 $class .= ' course-search-result-'. $key;
1870 $chelper = new coursecat_helper();
1871 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1872 set_courses_display_options($displayoptions)->
1873 set_search_criteria($searchcriteria)->
1874 set_attributes(array('class' => $class));
1876 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1877 $totalcount = coursecat::search_courses_count($searchcriteria);
1878 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1880 if (!$totalcount) {
1881 if (!empty($searchcriteria['search'])) {
1882 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1883 } else {
1884 $content .= $this->heading(get_string('novalidcourses'));
1886 } else {
1887 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1888 $content .= $courseslist;
1891 if (!empty($searchcriteria['search'])) {
1892 // print search form only if there was a search by search string, otherwise it is confusing
1893 $content .= $this->box_start('generalbox mdl-align');
1894 $content .= $this->course_search_form($searchcriteria['search']);
1895 $content .= $this->box_end();
1897 } else {
1898 // just print search form
1899 $content .= $this->box_start('generalbox mdl-align');
1900 $content .= $this->course_search_form();
1901 $content .= html_writer::tag('div', get_string("searchhelp"), array('class' => 'searchhelp'));
1902 $content .= $this->box_end();
1904 return $content;
1908 * Renders html to print list of courses tagged with particular tag
1910 * @param int $tagid id of the tag
1911 * @return string empty string if no courses are marked with this tag or rendered list of courses
1913 public function tagged_courses($tagid) {
1914 global $CFG;
1915 require_once($CFG->libdir. '/coursecatlib.php');
1916 $displayoptions = array('limit' => $CFG->coursesperpage);
1917 $displayoptions['viewmoreurl'] = new moodle_url('/course/search.php',
1918 array('tagid' => $tagid, 'page' => 1, 'perpage' => $CFG->coursesperpage));
1919 $displayoptions['viewmoretext'] = new lang_string('findmorecourses');
1920 $chelper = new coursecat_helper();
1921 $searchcriteria = array('tagid' => $tagid);
1922 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1923 set_search_criteria(array('tagid' => $tagid))->
1924 set_courses_display_options($displayoptions)->
1925 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1926 // (we set the same css class as in search results by tagid)
1927 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1928 $totalcount = coursecat::search_courses_count($searchcriteria);
1929 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1930 if ($totalcount) {
1931 require_once $CFG->dirroot.'/tag/lib.php';
1932 $heading = get_string('courses') . ' ' . get_string('taggedwith', 'tag', tag_get_name($tagid)) .': '. $totalcount;
1933 return $this->heading($heading, 3). $content;
1935 return '';
1939 * Returns HTML to display one remote course
1941 * @param stdClass $course remote course information, contains properties:
1942 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1943 * @return string
1945 protected function frontpage_remote_course(stdClass $course) {
1946 $url = new moodle_url('/auth/mnet/jump.php', array(
1947 'hostid' => $course->hostid,
1948 'wantsurl' => '/course/view.php?id='. $course->remoteid
1951 $output = '';
1952 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1953 $output .= html_writer::start_tag('div', array('class' => 'info'));
1954 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1955 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1956 $output .= html_writer::end_tag('h3'); // .name
1957 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1958 $output .= html_writer::end_tag('div'); // .info
1959 $output .= html_writer::start_tag('div', array('class' => 'content'));
1960 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1961 $options = new stdClass();
1962 $options->noclean = true;
1963 $options->para = false;
1964 $options->overflowdiv = true;
1965 $output .= format_text($course->summary, $course->summaryformat, $options);
1966 $output .= html_writer::end_tag('div'); // .summary
1967 $addinfo = format_string($course->hostname) . ' : '
1968 . format_string($course->cat_name) . ' : '
1969 . format_string($course->shortname);
1970 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1971 $output .= html_writer::end_tag('div'); // .content
1972 $output .= html_writer::end_tag('div'); // .coursebox
1973 return $output;
1977 * Returns HTML to display one remote host
1979 * @param array $host host information, contains properties: name, url, count
1980 * @return string
1982 protected function frontpage_remote_host($host) {
1983 $output = '';
1984 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1985 $output .= html_writer::start_tag('div', array('class' => 'info'));
1986 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1987 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1988 $output .= html_writer::end_tag('h3'); // .name
1989 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1990 $output .= html_writer::end_tag('div'); // .info
1991 $output .= html_writer::start_tag('div', array('class' => 'content'));
1992 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1993 $output .= $host['count'] . ' ' . get_string('courses');
1994 $output .= html_writer::end_tag('div'); // .content
1995 $output .= html_writer::end_tag('div'); // .coursebox
1996 return $output;
2000 * Returns HTML to print list of courses user is enrolled to for the frontpage
2002 * Also lists remote courses or remote hosts if MNET authorisation is used
2004 * @return string
2006 public function frontpage_my_courses() {
2007 global $USER, $CFG, $DB;
2009 if (!isloggedin() or isguestuser()) {
2010 return '';
2013 $output = '';
2014 if (!empty($CFG->navsortmycoursessort)) {
2015 // sort courses the same as in navigation menu
2016 $sortorder = 'visible DESC,'. $CFG->navsortmycoursessort.' ASC';
2017 } else {
2018 $sortorder = 'visible DESC,sortorder ASC';
2020 $courses = enrol_get_my_courses('summary, summaryformat', $sortorder);
2021 $rhosts = array();
2022 $rcourses = array();
2023 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2024 $rcourses = get_my_remotecourses($USER->id);
2025 $rhosts = get_my_remotehosts();
2028 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2030 $chelper = new coursecat_helper();
2031 if (count($courses) > $CFG->frontpagecourselimit) {
2032 // There are more enrolled courses than we can display, display link to 'My courses'.
2033 $totalcount = count($courses);
2034 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
2035 $chelper->set_courses_display_options(array(
2036 'viewmoreurl' => new moodle_url('/my/'),
2037 'viewmoretext' => new lang_string('mycourses')
2039 } else {
2040 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
2041 $chelper->set_courses_display_options(array(
2042 'viewmoreurl' => new moodle_url('/course/index.php'),
2043 'viewmoretext' => new lang_string('fulllistofcourses')
2045 $totalcount = $DB->count_records('course') - 1;
2047 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2048 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
2049 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
2051 // MNET
2052 if (!empty($rcourses)) {
2053 // at the IDP, we know of all the remote courses
2054 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2055 foreach ($rcourses as $course) {
2056 $output .= $this->frontpage_remote_course($course);
2058 $output .= html_writer::end_tag('div'); // .courses
2059 } elseif (!empty($rhosts)) {
2060 // non-IDP, we know of all the remote servers, but not courses
2061 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2062 foreach ($rhosts as $host) {
2063 $output .= $this->frontpage_remote_host($host);
2065 $output .= html_writer::end_tag('div'); // .courses
2068 return $output;
2072 * Returns HTML to print list of available courses for the frontpage
2074 * @return string
2076 public function frontpage_available_courses() {
2077 global $CFG;
2078 require_once($CFG->libdir. '/coursecatlib.php');
2080 $chelper = new coursecat_helper();
2081 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2082 set_courses_display_options(array(
2083 'recursive' => true,
2084 'limit' => $CFG->frontpagecourselimit,
2085 'viewmoreurl' => new moodle_url('/course/index.php'),
2086 'viewmoretext' => new lang_string('fulllistofcourses')));
2088 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
2089 $courses = coursecat::get(0)->get_courses($chelper->get_courses_display_options());
2090 $totalcount = coursecat::get(0)->get_courses_count($chelper->get_courses_display_options());
2091 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
2092 // Print link to create a new course, for the 1st available category.
2093 return $this->add_new_course_button();
2095 return $this->coursecat_courses($chelper, $courses, $totalcount);
2099 * Returns HTML to the "add new course" button for the page
2101 * @return string
2103 public function add_new_course_button() {
2104 global $CFG;
2105 // Print link to create a new course, for the 1st available category.
2106 $output = $this->container_start('buttons');
2107 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2108 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2109 $output .= $this->container_end('buttons');
2110 return $output;
2114 * Returns HTML to print tree with course categories and courses for the frontpage
2116 * @return string
2118 public function frontpage_combo_list() {
2119 global $CFG;
2120 require_once($CFG->libdir. '/coursecatlib.php');
2121 $chelper = new coursecat_helper();
2122 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2123 set_categories_display_options(array(
2124 'limit' => $CFG->coursesperpage,
2125 'viewmoreurl' => new moodle_url('/course/index.php',
2126 array('browse' => 'categories', 'page' => 1))
2127 ))->
2128 set_courses_display_options(array(
2129 'limit' => $CFG->coursesperpage,
2130 'viewmoreurl' => new moodle_url('/course/index.php',
2131 array('browse' => 'courses', 'page' => 1))
2132 ))->
2133 set_attributes(array('class' => 'frontpage-category-combo'));
2134 return $this->coursecat_tree($chelper, coursecat::get(0));
2138 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2140 * @return string
2142 public function frontpage_categories_list() {
2143 global $CFG;
2144 require_once($CFG->libdir. '/coursecatlib.php');
2145 $chelper = new coursecat_helper();
2146 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2147 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2148 set_categories_display_options(array(
2149 'limit' => $CFG->coursesperpage,
2150 'viewmoreurl' => new moodle_url('/course/index.php',
2151 array('browse' => 'categories', 'page' => 1))
2152 ))->
2153 set_attributes(array('class' => 'frontpage-category-names'));
2154 return $this->coursecat_tree($chelper, coursecat::get(0));
2159 * Class storing display options and functions to help display course category and/or courses lists
2161 * This is a wrapper for coursecat objects that also stores display options
2162 * and functions to retrieve sorted and paginated lists of categories/courses.
2164 * If theme overrides methods in core_course_renderers that access this class
2165 * it may as well not use this class at all or extend it.
2167 * @package core
2168 * @copyright 2013 Marina Glancy
2169 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2171 class coursecat_helper {
2172 /** @var string [none, collapsed, expanded] how (if) display courses list */
2173 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2174 /** @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) */
2175 protected $subcatdepth = 1;
2176 /** @var array options to display courses list */
2177 protected $coursesdisplayoptions = array();
2178 /** @var array options to display subcategories list */
2179 protected $categoriesdisplayoptions = array();
2180 /** @var array additional HTML attributes */
2181 protected $attributes = array();
2182 /** @var array search criteria if the list is a search result */
2183 protected $searchcriteria = null;
2186 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2188 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2189 * @return coursecat_helper
2191 public function set_show_courses($showcourses) {
2192 $this->showcourses = $showcourses;
2193 // Automatically set the options to preload summary and coursecontacts for coursecat::get_courses() and coursecat::search_courses()
2194 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2195 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2196 return $this;
2200 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2202 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2204 public function get_show_courses() {
2205 return $this->showcourses;
2209 * Sets the maximum depth to expand subcategories in the tree
2211 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2213 * @param int $subcatdepth
2214 * @return coursecat_helper
2216 public function set_subcat_depth($subcatdepth) {
2217 $this->subcatdepth = $subcatdepth;
2218 return $this;
2222 * Returns the maximum depth to expand subcategories in the tree
2224 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2226 * @return int
2228 public function get_subcat_depth() {
2229 return $this->subcatdepth;
2233 * Sets options to display list of courses
2235 * Options are later submitted as argument to coursecat::get_courses() and/or coursecat::search_courses()
2237 * Options that coursecat::get_courses() accept:
2238 * - recursive - return courses from subcategories as well. Use with care,
2239 * this may be a huge list!
2240 * - summary - preloads fields 'summary' and 'summaryformat'
2241 * - coursecontacts - preloads course contacts
2242 * - isenrolled - preloads indication whether this user is enrolled in the course
2243 * - sort - list of fields to sort. Example
2244 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2245 * will sort by idnumber asc, shortname asc and id desc.
2246 * Default: array('sortorder' => 1)
2247 * Only cached fields may be used for sorting!
2248 * - offset
2249 * - limit - maximum number of children to return, 0 or null for no limit
2251 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2253 * Also renderer can set here any additional options it wants to pass between renderer functions.
2255 * @param array $options
2256 * @return coursecat_helper
2258 public function set_courses_display_options($options) {
2259 $this->coursesdisplayoptions = $options;
2260 $this->set_show_courses($this->showcourses); // this will calculate special display options
2261 return $this;
2265 * Sets one option to display list of courses
2267 * @see coursecat_helper::set_courses_display_options()
2269 * @param string $key
2270 * @param mixed $value
2271 * @return coursecat_helper
2273 public function set_courses_display_option($key, $value) {
2274 $this->coursesdisplayoptions[$key] = $value;
2275 return $this;
2279 * Return the specified option to display list of courses
2281 * @param string $optionname option name
2282 * @param mixed $defaultvalue default value for option if it is not specified
2283 * @return mixed
2285 public function get_courses_display_option($optionname, $defaultvalue = null) {
2286 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2287 return $this->coursesdisplayoptions[$optionname];
2288 } else {
2289 return $defaultvalue;
2294 * Returns all options to display the courses
2296 * This array is usually passed to {@link coursecat::get_courses()} or
2297 * {@link coursecat::search_courses()}
2299 * @return array
2301 public function get_courses_display_options() {
2302 return $this->coursesdisplayoptions;
2306 * Sets options to display list of subcategories
2308 * Options 'sort', 'offset' and 'limit' are passed to coursecat::get_children().
2309 * Any other options may be used by renderer functions
2311 * @param array $options
2312 * @return coursecat_helper
2314 public function set_categories_display_options($options) {
2315 $this->categoriesdisplayoptions = $options;
2316 return $this;
2320 * Return the specified option to display list of subcategories
2322 * @param string $optionname option name
2323 * @param mixed $defaultvalue default value for option if it is not specified
2324 * @return mixed
2326 public function get_categories_display_option($optionname, $defaultvalue = null) {
2327 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2328 return $this->categoriesdisplayoptions[$optionname];
2329 } else {
2330 return $defaultvalue;
2335 * Returns all options to display list of subcategories
2337 * This array is usually passed to {@link coursecat::get_children()}
2339 * @return array
2341 public function get_categories_display_options() {
2342 return $this->categoriesdisplayoptions;
2346 * Sets additional general options to pass between renderer functions, usually HTML attributes
2348 * @param array $attributes
2349 * @return coursecat_helper
2351 public function set_attributes($attributes) {
2352 $this->attributes = $attributes;
2353 return $this;
2357 * Return all attributes and erases them so they are not applied again
2359 * @param string $classname adds additional class name to the beginning of $attributes['class']
2360 * @return array
2362 public function get_and_erase_attributes($classname) {
2363 $attributes = $this->attributes;
2364 $this->attributes = array();
2365 if (empty($attributes['class'])) {
2366 $attributes['class'] = '';
2368 $attributes['class'] = $classname . ' '. $attributes['class'];
2369 return $attributes;
2373 * Sets the search criteria if the course is a search result
2375 * Search string will be used to highlight terms in course name and description
2377 * @param array $searchcriteria
2378 * @return coursecat_helper
2380 public function set_search_criteria($searchcriteria) {
2381 $this->searchcriteria = $searchcriteria;
2382 return $this;
2386 * Returns formatted and filtered description of the given category
2388 * @param coursecat $coursecat category
2389 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2390 * if context is not specified it will be added automatically
2391 * @return string|null
2393 public function get_category_formatted_description($coursecat, $options = null) {
2394 if ($coursecat->id && !empty($coursecat->description)) {
2395 if (!isset($coursecat->descriptionformat)) {
2396 $descriptionformat = FORMAT_MOODLE;
2397 } else {
2398 $descriptionformat = $coursecat->descriptionformat;
2400 if ($options === null) {
2401 $options = array('noclean' => true, 'overflowdiv' => true);
2402 } else {
2403 $options = (array)$options;
2405 $context = context_coursecat::instance($coursecat->id);
2406 if (!isset($options['context'])) {
2407 $options['context'] = $context;
2409 $text = file_rewrite_pluginfile_urls($coursecat->description,
2410 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2411 return format_text($text, $descriptionformat, $options);
2413 return null;
2417 * Returns given course's summary with proper embedded files urls and formatted
2419 * @param course_in_list $course
2420 * @param array|stdClass $options additional formatting options
2421 * @return string
2423 public function get_course_formatted_summary($course, $options = array()) {
2424 global $CFG;
2425 require_once($CFG->libdir. '/filelib.php');
2426 if (!$course->has_summary()) {
2427 return '';
2429 $options = (array)$options;
2430 $context = context_course::instance($course->id);
2431 if (!isset($options['context'])) {
2432 // TODO see MDL-38521
2433 // option 1 (current), page context - no code required
2434 // option 2, system context
2435 // $options['context'] = context_system::instance();
2436 // option 3, course context:
2437 // $options['context'] = $context;
2438 // option 4, course category context:
2439 // $options['context'] = $context->get_parent_context();
2441 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2442 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2443 if (!empty($this->searchcriteria['search'])) {
2444 $summary = highlight($this->searchcriteria['search'], $summary);
2446 return $summary;
2450 * Returns course name as it is configured to appear in courses lists formatted to course context
2452 * @param course_in_list $course
2453 * @param array|stdClass $options additional formatting options
2454 * @return string
2456 public function get_course_formatted_name($course, $options = array()) {
2457 $options = (array)$options;
2458 if (!isset($options['context'])) {
2459 $options['context'] = context_course::instance($course->id);
2461 $name = format_string(get_course_display_name_for_list($course), true, $options);
2462 if (!empty($this->searchcriteria['search'])) {
2463 $name = highlight($this->searchcriteria['search'], $name);
2465 return $name;