Merge branch 'MDL-44620_master' of git://github.com/dmonllao/moodle into MOODLE_27_STABLE
[moodle.git] / course / renderer.php
blob8450cebcb0697c9db56adb6c13141094c8bb1894
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 core_availability\info::completion_value_used($course, $mod->id)) {
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 $info = new \core_availability\info_module($mod);
715 $conditionalhidden = !$info->is_available_for_all();
717 return $conditionalhidden;
721 * Renders html to display a name with the link to the course module on a course page
723 * If module is unavailable for user but still needs to be displayed
724 * in the list, just the name is returned without a link
726 * Note, that for course modules that never have separate pages (i.e. labels)
727 * this function return an empty string
729 * @param cm_info $mod
730 * @param array $displayoptions
731 * @return string
733 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
734 global $CFG;
735 $output = '';
736 if (!$mod->uservisible && empty($mod->availableinfo)) {
737 // nothing to be displayed to the user
738 return $output;
740 $url = $mod->url;
741 if (!$url) {
742 return $output;
745 //Accessibility: for files get description via icon, this is very ugly hack!
746 $instancename = $mod->get_formatted_name();
747 $altname = $mod->modfullname;
748 // Avoid unnecessary duplication: if e.g. a forum name already
749 // includes the word forum (or Forum, etc) then it is unhelpful
750 // to include that in the accessible description that is added.
751 if (false !== strpos(core_text::strtolower($instancename),
752 core_text::strtolower($altname))) {
753 $altname = '';
755 // File type after name, for alphabetic lists (screen reader).
756 if ($altname) {
757 $altname = get_accesshide(' '.$altname);
760 // For items which are hidden but available to current user
761 // ($mod->uservisible), we show those as dimmed only if the user has
762 // viewhiddenactivities, so that teachers see 'items which might not
763 // be available to some students' dimmed but students do not see 'item
764 // which is actually available to current student' dimmed.
765 $linkclasses = '';
766 $accesstext = '';
767 $textclasses = '';
768 if ($mod->uservisible) {
769 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
770 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
771 has_capability('moodle/course:viewhiddenactivities',
772 context_course::instance($mod->course));
773 if ($accessiblebutdim) {
774 $linkclasses .= ' dimmed';
775 $textclasses .= ' dimmed_text';
776 if ($conditionalhidden) {
777 $linkclasses .= ' conditionalhidden';
778 $textclasses .= ' conditionalhidden';
780 // Show accessibility note only if user can access the module himself.
781 $accesstext = get_accesshide(get_string('hiddenfromstudents').':'. $mod->modfullname);
783 } else {
784 $linkclasses .= ' dimmed';
785 $textclasses .= ' dimmed_text';
788 // Get on-click attribute value if specified and decode the onclick - it
789 // has already been encoded for display (puke).
790 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
792 $groupinglabel = '';
793 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($mod->course))) {
794 $groupings = groups_get_all_groupings($mod->course);
795 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$mod->groupingid]->name).')',
796 array('class' => 'groupinglabel '.$textclasses));
799 // Display link itself.
800 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
801 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) . $accesstext .
802 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
803 if ($mod->uservisible) {
804 $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick)) .
805 $groupinglabel;
806 } else {
807 // We may be displaying this just in order to show information
808 // about visibility, without the actual link ($mod->uservisible)
809 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses)) .
810 $groupinglabel;
812 return $output;
816 * Renders html to display the module content on the course page (i.e. text of the labels)
818 * @param cm_info $mod
819 * @param array $displayoptions
820 * @return string
822 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
823 $output = '';
824 if (!$mod->uservisible && empty($mod->availableinfo)) {
825 // nothing to be displayed to the user
826 return $output;
828 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
829 $accesstext = '';
830 $textclasses = '';
831 if ($mod->uservisible) {
832 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
833 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
834 has_capability('moodle/course:viewhiddenactivities',
835 context_course::instance($mod->course));
836 if ($accessiblebutdim) {
837 $textclasses .= ' dimmed_text';
838 if ($conditionalhidden) {
839 $textclasses .= ' conditionalhidden';
841 // Show accessibility note only if user can access the module himself.
842 $accesstext = get_accesshide(get_string('hiddenfromstudents').':'. $mod->modfullname);
844 } else {
845 $textclasses .= ' dimmed_text';
847 if ($mod->url) {
848 if ($content) {
849 // If specified, display extra content after link.
850 $output = html_writer::tag('div', $content, array('class' =>
851 trim('contentafterlink ' . $textclasses)));
853 } else {
854 // No link, so display only content.
855 $output = html_writer::tag('div', $accesstext . $content,
856 array('class' => 'contentwithoutlink ' . $textclasses));
858 return $output;
862 * Renders HTML to show course module availability information (for someone who isn't allowed
863 * to see the activity itself, or for staff)
865 * @param cm_info $mod
866 * @param array $displayoptions
867 * @return string
869 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
870 global $CFG;
871 if (!$mod->uservisible) {
872 // this is a student who is not allowed to see the module but might be allowed
873 // to see availability info (i.e. "Available from ...")
874 if (!empty($mod->availableinfo)) {
875 $formattedinfo = \core_availability\info::format_info(
876 $mod->availableinfo, $mod->get_course());
877 $output = html_writer::tag('div', $formattedinfo, array('class' => 'availabilityinfo'));
879 return $output;
881 // this is a teacher who is allowed to see module but still should see the
882 // information that module is not available to all/some students
883 $modcontext = context_module::instance($mod->id);
884 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
885 if ($canviewhidden && !empty($CFG->enableavailability)) {
886 // Don't add availability information if user is not editing and activity is hidden.
887 if ($mod->visible || $this->page->user_is_editing()) {
888 $hidinfoclass = '';
889 if (!$mod->visible) {
890 $hidinfoclass = 'hide';
892 $ci = new \core_availability\info_module($mod);
893 $fullinfo = $ci->get_full_information();
894 if ($fullinfo) {
895 $formattedinfo = \core_availability\info::format_info(
896 $fullinfo, $mod->get_course());
897 return html_writer::div($formattedinfo, 'availabilityinfo ' . $hidinfoclass);
901 return '';
905 * Renders HTML to display one course module for display within a section.
907 * This function calls:
908 * {@link core_course_renderer::course_section_cm()}
910 * @param stdClass $course
911 * @param completion_info $completioninfo
912 * @param cm_info $mod
913 * @param int|null $sectionreturn
914 * @param array $displayoptions
915 * @return String
917 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
918 $output = '';
919 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
920 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
921 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
923 return $output;
927 * Renders HTML to display one course module in a course section
929 * This includes link, content, availability, completion info and additional information
930 * that module type wants to display (i.e. number of unread forum posts)
932 * This function calls:
933 * {@link core_course_renderer::course_section_cm_name()}
934 * {@link core_course_renderer::course_section_cm_text()}
935 * {@link core_course_renderer::course_section_cm_availability()}
936 * {@link core_course_renderer::course_section_cm_completion()}
937 * {@link course_get_cm_edit_actions()}
938 * {@link core_course_renderer::course_section_cm_edit_actions()}
940 * @param stdClass $course
941 * @param completion_info $completioninfo
942 * @param cm_info $mod
943 * @param int|null $sectionreturn
944 * @param array $displayoptions
945 * @return string
947 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
948 $output = '';
949 // We return empty string (because course module will not be displayed at all)
950 // if:
951 // 1) The activity is not visible to users
952 // and
953 // 2) The 'availableinfo' is empty, i.e. the activity was
954 // hidden in a way that leaves no info, such as using the
955 // eye icon.
956 if (!$mod->uservisible && empty($mod->availableinfo)) {
957 return $output;
960 $indentclasses = 'mod-indent';
961 if (!empty($mod->indent)) {
962 $indentclasses .= ' mod-indent-'.$mod->indent;
963 if ($mod->indent > 15) {
964 $indentclasses .= ' mod-indent-huge';
968 $output .= html_writer::start_tag('div');
970 if ($this->page->user_is_editing()) {
971 $output .= course_get_cm_move($mod, $sectionreturn);
974 $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer'));
976 // This div is used to indent the content.
977 $output .= html_writer::div('', $indentclasses);
979 // Start a wrapper for the actual content to keep the indentation consistent
980 $output .= html_writer::start_tag('div');
982 // Display the link to the module (or do nothing if module has no url)
983 $cmname = $this->course_section_cm_name($mod, $displayoptions);
985 if (!empty($cmname)) {
986 // Start the div for the activity title, excluding the edit icons.
987 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
988 $output .= $cmname;
991 if ($this->page->user_is_editing()) {
992 $output .= ' ' . course_get_cm_rename_action($mod, $sectionreturn);
995 // Module can put text after the link (e.g. forum unread)
996 $output .= $mod->afterlink;
998 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
999 $output .= html_writer::end_tag('div'); // .activityinstance
1002 // If there is content but NO link (eg label), then display the
1003 // content here (BEFORE any icons). In this case cons must be
1004 // displayed after the content so that it makes more sense visually
1005 // and for accessibility reasons, e.g. if you have a one-line label
1006 // it should work similarly (at least in terms of ordering) to an
1007 // activity.
1008 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
1009 $url = $mod->url;
1010 if (empty($url)) {
1011 $output .= $contentpart;
1014 $modicons = '';
1015 if ($this->page->user_is_editing()) {
1016 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
1017 $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
1018 $modicons .= $mod->afterediticons;
1021 $modicons .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
1023 if (!empty($modicons)) {
1024 $output .= html_writer::span($modicons, 'actions');
1027 // If there is content AND a link, then display the content here
1028 // (AFTER any icons). Otherwise it was displayed before
1029 if (!empty($url)) {
1030 $output .= $contentpart;
1033 // show availability info (if module is not available)
1034 $output .= $this->course_section_cm_availability($mod, $displayoptions);
1036 $output .= html_writer::end_tag('div'); // $indentclasses
1038 // End of indentation div.
1039 $output .= html_writer::end_tag('div');
1041 $output .= html_writer::end_tag('div');
1042 return $output;
1046 * Renders HTML to display a list of course modules in a course section
1047 * Also displays "move here" controls in Javascript-disabled mode
1049 * This function calls {@link core_course_renderer::course_section_cm()}
1051 * @param stdClass $course course object
1052 * @param int|stdClass|section_info $section relative section number or section object
1053 * @param int $sectionreturn section number to return to
1054 * @param int $displayoptions
1055 * @return void
1057 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
1058 global $USER;
1060 $output = '';
1061 $modinfo = get_fast_modinfo($course);
1062 if (is_object($section)) {
1063 $section = $modinfo->get_section_info($section->section);
1064 } else {
1065 $section = $modinfo->get_section_info($section);
1067 $completioninfo = new completion_info($course);
1069 // check if we are currently in the process of moving a module with JavaScript disabled
1070 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
1071 if ($ismoving) {
1072 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
1073 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1076 // Get the list of modules visible to user (excluding the module being moved if there is one)
1077 $moduleshtml = array();
1078 if (!empty($modinfo->sections[$section->section])) {
1079 foreach ($modinfo->sections[$section->section] as $modnumber) {
1080 $mod = $modinfo->cms[$modnumber];
1082 if ($ismoving and $mod->id == $USER->activitycopy) {
1083 // do not display moving mod
1084 continue;
1087 if ($modulehtml = $this->course_section_cm_list_item($course,
1088 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
1089 $moduleshtml[$modnumber] = $modulehtml;
1094 $sectionoutput = '';
1095 if (!empty($moduleshtml) || $ismoving) {
1096 foreach ($moduleshtml as $modnumber => $modulehtml) {
1097 if ($ismoving) {
1098 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
1099 $sectionoutput .= html_writer::tag('li', html_writer::link($movingurl, $this->output->render($movingpix)),
1100 array('class' => 'movehere', 'title' => $strmovefull));
1103 $sectionoutput .= $modulehtml;
1106 if ($ismoving) {
1107 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1108 $sectionoutput .= html_writer::tag('li', html_writer::link($movingurl, $this->output->render($movingpix)),
1109 array('class' => 'movehere', 'title' => $strmovefull));
1113 // Always output the section module list.
1114 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1116 return $output;
1120 * Displays a custom list of courses with paging bar if necessary
1122 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1123 * appears under the list.
1125 * If both $paginationurl and $totalcount are specified, and $totalcount is
1126 * bigger than count($courses), a paging bar is displayed above and under the
1127 * courses list.
1129 * @param array $courses array of course records (or instances of course_in_list) to show on this page
1130 * @param bool $showcategoryname whether to add category name to the course description
1131 * @param string $additionalclasses additional CSS classes to add to the div.courses
1132 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1133 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1134 * @param int $page current page number (defaults to 0 referring to the first page)
1135 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1136 * @return string
1138 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1139 global $CFG;
1140 // create instance of coursecat_helper to pass display options to function rendering courses list
1141 $chelper = new coursecat_helper();
1142 if ($showcategoryname) {
1143 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1144 } else {
1145 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1147 if ($totalcount !== null && $paginationurl !== null) {
1148 // add options to display pagination
1149 if ($perpage === null) {
1150 $perpage = $CFG->coursesperpage;
1152 $chelper->set_courses_display_options(array(
1153 'limit' => $perpage,
1154 'offset' => ((int)$page) * $perpage,
1155 'paginationurl' => $paginationurl,
1157 } else if ($paginationurl !== null) {
1158 // add options to display 'View more' link
1159 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1160 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1162 $chelper->set_attributes(array('class' => $additionalclasses));
1163 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1164 return $content;
1168 * Displays one course in the list of courses.
1170 * This is an internal function, to display an information about just one course
1171 * please use {@link core_course_renderer::course_info_box()}
1173 * @param coursecat_helper $chelper various display options
1174 * @param course_in_list|stdClass $course
1175 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1176 * depend on the course position in list - first/last/even/odd)
1177 * @return string
1179 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1180 global $CFG;
1181 if (!isset($this->strings->summary)) {
1182 $this->strings->summary = get_string('summary');
1184 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1185 return '';
1187 if ($course instanceof stdClass) {
1188 require_once($CFG->libdir. '/coursecatlib.php');
1189 $course = new course_in_list($course);
1191 $content = '';
1192 $classes = trim('coursebox clearfix '. $additionalclasses);
1193 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1194 $nametag = 'h3';
1195 } else {
1196 $classes .= ' collapsed';
1197 $nametag = 'div';
1200 // .coursebox
1201 $content .= html_writer::start_tag('div', array(
1202 'class' => $classes,
1203 'data-courseid' => $course->id,
1204 'data-type' => self::COURSECAT_TYPE_COURSE,
1207 $content .= html_writer::start_tag('div', array('class' => 'info'));
1209 // course name
1210 $coursename = $chelper->get_course_formatted_name($course);
1211 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', array('id' => $course->id)),
1212 $coursename, array('class' => $course->visible ? '' : 'dimmed'));
1213 $content .= html_writer::tag($nametag, $coursenamelink, array('class' => 'coursename'));
1214 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1215 $content .= html_writer::start_tag('div', array('class' => 'moreinfo'));
1216 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1217 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()) {
1218 $url = new moodle_url('/course/info.php', array('id' => $course->id));
1219 $image = html_writer::empty_tag('img', array('src' => $this->output->pix_url('i/info'),
1220 'alt' => $this->strings->summary));
1221 $content .= html_writer::link($url, $image, array('title' => $this->strings->summary));
1222 // Make sure JS file to expand course content is included.
1223 $this->coursecat_include_js();
1226 $content .= html_writer::end_tag('div'); // .moreinfo
1228 // print enrolmenticons
1229 if ($icons = enrol_get_course_info_icons($course)) {
1230 $content .= html_writer::start_tag('div', array('class' => 'enrolmenticons'));
1231 foreach ($icons as $pix_icon) {
1232 $content .= $this->render($pix_icon);
1234 $content .= html_writer::end_tag('div'); // .enrolmenticons
1237 $content .= html_writer::end_tag('div'); // .info
1239 $content .= html_writer::start_tag('div', array('class' => 'content'));
1240 $content .= $this->coursecat_coursebox_content($chelper, $course);
1241 $content .= html_writer::end_tag('div'); // .content
1243 $content .= html_writer::end_tag('div'); // .coursebox
1244 return $content;
1248 * Returns HTML to display course content (summary, course contacts and optionally category name)
1250 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1252 * @param coursecat_helper $chelper various display options
1253 * @param stdClass|course_in_list $course
1254 * @return string
1256 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1257 global $CFG;
1258 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1259 return '';
1261 if ($course instanceof stdClass) {
1262 require_once($CFG->libdir. '/coursecatlib.php');
1263 $course = new course_in_list($course);
1265 $content = '';
1267 // display course summary
1268 if ($course->has_summary()) {
1269 $content .= html_writer::start_tag('div', array('class' => 'summary'));
1270 $content .= $chelper->get_course_formatted_summary($course,
1271 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1272 $content .= html_writer::end_tag('div'); // .summary
1275 // display course overview files
1276 $contentimages = $contentfiles = '';
1277 foreach ($course->get_course_overviewfiles() as $file) {
1278 $isimage = $file->is_valid_image();
1279 $url = file_encode_url("$CFG->wwwroot/pluginfile.php",
1280 '/'. $file->get_contextid(). '/'. $file->get_component(). '/'.
1281 $file->get_filearea(). $file->get_filepath(). $file->get_filename(), !$isimage);
1282 if ($isimage) {
1283 $contentimages .= html_writer::tag('div',
1284 html_writer::empty_tag('img', array('src' => $url)),
1285 array('class' => 'courseimage'));
1286 } else {
1287 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1288 $filename = html_writer::tag('span', $image, array('class' => 'fp-icon')).
1289 html_writer::tag('span', $file->get_filename(), array('class' => 'fp-filename'));
1290 $contentfiles .= html_writer::tag('span',
1291 html_writer::link($url, $filename),
1292 array('class' => 'coursefile fp-filename-icon'));
1295 $content .= $contentimages. $contentfiles;
1297 // display course contacts. See course_in_list::get_course_contacts()
1298 if ($course->has_course_contacts()) {
1299 $content .= html_writer::start_tag('ul', array('class' => 'teachers'));
1300 foreach ($course->get_course_contacts() as $userid => $coursecontact) {
1301 $name = $coursecontact['rolename'].': '.
1302 html_writer::link(new moodle_url('/user/view.php',
1303 array('id' => $userid, 'course' => SITEID)),
1304 $coursecontact['username']);
1305 $content .= html_writer::tag('li', $name);
1307 $content .= html_writer::end_tag('ul'); // .teachers
1310 // display course category if necessary (for example in search results)
1311 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1312 require_once($CFG->libdir. '/coursecatlib.php');
1313 if ($cat = coursecat::get($course->category, IGNORE_MISSING)) {
1314 $content .= html_writer::start_tag('div', array('class' => 'coursecat'));
1315 $content .= get_string('category').': '.
1316 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1317 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1318 $content .= html_writer::end_tag('div'); // .coursecat
1322 return $content;
1326 * Renders the list of courses
1328 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1329 * method from outside of the class
1331 * If list of courses is specified in $courses; the argument $chelper is only used
1332 * to retrieve display options and attributes, only methods get_show_courses(),
1333 * get_courses_display_option() and get_and_erase_attributes() are called.
1335 * @param coursecat_helper $chelper various display options
1336 * @param array $courses the list of courses to display
1337 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1338 * defaulted to count($courses)
1339 * @return string
1341 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1342 global $CFG;
1343 if ($totalcount === null) {
1344 $totalcount = count($courses);
1346 if (!$totalcount) {
1347 // Courses count is cached during courses retrieval.
1348 return '';
1351 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1352 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1353 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1354 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1355 } else {
1356 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1360 // prepare content of paging bar if it is needed
1361 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1362 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1363 if ($totalcount > count($courses)) {
1364 // there are more results that can fit on one page
1365 if ($paginationurl) {
1366 // the option paginationurl was specified, display pagingbar
1367 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1368 $page = $chelper->get_courses_display_option('offset') / $perpage;
1369 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1370 $paginationurl->out(false, array('perpage' => $perpage)));
1371 if ($paginationallowall) {
1372 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1373 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1375 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1376 // the option for 'View more' link was specified, display more link
1377 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1378 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1379 array('class' => 'paging paging-morelink'));
1381 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1382 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1383 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1384 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1387 // display list of courses
1388 $attributes = $chelper->get_and_erase_attributes('courses');
1389 $content = html_writer::start_tag('div', $attributes);
1391 if (!empty($pagingbar)) {
1392 $content .= $pagingbar;
1395 $coursecount = 0;
1396 foreach ($courses as $course) {
1397 $coursecount ++;
1398 $classes = ($coursecount%2) ? 'odd' : 'even';
1399 if ($coursecount == 1) {
1400 $classes .= ' first';
1402 if ($coursecount >= count($courses)) {
1403 $classes .= ' last';
1405 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1408 if (!empty($pagingbar)) {
1409 $content .= $pagingbar;
1411 if (!empty($morelink)) {
1412 $content .= $morelink;
1415 $content .= html_writer::end_tag('div'); // .courses
1416 return $content;
1420 * Renders the list of subcategories in a category
1422 * @param coursecat_helper $chelper various display options
1423 * @param coursecat $coursecat
1424 * @param int $depth depth of the category in the current tree
1425 * @return string
1427 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1428 global $CFG;
1429 $subcategories = array();
1430 if (!$chelper->get_categories_display_option('nodisplay')) {
1431 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1433 $totalcount = $coursecat->get_children_count();
1434 if (!$totalcount) {
1435 // Note that we call get_child_categories_count() AFTER get_child_categories() to avoid extra DB requests.
1436 // Categories count is cached during children categories retrieval.
1437 return '';
1440 // prepare content of paging bar or more link if it is needed
1441 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1442 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1443 if ($totalcount > count($subcategories)) {
1444 if ($paginationurl) {
1445 // the option 'paginationurl was specified, display pagingbar
1446 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1447 $page = $chelper->get_categories_display_option('offset') / $perpage;
1448 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1449 $paginationurl->out(false, array('perpage' => $perpage)));
1450 if ($paginationallowall) {
1451 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1452 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1454 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1455 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1456 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1457 $viewmoreurl->param('categoryid', $coursecat->id);
1459 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1460 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1461 array('class' => 'paging paging-morelink'));
1463 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1464 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1465 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1466 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1469 // display list of subcategories
1470 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1472 if (!empty($pagingbar)) {
1473 $content .= $pagingbar;
1476 foreach ($subcategories as $subcategory) {
1477 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1480 if (!empty($pagingbar)) {
1481 $content .= $pagingbar;
1483 if (!empty($morelink)) {
1484 $content .= $morelink;
1487 $content .= html_writer::end_tag('div');
1488 return $content;
1492 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1494 protected function coursecat_include_js() {
1495 global $CFG;
1496 static $jsloaded = false;
1497 if (!$jsloaded) {
1498 // We must only load this module once.
1499 $this->page->requires->yui_module('moodle-course-categoryexpander',
1500 'Y.Moodle.course.categoryexpander.init');
1501 $jsloaded = true;
1506 * Returns HTML to display the subcategories and courses in the given category
1508 * This method is re-used by AJAX to expand content of not loaded category
1510 * @param coursecat_helper $chelper various display options
1511 * @param coursecat $coursecat
1512 * @param int $depth depth of the category in the current tree
1513 * @return string
1515 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1516 $content = '';
1517 // Subcategories
1518 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1520 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1521 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1522 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1523 if ($showcoursesauto && $depth) {
1524 // this is definitely collapsed mode
1525 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1528 // Courses
1529 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1530 $courses = array();
1531 if (!$chelper->get_courses_display_option('nodisplay')) {
1532 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1534 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1535 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1536 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1537 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1540 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1543 if ($showcoursesauto) {
1544 // restore the show_courses back to AUTO
1545 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1548 return $content;
1552 * Returns HTML to display a course category as a part of a tree
1554 * This is an internal function, to display a particular category and all its contents
1555 * use {@link core_course_renderer::course_category()}
1557 * @param coursecat_helper $chelper various display options
1558 * @param coursecat $coursecat
1559 * @param int $depth depth of this category in the current tree
1560 * @return string
1562 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1563 // open category tag
1564 $classes = array('category');
1565 if (empty($coursecat->visible)) {
1566 $classes[] = 'dimmed_category';
1568 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1569 // do not load content
1570 $categorycontent = '';
1571 $classes[] = 'notloaded';
1572 if ($coursecat->get_children_count() ||
1573 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1574 $classes[] = 'with_children';
1575 $classes[] = 'collapsed';
1577 } else {
1578 // load category content
1579 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1580 $classes[] = 'loaded';
1581 if (!empty($categorycontent)) {
1582 $classes[] = 'with_children';
1586 // Make sure JS file to expand category content is included.
1587 $this->coursecat_include_js();
1589 $content = html_writer::start_tag('div', array(
1590 'class' => join(' ', $classes),
1591 'data-categoryid' => $coursecat->id,
1592 'data-depth' => $depth,
1593 'data-showcourses' => $chelper->get_show_courses(),
1594 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1597 // category name
1598 $categoryname = $coursecat->get_formatted_name();
1599 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1600 array('categoryid' => $coursecat->id)),
1601 $categoryname);
1602 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1603 && ($coursescount = $coursecat->get_courses_count())) {
1604 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1605 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1607 $content .= html_writer::start_tag('div', array('class' => 'info'));
1609 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname'));
1610 $content .= html_writer::end_tag('div'); // .info
1612 // add category content to the output
1613 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1615 $content .= html_writer::end_tag('div'); // .category
1617 // Return the course category tree HTML
1618 return $content;
1622 * Returns HTML to display a tree of subcategories and courses in the given category
1624 * @param coursecat_helper $chelper various display options
1625 * @param coursecat $coursecat top category (this category's name and description will NOT be added to the tree)
1626 * @return string
1628 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1629 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1630 if (empty($categorycontent)) {
1631 return '';
1634 // Start content generation
1635 $content = '';
1636 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1637 $content .= html_writer::start_tag('div', $attributes);
1639 if ($coursecat->get_children_count()) {
1640 $classes = array(
1641 'collapseexpand',
1642 'collapse-all',
1644 if ($chelper->get_subcat_depth() == 1) {
1645 $classes[] = 'disabled';
1647 // Only show the collapse/expand if there are children to expand.
1648 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1649 $content .= html_writer::link('#', get_string('collapseall'),
1650 array('class' => implode(' ', $classes)));
1651 $content .= html_writer::end_tag('div');
1652 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1655 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1657 $content .= html_writer::end_tag('div'); // .course_category_tree
1659 return $content;
1663 * Renders HTML to display particular course category - list of it's subcategories and courses
1665 * Invoked from /course/index.php
1667 * @param int|stdClass|coursecat $category
1669 public function course_category($category) {
1670 global $CFG;
1671 require_once($CFG->libdir. '/coursecatlib.php');
1672 $coursecat = coursecat::get(is_object($category) ? $category->id : $category);
1673 $site = get_site();
1674 $output = '';
1676 $this->page->set_button($this->course_search_form('', 'navbar'));
1677 if (!$coursecat->id) {
1678 if (can_edit_in_category()) {
1679 // add 'Manage' button instead of course search form
1680 $managebutton = $this->single_button(new moodle_url('/course/management.php'), get_string('managecourses'), 'get');
1681 $this->page->set_button($managebutton);
1683 if (coursecat::count_all() == 1) {
1684 // There exists only one category in the system, do not display link to it
1685 $coursecat = coursecat::get_default();
1686 $strfulllistofcourses = get_string('fulllistofcourses');
1687 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1688 } else {
1689 $strcategories = get_string('categories');
1690 $this->page->set_title("$site->shortname: $strcategories");
1692 } else {
1693 $this->page->set_title("$site->shortname: ". $coursecat->get_formatted_name());
1695 // Print the category selector
1696 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1697 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1698 coursecat::make_categories_list(), $coursecat->id, null, 'switchcategory');
1699 $select->set_label(get_string('categories').':');
1700 $output .= $this->render($select);
1701 $output .= html_writer::end_tag('div'); // .categorypicker
1704 // Print current category description
1705 $chelper = new coursecat_helper();
1706 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1707 $output .= $this->box($description, array('class' => 'generalbox info'));
1710 // Prepare parameters for courses and categories lists in the tree
1711 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1712 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1714 $coursedisplayoptions = array();
1715 $catdisplayoptions = array();
1716 $browse = optional_param('browse', null, PARAM_ALPHA);
1717 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1718 $page = optional_param('page', 0, PARAM_INT);
1719 $baseurl = new moodle_url('/course/index.php');
1720 if ($coursecat->id) {
1721 $baseurl->param('categoryid', $coursecat->id);
1723 if ($perpage != $CFG->coursesperpage) {
1724 $baseurl->param('perpage', $perpage);
1726 $coursedisplayoptions['limit'] = $perpage;
1727 $catdisplayoptions['limit'] = $perpage;
1728 if ($browse === 'courses' || !$coursecat->has_children()) {
1729 $coursedisplayoptions['offset'] = $page * $perpage;
1730 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1731 $catdisplayoptions['nodisplay'] = true;
1732 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1733 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1734 } else if ($browse === 'categories' || !$coursecat->has_courses()) {
1735 $coursedisplayoptions['nodisplay'] = true;
1736 $catdisplayoptions['offset'] = $page * $perpage;
1737 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1738 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1739 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1740 } else {
1741 // we have a category that has both subcategories and courses, display pagination separately
1742 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1743 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1745 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1747 // Display course category tree
1748 $output .= $this->coursecat_tree($chelper, $coursecat);
1750 // Add course search form (if we are inside category it was already added to the navbar)
1751 if (!$coursecat->id) {
1752 $output .= $this->course_search_form();
1755 // Add action buttons
1756 $output .= $this->container_start('buttons');
1757 $context = get_category_or_system_context($coursecat->id);
1758 if (has_capability('moodle/course:create', $context)) {
1759 // Print link to create a new course, for the 1st available category.
1760 if ($coursecat->id) {
1761 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1762 } else {
1763 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1765 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1767 ob_start();
1768 if (coursecat::count_all() == 1) {
1769 print_course_request_buttons(context_system::instance());
1770 } else {
1771 print_course_request_buttons($context);
1773 $output .= ob_get_contents();
1774 ob_end_clean();
1775 $output .= $this->container_end();
1777 return $output;
1781 * Serves requests to /course/category.ajax.php
1783 * In this renderer implementation it may expand the category content or
1784 * course content.
1786 * @return string
1787 * @throws coding_exception
1789 public function coursecat_ajax() {
1790 global $DB, $CFG;
1791 require_once($CFG->libdir. '/coursecatlib.php');
1793 $type = required_param('type', PARAM_INT);
1795 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1796 // This is a request for a category list of some kind.
1797 $categoryid = required_param('categoryid', PARAM_INT);
1798 $showcourses = required_param('showcourses', PARAM_INT);
1799 $depth = required_param('depth', PARAM_INT);
1801 $category = coursecat::get($categoryid);
1803 $chelper = new coursecat_helper();
1804 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1805 $coursedisplayoptions = array(
1806 'limit' => $CFG->coursesperpage,
1807 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1809 $catdisplayoptions = array(
1810 'limit' => $CFG->coursesperpage,
1811 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1813 $chelper->set_show_courses($showcourses)->
1814 set_courses_display_options($coursedisplayoptions)->
1815 set_categories_display_options($catdisplayoptions);
1817 return $this->coursecat_category_content($chelper, $category, $depth);
1818 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1819 // This is a request for the course information.
1820 $courseid = required_param('courseid', PARAM_INT);
1822 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1824 $chelper = new coursecat_helper();
1825 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1826 return $this->coursecat_coursebox_content($chelper, $course);
1827 } else {
1828 throw new coding_exception('Invalid request type');
1833 * Renders html to display search result page
1835 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1836 * @return string
1838 public function search_courses($searchcriteria) {
1839 global $CFG;
1840 $content = '';
1841 if (!empty($searchcriteria)) {
1842 // print search results
1843 require_once($CFG->libdir. '/coursecatlib.php');
1845 $displayoptions = array('sort' => array('displayname' => 1));
1846 // take the current page and number of results per page from query
1847 $perpage = optional_param('perpage', 0, PARAM_RAW);
1848 if ($perpage !== 'all') {
1849 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1850 $page = optional_param('page', 0, PARAM_INT);
1851 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1853 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1854 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1855 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1857 $class = 'course-search-result';
1858 foreach ($searchcriteria as $key => $value) {
1859 if (!empty($value)) {
1860 $class .= ' course-search-result-'. $key;
1863 $chelper = new coursecat_helper();
1864 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1865 set_courses_display_options($displayoptions)->
1866 set_search_criteria($searchcriteria)->
1867 set_attributes(array('class' => $class));
1869 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1870 $totalcount = coursecat::search_courses_count($searchcriteria);
1871 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1873 if (!$totalcount) {
1874 if (!empty($searchcriteria['search'])) {
1875 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1876 } else {
1877 $content .= $this->heading(get_string('novalidcourses'));
1879 } else {
1880 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1881 $content .= $courseslist;
1884 if (!empty($searchcriteria['search'])) {
1885 // print search form only if there was a search by search string, otherwise it is confusing
1886 $content .= $this->box_start('generalbox mdl-align');
1887 $content .= $this->course_search_form($searchcriteria['search']);
1888 $content .= $this->box_end();
1890 } else {
1891 // just print search form
1892 $content .= $this->box_start('generalbox mdl-align');
1893 $content .= $this->course_search_form();
1894 $content .= html_writer::tag('div', get_string("searchhelp"), array('class' => 'searchhelp'));
1895 $content .= $this->box_end();
1897 return $content;
1901 * Renders html to print list of courses tagged with particular tag
1903 * @param int $tagid id of the tag
1904 * @return string empty string if no courses are marked with this tag or rendered list of courses
1906 public function tagged_courses($tagid) {
1907 global $CFG;
1908 require_once($CFG->libdir. '/coursecatlib.php');
1909 $displayoptions = array('limit' => $CFG->coursesperpage);
1910 $displayoptions['viewmoreurl'] = new moodle_url('/course/search.php',
1911 array('tagid' => $tagid, 'page' => 1, 'perpage' => $CFG->coursesperpage));
1912 $displayoptions['viewmoretext'] = new lang_string('findmorecourses');
1913 $chelper = new coursecat_helper();
1914 $searchcriteria = array('tagid' => $tagid);
1915 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1916 set_search_criteria(array('tagid' => $tagid))->
1917 set_courses_display_options($displayoptions)->
1918 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1919 // (we set the same css class as in search results by tagid)
1920 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1921 $totalcount = coursecat::search_courses_count($searchcriteria);
1922 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1923 if ($totalcount) {
1924 require_once $CFG->dirroot.'/tag/lib.php';
1925 $heading = get_string('courses') . ' ' . get_string('taggedwith', 'tag', tag_get_name($tagid)) .': '. $totalcount;
1926 return $this->heading($heading, 3). $content;
1928 return '';
1932 * Returns HTML to display one remote course
1934 * @param stdClass $course remote course information, contains properties:
1935 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1936 * @return string
1938 protected function frontpage_remote_course(stdClass $course) {
1939 $url = new moodle_url('/auth/mnet/jump.php', array(
1940 'hostid' => $course->hostid,
1941 'wantsurl' => '/course/view.php?id='. $course->remoteid
1944 $output = '';
1945 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1946 $output .= html_writer::start_tag('div', array('class' => 'info'));
1947 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1948 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1949 $output .= html_writer::end_tag('h3'); // .name
1950 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1951 $output .= html_writer::end_tag('div'); // .info
1952 $output .= html_writer::start_tag('div', array('class' => 'content'));
1953 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1954 $options = new stdClass();
1955 $options->noclean = true;
1956 $options->para = false;
1957 $options->overflowdiv = true;
1958 $output .= format_text($course->summary, $course->summaryformat, $options);
1959 $output .= html_writer::end_tag('div'); // .summary
1960 $addinfo = format_string($course->hostname) . ' : '
1961 . format_string($course->cat_name) . ' : '
1962 . format_string($course->shortname);
1963 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1964 $output .= html_writer::end_tag('div'); // .content
1965 $output .= html_writer::end_tag('div'); // .coursebox
1966 return $output;
1970 * Returns HTML to display one remote host
1972 * @param array $host host information, contains properties: name, url, count
1973 * @return string
1975 protected function frontpage_remote_host($host) {
1976 $output = '';
1977 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1978 $output .= html_writer::start_tag('div', array('class' => 'info'));
1979 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1980 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1981 $output .= html_writer::end_tag('h3'); // .name
1982 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1983 $output .= html_writer::end_tag('div'); // .info
1984 $output .= html_writer::start_tag('div', array('class' => 'content'));
1985 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1986 $output .= $host['count'] . ' ' . get_string('courses');
1987 $output .= html_writer::end_tag('div'); // .content
1988 $output .= html_writer::end_tag('div'); // .coursebox
1989 return $output;
1993 * Returns HTML to print list of courses user is enrolled to for the frontpage
1995 * Also lists remote courses or remote hosts if MNET authorisation is used
1997 * @return string
1999 public function frontpage_my_courses() {
2000 global $USER, $CFG, $DB;
2002 if (!isloggedin() or isguestuser()) {
2003 return '';
2006 $output = '';
2007 if (!empty($CFG->navsortmycoursessort)) {
2008 // sort courses the same as in navigation menu
2009 $sortorder = 'visible DESC,'. $CFG->navsortmycoursessort.' ASC';
2010 } else {
2011 $sortorder = 'visible DESC,sortorder ASC';
2013 $courses = enrol_get_my_courses('summary, summaryformat', $sortorder);
2014 $rhosts = array();
2015 $rcourses = array();
2016 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2017 $rcourses = get_my_remotecourses($USER->id);
2018 $rhosts = get_my_remotehosts();
2021 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2023 $chelper = new coursecat_helper();
2024 if (count($courses) > $CFG->frontpagecourselimit) {
2025 // There are more enrolled courses than we can display, display link to 'My courses'.
2026 $totalcount = count($courses);
2027 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
2028 $chelper->set_courses_display_options(array(
2029 'viewmoreurl' => new moodle_url('/my/'),
2030 'viewmoretext' => new lang_string('mycourses')
2032 } else {
2033 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
2034 $chelper->set_courses_display_options(array(
2035 'viewmoreurl' => new moodle_url('/course/index.php'),
2036 'viewmoretext' => new lang_string('fulllistofcourses')
2038 $totalcount = $DB->count_records('course') - 1;
2040 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2041 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
2042 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
2044 // MNET
2045 if (!empty($rcourses)) {
2046 // at the IDP, we know of all the remote courses
2047 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2048 foreach ($rcourses as $course) {
2049 $output .= $this->frontpage_remote_course($course);
2051 $output .= html_writer::end_tag('div'); // .courses
2052 } elseif (!empty($rhosts)) {
2053 // non-IDP, we know of all the remote servers, but not courses
2054 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2055 foreach ($rhosts as $host) {
2056 $output .= $this->frontpage_remote_host($host);
2058 $output .= html_writer::end_tag('div'); // .courses
2061 return $output;
2065 * Returns HTML to print list of available courses for the frontpage
2067 * @return string
2069 public function frontpage_available_courses() {
2070 global $CFG;
2071 require_once($CFG->libdir. '/coursecatlib.php');
2073 $chelper = new coursecat_helper();
2074 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2075 set_courses_display_options(array(
2076 'recursive' => true,
2077 'limit' => $CFG->frontpagecourselimit,
2078 'viewmoreurl' => new moodle_url('/course/index.php'),
2079 'viewmoretext' => new lang_string('fulllistofcourses')));
2081 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
2082 $courses = coursecat::get(0)->get_courses($chelper->get_courses_display_options());
2083 $totalcount = coursecat::get(0)->get_courses_count($chelper->get_courses_display_options());
2084 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
2085 // Print link to create a new course, for the 1st available category.
2086 return $this->add_new_course_button();
2088 return $this->coursecat_courses($chelper, $courses, $totalcount);
2092 * Returns HTML to the "add new course" button for the page
2094 * @return string
2096 public function add_new_course_button() {
2097 global $CFG;
2098 // Print link to create a new course, for the 1st available category.
2099 $output = $this->container_start('buttons');
2100 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2101 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2102 $output .= $this->container_end('buttons');
2103 return $output;
2107 * Returns HTML to print tree with course categories and courses for the frontpage
2109 * @return string
2111 public function frontpage_combo_list() {
2112 global $CFG;
2113 require_once($CFG->libdir. '/coursecatlib.php');
2114 $chelper = new coursecat_helper();
2115 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2116 set_categories_display_options(array(
2117 'limit' => $CFG->coursesperpage,
2118 'viewmoreurl' => new moodle_url('/course/index.php',
2119 array('browse' => 'categories', 'page' => 1))
2120 ))->
2121 set_courses_display_options(array(
2122 'limit' => $CFG->coursesperpage,
2123 'viewmoreurl' => new moodle_url('/course/index.php',
2124 array('browse' => 'courses', 'page' => 1))
2125 ))->
2126 set_attributes(array('class' => 'frontpage-category-combo'));
2127 return $this->coursecat_tree($chelper, coursecat::get(0));
2131 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2133 * @return string
2135 public function frontpage_categories_list() {
2136 global $CFG;
2137 require_once($CFG->libdir. '/coursecatlib.php');
2138 $chelper = new coursecat_helper();
2139 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2140 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2141 set_categories_display_options(array(
2142 'limit' => $CFG->coursesperpage,
2143 'viewmoreurl' => new moodle_url('/course/index.php',
2144 array('browse' => 'categories', 'page' => 1))
2145 ))->
2146 set_attributes(array('class' => 'frontpage-category-names'));
2147 return $this->coursecat_tree($chelper, coursecat::get(0));
2152 * Class storing display options and functions to help display course category and/or courses lists
2154 * This is a wrapper for coursecat objects that also stores display options
2155 * and functions to retrieve sorted and paginated lists of categories/courses.
2157 * If theme overrides methods in core_course_renderers that access this class
2158 * it may as well not use this class at all or extend it.
2160 * @package core
2161 * @copyright 2013 Marina Glancy
2162 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2164 class coursecat_helper {
2165 /** @var string [none, collapsed, expanded] how (if) display courses list */
2166 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2167 /** @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) */
2168 protected $subcatdepth = 1;
2169 /** @var array options to display courses list */
2170 protected $coursesdisplayoptions = array();
2171 /** @var array options to display subcategories list */
2172 protected $categoriesdisplayoptions = array();
2173 /** @var array additional HTML attributes */
2174 protected $attributes = array();
2175 /** @var array search criteria if the list is a search result */
2176 protected $searchcriteria = null;
2179 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2181 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2182 * @return coursecat_helper
2184 public function set_show_courses($showcourses) {
2185 $this->showcourses = $showcourses;
2186 // Automatically set the options to preload summary and coursecontacts for coursecat::get_courses() and coursecat::search_courses()
2187 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2188 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2189 return $this;
2193 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2195 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2197 public function get_show_courses() {
2198 return $this->showcourses;
2202 * Sets the maximum depth to expand subcategories in the tree
2204 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2206 * @param int $subcatdepth
2207 * @return coursecat_helper
2209 public function set_subcat_depth($subcatdepth) {
2210 $this->subcatdepth = $subcatdepth;
2211 return $this;
2215 * Returns the maximum depth to expand subcategories in the tree
2217 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2219 * @return int
2221 public function get_subcat_depth() {
2222 return $this->subcatdepth;
2226 * Sets options to display list of courses
2228 * Options are later submitted as argument to coursecat::get_courses() and/or coursecat::search_courses()
2230 * Options that coursecat::get_courses() accept:
2231 * - recursive - return courses from subcategories as well. Use with care,
2232 * this may be a huge list!
2233 * - summary - preloads fields 'summary' and 'summaryformat'
2234 * - coursecontacts - preloads course contacts
2235 * - isenrolled - preloads indication whether this user is enrolled in the course
2236 * - sort - list of fields to sort. Example
2237 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2238 * will sort by idnumber asc, shortname asc and id desc.
2239 * Default: array('sortorder' => 1)
2240 * Only cached fields may be used for sorting!
2241 * - offset
2242 * - limit - maximum number of children to return, 0 or null for no limit
2244 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2246 * Also renderer can set here any additional options it wants to pass between renderer functions.
2248 * @param array $options
2249 * @return coursecat_helper
2251 public function set_courses_display_options($options) {
2252 $this->coursesdisplayoptions = $options;
2253 $this->set_show_courses($this->showcourses); // this will calculate special display options
2254 return $this;
2258 * Sets one option to display list of courses
2260 * @see coursecat_helper::set_courses_display_options()
2262 * @param string $key
2263 * @param mixed $value
2264 * @return coursecat_helper
2266 public function set_courses_display_option($key, $value) {
2267 $this->coursesdisplayoptions[$key] = $value;
2268 return $this;
2272 * Return the specified option to display list of courses
2274 * @param string $optionname option name
2275 * @param mixed $defaultvalue default value for option if it is not specified
2276 * @return mixed
2278 public function get_courses_display_option($optionname, $defaultvalue = null) {
2279 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2280 return $this->coursesdisplayoptions[$optionname];
2281 } else {
2282 return $defaultvalue;
2287 * Returns all options to display the courses
2289 * This array is usually passed to {@link coursecat::get_courses()} or
2290 * {@link coursecat::search_courses()}
2292 * @return array
2294 public function get_courses_display_options() {
2295 return $this->coursesdisplayoptions;
2299 * Sets options to display list of subcategories
2301 * Options 'sort', 'offset' and 'limit' are passed to coursecat::get_children().
2302 * Any other options may be used by renderer functions
2304 * @param array $options
2305 * @return coursecat_helper
2307 public function set_categories_display_options($options) {
2308 $this->categoriesdisplayoptions = $options;
2309 return $this;
2313 * Return the specified option to display list of subcategories
2315 * @param string $optionname option name
2316 * @param mixed $defaultvalue default value for option if it is not specified
2317 * @return mixed
2319 public function get_categories_display_option($optionname, $defaultvalue = null) {
2320 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2321 return $this->categoriesdisplayoptions[$optionname];
2322 } else {
2323 return $defaultvalue;
2328 * Returns all options to display list of subcategories
2330 * This array is usually passed to {@link coursecat::get_children()}
2332 * @return array
2334 public function get_categories_display_options() {
2335 return $this->categoriesdisplayoptions;
2339 * Sets additional general options to pass between renderer functions, usually HTML attributes
2341 * @param array $attributes
2342 * @return coursecat_helper
2344 public function set_attributes($attributes) {
2345 $this->attributes = $attributes;
2346 return $this;
2350 * Return all attributes and erases them so they are not applied again
2352 * @param string $classname adds additional class name to the beginning of $attributes['class']
2353 * @return array
2355 public function get_and_erase_attributes($classname) {
2356 $attributes = $this->attributes;
2357 $this->attributes = array();
2358 if (empty($attributes['class'])) {
2359 $attributes['class'] = '';
2361 $attributes['class'] = $classname . ' '. $attributes['class'];
2362 return $attributes;
2366 * Sets the search criteria if the course is a search result
2368 * Search string will be used to highlight terms in course name and description
2370 * @param array $searchcriteria
2371 * @return coursecat_helper
2373 public function set_search_criteria($searchcriteria) {
2374 $this->searchcriteria = $searchcriteria;
2375 return $this;
2379 * Returns formatted and filtered description of the given category
2381 * @param coursecat $coursecat category
2382 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2383 * if context is not specified it will be added automatically
2384 * @return string|null
2386 public function get_category_formatted_description($coursecat, $options = null) {
2387 if ($coursecat->id && !empty($coursecat->description)) {
2388 if (!isset($coursecat->descriptionformat)) {
2389 $descriptionformat = FORMAT_MOODLE;
2390 } else {
2391 $descriptionformat = $coursecat->descriptionformat;
2393 if ($options === null) {
2394 $options = array('noclean' => true, 'overflowdiv' => true);
2395 } else {
2396 $options = (array)$options;
2398 $context = context_coursecat::instance($coursecat->id);
2399 if (!isset($options['context'])) {
2400 $options['context'] = $context;
2402 $text = file_rewrite_pluginfile_urls($coursecat->description,
2403 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2404 return format_text($text, $descriptionformat, $options);
2406 return null;
2410 * Returns given course's summary with proper embedded files urls and formatted
2412 * @param course_in_list $course
2413 * @param array|stdClass $options additional formatting options
2414 * @return string
2416 public function get_course_formatted_summary($course, $options = array()) {
2417 global $CFG;
2418 require_once($CFG->libdir. '/filelib.php');
2419 if (!$course->has_summary()) {
2420 return '';
2422 $options = (array)$options;
2423 $context = context_course::instance($course->id);
2424 if (!isset($options['context'])) {
2425 // TODO see MDL-38521
2426 // option 1 (current), page context - no code required
2427 // option 2, system context
2428 // $options['context'] = context_system::instance();
2429 // option 3, course context:
2430 // $options['context'] = $context;
2431 // option 4, course category context:
2432 // $options['context'] = $context->get_parent_context();
2434 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2435 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2436 if (!empty($this->searchcriteria['search'])) {
2437 $summary = highlight($this->searchcriteria['search'], $summary);
2439 return $summary;
2443 * Returns course name as it is configured to appear in courses lists formatted to course context
2445 * @param course_in_list $course
2446 * @param array|stdClass $options additional formatting options
2447 * @return string
2449 public function get_course_formatted_name($course, $options = array()) {
2450 $options = (array)$options;
2451 if (!isset($options['context'])) {
2452 $options['context'] = context_course::instance($course->id);
2454 $name = format_string(get_course_display_name_for_list($course), true, $options);
2455 if (!empty($this->searchcriteria['search'])) {
2456 $name = highlight($this->searchcriteria['search'], $name);
2458 return $name;