Merge branch 'MDL-52018-28-enfix' of git://github.com/mudrd8mz/moodle into MOODLE_28_...
[moodle.git] / course / renderer.php
blob1f6456310a2947abe0dac0609b2cf895735239a2
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;
73 // Only needs to be done once per page.
74 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchoosertoggle')) {
75 return;
78 if ($this->page->state > moodle_page::STATE_PRINTING_HEADER ||
79 $this->page->course->id == SITEID ||
80 !$this->page->user_is_editing() ||
81 !($context = context_course::instance($this->page->course->id)) ||
82 !has_capability('moodle/course:manageactivities', $context) ||
83 !course_ajax_enabled($this->page->course) ||
84 !($coursenode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE)) ||
85 !($turneditingnode = $coursenode->get('turneditingonoff'))) {
86 // Too late, or we are on site page, or we could not find the
87 // adjacent nodes in course settings menu, or we are not allowed to edit.
88 return;
91 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
92 // We are on the course page, retain the current page params e.g. section.
93 $modchoosertoggleurl = clone($this->page->url);
94 } else {
95 // Edit on the main course page.
96 $modchoosertoggleurl = new moodle_url('/course/view.php', array('id' => $this->page->course->id,
97 'return' => $this->page->url->out_as_local_url(false)));
99 $modchoosertoggleurl->param('sesskey', sesskey());
100 if ($usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault)) {
101 $modchoosertogglestring = get_string('modchooserdisable', 'moodle');
102 $modchoosertoggleurl->param('modchooser', 'off');
103 } else {
104 $modchoosertogglestring = get_string('modchooserenable', 'moodle');
105 $modchoosertoggleurl->param('modchooser', 'on');
107 $modchoosertoggle = navigation_node::create($modchoosertogglestring, $modchoosertoggleurl, navigation_node::TYPE_SETTING, null, 'modchoosertoggle');
109 // Insert the modchoosertoggle after the settings node 'turneditingonoff' (navigation_node only has function to insert before, so we insert before and then swap).
110 $coursenode->add_node($modchoosertoggle, 'turneditingonoff');
111 $turneditingnode->remove();
112 $coursenode->add_node($turneditingnode, 'modchoosertoggle');
114 $modchoosertoggle->add_class('modchoosertoggle');
115 $modchoosertoggle->add_class('visibleifjs');
116 user_preference_allow_ajax_update('usemodchooser', PARAM_BOOL);
120 * Renders course info box.
122 * @param stdClass|course_in_list $course
123 * @return string
125 public function course_info_box(stdClass $course) {
126 $content = '';
127 $content .= $this->output->box_start('generalbox info');
128 $chelper = new coursecat_helper();
129 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
130 $content .= $this->coursecat_coursebox($chelper, $course);
131 $content .= $this->output->box_end();
132 return $content;
136 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
138 * @deprecated since 2.5
140 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
142 * @param array $ignored argument ignored
143 * @return string
145 public final function course_category_tree(array $ignored) {
146 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
147 return $this->frontpage_combo_list();
151 * Renderers a category for use with course_category_tree
153 * @deprecated since 2.5
155 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
157 * @param array $category
158 * @param int $depth
159 * @return string
161 protected final function course_category_tree_category(stdClass $category, $depth=1) {
162 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
163 return '';
167 * Build the HTML for the module chooser javascript popup
169 * @param array $modules A set of modules as returned form @see
170 * get_module_metadata
171 * @param object $course The course that will be displayed
172 * @return string The composed HTML for the module
174 public function course_modchooser($modules, $course) {
175 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchooser')) {
176 return '';
179 // Add the module chooser
180 $this->page->requires->yui_module('moodle-course-modchooser',
181 'M.course.init_chooser',
182 array(array('courseid' => $course->id, 'closeButtonTitle' => get_string('close', 'editor')))
184 $this->page->requires->strings_for_js(array(
185 'addresourceoractivity',
186 'modchooserenable',
187 'modchooserdisable',
188 ), 'moodle');
190 // Add the header
191 $header = html_writer::tag('div', get_string('addresourceoractivity', 'moodle'),
192 array('class' => 'hd choosertitle'));
194 $formcontent = html_writer::start_tag('form', array('action' => new moodle_url('/course/jumpto.php'),
195 'id' => 'chooserform', 'method' => 'post'));
196 $formcontent .= html_writer::start_tag('div', array('id' => 'typeformdiv'));
197 $formcontent .= html_writer::tag('input', '', array('type' => 'hidden', 'id' => 'course',
198 'name' => 'course', 'value' => $course->id));
199 $formcontent .= html_writer::tag('input', '', array('type' => 'hidden', 'name' => 'sesskey',
200 'value' => sesskey()));
201 $formcontent .= html_writer::end_tag('div');
203 // Put everything into one tag 'options'
204 $formcontent .= html_writer::start_tag('div', array('class' => 'options'));
205 $formcontent .= html_writer::tag('div', get_string('selectmoduletoviewhelp', 'moodle'),
206 array('class' => 'instruction'));
207 // Put all options into one tag 'alloptions' to allow us to handle scrolling
208 $formcontent .= html_writer::start_tag('div', array('class' => 'alloptions'));
210 // Activities
211 $activities = array_filter($modules, create_function('$mod', 'return ($mod->archetype !== MOD_ARCHETYPE_RESOURCE && $mod->archetype !== MOD_ARCHETYPE_SYSTEM);'));
212 if (count($activities)) {
213 $formcontent .= $this->course_modchooser_title('activities');
214 $formcontent .= $this->course_modchooser_module_types($activities);
217 // Resources
218 $resources = array_filter($modules, create_function('$mod', 'return ($mod->archetype === MOD_ARCHETYPE_RESOURCE);'));
219 if (count($resources)) {
220 $formcontent .= $this->course_modchooser_title('resources');
221 $formcontent .= $this->course_modchooser_module_types($resources);
224 $formcontent .= html_writer::end_tag('div'); // modoptions
225 $formcontent .= html_writer::end_tag('div'); // types
227 $formcontent .= html_writer::start_tag('div', array('class' => 'submitbuttons'));
228 $formcontent .= html_writer::tag('input', '',
229 array('type' => 'submit', 'name' => 'submitbutton', 'class' => 'submitbutton', 'value' => get_string('add')));
230 $formcontent .= html_writer::tag('input', '',
231 array('type' => 'submit', 'name' => 'addcancel', 'class' => 'addcancel', 'value' => get_string('cancel')));
232 $formcontent .= html_writer::end_tag('div');
233 $formcontent .= html_writer::end_tag('form');
235 // Wrap the whole form in a div
236 $formcontent = html_writer::tag('div', $formcontent, array('id' => 'chooseform'));
238 // Put all of the content together
239 $content = $formcontent;
241 $content = html_writer::tag('div', $content, array('class' => 'choosercontainer'));
242 return $header . html_writer::tag('div', $content, array('class' => 'chooserdialoguebody'));
246 * Build the HTML for a specified set of modules
248 * @param array $modules A set of modules as used by the
249 * course_modchooser_module function
250 * @return string The composed HTML for the module
252 protected function course_modchooser_module_types($modules) {
253 $return = '';
254 foreach ($modules as $module) {
255 if (!isset($module->types)) {
256 $return .= $this->course_modchooser_module($module);
257 } else {
258 $return .= $this->course_modchooser_module($module, array('nonoption'));
259 foreach ($module->types as $type) {
260 $return .= $this->course_modchooser_module($type, array('option', 'subtype'));
264 return $return;
268 * Return the HTML for the specified module adding any required classes
270 * @param object $module An object containing the title, and link. An
271 * icon, and help text may optionally be specified. If the module
272 * contains subtypes in the types option, then these will also be
273 * displayed.
274 * @param array $classes Additional classes to add to the encompassing
275 * div element
276 * @return string The composed HTML for the module
278 protected function course_modchooser_module($module, $classes = array('option')) {
279 $output = '';
280 $output .= html_writer::start_tag('div', array('class' => implode(' ', $classes)));
281 $output .= html_writer::start_tag('label', array('for' => 'module_' . $module->name));
282 if (!isset($module->types)) {
283 $output .= html_writer::tag('input', '', array('type' => 'radio',
284 'name' => 'jumplink', 'id' => 'module_' . $module->name, 'value' => $module->link));
287 $output .= html_writer::start_tag('span', array('class' => 'modicon'));
288 if (isset($module->icon)) {
289 // Add an icon if we have one
290 $output .= $module->icon;
292 $output .= html_writer::end_tag('span');
294 $output .= html_writer::tag('span', $module->title, array('class' => 'typename'));
295 if (!isset($module->help)) {
296 // Add help if found
297 $module->help = get_string('nohelpforactivityorresource', 'moodle');
300 // Format the help text using markdown with the following options
301 $options = new stdClass();
302 $options->trusted = false;
303 $options->noclean = false;
304 $options->smiley = false;
305 $options->filter = false;
306 $options->para = true;
307 $options->newlines = false;
308 $options->overflowdiv = false;
309 $module->help = format_text($module->help, FORMAT_MARKDOWN, $options);
310 $output .= html_writer::tag('span', $module->help, array('class' => 'typesummary'));
311 $output .= html_writer::end_tag('label');
312 $output .= html_writer::end_tag('div');
314 return $output;
317 protected function course_modchooser_title($title, $identifier = null) {
318 $module = new stdClass();
319 $module->name = $title;
320 $module->types = array();
321 $module->title = get_string($title, $identifier);
322 $module->help = '';
323 return $this->course_modchooser_module($module, array('moduletypetitle'));
327 * Renders HTML for displaying the sequence of course module editing buttons
329 * @see course_get_cm_edit_actions()
331 * @param action_link[] $actions Array of action_link objects
332 * @param cm_info $mod The module we are displaying actions for.
333 * @param array $displayoptions additional display options:
334 * ownerselector => A JS/CSS selector that can be used to find an cm node.
335 * If specified the owning node will be given the class 'action-menu-shown' when the action
336 * menu is being displayed.
337 * constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
338 * the action menu to when it is being displayed.
339 * donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
340 * @return string
342 public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
343 global $CFG;
345 if (empty($actions)) {
346 return '';
349 if (isset($displayoptions['ownerselector'])) {
350 $ownerselector = $displayoptions['ownerselector'];
351 } else if ($mod) {
352 $ownerselector = '#module-'.$mod->id;
353 } else {
354 debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
355 $ownerselector = 'li.activity';
358 if (isset($displayoptions['constraintselector'])) {
359 $constraint = $displayoptions['constraintselector'];
360 } else {
361 $constraint = '.course-content';
364 $menu = new action_menu();
365 $menu->set_owner_selector($ownerselector);
366 $menu->set_constraint($constraint);
367 $menu->set_alignment(action_menu::TR, action_menu::BR);
368 $menu->set_menu_trigger(get_string('edit'));
369 if (isset($CFG->modeditingmenu) && !$CFG->modeditingmenu || !empty($displayoptions['donotenhance'])) {
370 $menu->do_not_enhance();
372 // Swap the left/right icons.
373 // Normally we have have right, then left but this does not
374 // make sense when modactionmenu is disabled.
375 $moveright = null;
376 $_actions = array();
377 foreach ($actions as $key => $value) {
378 if ($key === 'moveright') {
380 // Save moveright for later.
381 $moveright = $value;
382 } else if ($moveright) {
384 // This assumes that the order was moveright, moveleft.
385 // If we have a moveright, then we should place it immediately after the current value.
386 $_actions[$key] = $value;
387 $_actions['moveright'] = $moveright;
389 // Clear the value to prevent it being used multiple times.
390 $moveright = null;
391 } else {
393 $_actions[$key] = $value;
396 $actions = $_actions;
397 unset($_actions);
399 foreach ($actions as $action) {
400 if ($action instanceof action_menu_link) {
401 $action->add_class('cm-edit-action');
403 $menu->add($action);
405 $menu->attributes['class'] .= ' section-cm-edit-actions commands';
407 // Prioritise the menu ahead of all other actions.
408 $menu->prioritise = true;
410 return $this->render($menu);
414 * Renders HTML for the menus to add activities and resources to the current course
416 * Note, if theme overwrites this function and it does not use modchooser,
417 * see also {@link core_course_renderer::add_modchoosertoggle()}
419 * @param stdClass $course
420 * @param int $section relative section number (field course_sections.section)
421 * @param int $sectionreturn The section to link back to
422 * @param array $displayoptions additional display options, for example blocks add
423 * option 'inblock' => true, suggesting to display controls vertically
424 * @return string
426 function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
427 global $CFG;
429 $vertical = !empty($displayoptions['inblock']);
431 // check to see if user can add menus and there are modules to add
432 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
433 || !$this->page->user_is_editing()
434 || !($modnames = get_module_types_names()) || empty($modnames)) {
435 return '';
438 // Retrieve all modules with associated metadata
439 $modules = get_module_metadata($course, $modnames, $sectionreturn);
440 $urlparams = array('section' => $section);
442 // We'll sort resources and activities into two lists
443 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
445 foreach ($modules as $module) {
446 if (isset($module->types)) {
447 // This module has a subtype
448 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
449 $subtypes = array();
450 foreach ($module->types as $subtype) {
451 $link = $subtype->link->out(true, $urlparams);
452 $subtypes[$link] = $subtype->title;
455 // Sort module subtypes into the list
456 $activityclass = MOD_CLASS_ACTIVITY;
457 if ($module->archetype == MOD_CLASS_RESOURCE) {
458 $activityclass = MOD_CLASS_RESOURCE;
460 if (!empty($module->title)) {
461 // This grouping has a name
462 $activities[$activityclass][] = array($module->title => $subtypes);
463 } else {
464 // This grouping does not have a name
465 $activities[$activityclass] = array_merge($activities[$activityclass], $subtypes);
467 } else {
468 // This module has no subtypes
469 $activityclass = MOD_CLASS_ACTIVITY;
470 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
471 $activityclass = MOD_CLASS_RESOURCE;
472 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
473 // System modules cannot be added by user, do not add to dropdown
474 continue;
476 $link = $module->link->out(true, $urlparams);
477 $activities[$activityclass][$link] = $module->title;
481 $straddactivity = get_string('addactivity');
482 $straddresource = get_string('addresource');
483 $sectionname = get_section_name($course, $section);
484 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
485 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
487 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
489 if (!$vertical) {
490 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
493 if (!empty($activities[MOD_CLASS_RESOURCE])) {
494 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array(''=>$straddresource), "ressection$section");
495 $select->set_help_icon('resources');
496 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
497 $output .= $this->output->render($select);
500 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
501 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array(''=>$straddactivity), "section$section");
502 $select->set_help_icon('activities');
503 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
504 $output .= $this->output->render($select);
507 if (!$vertical) {
508 $output .= html_writer::end_tag('div');
511 $output .= html_writer::end_tag('div');
513 if (course_ajax_enabled($course) && $course->id == $this->page->course->id) {
514 // modchooser can be added only for the current course set on the page!
515 $straddeither = get_string('addresourceoractivity');
516 // The module chooser link
517 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
518 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
519 $icon = $this->output->pix_icon('t/add', '');
520 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
521 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
522 $modchooser.= html_writer::end_tag('div');
523 $modchooser.= html_writer::end_tag('div');
525 // Wrap the normal output in a noscript div
526 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
527 if ($usemodchooser) {
528 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
529 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
530 } else {
531 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
532 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
533 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
535 $output = $this->course_modchooser($modules, $course) . $modchooser . $output;
538 return $output;
542 * Renders html to display a course search form
544 * @param string $value default value to populate the search field
545 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
546 * @return string
548 function course_search_form($value = '', $format = 'plain') {
549 static $count = 0;
550 $formid = 'coursesearch';
551 if ((++$count) > 1) {
552 $formid .= $count;
555 switch ($format) {
556 case 'navbar' :
557 $formid = 'coursesearchnavbar';
558 $inputid = 'navsearchbox';
559 $inputsize = 20;
560 break;
561 case 'short' :
562 $inputid = 'shortsearchbox';
563 $inputsize = 12;
564 break;
565 default :
566 $inputid = 'coursesearchbox';
567 $inputsize = 30;
570 $strsearchcourses= get_string("searchcourses");
571 $searchurl = new moodle_url('/course/search.php');
573 $output = html_writer::start_tag('form', array('id' => $formid, 'action' => $searchurl, 'method' => 'get'));
574 $output .= html_writer::start_tag('fieldset', array('class' => 'coursesearchbox invisiblefieldset'));
575 $output .= html_writer::tag('label', $strsearchcourses.': ', array('for' => $inputid));
576 $output .= html_writer::empty_tag('input', array('type' => 'text', 'id' => $inputid,
577 'size' => $inputsize, 'name' => 'search', 'value' => s($value)));
578 $output .= html_writer::empty_tag('input', array('type' => 'submit',
579 'value' => get_string('go')));
580 $output .= html_writer::end_tag('fieldset');
581 $output .= html_writer::end_tag('form');
583 return $output;
587 * Renders html for completion box on course page
589 * If completion is disabled, returns empty string
590 * If completion is automatic, returns an icon of the current completion state
591 * If completion is manual, returns a form (with an icon inside) that allows user to
592 * toggle completion
594 * @param stdClass $course course object
595 * @param completion_info $completioninfo completion info for the course, it is recommended
596 * to fetch once for all modules in course/section for performance
597 * @param cm_info $mod module to show completion for
598 * @param array $displayoptions display options, not used in core
599 * @return string
601 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
602 global $CFG;
603 $output = '';
604 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
605 return $output;
607 if ($completioninfo === null) {
608 $completioninfo = new completion_info($course);
610 $completion = $completioninfo->is_enabled($mod);
611 if ($completion == COMPLETION_TRACKING_NONE) {
612 if ($this->page->user_is_editing()) {
613 $output .= html_writer::span('&nbsp;', 'filler');
615 return $output;
618 $completiondata = $completioninfo->get_data($mod, true);
619 $completionicon = '';
621 if ($this->page->user_is_editing()) {
622 switch ($completion) {
623 case COMPLETION_TRACKING_MANUAL :
624 $completionicon = 'manual-enabled'; break;
625 case COMPLETION_TRACKING_AUTOMATIC :
626 $completionicon = 'auto-enabled'; break;
628 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
629 switch($completiondata->completionstate) {
630 case COMPLETION_INCOMPLETE:
631 $completionicon = 'manual-n'; break;
632 case COMPLETION_COMPLETE:
633 $completionicon = 'manual-y'; break;
635 } else { // Automatic
636 switch($completiondata->completionstate) {
637 case COMPLETION_INCOMPLETE:
638 $completionicon = 'auto-n'; break;
639 case COMPLETION_COMPLETE:
640 $completionicon = 'auto-y'; break;
641 case COMPLETION_COMPLETE_PASS:
642 $completionicon = 'auto-pass'; break;
643 case COMPLETION_COMPLETE_FAIL:
644 $completionicon = 'auto-fail'; break;
647 if ($completionicon) {
648 $formattedname = $mod->get_formatted_name();
649 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
651 if ($this->page->user_is_editing()) {
652 // When editing, the icon is just an image.
653 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
654 array('title' => $imgalt, 'class' => 'iconsmall'));
655 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
656 array('class' => 'autocompletion'));
657 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
658 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
659 $newstate =
660 $completiondata->completionstate == COMPLETION_COMPLETE
661 ? COMPLETION_INCOMPLETE
662 : COMPLETION_COMPLETE;
663 // In manual mode the icon is a toggle form...
665 // If this completion state is used by the
666 // conditional activities system, we need to turn
667 // off the JS.
668 $extraclass = '';
669 if (!empty($CFG->enableavailability) &&
670 core_availability\info::completion_value_used($course, $mod->id)) {
671 $extraclass = ' preventjs';
673 $output .= html_writer::start_tag('form', array('method' => 'post',
674 'action' => new moodle_url('/course/togglecompletion.php'),
675 'class' => 'togglecompletion'. $extraclass));
676 $output .= html_writer::start_tag('div');
677 $output .= html_writer::empty_tag('input', array(
678 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
679 $output .= html_writer::empty_tag('input', array(
680 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
681 $output .= html_writer::empty_tag('input', array(
682 'type' => 'hidden', 'name' => 'modulename', 'value' => $mod->name));
683 $output .= html_writer::empty_tag('input', array(
684 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
685 $output .= html_writer::empty_tag('input', array(
686 'type' => 'image',
687 'src' => $this->output->pix_url('i/completion-'.$completionicon),
688 'alt' => $imgalt, 'title' => $imgtitle,
689 'aria-live' => 'polite'));
690 $output .= html_writer::end_tag('div');
691 $output .= html_writer::end_tag('form');
692 } else {
693 // In auto mode, the icon is just an image.
694 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
695 array('title' => $imgalt));
696 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
697 array('class' => 'autocompletion'));
700 return $output;
704 * Checks if course module has any conditions that may make it unavailable for
705 * all or some of the students
707 * This function is internal and is only used to create CSS classes for the module name/text
709 * @param cm_info $mod
710 * @return bool
712 protected function is_cm_conditionally_hidden(cm_info $mod) {
713 global $CFG;
714 $conditionalhidden = false;
715 if (!empty($CFG->enableavailability)) {
716 $info = new \core_availability\info_module($mod);
717 $conditionalhidden = !$info->is_available_for_all();
719 return $conditionalhidden;
723 * Renders html to display a name with the link to the course module on a course page
725 * If module is unavailable for user but still needs to be displayed
726 * in the list, just the name is returned without a link
728 * Note, that for course modules that never have separate pages (i.e. labels)
729 * this function return an empty string
731 * @param cm_info $mod
732 * @param array $displayoptions
733 * @return string
735 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
736 global $CFG;
737 $output = '';
738 if (!$mod->uservisible && empty($mod->availableinfo)) {
739 // nothing to be displayed to the user
740 return $output;
742 $url = $mod->url;
743 if (!$url) {
744 return $output;
747 //Accessibility: for files get description via icon, this is very ugly hack!
748 $instancename = $mod->get_formatted_name();
749 $altname = $mod->modfullname;
750 // Avoid unnecessary duplication: if e.g. a forum name already
751 // includes the word forum (or Forum, etc) then it is unhelpful
752 // to include that in the accessible description that is added.
753 if (false !== strpos(core_text::strtolower($instancename),
754 core_text::strtolower($altname))) {
755 $altname = '';
757 // File type after name, for alphabetic lists (screen reader).
758 if ($altname) {
759 $altname = get_accesshide(' '.$altname);
762 // For items which are hidden but available to current user
763 // ($mod->uservisible), we show those as dimmed only if the user has
764 // viewhiddenactivities, so that teachers see 'items which might not
765 // be available to some students' dimmed but students do not see 'item
766 // which is actually available to current student' dimmed.
767 $linkclasses = '';
768 $accesstext = '';
769 $textclasses = '';
770 if ($mod->uservisible) {
771 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
772 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
773 has_capability('moodle/course:viewhiddenactivities', $mod->context);
774 if ($accessiblebutdim) {
775 $linkclasses .= ' dimmed';
776 $textclasses .= ' dimmed_text';
777 if ($conditionalhidden) {
778 $linkclasses .= ' conditionalhidden';
779 $textclasses .= ' conditionalhidden';
781 // Show accessibility note only if user can access the module himself.
782 $accesstext = get_accesshide(get_string('hiddenfromstudents').':'. $mod->modfullname);
784 } else {
785 $linkclasses .= ' dimmed';
786 $textclasses .= ' dimmed_text';
789 // Get on-click attribute value if specified and decode the onclick - it
790 // has already been encoded for display (puke).
791 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
793 $groupinglabel = $mod->get_grouping_label($textclasses);
795 // Display link itself.
796 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
797 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) . $accesstext .
798 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
799 if ($mod->uservisible) {
800 $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick)) .
801 $groupinglabel;
802 } else {
803 // We may be displaying this just in order to show information
804 // about visibility, without the actual link ($mod->uservisible)
805 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses)) .
806 $groupinglabel;
808 return $output;
812 * Renders html to display the module content on the course page (i.e. text of the labels)
814 * @param cm_info $mod
815 * @param array $displayoptions
816 * @return string
818 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
819 $output = '';
820 if (!$mod->uservisible && empty($mod->availableinfo)) {
821 // nothing to be displayed to the user
822 return $output;
824 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
825 $accesstext = '';
826 $textclasses = '';
827 if ($mod->uservisible) {
828 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
829 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
830 has_capability('moodle/course:viewhiddenactivities', $mod->context);
831 if ($accessiblebutdim) {
832 $textclasses .= ' dimmed_text';
833 if ($conditionalhidden) {
834 $textclasses .= ' conditionalhidden';
836 // Show accessibility note only if user can access the module himself.
837 $accesstext = get_accesshide(get_string('hiddenfromstudents').':'. $mod->modfullname);
839 } else {
840 $textclasses .= ' dimmed_text';
842 if ($mod->url) {
843 if ($content) {
844 // If specified, display extra content after link.
845 $output = html_writer::tag('div', $content, array('class' =>
846 trim('contentafterlink ' . $textclasses)));
848 } else {
849 $groupinglabel = $mod->get_grouping_label($textclasses);
851 // No link, so display only content.
852 $output = html_writer::tag('div', $accesstext . $content . $groupinglabel,
853 array('class' => 'contentwithoutlink ' . $textclasses));
855 return $output;
859 * Renders HTML to show course module availability information (for someone who isn't allowed
860 * to see the activity itself, or for staff)
862 * @param cm_info $mod
863 * @param array $displayoptions
864 * @return string
866 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
867 global $CFG;
868 if (!$mod->uservisible) {
869 // this is a student who is not allowed to see the module but might be allowed
870 // to see availability info (i.e. "Available from ...")
871 if (!empty($mod->availableinfo)) {
872 $formattedinfo = \core_availability\info::format_info(
873 $mod->availableinfo, $mod->get_course());
874 $output = html_writer::tag('div', $formattedinfo, array('class' => 'availabilityinfo'));
876 return $output;
878 // this is a teacher who is allowed to see module but still should see the
879 // information that module is not available to all/some students
880 $modcontext = context_module::instance($mod->id);
881 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
882 if ($canviewhidden && !empty($CFG->enableavailability)) {
883 // Don't add availability information if user is not editing and activity is hidden.
884 if ($mod->visible || $this->page->user_is_editing()) {
885 $hidinfoclass = '';
886 if (!$mod->visible) {
887 $hidinfoclass = 'hide';
889 $ci = new \core_availability\info_module($mod);
890 $fullinfo = $ci->get_full_information();
891 if ($fullinfo) {
892 $formattedinfo = \core_availability\info::format_info(
893 $fullinfo, $mod->get_course());
894 return html_writer::div($formattedinfo, 'availabilityinfo ' . $hidinfoclass);
898 return '';
902 * Renders HTML to display one course module for display within a section.
904 * This function calls:
905 * {@link core_course_renderer::course_section_cm()}
907 * @param stdClass $course
908 * @param completion_info $completioninfo
909 * @param cm_info $mod
910 * @param int|null $sectionreturn
911 * @param array $displayoptions
912 * @return String
914 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
915 $output = '';
916 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
917 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
918 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
920 return $output;
924 * Renders HTML to display one course module in a course section
926 * This includes link, content, availability, completion info and additional information
927 * that module type wants to display (i.e. number of unread forum posts)
929 * This function calls:
930 * {@link core_course_renderer::course_section_cm_name()}
931 * {@link core_course_renderer::course_section_cm_text()}
932 * {@link core_course_renderer::course_section_cm_availability()}
933 * {@link core_course_renderer::course_section_cm_completion()}
934 * {@link course_get_cm_edit_actions()}
935 * {@link core_course_renderer::course_section_cm_edit_actions()}
937 * @param stdClass $course
938 * @param completion_info $completioninfo
939 * @param cm_info $mod
940 * @param int|null $sectionreturn
941 * @param array $displayoptions
942 * @return string
944 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
945 $output = '';
946 // We return empty string (because course module will not be displayed at all)
947 // if:
948 // 1) The activity is not visible to users
949 // and
950 // 2) The 'availableinfo' is empty, i.e. the activity was
951 // hidden in a way that leaves no info, such as using the
952 // eye icon.
953 if (!$mod->uservisible && empty($mod->availableinfo)) {
954 return $output;
957 $indentclasses = 'mod-indent';
958 if (!empty($mod->indent)) {
959 $indentclasses .= ' mod-indent-'.$mod->indent;
960 if ($mod->indent > 15) {
961 $indentclasses .= ' mod-indent-huge';
965 $output .= html_writer::start_tag('div');
967 if ($this->page->user_is_editing()) {
968 $output .= course_get_cm_move($mod, $sectionreturn);
971 $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer'));
973 // This div is used to indent the content.
974 $output .= html_writer::div('', $indentclasses);
976 // Start a wrapper for the actual content to keep the indentation consistent
977 $output .= html_writer::start_tag('div');
979 // Display the link to the module (or do nothing if module has no url)
980 $cmname = $this->course_section_cm_name($mod, $displayoptions);
982 if (!empty($cmname)) {
983 // Start the div for the activity title, excluding the edit icons.
984 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
985 $output .= $cmname;
988 if ($this->page->user_is_editing()) {
989 $output .= ' ' . course_get_cm_rename_action($mod, $sectionreturn);
992 // Module can put text after the link (e.g. forum unread)
993 $output .= $mod->afterlink;
995 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
996 $output .= html_writer::end_tag('div'); // .activityinstance
999 // If there is content but NO link (eg label), then display the
1000 // content here (BEFORE any icons). In this case cons must be
1001 // displayed after the content so that it makes more sense visually
1002 // and for accessibility reasons, e.g. if you have a one-line label
1003 // it should work similarly (at least in terms of ordering) to an
1004 // activity.
1005 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
1006 $url = $mod->url;
1007 if (empty($url)) {
1008 $output .= $contentpart;
1011 $modicons = '';
1012 if ($this->page->user_is_editing()) {
1013 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
1014 $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
1015 $modicons .= $mod->afterediticons;
1018 $modicons .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
1020 if (!empty($modicons)) {
1021 $output .= html_writer::span($modicons, 'actions');
1024 // If there is content AND a link, then display the content here
1025 // (AFTER any icons). Otherwise it was displayed before
1026 if (!empty($url)) {
1027 $output .= $contentpart;
1030 // show availability info (if module is not available)
1031 $output .= $this->course_section_cm_availability($mod, $displayoptions);
1033 $output .= html_writer::end_tag('div'); // $indentclasses
1035 // End of indentation div.
1036 $output .= html_writer::end_tag('div');
1038 $output .= html_writer::end_tag('div');
1039 return $output;
1043 * Renders HTML to display a list of course modules in a course section
1044 * Also displays "move here" controls in Javascript-disabled mode
1046 * This function calls {@link core_course_renderer::course_section_cm()}
1048 * @param stdClass $course course object
1049 * @param int|stdClass|section_info $section relative section number or section object
1050 * @param int $sectionreturn section number to return to
1051 * @param int $displayoptions
1052 * @return void
1054 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
1055 global $USER;
1057 $output = '';
1058 $modinfo = get_fast_modinfo($course);
1059 if (is_object($section)) {
1060 $section = $modinfo->get_section_info($section->section);
1061 } else {
1062 $section = $modinfo->get_section_info($section);
1064 $completioninfo = new completion_info($course);
1066 // check if we are currently in the process of moving a module with JavaScript disabled
1067 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
1068 if ($ismoving) {
1069 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
1070 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1073 // Get the list of modules visible to user (excluding the module being moved if there is one)
1074 $moduleshtml = array();
1075 if (!empty($modinfo->sections[$section->section])) {
1076 foreach ($modinfo->sections[$section->section] as $modnumber) {
1077 $mod = $modinfo->cms[$modnumber];
1079 if ($ismoving and $mod->id == $USER->activitycopy) {
1080 // do not display moving mod
1081 continue;
1084 if ($modulehtml = $this->course_section_cm_list_item($course,
1085 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
1086 $moduleshtml[$modnumber] = $modulehtml;
1091 $sectionoutput = '';
1092 if (!empty($moduleshtml) || $ismoving) {
1093 foreach ($moduleshtml as $modnumber => $modulehtml) {
1094 if ($ismoving) {
1095 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
1096 $sectionoutput .= html_writer::tag('li',
1097 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1098 array('class' => 'movehere'));
1101 $sectionoutput .= $modulehtml;
1104 if ($ismoving) {
1105 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1106 $sectionoutput .= html_writer::tag('li',
1107 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1108 array('class' => 'movehere'));
1112 // Always output the section module list.
1113 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1115 return $output;
1119 * Displays a custom list of courses with paging bar if necessary
1121 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1122 * appears under the list.
1124 * If both $paginationurl and $totalcount are specified, and $totalcount is
1125 * bigger than count($courses), a paging bar is displayed above and under the
1126 * courses list.
1128 * @param array $courses array of course records (or instances of course_in_list) to show on this page
1129 * @param bool $showcategoryname whether to add category name to the course description
1130 * @param string $additionalclasses additional CSS classes to add to the div.courses
1131 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1132 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1133 * @param int $page current page number (defaults to 0 referring to the first page)
1134 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1135 * @return string
1137 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1138 global $CFG;
1139 // create instance of coursecat_helper to pass display options to function rendering courses list
1140 $chelper = new coursecat_helper();
1141 if ($showcategoryname) {
1142 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1143 } else {
1144 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1146 if ($totalcount !== null && $paginationurl !== null) {
1147 // add options to display pagination
1148 if ($perpage === null) {
1149 $perpage = $CFG->coursesperpage;
1151 $chelper->set_courses_display_options(array(
1152 'limit' => $perpage,
1153 'offset' => ((int)$page) * $perpage,
1154 'paginationurl' => $paginationurl,
1156 } else if ($paginationurl !== null) {
1157 // add options to display 'View more' link
1158 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1159 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1161 $chelper->set_attributes(array('class' => $additionalclasses));
1162 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1163 return $content;
1167 * Displays one course in the list of courses.
1169 * This is an internal function, to display an information about just one course
1170 * please use {@link core_course_renderer::course_info_box()}
1172 * @param coursecat_helper $chelper various display options
1173 * @param course_in_list|stdClass $course
1174 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1175 * depend on the course position in list - first/last/even/odd)
1176 * @return string
1178 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1179 global $CFG;
1180 if (!isset($this->strings->summary)) {
1181 $this->strings->summary = get_string('summary');
1183 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1184 return '';
1186 if ($course instanceof stdClass) {
1187 require_once($CFG->libdir. '/coursecatlib.php');
1188 $course = new course_in_list($course);
1190 $content = '';
1191 $classes = trim('coursebox clearfix '. $additionalclasses);
1192 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1193 $nametag = 'h3';
1194 } else {
1195 $classes .= ' collapsed';
1196 $nametag = 'div';
1199 // .coursebox
1200 $content .= html_writer::start_tag('div', array(
1201 'class' => $classes,
1202 'data-courseid' => $course->id,
1203 'data-type' => self::COURSECAT_TYPE_COURSE,
1206 $content .= html_writer::start_tag('div', array('class' => 'info'));
1208 // course name
1209 $coursename = $chelper->get_course_formatted_name($course);
1210 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', array('id' => $course->id)),
1211 $coursename, array('class' => $course->visible ? '' : 'dimmed'));
1212 $content .= html_writer::tag($nametag, $coursenamelink, array('class' => 'coursename'));
1213 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1214 $content .= html_writer::start_tag('div', array('class' => 'moreinfo'));
1215 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1216 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()) {
1217 $url = new moodle_url('/course/info.php', array('id' => $course->id));
1218 $image = html_writer::empty_tag('img', array('src' => $this->output->pix_url('i/info'),
1219 'alt' => $this->strings->summary));
1220 $content .= html_writer::link($url, $image, array('title' => $this->strings->summary));
1221 // Make sure JS file to expand course content is included.
1222 $this->coursecat_include_js();
1225 $content .= html_writer::end_tag('div'); // .moreinfo
1227 // print enrolmenticons
1228 if ($icons = enrol_get_course_info_icons($course)) {
1229 $content .= html_writer::start_tag('div', array('class' => 'enrolmenticons'));
1230 foreach ($icons as $pix_icon) {
1231 $content .= $this->render($pix_icon);
1233 $content .= html_writer::end_tag('div'); // .enrolmenticons
1236 $content .= html_writer::end_tag('div'); // .info
1238 $content .= html_writer::start_tag('div', array('class' => 'content'));
1239 $content .= $this->coursecat_coursebox_content($chelper, $course);
1240 $content .= html_writer::end_tag('div'); // .content
1242 $content .= html_writer::end_tag('div'); // .coursebox
1243 return $content;
1247 * Returns HTML to display course content (summary, course contacts and optionally category name)
1249 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1251 * @param coursecat_helper $chelper various display options
1252 * @param stdClass|course_in_list $course
1253 * @return string
1255 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1256 global $CFG;
1257 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1258 return '';
1260 if ($course instanceof stdClass) {
1261 require_once($CFG->libdir. '/coursecatlib.php');
1262 $course = new course_in_list($course);
1264 $content = '';
1266 // display course summary
1267 if ($course->has_summary()) {
1268 $content .= html_writer::start_tag('div', array('class' => 'summary'));
1269 $content .= $chelper->get_course_formatted_summary($course,
1270 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1271 $content .= html_writer::end_tag('div'); // .summary
1274 // display course overview files
1275 $contentimages = $contentfiles = '';
1276 foreach ($course->get_course_overviewfiles() as $file) {
1277 $isimage = $file->is_valid_image();
1278 $url = file_encode_url("$CFG->wwwroot/pluginfile.php",
1279 '/'. $file->get_contextid(). '/'. $file->get_component(). '/'.
1280 $file->get_filearea(). $file->get_filepath(). $file->get_filename(), !$isimage);
1281 if ($isimage) {
1282 $contentimages .= html_writer::tag('div',
1283 html_writer::empty_tag('img', array('src' => $url)),
1284 array('class' => 'courseimage'));
1285 } else {
1286 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1287 $filename = html_writer::tag('span', $image, array('class' => 'fp-icon')).
1288 html_writer::tag('span', $file->get_filename(), array('class' => 'fp-filename'));
1289 $contentfiles .= html_writer::tag('span',
1290 html_writer::link($url, $filename),
1291 array('class' => 'coursefile fp-filename-icon'));
1294 $content .= $contentimages. $contentfiles;
1296 // display course contacts. See course_in_list::get_course_contacts()
1297 if ($course->has_course_contacts()) {
1298 $content .= html_writer::start_tag('ul', array('class' => 'teachers'));
1299 foreach ($course->get_course_contacts() as $userid => $coursecontact) {
1300 $name = $coursecontact['rolename'].': '.
1301 html_writer::link(new moodle_url('/user/view.php',
1302 array('id' => $userid, 'course' => SITEID)),
1303 $coursecontact['username']);
1304 $content .= html_writer::tag('li', $name);
1306 $content .= html_writer::end_tag('ul'); // .teachers
1309 // display course category if necessary (for example in search results)
1310 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1311 require_once($CFG->libdir. '/coursecatlib.php');
1312 if ($cat = coursecat::get($course->category, IGNORE_MISSING)) {
1313 $content .= html_writer::start_tag('div', array('class' => 'coursecat'));
1314 $content .= get_string('category').': '.
1315 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1316 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1317 $content .= html_writer::end_tag('div'); // .coursecat
1321 return $content;
1325 * Renders the list of courses
1327 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1328 * method from outside of the class
1330 * If list of courses is specified in $courses; the argument $chelper is only used
1331 * to retrieve display options and attributes, only methods get_show_courses(),
1332 * get_courses_display_option() and get_and_erase_attributes() are called.
1334 * @param coursecat_helper $chelper various display options
1335 * @param array $courses the list of courses to display
1336 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1337 * defaulted to count($courses)
1338 * @return string
1340 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1341 global $CFG;
1342 if ($totalcount === null) {
1343 $totalcount = count($courses);
1345 if (!$totalcount) {
1346 // Courses count is cached during courses retrieval.
1347 return '';
1350 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1351 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1352 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1353 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1354 } else {
1355 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1359 // prepare content of paging bar if it is needed
1360 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1361 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1362 if ($totalcount > count($courses)) {
1363 // there are more results that can fit on one page
1364 if ($paginationurl) {
1365 // the option paginationurl was specified, display pagingbar
1366 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1367 $page = $chelper->get_courses_display_option('offset') / $perpage;
1368 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1369 $paginationurl->out(false, array('perpage' => $perpage)));
1370 if ($paginationallowall) {
1371 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1372 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1374 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1375 // the option for 'View more' link was specified, display more link
1376 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1377 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1378 array('class' => 'paging paging-morelink'));
1380 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1381 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1382 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1383 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1386 // display list of courses
1387 $attributes = $chelper->get_and_erase_attributes('courses');
1388 $content = html_writer::start_tag('div', $attributes);
1390 if (!empty($pagingbar)) {
1391 $content .= $pagingbar;
1394 $coursecount = 0;
1395 foreach ($courses as $course) {
1396 $coursecount ++;
1397 $classes = ($coursecount%2) ? 'odd' : 'even';
1398 if ($coursecount == 1) {
1399 $classes .= ' first';
1401 if ($coursecount >= count($courses)) {
1402 $classes .= ' last';
1404 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1407 if (!empty($pagingbar)) {
1408 $content .= $pagingbar;
1410 if (!empty($morelink)) {
1411 $content .= $morelink;
1414 $content .= html_writer::end_tag('div'); // .courses
1415 return $content;
1419 * Renders the list of subcategories in a category
1421 * @param coursecat_helper $chelper various display options
1422 * @param coursecat $coursecat
1423 * @param int $depth depth of the category in the current tree
1424 * @return string
1426 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1427 global $CFG;
1428 $subcategories = array();
1429 if (!$chelper->get_categories_display_option('nodisplay')) {
1430 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1432 $totalcount = $coursecat->get_children_count();
1433 if (!$totalcount) {
1434 // Note that we call get_child_categories_count() AFTER get_child_categories() to avoid extra DB requests.
1435 // Categories count is cached during children categories retrieval.
1436 return '';
1439 // prepare content of paging bar or more link if it is needed
1440 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1441 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1442 if ($totalcount > count($subcategories)) {
1443 if ($paginationurl) {
1444 // the option 'paginationurl was specified, display pagingbar
1445 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1446 $page = $chelper->get_categories_display_option('offset') / $perpage;
1447 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1448 $paginationurl->out(false, array('perpage' => $perpage)));
1449 if ($paginationallowall) {
1450 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1451 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1453 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1454 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1455 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1456 $viewmoreurl->param('categoryid', $coursecat->id);
1458 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1459 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1460 array('class' => 'paging paging-morelink'));
1462 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1463 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1464 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1465 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1468 // display list of subcategories
1469 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1471 if (!empty($pagingbar)) {
1472 $content .= $pagingbar;
1475 foreach ($subcategories as $subcategory) {
1476 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1479 if (!empty($pagingbar)) {
1480 $content .= $pagingbar;
1482 if (!empty($morelink)) {
1483 $content .= $morelink;
1486 $content .= html_writer::end_tag('div');
1487 return $content;
1491 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1493 protected function coursecat_include_js() {
1494 if (!$this->page->requires->should_create_one_time_item_now('core_course_categoryexpanderjsinit')) {
1495 return;
1498 // We must only load this module once.
1499 $this->page->requires->yui_module('moodle-course-categoryexpander',
1500 'Y.Moodle.course.categoryexpander.init');
1504 * Returns HTML to display the subcategories and courses in the given category
1506 * This method is re-used by AJAX to expand content of not loaded category
1508 * @param coursecat_helper $chelper various display options
1509 * @param coursecat $coursecat
1510 * @param int $depth depth of the category in the current tree
1511 * @return string
1513 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1514 $content = '';
1515 // Subcategories
1516 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1518 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1519 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1520 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1521 if ($showcoursesauto && $depth) {
1522 // this is definitely collapsed mode
1523 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1526 // Courses
1527 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1528 $courses = array();
1529 if (!$chelper->get_courses_display_option('nodisplay')) {
1530 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1532 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1533 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1534 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1535 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1538 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1541 if ($showcoursesauto) {
1542 // restore the show_courses back to AUTO
1543 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1546 return $content;
1550 * Returns HTML to display a course category as a part of a tree
1552 * This is an internal function, to display a particular category and all its contents
1553 * use {@link core_course_renderer::course_category()}
1555 * @param coursecat_helper $chelper various display options
1556 * @param coursecat $coursecat
1557 * @param int $depth depth of this category in the current tree
1558 * @return string
1560 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1561 // open category tag
1562 $classes = array('category');
1563 if (empty($coursecat->visible)) {
1564 $classes[] = 'dimmed_category';
1566 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1567 // do not load content
1568 $categorycontent = '';
1569 $classes[] = 'notloaded';
1570 if ($coursecat->get_children_count() ||
1571 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1572 $classes[] = 'with_children';
1573 $classes[] = 'collapsed';
1575 } else {
1576 // load category content
1577 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1578 $classes[] = 'loaded';
1579 if (!empty($categorycontent)) {
1580 $classes[] = 'with_children';
1584 // Make sure JS file to expand category content is included.
1585 $this->coursecat_include_js();
1587 $content = html_writer::start_tag('div', array(
1588 'class' => join(' ', $classes),
1589 'data-categoryid' => $coursecat->id,
1590 'data-depth' => $depth,
1591 'data-showcourses' => $chelper->get_show_courses(),
1592 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1595 // category name
1596 $categoryname = $coursecat->get_formatted_name();
1597 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1598 array('categoryid' => $coursecat->id)),
1599 $categoryname);
1600 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1601 && ($coursescount = $coursecat->get_courses_count())) {
1602 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1603 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1605 $content .= html_writer::start_tag('div', array('class' => 'info'));
1607 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname'));
1608 $content .= html_writer::end_tag('div'); // .info
1610 // add category content to the output
1611 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1613 $content .= html_writer::end_tag('div'); // .category
1615 // Return the course category tree HTML
1616 return $content;
1620 * Returns HTML to display a tree of subcategories and courses in the given category
1622 * @param coursecat_helper $chelper various display options
1623 * @param coursecat $coursecat top category (this category's name and description will NOT be added to the tree)
1624 * @return string
1626 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1627 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1628 if (empty($categorycontent)) {
1629 return '';
1632 // Start content generation
1633 $content = '';
1634 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1635 $content .= html_writer::start_tag('div', $attributes);
1637 if ($coursecat->get_children_count()) {
1638 $classes = array(
1639 'collapseexpand',
1640 'collapse-all',
1642 if ($chelper->get_subcat_depth() == 1) {
1643 $classes[] = 'disabled';
1645 // Only show the collapse/expand if there are children to expand.
1646 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1647 $content .= html_writer::link('#', get_string('collapseall'),
1648 array('class' => implode(' ', $classes)));
1649 $content .= html_writer::end_tag('div');
1650 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1653 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1655 $content .= html_writer::end_tag('div'); // .course_category_tree
1657 return $content;
1661 * Renders HTML to display particular course category - list of it's subcategories and courses
1663 * Invoked from /course/index.php
1665 * @param int|stdClass|coursecat $category
1667 public function course_category($category) {
1668 global $CFG;
1669 require_once($CFG->libdir. '/coursecatlib.php');
1670 $coursecat = coursecat::get(is_object($category) ? $category->id : $category);
1671 $site = get_site();
1672 $output = '';
1674 if (can_edit_in_category($coursecat->id)) {
1675 // Add 'Manage' button if user has permissions to edit this category.
1676 $managebutton = $this->single_button(new moodle_url('/course/management.php',
1677 array('categoryid' => $coursecat->id)), get_string('managecourses'), 'get');
1678 $this->page->set_button($managebutton);
1680 if (!$coursecat->id) {
1681 if (coursecat::count_all() == 1) {
1682 // There exists only one category in the system, do not display link to it
1683 $coursecat = coursecat::get_default();
1684 $strfulllistofcourses = get_string('fulllistofcourses');
1685 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1686 } else {
1687 $strcategories = get_string('categories');
1688 $this->page->set_title("$site->shortname: $strcategories");
1690 } else {
1691 $this->page->set_title("$site->shortname: ". $coursecat->get_formatted_name());
1693 // Print the category selector
1694 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1695 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1696 coursecat::make_categories_list(), $coursecat->id, null, 'switchcategory');
1697 $select->set_label(get_string('categories').':');
1698 $output .= $this->render($select);
1699 $output .= html_writer::end_tag('div'); // .categorypicker
1702 // Print current category description
1703 $chelper = new coursecat_helper();
1704 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1705 $output .= $this->box($description, array('class' => 'generalbox info'));
1708 // Prepare parameters for courses and categories lists in the tree
1709 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1710 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1712 $coursedisplayoptions = array();
1713 $catdisplayoptions = array();
1714 $browse = optional_param('browse', null, PARAM_ALPHA);
1715 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1716 $page = optional_param('page', 0, PARAM_INT);
1717 $baseurl = new moodle_url('/course/index.php');
1718 if ($coursecat->id) {
1719 $baseurl->param('categoryid', $coursecat->id);
1721 if ($perpage != $CFG->coursesperpage) {
1722 $baseurl->param('perpage', $perpage);
1724 $coursedisplayoptions['limit'] = $perpage;
1725 $catdisplayoptions['limit'] = $perpage;
1726 if ($browse === 'courses' || !$coursecat->has_children()) {
1727 $coursedisplayoptions['offset'] = $page * $perpage;
1728 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1729 $catdisplayoptions['nodisplay'] = true;
1730 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1731 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1732 } else if ($browse === 'categories' || !$coursecat->has_courses()) {
1733 $coursedisplayoptions['nodisplay'] = true;
1734 $catdisplayoptions['offset'] = $page * $perpage;
1735 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1736 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1737 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1738 } else {
1739 // we have a category that has both subcategories and courses, display pagination separately
1740 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1741 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1743 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1744 // Add course search form.
1745 $output .= $this->course_search_form();
1747 // Display course category tree.
1748 $output .= $this->coursecat_tree($chelper, $coursecat);
1750 // Add action buttons
1751 $output .= $this->container_start('buttons');
1752 $context = get_category_or_system_context($coursecat->id);
1753 if (has_capability('moodle/course:create', $context)) {
1754 // Print link to create a new course, for the 1st available category.
1755 if ($coursecat->id) {
1756 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1757 } else {
1758 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1760 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1762 ob_start();
1763 if (coursecat::count_all() == 1) {
1764 print_course_request_buttons(context_system::instance());
1765 } else {
1766 print_course_request_buttons($context);
1768 $output .= ob_get_contents();
1769 ob_end_clean();
1770 $output .= $this->container_end();
1772 return $output;
1776 * Serves requests to /course/category.ajax.php
1778 * In this renderer implementation it may expand the category content or
1779 * course content.
1781 * @return string
1782 * @throws coding_exception
1784 public function coursecat_ajax() {
1785 global $DB, $CFG;
1786 require_once($CFG->libdir. '/coursecatlib.php');
1788 $type = required_param('type', PARAM_INT);
1790 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1791 // This is a request for a category list of some kind.
1792 $categoryid = required_param('categoryid', PARAM_INT);
1793 $showcourses = required_param('showcourses', PARAM_INT);
1794 $depth = required_param('depth', PARAM_INT);
1796 $category = coursecat::get($categoryid);
1798 $chelper = new coursecat_helper();
1799 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1800 $coursedisplayoptions = array(
1801 'limit' => $CFG->coursesperpage,
1802 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1804 $catdisplayoptions = array(
1805 'limit' => $CFG->coursesperpage,
1806 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1808 $chelper->set_show_courses($showcourses)->
1809 set_courses_display_options($coursedisplayoptions)->
1810 set_categories_display_options($catdisplayoptions);
1812 return $this->coursecat_category_content($chelper, $category, $depth);
1813 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1814 // This is a request for the course information.
1815 $courseid = required_param('courseid', PARAM_INT);
1817 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1819 $chelper = new coursecat_helper();
1820 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1821 return $this->coursecat_coursebox_content($chelper, $course);
1822 } else {
1823 throw new coding_exception('Invalid request type');
1828 * Renders html to display search result page
1830 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1831 * @return string
1833 public function search_courses($searchcriteria) {
1834 global $CFG;
1835 $content = '';
1836 if (!empty($searchcriteria)) {
1837 // print search results
1838 require_once($CFG->libdir. '/coursecatlib.php');
1840 $displayoptions = array('sort' => array('displayname' => 1));
1841 // take the current page and number of results per page from query
1842 $perpage = optional_param('perpage', 0, PARAM_RAW);
1843 if ($perpage !== 'all') {
1844 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1845 $page = optional_param('page', 0, PARAM_INT);
1846 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1848 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1849 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1850 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1852 $class = 'course-search-result';
1853 foreach ($searchcriteria as $key => $value) {
1854 if (!empty($value)) {
1855 $class .= ' course-search-result-'. $key;
1858 $chelper = new coursecat_helper();
1859 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1860 set_courses_display_options($displayoptions)->
1861 set_search_criteria($searchcriteria)->
1862 set_attributes(array('class' => $class));
1864 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1865 $totalcount = coursecat::search_courses_count($searchcriteria);
1866 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1868 if (!$totalcount) {
1869 if (!empty($searchcriteria['search'])) {
1870 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1871 } else {
1872 $content .= $this->heading(get_string('novalidcourses'));
1874 } else {
1875 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1876 $content .= $courseslist;
1879 if (!empty($searchcriteria['search'])) {
1880 // print search form only if there was a search by search string, otherwise it is confusing
1881 $content .= $this->box_start('generalbox mdl-align');
1882 $content .= $this->course_search_form($searchcriteria['search']);
1883 $content .= $this->box_end();
1885 } else {
1886 // just print search form
1887 $content .= $this->box_start('generalbox mdl-align');
1888 $content .= $this->course_search_form();
1889 $content .= html_writer::tag('div', get_string("searchhelp"), array('class' => 'searchhelp'));
1890 $content .= $this->box_end();
1892 return $content;
1896 * Renders html to print list of courses tagged with particular tag
1898 * @param int $tagid id of the tag
1899 * @return string empty string if no courses are marked with this tag or rendered list of courses
1901 public function tagged_courses($tagid) {
1902 global $CFG;
1903 require_once($CFG->libdir. '/coursecatlib.php');
1904 $displayoptions = array('limit' => $CFG->coursesperpage);
1905 $displayoptions['viewmoreurl'] = new moodle_url('/course/search.php',
1906 array('tagid' => $tagid, 'page' => 1, 'perpage' => $CFG->coursesperpage));
1907 $displayoptions['viewmoretext'] = new lang_string('findmorecourses');
1908 $chelper = new coursecat_helper();
1909 $searchcriteria = array('tagid' => $tagid);
1910 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1911 set_search_criteria(array('tagid' => $tagid))->
1912 set_courses_display_options($displayoptions)->
1913 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1914 // (we set the same css class as in search results by tagid)
1915 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1916 $totalcount = coursecat::search_courses_count($searchcriteria);
1917 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1918 if ($totalcount) {
1919 require_once $CFG->dirroot.'/tag/lib.php';
1920 $heading = get_string('courses') . ' ' . get_string('taggedwith', 'tag', tag_get_name($tagid)) .': '. $totalcount;
1921 return $this->heading($heading, 3). $content;
1923 return '';
1927 * Returns HTML to display one remote course
1929 * @param stdClass $course remote course information, contains properties:
1930 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1931 * @return string
1933 protected function frontpage_remote_course(stdClass $course) {
1934 $url = new moodle_url('/auth/mnet/jump.php', array(
1935 'hostid' => $course->hostid,
1936 'wantsurl' => '/course/view.php?id='. $course->remoteid
1939 $output = '';
1940 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1941 $output .= html_writer::start_tag('div', array('class' => 'info'));
1942 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1943 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1944 $output .= html_writer::end_tag('h3'); // .name
1945 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1946 $output .= html_writer::end_tag('div'); // .info
1947 $output .= html_writer::start_tag('div', array('class' => 'content'));
1948 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1949 $options = new stdClass();
1950 $options->noclean = true;
1951 $options->para = false;
1952 $options->overflowdiv = true;
1953 $output .= format_text($course->summary, $course->summaryformat, $options);
1954 $output .= html_writer::end_tag('div'); // .summary
1955 $addinfo = format_string($course->hostname) . ' : '
1956 . format_string($course->cat_name) . ' : '
1957 . format_string($course->shortname);
1958 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1959 $output .= html_writer::end_tag('div'); // .content
1960 $output .= html_writer::end_tag('div'); // .coursebox
1961 return $output;
1965 * Returns HTML to display one remote host
1967 * @param array $host host information, contains properties: name, url, count
1968 * @return string
1970 protected function frontpage_remote_host($host) {
1971 $output = '';
1972 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1973 $output .= html_writer::start_tag('div', array('class' => 'info'));
1974 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1975 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1976 $output .= html_writer::end_tag('h3'); // .name
1977 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1978 $output .= html_writer::end_tag('div'); // .info
1979 $output .= html_writer::start_tag('div', array('class' => 'content'));
1980 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1981 $output .= $host['count'] . ' ' . get_string('courses');
1982 $output .= html_writer::end_tag('div'); // .content
1983 $output .= html_writer::end_tag('div'); // .coursebox
1984 return $output;
1988 * Returns HTML to print list of courses user is enrolled to for the frontpage
1990 * Also lists remote courses or remote hosts if MNET authorisation is used
1992 * @return string
1994 public function frontpage_my_courses() {
1995 global $USER, $CFG, $DB;
1997 if (!isloggedin() or isguestuser()) {
1998 return '';
2001 $output = '';
2002 if (!empty($CFG->navsortmycoursessort)) {
2003 // sort courses the same as in navigation menu
2004 $sortorder = 'visible DESC,'. $CFG->navsortmycoursessort.' ASC';
2005 } else {
2006 $sortorder = 'visible DESC,sortorder ASC';
2008 $courses = enrol_get_my_courses('summary, summaryformat', $sortorder);
2009 $rhosts = array();
2010 $rcourses = array();
2011 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2012 $rcourses = get_my_remotecourses($USER->id);
2013 $rhosts = get_my_remotehosts();
2016 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2018 $chelper = new coursecat_helper();
2019 if (count($courses) > $CFG->frontpagecourselimit) {
2020 // There are more enrolled courses than we can display, display link to 'My courses'.
2021 $totalcount = count($courses);
2022 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
2023 $chelper->set_courses_display_options(array(
2024 'viewmoreurl' => new moodle_url('/my/'),
2025 'viewmoretext' => new lang_string('mycourses')
2027 } else {
2028 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
2029 $chelper->set_courses_display_options(array(
2030 'viewmoreurl' => new moodle_url('/course/index.php'),
2031 'viewmoretext' => new lang_string('fulllistofcourses')
2033 $totalcount = $DB->count_records('course') - 1;
2035 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2036 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
2037 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
2039 // MNET
2040 if (!empty($rcourses)) {
2041 // at the IDP, we know of all the remote courses
2042 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2043 foreach ($rcourses as $course) {
2044 $output .= $this->frontpage_remote_course($course);
2046 $output .= html_writer::end_tag('div'); // .courses
2047 } elseif (!empty($rhosts)) {
2048 // non-IDP, we know of all the remote servers, but not courses
2049 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2050 foreach ($rhosts as $host) {
2051 $output .= $this->frontpage_remote_host($host);
2053 $output .= html_writer::end_tag('div'); // .courses
2056 return $output;
2060 * Returns HTML to print list of available courses for the frontpage
2062 * @return string
2064 public function frontpage_available_courses() {
2065 global $CFG;
2066 require_once($CFG->libdir. '/coursecatlib.php');
2068 $chelper = new coursecat_helper();
2069 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2070 set_courses_display_options(array(
2071 'recursive' => true,
2072 'limit' => $CFG->frontpagecourselimit,
2073 'viewmoreurl' => new moodle_url('/course/index.php'),
2074 'viewmoretext' => new lang_string('fulllistofcourses')));
2076 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
2077 $courses = coursecat::get(0)->get_courses($chelper->get_courses_display_options());
2078 $totalcount = coursecat::get(0)->get_courses_count($chelper->get_courses_display_options());
2079 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
2080 // Print link to create a new course, for the 1st available category.
2081 return $this->add_new_course_button();
2083 return $this->coursecat_courses($chelper, $courses, $totalcount);
2087 * Returns HTML to the "add new course" button for the page
2089 * @return string
2091 public function add_new_course_button() {
2092 global $CFG;
2093 // Print link to create a new course, for the 1st available category.
2094 $output = $this->container_start('buttons');
2095 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2096 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2097 $output .= $this->container_end('buttons');
2098 return $output;
2102 * Returns HTML to print tree with course categories and courses for the frontpage
2104 * @return string
2106 public function frontpage_combo_list() {
2107 global $CFG;
2108 require_once($CFG->libdir. '/coursecatlib.php');
2109 $chelper = new coursecat_helper();
2110 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2111 set_categories_display_options(array(
2112 'limit' => $CFG->coursesperpage,
2113 'viewmoreurl' => new moodle_url('/course/index.php',
2114 array('browse' => 'categories', 'page' => 1))
2115 ))->
2116 set_courses_display_options(array(
2117 'limit' => $CFG->coursesperpage,
2118 'viewmoreurl' => new moodle_url('/course/index.php',
2119 array('browse' => 'courses', 'page' => 1))
2120 ))->
2121 set_attributes(array('class' => 'frontpage-category-combo'));
2122 return $this->coursecat_tree($chelper, coursecat::get(0));
2126 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2128 * @return string
2130 public function frontpage_categories_list() {
2131 global $CFG;
2132 require_once($CFG->libdir. '/coursecatlib.php');
2133 $chelper = new coursecat_helper();
2134 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2135 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2136 set_categories_display_options(array(
2137 'limit' => $CFG->coursesperpage,
2138 'viewmoreurl' => new moodle_url('/course/index.php',
2139 array('browse' => 'categories', 'page' => 1))
2140 ))->
2141 set_attributes(array('class' => 'frontpage-category-names'));
2142 return $this->coursecat_tree($chelper, coursecat::get(0));
2147 * Class storing display options and functions to help display course category and/or courses lists
2149 * This is a wrapper for coursecat objects that also stores display options
2150 * and functions to retrieve sorted and paginated lists of categories/courses.
2152 * If theme overrides methods in core_course_renderers that access this class
2153 * it may as well not use this class at all or extend it.
2155 * @package core
2156 * @copyright 2013 Marina Glancy
2157 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2159 class coursecat_helper {
2160 /** @var string [none, collapsed, expanded] how (if) display courses list */
2161 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2162 /** @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) */
2163 protected $subcatdepth = 1;
2164 /** @var array options to display courses list */
2165 protected $coursesdisplayoptions = array();
2166 /** @var array options to display subcategories list */
2167 protected $categoriesdisplayoptions = array();
2168 /** @var array additional HTML attributes */
2169 protected $attributes = array();
2170 /** @var array search criteria if the list is a search result */
2171 protected $searchcriteria = null;
2174 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2176 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2177 * @return coursecat_helper
2179 public function set_show_courses($showcourses) {
2180 $this->showcourses = $showcourses;
2181 // Automatically set the options to preload summary and coursecontacts for coursecat::get_courses() and coursecat::search_courses()
2182 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2183 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2184 return $this;
2188 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2190 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2192 public function get_show_courses() {
2193 return $this->showcourses;
2197 * Sets the maximum depth to expand subcategories in the tree
2199 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2201 * @param int $subcatdepth
2202 * @return coursecat_helper
2204 public function set_subcat_depth($subcatdepth) {
2205 $this->subcatdepth = $subcatdepth;
2206 return $this;
2210 * Returns the maximum depth to expand subcategories in the tree
2212 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2214 * @return int
2216 public function get_subcat_depth() {
2217 return $this->subcatdepth;
2221 * Sets options to display list of courses
2223 * Options are later submitted as argument to coursecat::get_courses() and/or coursecat::search_courses()
2225 * Options that coursecat::get_courses() accept:
2226 * - recursive - return courses from subcategories as well. Use with care,
2227 * this may be a huge list!
2228 * - summary - preloads fields 'summary' and 'summaryformat'
2229 * - coursecontacts - preloads course contacts
2230 * - isenrolled - preloads indication whether this user is enrolled in the course
2231 * - sort - list of fields to sort. Example
2232 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2233 * will sort by idnumber asc, shortname asc and id desc.
2234 * Default: array('sortorder' => 1)
2235 * Only cached fields may be used for sorting!
2236 * - offset
2237 * - limit - maximum number of children to return, 0 or null for no limit
2239 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2241 * Also renderer can set here any additional options it wants to pass between renderer functions.
2243 * @param array $options
2244 * @return coursecat_helper
2246 public function set_courses_display_options($options) {
2247 $this->coursesdisplayoptions = $options;
2248 $this->set_show_courses($this->showcourses); // this will calculate special display options
2249 return $this;
2253 * Sets one option to display list of courses
2255 * @see coursecat_helper::set_courses_display_options()
2257 * @param string $key
2258 * @param mixed $value
2259 * @return coursecat_helper
2261 public function set_courses_display_option($key, $value) {
2262 $this->coursesdisplayoptions[$key] = $value;
2263 return $this;
2267 * Return the specified option to display list of courses
2269 * @param string $optionname option name
2270 * @param mixed $defaultvalue default value for option if it is not specified
2271 * @return mixed
2273 public function get_courses_display_option($optionname, $defaultvalue = null) {
2274 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2275 return $this->coursesdisplayoptions[$optionname];
2276 } else {
2277 return $defaultvalue;
2282 * Returns all options to display the courses
2284 * This array is usually passed to {@link coursecat::get_courses()} or
2285 * {@link coursecat::search_courses()}
2287 * @return array
2289 public function get_courses_display_options() {
2290 return $this->coursesdisplayoptions;
2294 * Sets options to display list of subcategories
2296 * Options 'sort', 'offset' and 'limit' are passed to coursecat::get_children().
2297 * Any other options may be used by renderer functions
2299 * @param array $options
2300 * @return coursecat_helper
2302 public function set_categories_display_options($options) {
2303 $this->categoriesdisplayoptions = $options;
2304 return $this;
2308 * Return the specified option to display list of subcategories
2310 * @param string $optionname option name
2311 * @param mixed $defaultvalue default value for option if it is not specified
2312 * @return mixed
2314 public function get_categories_display_option($optionname, $defaultvalue = null) {
2315 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2316 return $this->categoriesdisplayoptions[$optionname];
2317 } else {
2318 return $defaultvalue;
2323 * Returns all options to display list of subcategories
2325 * This array is usually passed to {@link coursecat::get_children()}
2327 * @return array
2329 public function get_categories_display_options() {
2330 return $this->categoriesdisplayoptions;
2334 * Sets additional general options to pass between renderer functions, usually HTML attributes
2336 * @param array $attributes
2337 * @return coursecat_helper
2339 public function set_attributes($attributes) {
2340 $this->attributes = $attributes;
2341 return $this;
2345 * Return all attributes and erases them so they are not applied again
2347 * @param string $classname adds additional class name to the beginning of $attributes['class']
2348 * @return array
2350 public function get_and_erase_attributes($classname) {
2351 $attributes = $this->attributes;
2352 $this->attributes = array();
2353 if (empty($attributes['class'])) {
2354 $attributes['class'] = '';
2356 $attributes['class'] = $classname . ' '. $attributes['class'];
2357 return $attributes;
2361 * Sets the search criteria if the course is a search result
2363 * Search string will be used to highlight terms in course name and description
2365 * @param array $searchcriteria
2366 * @return coursecat_helper
2368 public function set_search_criteria($searchcriteria) {
2369 $this->searchcriteria = $searchcriteria;
2370 return $this;
2374 * Returns formatted and filtered description of the given category
2376 * @param coursecat $coursecat category
2377 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2378 * if context is not specified it will be added automatically
2379 * @return string|null
2381 public function get_category_formatted_description($coursecat, $options = null) {
2382 if ($coursecat->id && !empty($coursecat->description)) {
2383 if (!isset($coursecat->descriptionformat)) {
2384 $descriptionformat = FORMAT_MOODLE;
2385 } else {
2386 $descriptionformat = $coursecat->descriptionformat;
2388 if ($options === null) {
2389 $options = array('noclean' => true, 'overflowdiv' => true);
2390 } else {
2391 $options = (array)$options;
2393 $context = context_coursecat::instance($coursecat->id);
2394 if (!isset($options['context'])) {
2395 $options['context'] = $context;
2397 $text = file_rewrite_pluginfile_urls($coursecat->description,
2398 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2399 return format_text($text, $descriptionformat, $options);
2401 return null;
2405 * Returns given course's summary with proper embedded files urls and formatted
2407 * @param course_in_list $course
2408 * @param array|stdClass $options additional formatting options
2409 * @return string
2411 public function get_course_formatted_summary($course, $options = array()) {
2412 global $CFG;
2413 require_once($CFG->libdir. '/filelib.php');
2414 if (!$course->has_summary()) {
2415 return '';
2417 $options = (array)$options;
2418 $context = context_course::instance($course->id);
2419 if (!isset($options['context'])) {
2420 // TODO see MDL-38521
2421 // option 1 (current), page context - no code required
2422 // option 2, system context
2423 // $options['context'] = context_system::instance();
2424 // option 3, course context:
2425 // $options['context'] = $context;
2426 // option 4, course category context:
2427 // $options['context'] = $context->get_parent_context();
2429 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2430 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2431 if (!empty($this->searchcriteria['search'])) {
2432 $summary = highlight($this->searchcriteria['search'], $summary);
2434 return $summary;
2438 * Returns course name as it is configured to appear in courses lists formatted to course context
2440 * @param course_in_list $course
2441 * @param array|stdClass $options additional formatting options
2442 * @return string
2444 public function get_course_formatted_name($course, $options = array()) {
2445 $options = (array)$options;
2446 if (!isset($options['context'])) {
2447 $options['context'] = context_course::instance($course->id);
2449 $name = format_string(get_course_display_name_for_list($course), true, $options);
2450 if (!empty($this->searchcriteria['search'])) {
2451 $name = highlight($this->searchcriteria['search'], $name);
2453 return $name;