MDL-30431 mod_wiki: whitespace fix
[moodle.git] / course / renderer.php
blob9595d81b8cddcf403739a9383bfd77cfef8fdba2
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Renderer for use with the course section and all the goodness that falls
20 * within it.
22 * This renderer should contain methods useful to courses, and categories.
24 * @package moodlecore
25 * @copyright 2010 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 /**
30 * The core course renderer
32 * Can be retrieved with the following:
33 * $renderer = $PAGE->get_renderer('core','course');
35 class core_course_renderer extends plugin_renderer_base {
36 const COURSECAT_SHOW_COURSES_NONE = 0; /* do not show courses at all */
37 const COURSECAT_SHOW_COURSES_COUNT = 5; /* do not show courses but show number of courses next to category name */
38 const COURSECAT_SHOW_COURSES_COLLAPSED = 10;
39 const COURSECAT_SHOW_COURSES_AUTO = 15; /* will choose between collapsed and expanded automatically */
40 const COURSECAT_SHOW_COURSES_EXPANDED = 20;
41 const COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT = 30;
43 const COURSECAT_TYPE_CATEGORY = 0;
44 const COURSECAT_TYPE_COURSE = 1;
46 /**
47 * A cache of strings
48 * @var stdClass
50 protected $strings;
52 /**
53 * Override the constructor so that we can initialise the string cache
55 * @param moodle_page $page
56 * @param string $target
58 public function __construct(moodle_page $page, $target) {
59 $this->strings = new stdClass;
60 parent::__construct($page, $target);
61 $this->add_modchoosertoggle();
64 /**
65 * Adds the item in course settings navigation to toggle modchooser
67 * Theme can overwrite as an empty function to exclude it (for example if theme does not
68 * use modchooser at all)
70 protected function add_modchoosertoggle() {
71 global $CFG;
72 static $modchoosertoggleadded = false;
73 // Add the module chooser toggle to the course page
74 if ($modchoosertoggleadded || $this->page->state > moodle_page::STATE_PRINTING_HEADER ||
75 $this->page->course->id == SITEID ||
76 !$this->page->user_is_editing() ||
77 !($context = context_course::instance($this->page->course->id)) ||
78 !has_capability('moodle/course:manageactivities', $context) ||
79 !course_ajax_enabled($this->page->course) ||
80 !($coursenode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE)) ||
81 !($turneditingnode = $coursenode->get('turneditingonoff'))) {
82 // too late or we are on site page or we could not find the adjacent nodes in course settings menu
83 // or we are not allowed to edit
84 return;
86 $modchoosertoggleadded = true;
87 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
88 // We are on the course page, retain the current page params e.g. section.
89 $modchoosertoggleurl = clone($this->page->url);
90 } else {
91 // Edit on the main course page.
92 $modchoosertoggleurl = new moodle_url('/course/view.php', array('id' => $this->page->course->id,
93 'return' => $this->page->url->out_as_local_url(false)));
95 $modchoosertoggleurl->param('sesskey', sesskey());
96 if ($usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault)) {
97 $modchoosertogglestring = get_string('modchooserdisable', 'moodle');
98 $modchoosertoggleurl->param('modchooser', 'off');
99 } else {
100 $modchoosertogglestring = get_string('modchooserenable', 'moodle');
101 $modchoosertoggleurl->param('modchooser', 'on');
103 $modchoosertoggle = navigation_node::create($modchoosertogglestring, $modchoosertoggleurl, navigation_node::TYPE_SETTING, null, 'modchoosertoggle');
105 // Insert the modchoosertoggle after the settings node 'turneditingonoff' (navigation_node only has function to insert before, so we insert before and then swap).
106 $coursenode->add_node($modchoosertoggle, 'turneditingonoff');
107 $turneditingnode->remove();
108 $coursenode->add_node($turneditingnode, 'modchoosertoggle');
110 $modchoosertoggle->add_class('modchoosertoggle');
111 $modchoosertoggle->add_class('visibleifjs');
112 user_preference_allow_ajax_update('usemodchooser', PARAM_BOOL);
116 * Renders course info box.
118 * @param stdClass|course_in_list $course
119 * @return string
121 public function course_info_box(stdClass $course) {
122 $content = '';
123 $content .= $this->output->box_start('generalbox info');
124 $chelper = new coursecat_helper();
125 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
126 $content .= $this->coursecat_coursebox($chelper, $course);
127 $content .= $this->output->box_end();
128 return $content;
132 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
134 * @deprecated since 2.5
136 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
138 * @param array $ignored argument ignored
139 * @return string
141 public final function course_category_tree(array $ignored) {
142 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
143 return $this->frontpage_combo_list();
147 * Renderers a category for use with course_category_tree
149 * @deprecated since 2.5
151 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
153 * @param array $category
154 * @param int $depth
155 * @return string
157 protected final function course_category_tree_category(stdClass $category, $depth=1) {
158 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
159 return '';
163 * Build the HTML for the module chooser javascript popup
165 * @param array $modules A set of modules as returned form @see
166 * get_module_metadata
167 * @param object $course The course that will be displayed
168 * @return string The composed HTML for the module
170 public function course_modchooser($modules, $course) {
171 static $isdisplayed = false;
172 if ($isdisplayed) {
173 return '';
175 $isdisplayed = true;
177 // Add the module chooser
178 $this->page->requires->yui_module('moodle-course-modchooser',
179 'M.course.init_chooser',
180 array(array('courseid' => $course->id, 'closeButtonTitle' => get_string('close', 'editor')))
182 $this->page->requires->strings_for_js(array(
183 'addresourceoractivity',
184 'modchooserenable',
185 'modchooserdisable',
186 ), 'moodle');
188 // Add the header
189 $header = html_writer::tag('div', get_string('addresourceoractivity', 'moodle'),
190 array('class' => 'hd choosertitle'));
192 $formcontent = html_writer::start_tag('form', array('action' => new moodle_url('/course/jumpto.php'),
193 'id' => 'chooserform', 'method' => 'post'));
194 $formcontent .= html_writer::start_tag('div', array('id' => 'typeformdiv'));
195 $formcontent .= html_writer::tag('input', '', array('type' => 'hidden', 'id' => 'course',
196 'name' => 'course', 'value' => $course->id));
197 $formcontent .= html_writer::tag('input', '',
198 array('type' => 'hidden', 'class' => 'jump', 'name' => 'jump', 'value' => ''));
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 condition_info::completion_value_used_as_condition($course, $mod)) {
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 $conditionalhidden = $mod->availablefrom > time() ||
717 ($mod->availableuntil && $mod->availableuntil < time()) ||
718 count($mod->conditionsgrade) > 0 ||
719 count($mod->conditionscompletion) > 0 ||
720 count($mod->conditionsfield);
722 return $conditionalhidden;
726 * Renders html to display a name with the link to the course module on a course page
728 * If module is unavailable for user but still needs to be displayed
729 * in the list, just the name is returned without a link
731 * Note, that for course modules that never have separate pages (i.e. labels)
732 * this function return an empty string
734 * @param cm_info $mod
735 * @param array $displayoptions
736 * @return string
738 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
739 global $CFG;
740 $output = '';
741 if (!$mod->uservisible &&
742 (empty($mod->showavailability) || empty($mod->availableinfo))) {
743 // nothing to be displayed to the user
744 return $output;
746 $url = $mod->get_url();
747 if (!$url) {
748 return $output;
751 //Accessibility: for files get description via icon, this is very ugly hack!
752 $instancename = $mod->get_formatted_name();
753 $altname = $mod->modfullname;
754 // Avoid unnecessary duplication: if e.g. a forum name already
755 // includes the word forum (or Forum, etc) then it is unhelpful
756 // to include that in the accessible description that is added.
757 if (false !== strpos(core_text::strtolower($instancename),
758 core_text::strtolower($altname))) {
759 $altname = '';
761 // File type after name, for alphabetic lists (screen reader).
762 if ($altname) {
763 $altname = get_accesshide(' '.$altname);
766 // For items which are hidden but available to current user
767 // ($mod->uservisible), we show those as dimmed only if the user has
768 // viewhiddenactivities, so that teachers see 'items which might not
769 // be available to some students' dimmed but students do not see 'item
770 // which is actually available to current student' dimmed.
771 $linkclasses = '';
772 $accesstext = '';
773 $textclasses = '';
774 if ($mod->uservisible) {
775 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
776 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
777 has_capability('moodle/course:viewhiddenactivities',
778 context_course::instance($mod->course));
779 if ($accessiblebutdim) {
780 $linkclasses .= ' dimmed';
781 $textclasses .= ' dimmed_text';
782 if ($conditionalhidden) {
783 $linkclasses .= ' conditionalhidden';
784 $textclasses .= ' conditionalhidden';
786 // Show accessibility note only if user can access the module himself.
787 $accesstext = get_accesshide(get_string('hiddenfromstudents').':'. $mod->modfullname);
789 } else {
790 $linkclasses .= ' dimmed';
791 $textclasses .= ' dimmed_text';
794 // Get on-click attribute value if specified and decode the onclick - it
795 // has already been encoded for display (puke).
796 $onclick = htmlspecialchars_decode($mod->get_on_click(), ENT_QUOTES);
798 $groupinglabel = '';
799 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($mod->course))) {
800 $groupings = groups_get_all_groupings($mod->course);
801 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$mod->groupingid]->name).')',
802 array('class' => 'groupinglabel '.$textclasses));
805 // Display link itself.
806 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
807 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) . $accesstext .
808 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
809 if ($mod->uservisible) {
810 $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick)) .
811 $groupinglabel;
812 } else {
813 // We may be displaying this just in order to show information
814 // about visibility, without the actual link ($mod->uservisible)
815 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses)) .
816 $groupinglabel;
818 return $output;
822 * Renders html to display the module content on the course page (i.e. text of the labels)
824 * @param cm_info $mod
825 * @param array $displayoptions
826 * @return string
828 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
829 $output = '';
830 if (!$mod->uservisible &&
831 (empty($mod->showavailability) || empty($mod->availableinfo))) {
832 // nothing to be displayed to the user
833 return $output;
835 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
836 $accesstext = '';
837 $textclasses = '';
838 if ($mod->uservisible) {
839 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
840 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
841 has_capability('moodle/course:viewhiddenactivities',
842 context_course::instance($mod->course));
843 if ($accessiblebutdim) {
844 $textclasses .= ' dimmed_text';
845 if ($conditionalhidden) {
846 $textclasses .= ' conditionalhidden';
848 // Show accessibility note only if user can access the module himself.
849 $accesstext = get_accesshide(get_string('hiddenfromstudents').':'. $mod->modfullname);
851 } else {
852 $textclasses .= ' dimmed_text';
854 if ($mod->get_url()) {
855 if ($content) {
856 // If specified, display extra content after link.
857 $output = html_writer::tag('div', $content, array('class' =>
858 trim('contentafterlink ' . $textclasses)));
860 } else {
861 // No link, so display only content.
862 $output = html_writer::tag('div', $accesstext . $content,
863 array('class' => 'contentwithoutlink ' . $textclasses));
865 return $output;
869 * Renders HTML to show course module availability information (for someone who isn't allowed
870 * to see the activity itself, or for staff)
872 * @param cm_info $mod
873 * @param array $displayoptions
874 * @return string
876 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
877 global $CFG;
878 if (!$mod->uservisible) {
879 // this is a student who is not allowed to see the module but might be allowed
880 // to see availability info (i.e. "Available from ...")
881 if (!empty($mod->showavailability) && !empty($mod->availableinfo)) {
882 $output = html_writer::tag('div', $mod->availableinfo, array('class' => 'availabilityinfo'));
884 return $output;
886 // this is a teacher who is allowed to see module but still should see the
887 // information that module is not available to all/some students
888 $modcontext = context_module::instance($mod->id);
889 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
890 if ($canviewhidden && !empty($CFG->enableavailability)) {
891 // Don't add availability information if user is not editing and activity is hidden.
892 if ($mod->visible || $this->page->user_is_editing()) {
893 $hidinfoclass = '';
894 if (!$mod->visible) {
895 $hidinfoclass = 'hide';
897 $ci = new condition_info($mod);
898 $fullinfo = $ci->get_full_information();
899 if($fullinfo) {
900 return '<div class="availabilityinfo '.$hidinfoclass.'">'.get_string($mod->showavailability
901 ? 'userrestriction_visible'
902 : 'userrestriction_hidden','condition',
903 $fullinfo).'</div>';
907 return '';
911 * Renders HTML to display one course module for display within a section.
913 * This function calls:
914 * {@link core_course_renderer::course_section_cm()}
916 * @param stdClass $course
917 * @param completion_info $completioninfo
918 * @param cm_info $mod
919 * @param int|null $sectionreturn
920 * @param array $displayoptions
921 * @return String
923 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
924 $output = '';
925 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
926 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->get_extra_classes();
927 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
929 return $output;
933 * Renders HTML to display one course module in a course section
935 * This includes link, content, availability, completion info and additional information
936 * that module type wants to display (i.e. number of unread forum posts)
938 * This function calls:
939 * {@link core_course_renderer::course_section_cm_name()}
940 * {@link cm_info::get_after_link()}
941 * {@link core_course_renderer::course_section_cm_text()}
942 * {@link core_course_renderer::course_section_cm_availability()}
943 * {@link core_course_renderer::course_section_cm_completion()}
944 * {@link course_get_cm_edit_actions()}
945 * {@link core_course_renderer::course_section_cm_edit_actions()}
947 * @param stdClass $course
948 * @param completion_info $completioninfo
949 * @param cm_info $mod
950 * @param int|null $sectionreturn
951 * @param array $displayoptions
952 * @return string
954 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
955 $output = '';
956 // We return empty string (because course module will not be displayed at all)
957 // if:
958 // 1) The activity is not visible to users
959 // and
960 // 2a) The 'showavailability' option is not set (if that is set,
961 // we need to display the activity so we can show
962 // availability info)
963 // or
964 // 2b) The 'availableinfo' is empty, i.e. the activity was
965 // hidden in a way that leaves no info, such as using the
966 // eye icon.
967 if (!$mod->uservisible &&
968 (empty($mod->showavailability) || empty($mod->availableinfo))) {
969 return $output;
972 $indentclasses = 'mod-indent';
973 if (!empty($mod->indent)) {
974 $indentclasses .= ' mod-indent-'.$mod->indent;
975 if ($mod->indent > 15) {
976 $indentclasses .= ' mod-indent-huge';
980 $output .= html_writer::start_tag('div');
982 if ($this->page->user_is_editing()) {
983 $output .= course_get_cm_move($mod, $sectionreturn);
986 $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer'));
988 // This div is used to indent the content.
989 $output .= html_writer::div('', $indentclasses);
991 // Start a wrapper for the actual content to keep the indentation consistent
992 $output .= html_writer::start_tag('div');
994 // Display the link to the module (or do nothing if module has no url)
995 $cmname = $this->course_section_cm_name($mod, $displayoptions);
997 if (!empty($cmname)) {
998 // Start the div for the activity title, excluding the edit icons.
999 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
1000 $output .= $cmname;
1003 if ($this->page->user_is_editing()) {
1004 $output .= ' ' . course_get_cm_rename_action($mod, $sectionreturn);
1007 // Module can put text after the link (e.g. forum unread)
1008 $output .= $mod->get_after_link();
1010 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
1011 $output .= html_writer::end_tag('div'); // .activityinstance
1014 // If there is content but NO link (eg label), then display the
1015 // content here (BEFORE any icons). In this case cons must be
1016 // displayed after the content so that it makes more sense visually
1017 // and for accessibility reasons, e.g. if you have a one-line label
1018 // it should work similarly (at least in terms of ordering) to an
1019 // activity.
1020 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
1021 $url = $mod->get_url();
1022 if (empty($url)) {
1023 $output .= $contentpart;
1026 $modicons = '';
1027 if ($this->page->user_is_editing()) {
1028 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
1029 $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
1030 $modicons .= $mod->get_after_edit_icons();
1033 $modicons .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
1035 if (!empty($modicons)) {
1036 $output .= html_writer::span($modicons, 'actions');
1039 // If there is content AND a link, then display the content here
1040 // (AFTER any icons). Otherwise it was displayed before
1041 if (!empty($url)) {
1042 $output .= $contentpart;
1045 // show availability info (if module is not available)
1046 $output .= $this->course_section_cm_availability($mod, $displayoptions);
1048 $output .= html_writer::end_tag('div'); // $indentclasses
1050 // End of indentation div.
1051 $output .= html_writer::end_tag('div');
1053 $output .= html_writer::end_tag('div');
1054 return $output;
1058 * Renders HTML to display a list of course modules in a course section
1059 * Also displays "move here" controls in Javascript-disabled mode
1061 * This function calls {@link core_course_renderer::course_section_cm()}
1063 * @param stdClass $course course object
1064 * @param int|stdClass|section_info $section relative section number or section object
1065 * @param int $sectionreturn section number to return to
1066 * @param int $displayoptions
1067 * @return void
1069 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
1070 global $USER;
1072 $output = '';
1073 $modinfo = get_fast_modinfo($course);
1074 if (is_object($section)) {
1075 $section = $modinfo->get_section_info($section->section);
1076 } else {
1077 $section = $modinfo->get_section_info($section);
1079 $completioninfo = new completion_info($course);
1081 // check if we are currently in the process of moving a module with JavaScript disabled
1082 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
1083 if ($ismoving) {
1084 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
1085 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1088 // Get the list of modules visible to user (excluding the module being moved if there is one)
1089 $moduleshtml = array();
1090 if (!empty($modinfo->sections[$section->section])) {
1091 foreach ($modinfo->sections[$section->section] as $modnumber) {
1092 $mod = $modinfo->cms[$modnumber];
1094 if ($ismoving and $mod->id == $USER->activitycopy) {
1095 // do not display moving mod
1096 continue;
1099 if ($modulehtml = $this->course_section_cm_list_item($course,
1100 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
1101 $moduleshtml[$modnumber] = $modulehtml;
1106 $sectionoutput = '';
1107 if (!empty($moduleshtml) || $ismoving) {
1108 foreach ($moduleshtml as $modnumber => $modulehtml) {
1109 if ($ismoving) {
1110 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
1111 $sectionoutput .= html_writer::tag('li', html_writer::link($movingurl, $this->output->render($movingpix)),
1112 array('class' => 'movehere', 'title' => $strmovefull));
1115 $sectionoutput .= $modulehtml;
1118 if ($ismoving) {
1119 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1120 $sectionoutput .= html_writer::tag('li', html_writer::link($movingurl, $this->output->render($movingpix)),
1121 array('class' => 'movehere', 'title' => $strmovefull));
1125 // Always output the section module list.
1126 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1128 return $output;
1132 * Displays a custom list of courses with paging bar if necessary
1134 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1135 * appears under the list.
1137 * If both $paginationurl and $totalcount are specified, and $totalcount is
1138 * bigger than count($courses), a paging bar is displayed above and under the
1139 * courses list.
1141 * @param array $courses array of course records (or instances of course_in_list) to show on this page
1142 * @param bool $showcategoryname whether to add category name to the course description
1143 * @param string $additionalclasses additional CSS classes to add to the div.courses
1144 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1145 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1146 * @param int $page current page number (defaults to 0 referring to the first page)
1147 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1148 * @return string
1150 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1151 global $CFG;
1152 // create instance of coursecat_helper to pass display options to function rendering courses list
1153 $chelper = new coursecat_helper();
1154 if ($showcategoryname) {
1155 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1156 } else {
1157 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1159 if ($totalcount !== null && $paginationurl !== null) {
1160 // add options to display pagination
1161 if ($perpage === null) {
1162 $perpage = $CFG->coursesperpage;
1164 $chelper->set_courses_display_options(array(
1165 'limit' => $perpage,
1166 'offset' => ((int)$page) * $perpage,
1167 'paginationurl' => $paginationurl,
1169 } else if ($paginationurl !== null) {
1170 // add options to display 'View more' link
1171 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1172 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1174 $chelper->set_attributes(array('class' => $additionalclasses));
1175 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1176 return $content;
1180 * Displays one course in the list of courses.
1182 * This is an internal function, to display an information about just one course
1183 * please use {@link core_course_renderer::course_info_box()}
1185 * @param coursecat_helper $chelper various display options
1186 * @param course_in_list|stdClass $course
1187 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1188 * depend on the course position in list - first/last/even/odd)
1189 * @return string
1191 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1192 global $CFG;
1193 if (!isset($this->strings->summary)) {
1194 $this->strings->summary = get_string('summary');
1196 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1197 return '';
1199 if ($course instanceof stdClass) {
1200 require_once($CFG->libdir. '/coursecatlib.php');
1201 $course = new course_in_list($course);
1203 $content = '';
1204 $classes = trim('coursebox clearfix '. $additionalclasses);
1205 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1206 $nametag = 'h3';
1207 } else {
1208 $classes .= ' collapsed';
1209 $nametag = 'div';
1212 // .coursebox
1213 $content .= html_writer::start_tag('div', array(
1214 'class' => $classes,
1215 'data-courseid' => $course->id,
1216 'data-type' => self::COURSECAT_TYPE_COURSE,
1219 $content .= html_writer::start_tag('div', array('class' => 'info'));
1221 // course name
1222 $coursename = $chelper->get_course_formatted_name($course);
1223 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', array('id' => $course->id)),
1224 $coursename, array('class' => $course->visible ? '' : 'dimmed'));
1225 $content .= html_writer::tag($nametag, $coursenamelink, array('class' => 'coursename'));
1226 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1227 $content .= html_writer::start_tag('div', array('class' => 'moreinfo'));
1228 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1229 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()) {
1230 $url = new moodle_url('/course/info.php', array('id' => $course->id));
1231 $image = html_writer::empty_tag('img', array('src' => $this->output->pix_url('i/info'),
1232 'alt' => $this->strings->summary));
1233 $content .= html_writer::link($url, $image, array('title' => $this->strings->summary));
1234 // Make sure JS file to expand course content is included.
1235 $this->coursecat_include_js();
1238 $content .= html_writer::end_tag('div'); // .moreinfo
1240 // print enrolmenticons
1241 if ($icons = enrol_get_course_info_icons($course)) {
1242 $content .= html_writer::start_tag('div', array('class' => 'enrolmenticons'));
1243 foreach ($icons as $pix_icon) {
1244 $content .= $this->render($pix_icon);
1246 $content .= html_writer::end_tag('div'); // .enrolmenticons
1249 $content .= html_writer::end_tag('div'); // .info
1251 $content .= html_writer::start_tag('div', array('class' => 'content'));
1252 $content .= $this->coursecat_coursebox_content($chelper, $course);
1253 $content .= html_writer::end_tag('div'); // .content
1255 $content .= html_writer::end_tag('div'); // .coursebox
1256 return $content;
1260 * Returns HTML to display course content (summary, course contacts and optionally category name)
1262 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1264 * @param coursecat_helper $chelper various display options
1265 * @param stdClass|course_in_list $course
1266 * @return string
1268 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1269 global $CFG;
1270 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1271 return '';
1273 if ($course instanceof stdClass) {
1274 require_once($CFG->libdir. '/coursecatlib.php');
1275 $course = new course_in_list($course);
1277 $content = '';
1279 // display course summary
1280 if ($course->has_summary()) {
1281 $content .= html_writer::start_tag('div', array('class' => 'summary'));
1282 $content .= $chelper->get_course_formatted_summary($course,
1283 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1284 $content .= html_writer::end_tag('div'); // .summary
1287 // display course overview files
1288 $contentimages = $contentfiles = '';
1289 foreach ($course->get_course_overviewfiles() as $file) {
1290 $isimage = $file->is_valid_image();
1291 $url = file_encode_url("$CFG->wwwroot/pluginfile.php",
1292 '/'. $file->get_contextid(). '/'. $file->get_component(). '/'.
1293 $file->get_filearea(). $file->get_filepath(). $file->get_filename(), !$isimage);
1294 if ($isimage) {
1295 $contentimages .= html_writer::tag('div',
1296 html_writer::empty_tag('img', array('src' => $url)),
1297 array('class' => 'courseimage'));
1298 } else {
1299 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1300 $filename = html_writer::tag('span', $image, array('class' => 'fp-icon')).
1301 html_writer::tag('span', $file->get_filename(), array('class' => 'fp-filename'));
1302 $contentfiles .= html_writer::tag('span',
1303 html_writer::link($url, $filename),
1304 array('class' => 'coursefile fp-filename-icon'));
1307 $content .= $contentimages. $contentfiles;
1309 // display course contacts. See course_in_list::get_course_contacts()
1310 if ($course->has_course_contacts()) {
1311 $content .= html_writer::start_tag('ul', array('class' => 'teachers'));
1312 foreach ($course->get_course_contacts() as $userid => $coursecontact) {
1313 $name = $coursecontact['rolename'].': '.
1314 html_writer::link(new moodle_url('/user/view.php',
1315 array('id' => $userid, 'course' => SITEID)),
1316 $coursecontact['username']);
1317 $content .= html_writer::tag('li', $name);
1319 $content .= html_writer::end_tag('ul'); // .teachers
1322 // display course category if necessary (for example in search results)
1323 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1324 require_once($CFG->libdir. '/coursecatlib.php');
1325 if ($cat = coursecat::get($course->category, IGNORE_MISSING)) {
1326 $content .= html_writer::start_tag('div', array('class' => 'coursecat'));
1327 $content .= get_string('category').': '.
1328 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1329 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1330 $content .= html_writer::end_tag('div'); // .coursecat
1334 return $content;
1338 * Renders the list of courses
1340 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1341 * method from outside of the class
1343 * If list of courses is specified in $courses; the argument $chelper is only used
1344 * to retrieve display options and attributes, only methods get_show_courses(),
1345 * get_courses_display_option() and get_and_erase_attributes() are called.
1347 * @param coursecat_helper $chelper various display options
1348 * @param array $courses the list of courses to display
1349 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1350 * defaulted to count($courses)
1351 * @return string
1353 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1354 global $CFG;
1355 if ($totalcount === null) {
1356 $totalcount = count($courses);
1358 if (!$totalcount) {
1359 // Courses count is cached during courses retrieval.
1360 return '';
1363 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1364 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1365 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1366 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1367 } else {
1368 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1372 // prepare content of paging bar if it is needed
1373 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1374 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1375 if ($totalcount > count($courses)) {
1376 // there are more results that can fit on one page
1377 if ($paginationurl) {
1378 // the option paginationurl was specified, display pagingbar
1379 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1380 $page = $chelper->get_courses_display_option('offset') / $perpage;
1381 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1382 $paginationurl->out(false, array('perpage' => $perpage)));
1383 if ($paginationallowall) {
1384 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1385 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1387 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1388 // the option for 'View more' link was specified, display more link
1389 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1390 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1391 array('class' => 'paging paging-morelink'));
1393 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1394 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1395 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1396 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1399 // display list of courses
1400 $attributes = $chelper->get_and_erase_attributes('courses');
1401 $content = html_writer::start_tag('div', $attributes);
1403 if (!empty($pagingbar)) {
1404 $content .= $pagingbar;
1407 $coursecount = 0;
1408 foreach ($courses as $course) {
1409 $coursecount ++;
1410 $classes = ($coursecount%2) ? 'odd' : 'even';
1411 if ($coursecount == 1) {
1412 $classes .= ' first';
1414 if ($coursecount >= count($courses)) {
1415 $classes .= ' last';
1417 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1420 if (!empty($pagingbar)) {
1421 $content .= $pagingbar;
1423 if (!empty($morelink)) {
1424 $content .= $morelink;
1427 $content .= html_writer::end_tag('div'); // .courses
1428 return $content;
1432 * Renders the list of subcategories in a category
1434 * @param coursecat_helper $chelper various display options
1435 * @param coursecat $coursecat
1436 * @param int $depth depth of the category in the current tree
1437 * @return string
1439 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1440 global $CFG;
1441 $subcategories = array();
1442 if (!$chelper->get_categories_display_option('nodisplay')) {
1443 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1445 $totalcount = $coursecat->get_children_count();
1446 if (!$totalcount) {
1447 // Note that we call get_child_categories_count() AFTER get_child_categories() to avoid extra DB requests.
1448 // Categories count is cached during children categories retrieval.
1449 return '';
1452 // prepare content of paging bar or more link if it is needed
1453 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1454 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1455 if ($totalcount > count($subcategories)) {
1456 if ($paginationurl) {
1457 // the option 'paginationurl was specified, display pagingbar
1458 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1459 $page = $chelper->get_categories_display_option('offset') / $perpage;
1460 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1461 $paginationurl->out(false, array('perpage' => $perpage)));
1462 if ($paginationallowall) {
1463 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1464 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1466 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1467 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1468 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1469 $viewmoreurl->param('categoryid', $coursecat->id);
1471 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1472 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1473 array('class' => 'paging paging-morelink'));
1475 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1476 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1477 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1478 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1481 // display list of subcategories
1482 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1484 if (!empty($pagingbar)) {
1485 $content .= $pagingbar;
1488 foreach ($subcategories as $subcategory) {
1489 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1492 if (!empty($pagingbar)) {
1493 $content .= $pagingbar;
1495 if (!empty($morelink)) {
1496 $content .= $morelink;
1499 $content .= html_writer::end_tag('div');
1500 return $content;
1504 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1506 protected function coursecat_include_js() {
1507 global $CFG;
1508 static $jsloaded = false;
1509 if (!$jsloaded) {
1510 // We must only load this module once.
1511 $this->page->requires->yui_module('moodle-course-categoryexpander',
1512 'Y.Moodle.course.categoryexpander.init');
1513 $jsloaded = true;
1518 * Returns HTML to display the subcategories and courses in the given category
1520 * This method is re-used by AJAX to expand content of not loaded category
1522 * @param coursecat_helper $chelper various display options
1523 * @param coursecat $coursecat
1524 * @param int $depth depth of the category in the current tree
1525 * @return string
1527 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1528 $content = '';
1529 // Subcategories
1530 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1532 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1533 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1534 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1535 if ($showcoursesauto && $depth) {
1536 // this is definitely collapsed mode
1537 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1540 // Courses
1541 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1542 $courses = array();
1543 if (!$chelper->get_courses_display_option('nodisplay')) {
1544 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1546 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1547 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1548 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1549 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1552 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1555 if ($showcoursesauto) {
1556 // restore the show_courses back to AUTO
1557 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1560 return $content;
1564 * Returns HTML to display a course category as a part of a tree
1566 * This is an internal function, to display a particular category and all its contents
1567 * use {@link core_course_renderer::course_category()}
1569 * @param coursecat_helper $chelper various display options
1570 * @param coursecat $coursecat
1571 * @param int $depth depth of this category in the current tree
1572 * @return string
1574 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1575 // open category tag
1576 $classes = array('category');
1577 if (empty($coursecat->visible)) {
1578 $classes[] = 'dimmed_category';
1580 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1581 // do not load content
1582 $categorycontent = '';
1583 $classes[] = 'notloaded';
1584 if ($coursecat->get_children_count() ||
1585 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1586 $classes[] = 'with_children';
1587 $classes[] = 'collapsed';
1589 } else {
1590 // load category content
1591 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1592 $classes[] = 'loaded';
1593 if (!empty($categorycontent)) {
1594 $classes[] = 'with_children';
1598 // Make sure JS file to expand category content is included.
1599 $this->coursecat_include_js();
1601 $content = html_writer::start_tag('div', array(
1602 'class' => join(' ', $classes),
1603 'data-categoryid' => $coursecat->id,
1604 'data-depth' => $depth,
1605 'data-showcourses' => $chelper->get_show_courses(),
1606 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1609 // category name
1610 $categoryname = $coursecat->get_formatted_name();
1611 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1612 array('categoryid' => $coursecat->id)),
1613 $categoryname);
1614 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1615 && ($coursescount = $coursecat->get_courses_count())) {
1616 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1617 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1619 $content .= html_writer::start_tag('div', array('class' => 'info'));
1621 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname'));
1622 $content .= html_writer::end_tag('div'); // .info
1624 // add category content to the output
1625 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1627 $content .= html_writer::end_tag('div'); // .category
1629 // Return the course category tree HTML
1630 return $content;
1634 * Returns HTML to display a tree of subcategories and courses in the given category
1636 * @param coursecat_helper $chelper various display options
1637 * @param coursecat $coursecat top category (this category's name and description will NOT be added to the tree)
1638 * @return string
1640 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1641 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1642 if (empty($categorycontent)) {
1643 return '';
1646 // Start content generation
1647 $content = '';
1648 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1649 $content .= html_writer::start_tag('div', $attributes);
1651 if ($coursecat->get_children_count()) {
1652 $classes = array(
1653 'collapseexpand',
1654 'collapse-all',
1656 if ($chelper->get_subcat_depth() == 1) {
1657 $classes[] = 'disabled';
1659 // Only show the collapse/expand if there are children to expand.
1660 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1661 $content .= html_writer::link('#', get_string('collapseall'),
1662 array('class' => implode(' ', $classes)));
1663 $content .= html_writer::end_tag('div');
1664 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1667 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1669 $content .= html_writer::end_tag('div'); // .course_category_tree
1671 return $content;
1675 * Renders HTML to display particular course category - list of it's subcategories and courses
1677 * Invoked from /course/index.php
1679 * @param int|stdClass|coursecat $category
1681 public function course_category($category) {
1682 global $CFG;
1683 require_once($CFG->libdir. '/coursecatlib.php');
1684 $coursecat = coursecat::get(is_object($category) ? $category->id : $category);
1685 $site = get_site();
1686 $output = '';
1688 $this->page->set_button($this->course_search_form('', 'navbar'));
1689 if (!$coursecat->id) {
1690 if (can_edit_in_category()) {
1691 // add 'Manage' button instead of course search form
1692 $managebutton = $this->single_button(new moodle_url('/course/management.php'), get_string('managecourses'), 'get');
1693 $this->page->set_button($managebutton);
1695 if (coursecat::count_all() == 1) {
1696 // There exists only one category in the system, do not display link to it
1697 $coursecat = coursecat::get_default();
1698 $strfulllistofcourses = get_string('fulllistofcourses');
1699 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1700 } else {
1701 $strcategories = get_string('categories');
1702 $this->page->set_title("$site->shortname: $strcategories");
1704 } else {
1705 $this->page->set_title("$site->shortname: ". $coursecat->get_formatted_name());
1707 // Print the category selector
1708 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1709 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1710 coursecat::make_categories_list(), $coursecat->id, null, 'switchcategory');
1711 $select->set_label(get_string('categories').':');
1712 $output .= $this->render($select);
1713 $output .= html_writer::end_tag('div'); // .categorypicker
1716 // Print current category description
1717 $chelper = new coursecat_helper();
1718 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1719 $output .= $this->box($description, array('class' => 'generalbox info'));
1722 // Prepare parameters for courses and categories lists in the tree
1723 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1724 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1726 $coursedisplayoptions = array();
1727 $catdisplayoptions = array();
1728 $browse = optional_param('browse', null, PARAM_ALPHA);
1729 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1730 $page = optional_param('page', 0, PARAM_INT);
1731 $baseurl = new moodle_url('/course/index.php');
1732 if ($coursecat->id) {
1733 $baseurl->param('categoryid', $coursecat->id);
1735 if ($perpage != $CFG->coursesperpage) {
1736 $baseurl->param('perpage', $perpage);
1738 $coursedisplayoptions['limit'] = $perpage;
1739 $catdisplayoptions['limit'] = $perpage;
1740 if ($browse === 'courses' || !$coursecat->has_children()) {
1741 $coursedisplayoptions['offset'] = $page * $perpage;
1742 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1743 $catdisplayoptions['nodisplay'] = true;
1744 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1745 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1746 } else if ($browse === 'categories' || !$coursecat->has_courses()) {
1747 $coursedisplayoptions['nodisplay'] = true;
1748 $catdisplayoptions['offset'] = $page * $perpage;
1749 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1750 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1751 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1752 } else {
1753 // we have a category that has both subcategories and courses, display pagination separately
1754 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1755 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1757 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1759 // Display course category tree
1760 $output .= $this->coursecat_tree($chelper, $coursecat);
1762 // Add course search form (if we are inside category it was already added to the navbar)
1763 if (!$coursecat->id) {
1764 $output .= $this->course_search_form();
1767 // Add action buttons
1768 $output .= $this->container_start('buttons');
1769 $context = get_category_or_system_context($coursecat->id);
1770 if (has_capability('moodle/course:create', $context)) {
1771 // Print link to create a new course, for the 1st available category.
1772 if ($coursecat->id) {
1773 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1774 } else {
1775 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1777 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1779 ob_start();
1780 if (coursecat::count_all() == 1) {
1781 print_course_request_buttons(context_system::instance());
1782 } else {
1783 print_course_request_buttons($context);
1785 $output .= ob_get_contents();
1786 ob_end_clean();
1787 $output .= $this->container_end();
1789 return $output;
1793 * Serves requests to /course/category.ajax.php
1795 * In this renderer implementation it may expand the category content or
1796 * course content.
1798 * @return string
1799 * @throws coding_exception
1801 public function coursecat_ajax() {
1802 global $DB, $CFG;
1803 require_once($CFG->libdir. '/coursecatlib.php');
1805 $type = required_param('type', PARAM_INT);
1807 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1808 // This is a request for a category list of some kind.
1809 $categoryid = required_param('categoryid', PARAM_INT);
1810 $showcourses = required_param('showcourses', PARAM_INT);
1811 $depth = required_param('depth', PARAM_INT);
1813 $category = coursecat::get($categoryid);
1815 $chelper = new coursecat_helper();
1816 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1817 $coursedisplayoptions = array(
1818 'limit' => $CFG->coursesperpage,
1819 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1821 $catdisplayoptions = array(
1822 'limit' => $CFG->coursesperpage,
1823 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1825 $chelper->set_show_courses($showcourses)->
1826 set_courses_display_options($coursedisplayoptions)->
1827 set_categories_display_options($catdisplayoptions);
1829 return $this->coursecat_category_content($chelper, $category, $depth);
1830 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1831 // This is a request for the course information.
1832 $courseid = required_param('courseid', PARAM_INT);
1834 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1836 $chelper = new coursecat_helper();
1837 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1838 return $this->coursecat_coursebox_content($chelper, $course);
1839 } else {
1840 throw new coding_exception('Invalid request type');
1845 * Renders html to display search result page
1847 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1848 * @return string
1850 public function search_courses($searchcriteria) {
1851 global $CFG;
1852 $content = '';
1853 if (!empty($searchcriteria)) {
1854 // print search results
1855 require_once($CFG->libdir. '/coursecatlib.php');
1857 $displayoptions = array('sort' => array('displayname' => 1));
1858 // take the current page and number of results per page from query
1859 $perpage = optional_param('perpage', 0, PARAM_RAW);
1860 if ($perpage !== 'all') {
1861 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1862 $page = optional_param('page', 0, PARAM_INT);
1863 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1865 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1866 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1867 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1869 $class = 'course-search-result';
1870 foreach ($searchcriteria as $key => $value) {
1871 if (!empty($value)) {
1872 $class .= ' course-search-result-'. $key;
1875 $chelper = new coursecat_helper();
1876 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1877 set_courses_display_options($displayoptions)->
1878 set_search_criteria($searchcriteria)->
1879 set_attributes(array('class' => $class));
1881 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1882 $totalcount = coursecat::search_courses_count($searchcriteria);
1883 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1885 if (!$totalcount) {
1886 if (!empty($searchcriteria['search'])) {
1887 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1888 } else {
1889 $content .= $this->heading(get_string('novalidcourses'));
1891 } else {
1892 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1893 $content .= $courseslist;
1896 if (!empty($searchcriteria['search'])) {
1897 // print search form only if there was a search by search string, otherwise it is confusing
1898 $content .= $this->box_start('generalbox mdl-align');
1899 $content .= $this->course_search_form($searchcriteria['search']);
1900 $content .= $this->box_end();
1902 } else {
1903 // just print search form
1904 $content .= $this->box_start('generalbox mdl-align');
1905 $content .= $this->course_search_form();
1906 $content .= html_writer::tag('div', get_string("searchhelp"), array('class' => 'searchhelp'));
1907 $content .= $this->box_end();
1909 return $content;
1913 * Renders html to print list of courses tagged with particular tag
1915 * @param int $tagid id of the tag
1916 * @return string empty string if no courses are marked with this tag or rendered list of courses
1918 public function tagged_courses($tagid) {
1919 global $CFG;
1920 require_once($CFG->libdir. '/coursecatlib.php');
1921 $displayoptions = array('limit' => $CFG->coursesperpage);
1922 $displayoptions['viewmoreurl'] = new moodle_url('/course/search.php',
1923 array('tagid' => $tagid, 'page' => 1, 'perpage' => $CFG->coursesperpage));
1924 $displayoptions['viewmoretext'] = new lang_string('findmorecourses');
1925 $chelper = new coursecat_helper();
1926 $searchcriteria = array('tagid' => $tagid);
1927 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1928 set_search_criteria(array('tagid' => $tagid))->
1929 set_courses_display_options($displayoptions)->
1930 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1931 // (we set the same css class as in search results by tagid)
1932 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1933 $totalcount = coursecat::search_courses_count($searchcriteria);
1934 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1935 if ($totalcount) {
1936 require_once $CFG->dirroot.'/tag/lib.php';
1937 $heading = get_string('courses') . ' ' . get_string('taggedwith', 'tag', tag_get_name($tagid)) .': '. $totalcount;
1938 return $this->heading($heading, 3). $content;
1940 return '';
1944 * Returns HTML to display one remote course
1946 * @param stdClass $course remote course information, contains properties:
1947 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1948 * @return string
1950 protected function frontpage_remote_course(stdClass $course) {
1951 $url = new moodle_url('/auth/mnet/jump.php', array(
1952 'hostid' => $course->hostid,
1953 'wantsurl' => '/course/view.php?id='. $course->remoteid
1956 $output = '';
1957 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1958 $output .= html_writer::start_tag('div', array('class' => 'info'));
1959 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1960 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1961 $output .= html_writer::end_tag('h3'); // .name
1962 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1963 $output .= html_writer::end_tag('div'); // .info
1964 $output .= html_writer::start_tag('div', array('class' => 'content'));
1965 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1966 $options = new stdClass();
1967 $options->noclean = true;
1968 $options->para = false;
1969 $options->overflowdiv = true;
1970 $output .= format_text($course->summary, $course->summaryformat, $options);
1971 $output .= html_writer::end_tag('div'); // .summary
1972 $addinfo = format_string($course->hostname) . ' : '
1973 . format_string($course->cat_name) . ' : '
1974 . format_string($course->shortname);
1975 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1976 $output .= html_writer::end_tag('div'); // .content
1977 $output .= html_writer::end_tag('div'); // .coursebox
1978 return $output;
1982 * Returns HTML to display one remote host
1984 * @param array $host host information, contains properties: name, url, count
1985 * @return string
1987 protected function frontpage_remote_host($host) {
1988 $output = '';
1989 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1990 $output .= html_writer::start_tag('div', array('class' => 'info'));
1991 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1992 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1993 $output .= html_writer::end_tag('h3'); // .name
1994 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1995 $output .= html_writer::end_tag('div'); // .info
1996 $output .= html_writer::start_tag('div', array('class' => 'content'));
1997 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1998 $output .= $host['count'] . ' ' . get_string('courses');
1999 $output .= html_writer::end_tag('div'); // .content
2000 $output .= html_writer::end_tag('div'); // .coursebox
2001 return $output;
2005 * Returns HTML to print list of courses user is enrolled to for the frontpage
2007 * Also lists remote courses or remote hosts if MNET authorisation is used
2009 * @return string
2011 public function frontpage_my_courses() {
2012 global $USER, $CFG, $DB;
2014 if (!isloggedin() or isguestuser()) {
2015 return '';
2018 $output = '';
2019 if (!empty($CFG->navsortmycoursessort)) {
2020 // sort courses the same as in navigation menu
2021 $sortorder = 'visible DESC,'. $CFG->navsortmycoursessort.' ASC';
2022 } else {
2023 $sortorder = 'visible DESC,sortorder ASC';
2025 $courses = enrol_get_my_courses('summary, summaryformat', $sortorder);
2026 $rhosts = array();
2027 $rcourses = array();
2028 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
2029 $rcourses = get_my_remotecourses($USER->id);
2030 $rhosts = get_my_remotehosts();
2033 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2035 $chelper = new coursecat_helper();
2036 if (count($courses) > $CFG->frontpagecourselimit) {
2037 // There are more enrolled courses than we can display, display link to 'My courses'.
2038 $totalcount = count($courses);
2039 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
2040 $chelper->set_courses_display_options(array(
2041 'viewmoreurl' => new moodle_url('/my/'),
2042 'viewmoretext' => new lang_string('mycourses')
2044 } else {
2045 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
2046 $chelper->set_courses_display_options(array(
2047 'viewmoreurl' => new moodle_url('/course/index.php'),
2048 'viewmoretext' => new lang_string('fulllistofcourses')
2050 $totalcount = $DB->count_records('course') - 1;
2052 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2053 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
2054 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
2056 // MNET
2057 if (!empty($rcourses)) {
2058 // at the IDP, we know of all the remote courses
2059 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2060 foreach ($rcourses as $course) {
2061 $output .= $this->frontpage_remote_course($course);
2063 $output .= html_writer::end_tag('div'); // .courses
2064 } elseif (!empty($rhosts)) {
2065 // non-IDP, we know of all the remote servers, but not courses
2066 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2067 foreach ($rhosts as $host) {
2068 $output .= $this->frontpage_remote_host($host);
2070 $output .= html_writer::end_tag('div'); // .courses
2073 return $output;
2077 * Returns HTML to print list of available courses for the frontpage
2079 * @return string
2081 public function frontpage_available_courses() {
2082 global $CFG;
2083 require_once($CFG->libdir. '/coursecatlib.php');
2085 $chelper = new coursecat_helper();
2086 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2087 set_courses_display_options(array(
2088 'recursive' => true,
2089 'limit' => $CFG->frontpagecourselimit,
2090 'viewmoreurl' => new moodle_url('/course/index.php'),
2091 'viewmoretext' => new lang_string('fulllistofcourses')));
2093 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
2094 $courses = coursecat::get(0)->get_courses($chelper->get_courses_display_options());
2095 $totalcount = coursecat::get(0)->get_courses_count($chelper->get_courses_display_options());
2096 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
2097 // Print link to create a new course, for the 1st available category.
2098 return $this->add_new_course_button();
2100 return $this->coursecat_courses($chelper, $courses, $totalcount);
2104 * Returns HTML to the "add new course" button for the page
2106 * @return string
2108 public function add_new_course_button() {
2109 global $CFG;
2110 // Print link to create a new course, for the 1st available category.
2111 $output = $this->container_start('buttons');
2112 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2113 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2114 $output .= $this->container_end('buttons');
2115 return $output;
2119 * Returns HTML to print tree with course categories and courses for the frontpage
2121 * @return string
2123 public function frontpage_combo_list() {
2124 global $CFG;
2125 require_once($CFG->libdir. '/coursecatlib.php');
2126 $chelper = new coursecat_helper();
2127 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2128 set_categories_display_options(array(
2129 'limit' => $CFG->coursesperpage,
2130 'viewmoreurl' => new moodle_url('/course/index.php',
2131 array('browse' => 'categories', 'page' => 1))
2132 ))->
2133 set_courses_display_options(array(
2134 'limit' => $CFG->coursesperpage,
2135 'viewmoreurl' => new moodle_url('/course/index.php',
2136 array('browse' => 'courses', 'page' => 1))
2137 ))->
2138 set_attributes(array('class' => 'frontpage-category-combo'));
2139 return $this->coursecat_tree($chelper, coursecat::get(0));
2143 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2145 * @return string
2147 public function frontpage_categories_list() {
2148 global $CFG;
2149 require_once($CFG->libdir. '/coursecatlib.php');
2150 $chelper = new coursecat_helper();
2151 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2152 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2153 set_categories_display_options(array(
2154 'limit' => $CFG->coursesperpage,
2155 'viewmoreurl' => new moodle_url('/course/index.php',
2156 array('browse' => 'categories', 'page' => 1))
2157 ))->
2158 set_attributes(array('class' => 'frontpage-category-names'));
2159 return $this->coursecat_tree($chelper, coursecat::get(0));
2164 * Class storing display options and functions to help display course category and/or courses lists
2166 * This is a wrapper for coursecat objects that also stores display options
2167 * and functions to retrieve sorted and paginated lists of categories/courses.
2169 * If theme overrides methods in core_course_renderers that access this class
2170 * it may as well not use this class at all or extend it.
2172 * @package core
2173 * @copyright 2013 Marina Glancy
2174 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2176 class coursecat_helper {
2177 /** @var string [none, collapsed, expanded] how (if) display courses list */
2178 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2179 /** @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) */
2180 protected $subcatdepth = 1;
2181 /** @var array options to display courses list */
2182 protected $coursesdisplayoptions = array();
2183 /** @var array options to display subcategories list */
2184 protected $categoriesdisplayoptions = array();
2185 /** @var array additional HTML attributes */
2186 protected $attributes = array();
2187 /** @var array search criteria if the list is a search result */
2188 protected $searchcriteria = null;
2191 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2193 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2194 * @return coursecat_helper
2196 public function set_show_courses($showcourses) {
2197 $this->showcourses = $showcourses;
2198 // Automatically set the options to preload summary and coursecontacts for coursecat::get_courses() and coursecat::search_courses()
2199 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2200 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2201 return $this;
2205 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2207 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2209 public function get_show_courses() {
2210 return $this->showcourses;
2214 * Sets the maximum depth to expand subcategories in the tree
2216 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2218 * @param int $subcatdepth
2219 * @return coursecat_helper
2221 public function set_subcat_depth($subcatdepth) {
2222 $this->subcatdepth = $subcatdepth;
2223 return $this;
2227 * Returns the maximum depth to expand subcategories in the tree
2229 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2231 * @return int
2233 public function get_subcat_depth() {
2234 return $this->subcatdepth;
2238 * Sets options to display list of courses
2240 * Options are later submitted as argument to coursecat::get_courses() and/or coursecat::search_courses()
2242 * Options that coursecat::get_courses() accept:
2243 * - recursive - return courses from subcategories as well. Use with care,
2244 * this may be a huge list!
2245 * - summary - preloads fields 'summary' and 'summaryformat'
2246 * - coursecontacts - preloads course contacts
2247 * - isenrolled - preloads indication whether this user is enrolled in the course
2248 * - sort - list of fields to sort. Example
2249 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2250 * will sort by idnumber asc, shortname asc and id desc.
2251 * Default: array('sortorder' => 1)
2252 * Only cached fields may be used for sorting!
2253 * - offset
2254 * - limit - maximum number of children to return, 0 or null for no limit
2256 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2258 * Also renderer can set here any additional options it wants to pass between renderer functions.
2260 * @param array $options
2261 * @return coursecat_helper
2263 public function set_courses_display_options($options) {
2264 $this->coursesdisplayoptions = $options;
2265 $this->set_show_courses($this->showcourses); // this will calculate special display options
2266 return $this;
2270 * Sets one option to display list of courses
2272 * @see coursecat_helper::set_courses_display_options()
2274 * @param string $key
2275 * @param mixed $value
2276 * @return coursecat_helper
2278 public function set_courses_display_option($key, $value) {
2279 $this->coursesdisplayoptions[$key] = $value;
2280 return $this;
2284 * Return the specified option to display list of courses
2286 * @param string $optionname option name
2287 * @param mixed $defaultvalue default value for option if it is not specified
2288 * @return mixed
2290 public function get_courses_display_option($optionname, $defaultvalue = null) {
2291 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2292 return $this->coursesdisplayoptions[$optionname];
2293 } else {
2294 return $defaultvalue;
2299 * Returns all options to display the courses
2301 * This array is usually passed to {@link coursecat::get_courses()} or
2302 * {@link coursecat::search_courses()}
2304 * @return array
2306 public function get_courses_display_options() {
2307 return $this->coursesdisplayoptions;
2311 * Sets options to display list of subcategories
2313 * Options 'sort', 'offset' and 'limit' are passed to coursecat::get_children().
2314 * Any other options may be used by renderer functions
2316 * @param array $options
2317 * @return coursecat_helper
2319 public function set_categories_display_options($options) {
2320 $this->categoriesdisplayoptions = $options;
2321 return $this;
2325 * Return the specified option to display list of subcategories
2327 * @param string $optionname option name
2328 * @param mixed $defaultvalue default value for option if it is not specified
2329 * @return mixed
2331 public function get_categories_display_option($optionname, $defaultvalue = null) {
2332 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2333 return $this->categoriesdisplayoptions[$optionname];
2334 } else {
2335 return $defaultvalue;
2340 * Returns all options to display list of subcategories
2342 * This array is usually passed to {@link coursecat::get_children()}
2344 * @return array
2346 public function get_categories_display_options() {
2347 return $this->categoriesdisplayoptions;
2351 * Sets additional general options to pass between renderer functions, usually HTML attributes
2353 * @param array $attributes
2354 * @return coursecat_helper
2356 public function set_attributes($attributes) {
2357 $this->attributes = $attributes;
2358 return $this;
2362 * Return all attributes and erases them so they are not applied again
2364 * @param string $classname adds additional class name to the beginning of $attributes['class']
2365 * @return array
2367 public function get_and_erase_attributes($classname) {
2368 $attributes = $this->attributes;
2369 $this->attributes = array();
2370 if (empty($attributes['class'])) {
2371 $attributes['class'] = '';
2373 $attributes['class'] = $classname . ' '. $attributes['class'];
2374 return $attributes;
2378 * Sets the search criteria if the course is a search result
2380 * Search string will be used to highlight terms in course name and description
2382 * @param array $searchcriteria
2383 * @return coursecat_helper
2385 public function set_search_criteria($searchcriteria) {
2386 $this->searchcriteria = $searchcriteria;
2387 return $this;
2391 * Returns formatted and filtered description of the given category
2393 * @param coursecat $coursecat category
2394 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2395 * if context is not specified it will be added automatically
2396 * @return string|null
2398 public function get_category_formatted_description($coursecat, $options = null) {
2399 if ($coursecat->id && !empty($coursecat->description)) {
2400 if (!isset($coursecat->descriptionformat)) {
2401 $descriptionformat = FORMAT_MOODLE;
2402 } else {
2403 $descriptionformat = $coursecat->descriptionformat;
2405 if ($options === null) {
2406 $options = array('noclean' => true, 'overflowdiv' => true);
2407 } else {
2408 $options = (array)$options;
2410 $context = context_coursecat::instance($coursecat->id);
2411 if (!isset($options['context'])) {
2412 $options['context'] = $context;
2414 $text = file_rewrite_pluginfile_urls($coursecat->description,
2415 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2416 return format_text($text, $descriptionformat, $options);
2418 return null;
2422 * Returns given course's summary with proper embedded files urls and formatted
2424 * @param course_in_list $course
2425 * @param array|stdClass $options additional formatting options
2426 * @return string
2428 public function get_course_formatted_summary($course, $options = array()) {
2429 global $CFG;
2430 require_once($CFG->libdir. '/filelib.php');
2431 if (!$course->has_summary()) {
2432 return '';
2434 $options = (array)$options;
2435 $context = context_course::instance($course->id);
2436 if (!isset($options['context'])) {
2437 // TODO see MDL-38521
2438 // option 1 (current), page context - no code required
2439 // option 2, system context
2440 // $options['context'] = context_system::instance();
2441 // option 3, course context:
2442 // $options['context'] = $context;
2443 // option 4, course category context:
2444 // $options['context'] = $context->get_parent_context();
2446 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2447 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2448 if (!empty($this->searchcriteria['search'])) {
2449 $summary = highlight($this->searchcriteria['search'], $summary);
2451 return $summary;
2455 * Returns course name as it is configured to appear in courses lists formatted to course context
2457 * @param course_in_list $course
2458 * @param array|stdClass $options additional formatting options
2459 * @return string
2461 public function get_course_formatted_name($course, $options = array()) {
2462 $options = (array)$options;
2463 if (!isset($options['context'])) {
2464 $options['context'] = context_course::instance($course->id);
2466 $name = format_string(get_course_display_name_for_list($course), true, $options);
2467 if (!empty($this->searchcriteria['search'])) {
2468 $name = highlight($this->searchcriteria['search'], $name);
2470 return $name;