MDL-41806 Add assessors to moodle_url class
[moodle.git] / course / renderer.php
blob8096fd60385d579e7a867517bdc52e51f6cbdf57
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Renderer for use with the course section and all the goodness that falls
20 * within it.
22 * This renderer should contain methods useful to courses, and categories.
24 * @package moodlecore
25 * @copyright 2010 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 /**
30 * The core course renderer
32 * Can be retrieved with the following:
33 * $renderer = $PAGE->get_renderer('core','course');
35 class core_course_renderer extends plugin_renderer_base {
36 const COURSECAT_SHOW_COURSES_NONE = 0; /* do not show courses at all */
37 const COURSECAT_SHOW_COURSES_COUNT = 5; /* do not show courses but show number of courses next to category name */
38 const COURSECAT_SHOW_COURSES_COLLAPSED = 10;
39 const COURSECAT_SHOW_COURSES_AUTO = 15; /* will choose between collapsed and expanded automatically */
40 const COURSECAT_SHOW_COURSES_EXPANDED = 20;
41 const COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT = 30;
43 /**
44 * A cache of strings
45 * @var stdClass
47 protected $strings;
49 /**
50 * Override the constructor so that we can initialise the string cache
52 * @param moodle_page $page
53 * @param string $target
55 public function __construct(moodle_page $page, $target) {
56 $this->strings = new stdClass;
57 parent::__construct($page, $target);
58 $this->add_modchoosertoggle();
61 /**
62 * Adds the item in course settings navigation to toggle modchooser
64 * Theme can overwrite as an empty function to exclude it (for example if theme does not
65 * use modchooser at all)
67 protected function add_modchoosertoggle() {
68 global $CFG;
69 static $modchoosertoggleadded = false;
70 // Add the module chooser toggle to the course page
71 if ($modchoosertoggleadded || $this->page->state > moodle_page::STATE_PRINTING_HEADER ||
72 $this->page->course->id == SITEID ||
73 !$this->page->user_is_editing() ||
74 !($context = context_course::instance($this->page->course->id)) ||
75 !has_capability('moodle/course:manageactivities', $context) ||
76 !course_ajax_enabled($this->page->course) ||
77 !($coursenode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE)) ||
78 !($turneditingnode = $coursenode->get('turneditingonoff'))) {
79 // too late or we are on site page or we could not find the adjacent nodes in course settings menu
80 // or we are not allowed to edit
81 return;
83 $modchoosertoggleadded = true;
84 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
85 // We are on the course page, retain the current page params e.g. section.
86 $modchoosertoggleurl = clone($this->page->url);
87 } else {
88 // Edit on the main course page.
89 $modchoosertoggleurl = new moodle_url('/course/view.php', array('id' => $this->page->course->id,
90 'return' => $this->page->url->out_as_local_url(false)));
92 $modchoosertoggleurl->param('sesskey', sesskey());
93 if ($usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault)) {
94 $modchoosertogglestring = get_string('modchooserdisable', 'moodle');
95 $modchoosertoggleurl->param('modchooser', 'off');
96 } else {
97 $modchoosertogglestring = get_string('modchooserenable', 'moodle');
98 $modchoosertoggleurl->param('modchooser', 'on');
100 $modchoosertoggle = navigation_node::create($modchoosertogglestring, $modchoosertoggleurl, navigation_node::TYPE_SETTING, null, 'modchoosertoggle');
102 // Insert the modchoosertoggle after the settings node 'turneditingonoff' (navigation_node only has function to insert before, so we insert before and then swap).
103 $coursenode->add_node($modchoosertoggle, 'turneditingonoff');
104 $turneditingnode->remove();
105 $coursenode->add_node($turneditingnode, 'modchoosertoggle');
107 $modchoosertoggle->add_class('modchoosertoggle');
108 $modchoosertoggle->add_class('visibleifjs');
109 user_preference_allow_ajax_update('usemodchooser', PARAM_BOOL);
113 * Renders course info box.
115 * @param stdClass|course_in_list $course
116 * @return string
118 public function course_info_box(stdClass $course) {
119 $content = '';
120 $content .= $this->output->box_start('generalbox info');
121 $chelper = new coursecat_helper();
122 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
123 $content .= $this->coursecat_coursebox($chelper, $course);
124 $content .= $this->output->box_end();
125 return $content;
129 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
131 * @deprecated since 2.5
133 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
135 * @param array $ignored argument ignored
136 * @return string
138 public final function course_category_tree(array $ignored) {
139 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
140 return $this->frontpage_combo_list();
144 * Renderers a category for use with course_category_tree
146 * @deprecated since 2.5
148 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
150 * @param array $category
151 * @param int $depth
152 * @return string
154 protected final function course_category_tree_category(stdClass $category, $depth=1) {
155 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
156 return '';
160 * Build the HTML for the module chooser javascript popup
162 * @param array $modules A set of modules as returned form @see
163 * get_module_metadata
164 * @param object $course The course that will be displayed
165 * @return string The composed HTML for the module
167 public function course_modchooser($modules, $course) {
168 static $isdisplayed = false;
169 if ($isdisplayed) {
170 return '';
172 $isdisplayed = true;
174 // Add the module chooser
175 $this->page->requires->yui_module('moodle-course-modchooser',
176 'M.course.init_chooser',
177 array(array('courseid' => $course->id, 'closeButtonTitle' => get_string('close', 'editor')))
179 $this->page->requires->strings_for_js(array(
180 'addresourceoractivity',
181 'modchooserenable',
182 'modchooserdisable',
183 ), 'moodle');
185 // Add the header
186 $header = html_writer::tag('div', get_string('addresourceoractivity', 'moodle'),
187 array('class' => 'hd choosertitle'));
189 $formcontent = html_writer::start_tag('form', array('action' => new moodle_url('/course/jumpto.php'),
190 'id' => 'chooserform', 'method' => 'post'));
191 $formcontent .= html_writer::start_tag('div', array('id' => 'typeformdiv'));
192 $formcontent .= html_writer::tag('input', '', array('type' => 'hidden', 'id' => 'course',
193 'name' => 'course', 'value' => $course->id));
194 $formcontent .= html_writer::tag('input', '',
195 array('type' => 'hidden', 'class' => 'jump', 'name' => 'jump', 'value' => ''));
196 $formcontent .= html_writer::tag('input', '', array('type' => 'hidden', 'name' => 'sesskey',
197 'value' => sesskey()));
198 $formcontent .= html_writer::end_tag('div');
200 // Put everything into one tag 'options'
201 $formcontent .= html_writer::start_tag('div', array('class' => 'options'));
202 $formcontent .= html_writer::tag('div', get_string('selectmoduletoviewhelp', 'moodle'),
203 array('class' => 'instruction'));
204 // Put all options into one tag 'alloptions' to allow us to handle scrolling
205 $formcontent .= html_writer::start_tag('div', array('class' => 'alloptions'));
207 // Activities
208 $activities = array_filter($modules, create_function('$mod', 'return ($mod->archetype !== MOD_ARCHETYPE_RESOURCE && $mod->archetype !== MOD_ARCHETYPE_SYSTEM);'));
209 if (count($activities)) {
210 $formcontent .= $this->course_modchooser_title('activities');
211 $formcontent .= $this->course_modchooser_module_types($activities);
214 // Resources
215 $resources = array_filter($modules, create_function('$mod', 'return ($mod->archetype === MOD_ARCHETYPE_RESOURCE);'));
216 if (count($resources)) {
217 $formcontent .= $this->course_modchooser_title('resources');
218 $formcontent .= $this->course_modchooser_module_types($resources);
221 $formcontent .= html_writer::end_tag('div'); // modoptions
222 $formcontent .= html_writer::end_tag('div'); // types
224 $formcontent .= html_writer::start_tag('div', array('class' => 'submitbuttons'));
225 $formcontent .= html_writer::tag('input', '',
226 array('type' => 'submit', 'name' => 'submitbutton', 'class' => 'submitbutton', 'value' => get_string('add')));
227 $formcontent .= html_writer::tag('input', '',
228 array('type' => 'submit', 'name' => 'addcancel', 'class' => 'addcancel', 'value' => get_string('cancel')));
229 $formcontent .= html_writer::end_tag('div');
230 $formcontent .= html_writer::end_tag('form');
232 // Wrap the whole form in a div
233 $formcontent = html_writer::tag('div', $formcontent, array('id' => 'chooseform'));
235 // Put all of the content together
236 $content = $formcontent;
238 $content = html_writer::tag('div', $content, array('class' => 'choosercontainer'));
239 return $header . html_writer::tag('div', $content, array('class' => 'chooserdialoguebody'));
243 * Build the HTML for a specified set of modules
245 * @param array $modules A set of modules as used by the
246 * course_modchooser_module function
247 * @return string The composed HTML for the module
249 protected function course_modchooser_module_types($modules) {
250 $return = '';
251 foreach ($modules as $module) {
252 if (!isset($module->types)) {
253 $return .= $this->course_modchooser_module($module);
254 } else {
255 $return .= $this->course_modchooser_module($module, array('nonoption'));
256 foreach ($module->types as $type) {
257 $return .= $this->course_modchooser_module($type, array('option', 'subtype'));
261 return $return;
265 * Return the HTML for the specified module adding any required classes
267 * @param object $module An object containing the title, and link. An
268 * icon, and help text may optionally be specified. If the module
269 * contains subtypes in the types option, then these will also be
270 * displayed.
271 * @param array $classes Additional classes to add to the encompassing
272 * div element
273 * @return string The composed HTML for the module
275 protected function course_modchooser_module($module, $classes = array('option')) {
276 $output = '';
277 $output .= html_writer::start_tag('div', array('class' => implode(' ', $classes)));
278 $output .= html_writer::start_tag('label', array('for' => 'module_' . $module->name));
279 if (!isset($module->types)) {
280 $output .= html_writer::tag('input', '', array('type' => 'radio',
281 'name' => 'jumplink', 'id' => 'module_' . $module->name, 'value' => $module->link));
284 $output .= html_writer::start_tag('span', array('class' => 'modicon'));
285 if (isset($module->icon)) {
286 // Add an icon if we have one
287 $output .= $module->icon;
289 $output .= html_writer::end_tag('span');
291 $output .= html_writer::tag('span', $module->title, array('class' => 'typename'));
292 if (!isset($module->help)) {
293 // Add help if found
294 $module->help = get_string('nohelpforactivityorresource', 'moodle');
297 // Format the help text using markdown with the following options
298 $options = new stdClass();
299 $options->trusted = false;
300 $options->noclean = false;
301 $options->smiley = false;
302 $options->filter = false;
303 $options->para = true;
304 $options->newlines = false;
305 $options->overflowdiv = false;
306 $module->help = format_text($module->help, FORMAT_MARKDOWN, $options);
307 $output .= html_writer::tag('span', $module->help, array('class' => 'typesummary'));
308 $output .= html_writer::end_tag('label');
309 $output .= html_writer::end_tag('div');
311 return $output;
314 protected function course_modchooser_title($title, $identifier = null) {
315 $module = new stdClass();
316 $module->name = $title;
317 $module->types = array();
318 $module->title = get_string($title, $identifier);
319 $module->help = '';
320 return $this->course_modchooser_module($module, array('moduletypetitle'));
324 * Renders HTML for displaying the sequence of course module editing buttons
326 * @see course_get_cm_edit_actions()
328 * @param action_link[] $actions Array of action_link objects
329 * @param cm_info $mod The module we are displaying actions for.
330 * @param array $displayoptions additional display options:
331 * ownerselector => A JS/CSS selector that can be used to find an cm node.
332 * If specified the owning node will be given the class 'action-menu-shown' when the action
333 * menu is being displayed.
334 * constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
335 * the action menu to when it is being displayed.
336 * donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
337 * @return string
339 public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
340 global $CFG;
342 if (empty($actions)) {
343 return '';
346 if (isset($displayoptions['ownerselector'])) {
347 $ownerselector = $displayoptions['ownerselector'];
348 } else if ($mod) {
349 $ownerselector = '#module-'.$mod->id;
350 } else {
351 debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
352 $ownerselector = 'li.activity';
355 if (isset($displayoptions['constraintselector'])) {
356 $constraint = $displayoptions['constraintselector'];
357 } else {
358 $constraint = '.course-content';
361 $menu = new action_menu();
362 $menu->set_owner_selector($ownerselector);
363 $menu->set_contraint($constraint);
364 $menu->set_alignment(action_menu::TL, action_menu::TR);
365 if (isset($CFG->modeditingmenu) && !$CFG->modeditingmenu || !empty($displayoptions['donotenhance'])) {
366 $menu->do_not_enhance();
368 foreach ($actions as $action) {
369 if ($action instanceof action_menu_link) {
370 $action->add_class('cm-edit-action');
372 $menu->add($action);
374 $menu->attributes['class'] .= ' section-cm-edit-actions commands';
375 return $this->render($menu);
379 * Renders HTML for the menus to add activities and resources to the current course
381 * Note, if theme overwrites this function and it does not use modchooser,
382 * see also {@link core_course_renderer::add_modchoosertoggle()}
384 * @param stdClass $course
385 * @param int $section relative section number (field course_sections.section)
386 * @param int $sectionreturn The section to link back to
387 * @param array $displayoptions additional display options, for example blocks add
388 * option 'inblock' => true, suggesting to display controls vertically
389 * @return string
391 function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
392 global $CFG;
394 $vertical = !empty($displayoptions['inblock']);
396 // check to see if user can add menus and there are modules to add
397 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
398 || !$this->page->user_is_editing()
399 || !($modnames = get_module_types_names()) || empty($modnames)) {
400 return '';
403 // Retrieve all modules with associated metadata
404 $modules = get_module_metadata($course, $modnames, $sectionreturn);
405 $urlparams = array('section' => $section);
407 // We'll sort resources and activities into two lists
408 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
410 foreach ($modules as $module) {
411 if (isset($module->types)) {
412 // This module has a subtype
413 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
414 $subtypes = array();
415 foreach ($module->types as $subtype) {
416 $link = $subtype->link->out(true, $urlparams);
417 $subtypes[$link] = $subtype->title;
420 // Sort module subtypes into the list
421 $activityclass = MOD_CLASS_ACTIVITY;
422 if ($module->archetype == MOD_CLASS_RESOURCE) {
423 $activityclass = MOD_CLASS_RESOURCE;
425 if (!empty($module->title)) {
426 // This grouping has a name
427 $activities[$activityclass][] = array($module->title => $subtypes);
428 } else {
429 // This grouping does not have a name
430 $activities[$activityclass] = array_merge($activities[$activityclass], $subtypes);
432 } else {
433 // This module has no subtypes
434 $activityclass = MOD_CLASS_ACTIVITY;
435 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
436 $activityclass = MOD_CLASS_RESOURCE;
437 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
438 // System modules cannot be added by user, do not add to dropdown
439 continue;
441 $link = $module->link->out(true, $urlparams);
442 $activities[$activityclass][$link] = $module->title;
446 $straddactivity = get_string('addactivity');
447 $straddresource = get_string('addresource');
448 $sectionname = get_section_name($course, $section);
449 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
450 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
452 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
454 if (!$vertical) {
455 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
458 if (!empty($activities[MOD_CLASS_RESOURCE])) {
459 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array(''=>$straddresource), "ressection$section");
460 $select->set_help_icon('resources');
461 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
462 $output .= $this->output->render($select);
465 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
466 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array(''=>$straddactivity), "section$section");
467 $select->set_help_icon('activities');
468 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
469 $output .= $this->output->render($select);
472 if (!$vertical) {
473 $output .= html_writer::end_tag('div');
476 $output .= html_writer::end_tag('div');
478 if (course_ajax_enabled($course) && $course->id == $this->page->course->id) {
479 // modchooser can be added only for the current course set on the page!
480 $straddeither = get_string('addresourceoractivity');
481 // The module chooser link
482 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
483 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
484 $icon = $this->output->pix_icon('t/add', '');
485 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
486 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
487 $modchooser.= html_writer::end_tag('div');
488 $modchooser.= html_writer::end_tag('div');
490 // Wrap the normal output in a noscript div
491 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
492 if ($usemodchooser) {
493 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
494 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
495 } else {
496 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
497 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
498 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
500 $output = $this->course_modchooser($modules, $course) . $modchooser . $output;
503 return $output;
507 * Renders html to display a course search form
509 * @param string $value default value to populate the search field
510 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
511 * @return string
513 function course_search_form($value = '', $format = 'plain') {
514 static $count = 0;
515 $formid = 'coursesearch';
516 if ((++$count) > 1) {
517 $formid .= $count;
520 switch ($format) {
521 case 'navbar' :
522 $formid = 'coursesearchnavbar';
523 $inputid = 'navsearchbox';
524 $inputsize = 20;
525 break;
526 case 'short' :
527 $inputid = 'shortsearchbox';
528 $inputsize = 12;
529 break;
530 default :
531 $inputid = 'coursesearchbox';
532 $inputsize = 30;
535 $strsearchcourses= get_string("searchcourses");
536 $searchurl = new moodle_url('/course/search.php');
538 $output = html_writer::start_tag('form', array('id' => $formid, 'action' => $searchurl, 'method' => 'get'));
539 $output .= html_writer::start_tag('fieldset', array('class' => 'coursesearchbox invisiblefieldset'));
540 $output .= html_writer::tag('label', $strsearchcourses.': ', array('for' => $inputid));
541 $output .= html_writer::empty_tag('input', array('type' => 'text', 'id' => $inputid,
542 'size' => $inputsize, 'name' => 'search', 'value' => s($value)));
543 $output .= html_writer::empty_tag('input', array('type' => 'submit',
544 'value' => get_string('go')));
545 $output .= html_writer::end_tag('fieldset');
546 $output .= html_writer::end_tag('form');
548 return $output;
552 * Renders html for completion box on course page
554 * If completion is disabled, returns empty string
555 * If completion is automatic, returns an icon of the current completion state
556 * If completion is manual, returns a form (with an icon inside) that allows user to
557 * toggle completion
559 * @param stdClass $course course object
560 * @param completion_info $completioninfo completion info for the course, it is recommended
561 * to fetch once for all modules in course/section for performance
562 * @param cm_info $mod module to show completion for
563 * @param array $displayoptions display options, not used in core
564 * @return string
566 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
567 global $CFG;
568 $output = '';
569 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
570 return $output;
572 if ($completioninfo === null) {
573 $completioninfo = new completion_info($course);
575 $completion = $completioninfo->is_enabled($mod);
576 if ($completion == COMPLETION_TRACKING_NONE) {
577 return $output;
580 $completiondata = $completioninfo->get_data($mod, true);
581 $completionicon = '';
583 if ($this->page->user_is_editing()) {
584 switch ($completion) {
585 case COMPLETION_TRACKING_MANUAL :
586 $completionicon = 'manual-enabled'; break;
587 case COMPLETION_TRACKING_AUTOMATIC :
588 $completionicon = 'auto-enabled'; break;
590 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
591 switch($completiondata->completionstate) {
592 case COMPLETION_INCOMPLETE:
593 $completionicon = 'manual-n'; break;
594 case COMPLETION_COMPLETE:
595 $completionicon = 'manual-y'; break;
597 } else { // Automatic
598 switch($completiondata->completionstate) {
599 case COMPLETION_INCOMPLETE:
600 $completionicon = 'auto-n'; break;
601 case COMPLETION_COMPLETE:
602 $completionicon = 'auto-y'; break;
603 case COMPLETION_COMPLETE_PASS:
604 $completionicon = 'auto-pass'; break;
605 case COMPLETION_COMPLETE_FAIL:
606 $completionicon = 'auto-fail'; break;
609 if ($completionicon) {
610 $formattedname = $mod->get_formatted_name();
611 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
612 if ($completion == COMPLETION_TRACKING_MANUAL && !$this->page->user_is_editing()) {
613 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
614 $newstate =
615 $completiondata->completionstate == COMPLETION_COMPLETE
616 ? COMPLETION_INCOMPLETE
617 : COMPLETION_COMPLETE;
618 // In manual mode the icon is a toggle form...
620 // If this completion state is used by the
621 // conditional activities system, we need to turn
622 // off the JS.
623 $extraclass = '';
624 if (!empty($CFG->enableavailability) &&
625 condition_info::completion_value_used_as_condition($course, $mod)) {
626 $extraclass = ' preventjs';
628 $output .= html_writer::start_tag('form', array('method' => 'post',
629 'action' => new moodle_url('/course/togglecompletion.php'),
630 'class' => 'togglecompletion'. $extraclass));
631 $output .= html_writer::start_tag('div');
632 $output .= html_writer::empty_tag('input', array(
633 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
634 $output .= html_writer::empty_tag('input', array(
635 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
636 $output .= html_writer::empty_tag('input', array(
637 'type' => 'hidden', 'name' => 'modulename', 'value' => $mod->name));
638 $output .= html_writer::empty_tag('input', array(
639 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
640 $output .= html_writer::empty_tag('input', array(
641 'type' => 'image',
642 'src' => $this->output->pix_url('i/completion-'.$completionicon),
643 'alt' => $imgalt, 'title' => $imgtitle,
644 'aria-live' => 'polite'));
645 $output .= html_writer::end_tag('div');
646 $output .= html_writer::end_tag('form');
647 } else {
648 // In auto mode, or when editing, the icon is just an image
649 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
650 array('title' => $imgalt));
651 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
652 array('class' => 'autocompletion'));
655 return $output;
659 * Checks if course module has any conditions that may make it unavailable for
660 * all or some of the students
662 * This function is internal and is only used to create CSS classes for the module name/text
664 * @param cm_info $mod
665 * @return bool
667 protected function is_cm_conditionally_hidden(cm_info $mod) {
668 global $CFG;
669 $conditionalhidden = false;
670 if (!empty($CFG->enableavailability)) {
671 $conditionalhidden = $mod->availablefrom > time() ||
672 ($mod->availableuntil && $mod->availableuntil < time()) ||
673 count($mod->conditionsgrade) > 0 ||
674 count($mod->conditionscompletion) > 0;
676 return $conditionalhidden;
680 * Renders html to display a name with the link to the course module on a course page
682 * If module is unavailable for user but still needs to be displayed
683 * in the list, just the name is returned without a link
685 * Note, that for course modules that never have separate pages (i.e. labels)
686 * this function return an empty string
688 * @param cm_info $mod
689 * @param array $displayoptions
690 * @return string
692 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
693 global $CFG;
694 $output = '';
695 if (!$mod->uservisible &&
696 (empty($mod->showavailability) || empty($mod->availableinfo))) {
697 // nothing to be displayed to the user
698 return $output;
700 $url = $mod->get_url();
701 if (!$url) {
702 return $output;
705 //Accessibility: for files get description via icon, this is very ugly hack!
706 $instancename = $mod->get_formatted_name();
707 $altname = $mod->modfullname;
708 // Avoid unnecessary duplication: if e.g. a forum name already
709 // includes the word forum (or Forum, etc) then it is unhelpful
710 // to include that in the accessible description that is added.
711 if (false !== strpos(core_text::strtolower($instancename),
712 core_text::strtolower($altname))) {
713 $altname = '';
715 // File type after name, for alphabetic lists (screen reader).
716 if ($altname) {
717 $altname = get_accesshide(' '.$altname);
720 // For items which are hidden but available to current user
721 // ($mod->uservisible), we show those as dimmed only if the user has
722 // viewhiddenactivities, so that teachers see 'items which might not
723 // be available to some students' dimmed but students do not see 'item
724 // which is actually available to current student' dimmed.
725 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
726 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
727 (!$mod->uservisible || has_capability('moodle/course:viewhiddenactivities',
728 context_course::instance($mod->course)));
730 $linkclasses = '';
731 $accesstext = '';
732 $textclasses = '';
733 if ($accessiblebutdim) {
734 $linkclasses .= ' dimmed';
735 $textclasses .= ' dimmed_text';
736 if ($conditionalhidden) {
737 $linkclasses .= ' conditionalhidden';
738 $textclasses .= ' conditionalhidden';
740 if ($mod->uservisible) {
741 // show accessibility note only if user can access the module himself
742 $accesstext = get_accesshide(get_string('hiddenfromstudents').':'. $mod->modfullname);
746 // Get on-click attribute value if specified and decode the onclick - it
747 // has already been encoded for display (puke).
748 $onclick = htmlspecialchars_decode($mod->get_on_click(), ENT_QUOTES);
750 $groupinglabel = '';
751 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($mod->course))) {
752 $groupings = groups_get_all_groupings($mod->course);
753 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$mod->groupingid]->name).')',
754 array('class' => 'groupinglabel '.$textclasses));
757 // Display link itself.
758 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
759 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) . $accesstext .
760 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
761 if ($mod->uservisible) {
762 $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick)) .
763 $groupinglabel;
764 } else {
765 // We may be displaying this just in order to show information
766 // about visibility, without the actual link ($mod->uservisible)
767 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses)) .
768 $groupinglabel;
770 return $output;
774 * Renders html to display the module content on the course page (i.e. text of the labels)
776 * @param cm_info $mod
777 * @param array $displayoptions
778 * @return string
780 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
781 $output = '';
782 if (!$mod->uservisible &&
783 (empty($mod->showavailability) || empty($mod->availableinfo))) {
784 // nothing to be displayed to the user
785 return $output;
787 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
788 if ($this->page->user_is_editing()) {
789 // In editing mode, when an item is conditionally hidden from some users
790 // we show it as greyed out.
791 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
792 $dim = !$mod->visible || $conditionalhidden;
793 } else {
794 // When not in editing mode, we only show item as hidden if it is
795 // actually not available to the user
796 $conditionalhidden = false;
797 $dim = !$mod->uservisible;
799 $textclasses = '';
800 $accesstext = '';
801 if ($dim) {
802 $textclasses .= ' dimmed_text';
803 if ($conditionalhidden) {
804 $textclasses .= ' conditionalhidden';
806 if ($mod->uservisible) {
807 // show accessibility note only if user can access the module himself
808 $accesstext = get_accesshide(get_string('hiddenfromstudents').': ');
811 if ($mod->get_url()) {
812 if ($content) {
813 // If specified, display extra content after link.
814 $output = html_writer::tag('div', $content, array('class' =>
815 trim('contentafterlink ' . $textclasses)));
817 } else {
818 // No link, so display only content.
819 $output = html_writer::tag('div', $accesstext . $content, array('class' => $textclasses));
821 return $output;
825 * Renders HTML to show course module availability information (for someone who isn't allowed
826 * to see the activity itself, or for staff)
828 * @param cm_info $mod
829 * @param array $displayoptions
830 * @return string
832 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
833 global $CFG;
834 if (!$mod->uservisible) {
835 // this is a student who is not allowed to see the module but might be allowed
836 // to see availability info (i.e. "Available from ...")
837 if (!empty($mod->showavailability) && !empty($mod->availableinfo)) {
838 $output = html_writer::tag('div', $mod->availableinfo, array('class' => 'availabilityinfo'));
840 return $output;
842 // this is a teacher who is allowed to see module but still should see the
843 // information that module is not available to all/some students
844 $modcontext = context_module::instance($mod->id);
845 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
846 if ($canviewhidden && !empty($CFG->enableavailability)) {
847 // Don't add availability information if user is not editing and activity is hidden.
848 if ($mod->visible || $this->page->user_is_editing()) {
849 $hidinfoclass = '';
850 if (!$mod->visible) {
851 $hidinfoclass = 'hide';
853 $ci = new condition_info($mod);
854 $fullinfo = $ci->get_full_information();
855 if($fullinfo) {
856 return '<div class="availabilityinfo '.$hidinfoclass.'">'.get_string($mod->showavailability
857 ? 'userrestriction_visible'
858 : 'userrestriction_hidden','condition',
859 $fullinfo).'</div>';
863 return '';
867 * Renders HTML to display one course module for display within a section.
869 * This function calls:
870 * {@link core_course_renderer::course_section_cm()}
872 * @param stdClass $course
873 * @param completion_info $completioninfo
874 * @param cm_info $mod
875 * @param int|null $sectionreturn
876 * @param array $displayoptions
877 * @return String
879 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
880 $output = '';
881 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
882 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->get_extra_classes();
883 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
885 return $output;
889 * Renders HTML to display one course module in a course section
891 * This includes link, content, availability, completion info and additional information
892 * that module type wants to display (i.e. number of unread forum posts)
894 * This function calls:
895 * {@link core_course_renderer::course_section_cm_name()}
896 * {@link cm_info::get_after_link()}
897 * {@link core_course_renderer::course_section_cm_text()}
898 * {@link core_course_renderer::course_section_cm_availability()}
899 * {@link core_course_renderer::course_section_cm_completion()}
900 * {@link course_get_cm_edit_actions()}
901 * {@link core_course_renderer::course_section_cm_edit_actions()}
903 * @param stdClass $course
904 * @param completion_info $completioninfo
905 * @param cm_info $mod
906 * @param int|null $sectionreturn
907 * @param array $displayoptions
908 * @return string
910 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
911 $output = '';
912 // We return empty string (because course module will not be displayed at all)
913 // if:
914 // 1) The activity is not visible to users
915 // and
916 // 2a) The 'showavailability' option is not set (if that is set,
917 // we need to display the activity so we can show
918 // availability info)
919 // or
920 // 2b) The 'availableinfo' is empty, i.e. the activity was
921 // hidden in a way that leaves no info, such as using the
922 // eye icon.
923 if (!$mod->uservisible &&
924 (empty($mod->showavailability) || empty($mod->availableinfo))) {
925 return $output;
928 $indentclasses = 'mod-indent';
929 if (!empty($mod->indent)) {
930 $indentclasses .= ' mod-indent-'.$mod->indent;
931 if ($mod->indent > 15) {
932 $indentclasses .= ' mod-indent-huge';
935 $output .= html_writer::start_tag('div', array('class' => $indentclasses));
937 // Start the div for the activity title, excluding the edit icons.
938 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
940 // Display the link to the module (or do nothing if module has no url)
941 $output .= $this->course_section_cm_name($mod, $displayoptions);
943 // Module can put text after the link (e.g. forum unread)
944 $output .= $mod->get_after_link();
946 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
947 $output .= html_writer::end_tag('div'); // .activityinstance
949 // If there is content but NO link (eg label), then display the
950 // content here (BEFORE any icons). In this case cons must be
951 // displayed after the content so that it makes more sense visually
952 // and for accessibility reasons, e.g. if you have a one-line label
953 // it should work similarly (at least in terms of ordering) to an
954 // activity.
955 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
956 $url = $mod->get_url();
957 if (empty($url)) {
958 $output .= $contentpart;
961 if ($this->page->user_is_editing()) {
962 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
963 $output .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
964 $output .= $mod->get_after_edit_icons();
967 $output .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
969 // If there is content AND a link, then display the content here
970 // (AFTER any icons). Otherwise it was displayed before
971 if (!empty($url)) {
972 $output .= $contentpart;
975 // show availability info (if module is not available)
976 $output .= $this->course_section_cm_availability($mod, $displayoptions);
978 $output .= html_writer::end_tag('div'); // $indentclasses
979 return $output;
983 * Renders HTML to display a list of course modules in a course section
984 * Also displays "move here" controls in Javascript-disabled mode
986 * This function calls {@link core_course_renderer::course_section_cm()}
988 * @param stdClass $course course object
989 * @param int|stdClass|section_info $section relative section number or section object
990 * @param int $sectionreturn section number to return to
991 * @param int $displayoptions
992 * @return void
994 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
995 global $USER;
997 $output = '';
998 $modinfo = get_fast_modinfo($course);
999 if (is_object($section)) {
1000 $section = $modinfo->get_section_info($section->section);
1001 } else {
1002 $section = $modinfo->get_section_info($section);
1004 $completioninfo = new completion_info($course);
1006 // check if we are currently in the process of moving a module with JavaScript disabled
1007 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
1008 if ($ismoving) {
1009 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
1010 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1013 // Get the list of modules visible to user (excluding the module being moved if there is one)
1014 $moduleshtml = array();
1015 if (!empty($modinfo->sections[$section->section])) {
1016 foreach ($modinfo->sections[$section->section] as $modnumber) {
1017 $mod = $modinfo->cms[$modnumber];
1019 if ($ismoving and $mod->id == $USER->activitycopy) {
1020 // do not display moving mod
1021 continue;
1024 if ($modulehtml = $this->course_section_cm_list_item($course,
1025 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
1026 $moduleshtml[$modnumber] = $modulehtml;
1031 $sectionoutput = '';
1032 if (!empty($moduleshtml) || $ismoving) {
1033 foreach ($moduleshtml as $modnumber => $modulehtml) {
1034 if ($ismoving) {
1035 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
1036 $sectionoutput .= html_writer::tag('li', html_writer::link($movingurl, $this->output->render($movingpix)),
1037 array('class' => 'movehere', 'title' => $strmovefull));
1040 $sectionoutput .= $modulehtml;
1043 if ($ismoving) {
1044 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1045 $sectionoutput .= html_writer::tag('li', html_writer::link($movingurl, $this->output->render($movingpix)),
1046 array('class' => 'movehere', 'title' => $strmovefull));
1050 // Always output the section module list.
1051 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1053 return $output;
1057 * Displays a custom list of courses with paging bar if necessary
1059 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1060 * appears under the list.
1062 * If both $paginationurl and $totalcount are specified, and $totalcount is
1063 * bigger than count($courses), a paging bar is displayed above and under the
1064 * courses list.
1066 * @param array $courses array of course records (or instances of course_in_list) to show on this page
1067 * @param bool $showcategoryname whether to add category name to the course description
1068 * @param string $additionalclasses additional CSS classes to add to the div.courses
1069 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1070 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1071 * @param int $page current page number (defaults to 0 referring to the first page)
1072 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1073 * @return string
1075 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1076 global $CFG;
1077 // create instance of coursecat_helper to pass display options to function rendering courses list
1078 $chelper = new coursecat_helper();
1079 if ($showcategoryname) {
1080 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1081 } else {
1082 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1084 if ($totalcount !== null && $paginationurl !== null) {
1085 // add options to display pagination
1086 if ($perpage === null) {
1087 $perpage = $CFG->coursesperpage;
1089 $chelper->set_courses_display_options(array(
1090 'limit' => $perpage,
1091 'offset' => ((int)$page) * $perpage,
1092 'paginationurl' => $paginationurl,
1094 } else if ($paginationurl !== null) {
1095 // add options to display 'View more' link
1096 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1097 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1099 $chelper->set_attributes(array('class' => $additionalclasses));
1100 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1101 return $content;
1105 * Displays one course in the list of courses.
1107 * This is an internal function, to display an information about just one course
1108 * please use {@link core_course_renderer::course_info_box()}
1110 * @param coursecat_helper $chelper various display options
1111 * @param course_in_list|stdClass $course
1112 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1113 * depend on the course position in list - first/last/even/odd)
1114 * @return string
1116 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1117 global $CFG;
1118 if (!isset($this->strings->summary)) {
1119 $this->strings->summary = get_string('summary');
1121 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1122 return '';
1124 if ($course instanceof stdClass) {
1125 require_once($CFG->libdir. '/coursecatlib.php');
1126 $course = new course_in_list($course);
1128 $content = '';
1129 $classes = trim('coursebox clearfix '. $additionalclasses);
1130 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1131 $nametag = 'h3';
1132 } else {
1133 $classes .= ' collapsed';
1134 $nametag = 'div';
1136 $content .= html_writer::start_tag('div', array('class' => $classes)); // .coursebox
1138 $content .= html_writer::start_tag('div', array('class' => 'info'));
1140 // course name
1141 $coursename = $chelper->get_course_formatted_name($course);
1142 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', array('id' => $course->id)),
1143 $coursename, array('class' => $course->visible ? '' : 'dimmed'));
1144 $content .= html_writer::tag($nametag, $coursenamelink, array('class' => 'name'));
1146 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1147 $content .= html_writer::start_tag('div', array('class' => 'moreinfo'));
1148 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1149 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()) {
1150 $url = new moodle_url('/course/info.php', array('id' => $course->id));
1151 $image = html_writer::empty_tag('img', array('src' => $this->output->pix_url('i/info'),
1152 'alt' => $this->strings->summary));
1153 $content .= html_writer::link($url, $image, array('title' => $this->strings->summary));
1156 $content .= html_writer::end_tag('div'); // .moreinfo
1158 // print enrolmenticons
1159 if ($icons = enrol_get_course_info_icons($course)) {
1160 $content .= html_writer::start_tag('div', array('class' => 'enrolmenticons'));
1161 foreach ($icons as $pix_icon) {
1162 $content .= $this->render($pix_icon);
1164 $content .= html_writer::end_tag('div'); // .enrolmenticons
1167 $content .= html_writer::end_tag('div'); // .info
1169 $content .= html_writer::start_tag('div', array('class' => 'content'));
1170 $content .= $this->coursecat_coursebox_content($chelper, $course);
1171 $content .= html_writer::end_tag('div'); // .content
1173 $content .= html_writer::end_tag('div'); // .coursebox
1174 return $content;
1178 * Returns HTML to display course content (summary, course contacts and optionally category name)
1180 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1182 * @param coursecat_helper $chelper various display options
1183 * @param stdClass|course_in_list $course
1184 * @return string
1186 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1187 global $CFG;
1188 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1189 return '';
1191 if ($course instanceof stdClass) {
1192 require_once($CFG->libdir. '/coursecatlib.php');
1193 $course = new course_in_list($course);
1195 $content = '';
1197 // display course summary
1198 if ($course->has_summary()) {
1199 $content .= html_writer::start_tag('div', array('class' => 'summary'));
1200 $content .= $chelper->get_course_formatted_summary($course,
1201 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1202 $content .= html_writer::end_tag('div'); // .summary
1205 // display course overview files
1206 $contentimages = $contentfiles = '';
1207 foreach ($course->get_course_overviewfiles() as $file) {
1208 $isimage = $file->is_valid_image();
1209 $url = file_encode_url("$CFG->wwwroot/pluginfile.php",
1210 '/'. $file->get_contextid(). '/'. $file->get_component(). '/'.
1211 $file->get_filearea(). $file->get_filepath(). $file->get_filename(), !$isimage);
1212 if ($isimage) {
1213 $contentimages .= html_writer::tag('div',
1214 html_writer::empty_tag('img', array('src' => $url)),
1215 array('class' => 'courseimage'));
1216 } else {
1217 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1218 $filename = html_writer::tag('span', $image, array('class' => 'fp-icon')).
1219 html_writer::tag('span', $file->get_filename(), array('class' => 'fp-filename'));
1220 $contentfiles .= html_writer::tag('span',
1221 html_writer::link($url, $filename),
1222 array('class' => 'coursefile fp-filename-icon'));
1225 $content .= $contentimages. $contentfiles;
1227 // display course contacts. See course_in_list::get_course_contacts()
1228 if ($course->has_course_contacts()) {
1229 $content .= html_writer::start_tag('ul', array('class' => 'teachers'));
1230 foreach ($course->get_course_contacts() as $userid => $coursecontact) {
1231 $name = $coursecontact['rolename'].': '.
1232 html_writer::link(new moodle_url('/user/view.php',
1233 array('id' => $userid, 'course' => SITEID)),
1234 $coursecontact['username']);
1235 $content .= html_writer::tag('li', $name);
1237 $content .= html_writer::end_tag('ul'); // .teachers
1240 // display course category if necessary (for example in search results)
1241 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1242 require_once($CFG->libdir. '/coursecatlib.php');
1243 if ($cat = coursecat::get($course->category, IGNORE_MISSING)) {
1244 $content .= html_writer::start_tag('div', array('class' => 'coursecat'));
1245 $content .= get_string('category').': '.
1246 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1247 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1248 $content .= html_writer::end_tag('div'); // .coursecat
1252 return $content;
1256 * Renders the list of courses
1258 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1259 * method from outside of the class
1261 * If list of courses is specified in $courses; the argument $chelper is only used
1262 * to retrieve display options and attributes, only methods get_show_courses(),
1263 * get_courses_display_option() and get_and_erase_attributes() are called.
1265 * @param coursecat_helper $chelper various display options
1266 * @param array $courses the list of courses to display
1267 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1268 * defaulted to count($courses)
1269 * @return string
1271 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1272 global $CFG;
1273 if ($totalcount === null) {
1274 $totalcount = count($courses);
1276 if (!$totalcount) {
1277 // Courses count is cached during courses retrieval.
1278 return '';
1281 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1282 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1283 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1284 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1285 } else {
1286 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1290 // prepare content of paging bar if it is needed
1291 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1292 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1293 if ($totalcount > count($courses)) {
1294 // there are more results that can fit on one page
1295 if ($paginationurl) {
1296 // the option paginationurl was specified, display pagingbar
1297 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1298 $page = $chelper->get_courses_display_option('offset') / $perpage;
1299 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1300 $paginationurl->out(false, array('perpage' => $perpage)));
1301 if ($paginationallowall) {
1302 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1303 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1305 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1306 // the option for 'View more' link was specified, display more link
1307 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1308 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1309 array('class' => 'paging paging-morelink'));
1311 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1312 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1313 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1314 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1317 // display list of courses
1318 $attributes = $chelper->get_and_erase_attributes('courses');
1319 $content = html_writer::start_tag('div', $attributes);
1321 if (!empty($pagingbar)) {
1322 $content .= $pagingbar;
1325 $coursecount = 0;
1326 foreach ($courses as $course) {
1327 $coursecount ++;
1328 $classes = ($coursecount%2) ? 'odd' : 'even';
1329 if ($coursecount == 1) {
1330 $classes .= ' first';
1332 if ($coursecount >= count($courses)) {
1333 $classes .= ' last';
1335 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1338 if (!empty($pagingbar)) {
1339 $content .= $pagingbar;
1341 if (!empty($morelink)) {
1342 $content .= $morelink;
1345 $content .= html_writer::end_tag('div'); // .courses
1346 return $content;
1350 * Renders the list of subcategories in a category
1352 * @param coursecat_helper $chelper various display options
1353 * @param coursecat $coursecat
1354 * @param int $depth depth of the category in the current tree
1355 * @return string
1357 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1358 global $CFG;
1359 $subcategories = array();
1360 if (!$chelper->get_categories_display_option('nodisplay')) {
1361 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1363 $totalcount = $coursecat->get_children_count();
1364 if (!$totalcount) {
1365 // Note that we call get_child_categories_count() AFTER get_child_categories() to avoid extra DB requests.
1366 // Categories count is cached during children categories retrieval.
1367 return '';
1370 // prepare content of paging bar or more link if it is needed
1371 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1372 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1373 if ($totalcount > count($subcategories)) {
1374 if ($paginationurl) {
1375 // the option 'paginationurl was specified, display pagingbar
1376 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1377 $page = $chelper->get_categories_display_option('offset') / $perpage;
1378 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1379 $paginationurl->out(false, array('perpage' => $perpage)));
1380 if ($paginationallowall) {
1381 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1382 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1384 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1385 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1386 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1387 $viewmoreurl->param('categoryid', $coursecat->id);
1389 $viewmoretext = $chelper->get_categories_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 subcategories
1400 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1402 if (!empty($pagingbar)) {
1403 $content .= $pagingbar;
1406 foreach ($subcategories as $subcategory) {
1407 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1410 if (!empty($pagingbar)) {
1411 $content .= $pagingbar;
1413 if (!empty($morelink)) {
1414 $content .= $morelink;
1417 $content .= html_writer::end_tag('div');
1418 return $content;
1422 * Returns HTML to display the subcategories and courses in the given category
1424 * This method is re-used by AJAX to expand content of not loaded category
1426 * @param coursecat_helper $chelper various display options
1427 * @param coursecat $coursecat
1428 * @param int $depth depth of the category in the current tree
1429 * @return string
1431 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1432 $content = '';
1433 // Subcategories
1434 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1436 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1437 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1438 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1439 if ($showcoursesauto && $depth) {
1440 // this is definitely collapsed mode
1441 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1444 // Courses
1445 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1446 $courses = array();
1447 if (!$chelper->get_courses_display_option('nodisplay')) {
1448 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1450 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1451 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1452 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1453 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1456 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1459 if ($showcoursesauto) {
1460 // restore the show_courses back to AUTO
1461 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1464 return $content;
1468 * Returns HTML to display a course category as a part of a tree
1470 * This is an internal function, to display a particular category and all its contents
1471 * use {@link core_course_renderer::course_category()}
1473 * @param coursecat_helper $chelper various display options
1474 * @param coursecat $coursecat
1475 * @param int $depth depth of this category in the current tree
1476 * @return string
1478 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1479 // open category tag
1480 $classes = array('category');
1481 if (empty($coursecat->visible)) {
1482 $classes[] = 'dimmed_category';
1484 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1485 // do not load content
1486 $categorycontent = '';
1487 $classes[] = 'notloaded';
1488 if ($coursecat->get_children_count() ||
1489 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1490 $classes[] = 'with_children';
1491 $classes[] = 'collapsed';
1493 } else {
1494 // load category content
1495 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1496 $classes[] = 'loaded';
1497 if (!empty($categorycontent)) {
1498 $classes[] = 'with_children';
1501 $content = html_writer::start_tag('div', array('class' => join(' ', $classes),
1502 'data-categoryid' => $coursecat->id,
1503 'data-depth' => $depth));
1505 // category name
1506 $categoryname = $coursecat->get_formatted_name();
1507 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1508 array('categoryid' => $coursecat->id)),
1509 $categoryname);
1510 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1511 && ($coursescount = $coursecat->get_courses_count())) {
1512 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1513 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1515 $content .= html_writer::start_tag('div', array('class' => 'info'));
1516 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'name'));
1517 $content .= html_writer::end_tag('div'); // .info
1519 // add category content to the output
1520 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1522 $content .= html_writer::end_tag('div'); // .category
1524 // Return the course category tree HTML
1525 return $content;
1529 * Returns HTML to display a tree of subcategories and courses in the given category
1531 * @param coursecat_helper $chelper various display options
1532 * @param coursecat $coursecat top category (this category's name and description will NOT be added to the tree)
1533 * @return string
1535 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1536 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1537 if (empty($categorycontent)) {
1538 return '';
1541 // Generate an id and the required JS call to make this a nice widget
1542 $id = html_writer::random_id('course_category_tree');
1543 $this->page->requires->js_init_call('M.util.init_toggle_class_on_click',
1544 array($id, '.category.with_children.loaded > .info .name', 'collapsed', '.category.with_children.loaded'));
1546 // Start content generation
1547 $content = '';
1548 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1549 $content .= html_writer::start_tag('div',
1550 array('id' => $id, 'data-showcourses' => $chelper->get_show_courses()) + $attributes);
1552 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1554 if ($coursecat->get_children_count() && $chelper->get_subcat_depth() != 1) {
1555 // We don't need to display "Expand all"/"Collapse all" buttons if there are no
1556 // subcategories or there is only one level of subcategories loaded
1557 // TODO if subcategories are loaded by AJAX this might still be needed!
1558 $content .= html_writer::start_tag('div', array('class' => 'controls'));
1559 $content .= html_writer::tag('div', get_string('collapseall'), array('class' => 'addtoall expandall'));
1560 $content .= html_writer::tag('div', get_string('expandall'), array('class' => 'removefromall collapseall'));
1561 $content .= html_writer::end_tag('div');
1564 $content .= html_writer::end_tag('div'); // .course_category_tree
1566 return $content;
1570 * Renders HTML to display particular course category - list of it's subcategories and courses
1572 * Invoked from /course/index.php
1574 * @param int|stdClass|coursecat $category
1576 public function course_category($category) {
1577 global $CFG;
1578 require_once($CFG->libdir. '/coursecatlib.php');
1579 $coursecat = coursecat::get(is_object($category) ? $category->id : $category);
1580 $site = get_site();
1581 $output = '';
1583 $this->page->set_button($this->course_search_form('', 'navbar'));
1584 if (!$coursecat->id) {
1585 if (can_edit_in_category()) {
1586 // add 'Manage' button instead of course search form
1587 $managebutton = $this->single_button(new moodle_url('/course/manage.php'),
1588 get_string('managecourses'), 'get');
1589 $this->page->set_button($managebutton);
1591 if (coursecat::count_all() == 1) {
1592 // There exists only one category in the system, do not display link to it
1593 $coursecat = coursecat::get_default();
1594 $strfulllistofcourses = get_string('fulllistofcourses');
1595 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1596 } else {
1597 $strcategories = get_string('categories');
1598 $this->page->set_title("$site->shortname: $strcategories");
1600 } else {
1601 $this->page->set_title("$site->shortname: ". $coursecat->get_formatted_name());
1603 // Print the category selector
1604 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1605 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1606 coursecat::make_categories_list(), $coursecat->id, null, 'switchcategory');
1607 $select->set_label(get_string('categories').':');
1608 $output .= $this->render($select);
1609 $output .= html_writer::end_tag('div'); // .categorypicker
1612 // Print current category description
1613 $chelper = new coursecat_helper();
1614 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1615 $output .= $this->box($description, array('class' => 'generalbox info'));
1618 // Prepare parameters for courses and categories lists in the tree
1619 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1620 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1622 $coursedisplayoptions = array();
1623 $catdisplayoptions = array();
1624 $browse = optional_param('browse', null, PARAM_ALPHA);
1625 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1626 $page = optional_param('page', 0, PARAM_INT);
1627 $baseurl = new moodle_url('/course/index.php');
1628 if ($coursecat->id) {
1629 $baseurl->param('categoryid', $coursecat->id);
1631 if ($perpage != $CFG->coursesperpage) {
1632 $baseurl->param('perpage', $perpage);
1634 $coursedisplayoptions['limit'] = $perpage;
1635 $catdisplayoptions['limit'] = $perpage;
1636 if ($browse === 'courses' || !$coursecat->has_children()) {
1637 $coursedisplayoptions['offset'] = $page * $perpage;
1638 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1639 $catdisplayoptions['nodisplay'] = true;
1640 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1641 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1642 } else if ($browse === 'categories' || !$coursecat->has_courses()) {
1643 $coursedisplayoptions['nodisplay'] = true;
1644 $catdisplayoptions['offset'] = $page * $perpage;
1645 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1646 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1647 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1648 } else {
1649 // we have a category that has both subcategories and courses, display pagination separately
1650 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1651 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1653 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1655 // Display course category tree
1656 $output .= $this->coursecat_tree($chelper, $coursecat);
1658 // Add course search form (if we are inside category it was already added to the navbar)
1659 if (!$coursecat->id) {
1660 $output .= $this->course_search_form();
1663 // Add action buttons
1664 $output .= $this->container_start('buttons');
1665 $context = get_category_or_system_context($coursecat->id);
1666 if (has_capability('moodle/course:create', $context)) {
1667 // Print link to create a new course, for the 1st available category.
1668 if ($coursecat->id) {
1669 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1670 } else {
1671 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1673 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1675 ob_start();
1676 if (coursecat::count_all() == 1) {
1677 print_course_request_buttons(context_system::instance());
1678 } else {
1679 print_course_request_buttons($context);
1681 $output .= ob_get_contents();
1682 ob_end_clean();
1683 $output .= $this->container_end();
1685 return $output;
1689 * Renders html to display search result page
1691 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1692 * @return string
1694 public function search_courses($searchcriteria) {
1695 global $CFG;
1696 $content = '';
1697 if (!empty($searchcriteria)) {
1698 // print search results
1699 require_once($CFG->libdir. '/coursecatlib.php');
1701 $displayoptions = array('sort' => array('displayname' => 1));
1702 // take the current page and number of results per page from query
1703 $perpage = optional_param('perpage', 0, PARAM_RAW);
1704 if ($perpage !== 'all') {
1705 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1706 $page = optional_param('page', 0, PARAM_INT);
1707 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1709 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1710 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1711 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1713 $class = 'course-search-result';
1714 foreach ($searchcriteria as $key => $value) {
1715 if (!empty($value)) {
1716 $class .= ' course-search-result-'. $key;
1719 $chelper = new coursecat_helper();
1720 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1721 set_courses_display_options($displayoptions)->
1722 set_search_criteria($searchcriteria)->
1723 set_attributes(array('class' => $class));
1725 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1726 $totalcount = coursecat::search_courses_count($searchcriteria);
1727 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1729 if (!$totalcount) {
1730 if (!empty($searchcriteria['search'])) {
1731 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1732 } else {
1733 $content .= $this->heading(get_string('novalidcourses'));
1735 } else {
1736 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1737 $content .= $courseslist;
1740 if (!empty($searchcriteria['search'])) {
1741 // print search form only if there was a search by search string, otherwise it is confusing
1742 $content .= $this->box_start('generalbox mdl-align');
1743 $content .= $this->course_search_form($searchcriteria['search']);
1744 $content .= $this->box_end();
1746 } else {
1747 // just print search form
1748 $content .= $this->box_start('generalbox mdl-align');
1749 $content .= $this->course_search_form();
1750 $content .= html_writer::tag('div', get_string("searchhelp"), array('class' => 'searchhelp'));
1751 $content .= $this->box_end();
1753 return $content;
1757 * Renders html to print list of courses tagged with particular tag
1759 * @param int $tagid id of the tag
1760 * @return string empty string if no courses are marked with this tag or rendered list of courses
1762 public function tagged_courses($tagid) {
1763 global $CFG;
1764 require_once($CFG->libdir. '/coursecatlib.php');
1765 $displayoptions = array('limit' => $CFG->coursesperpage);
1766 $displayoptions['viewmoreurl'] = new moodle_url('/course/search.php',
1767 array('tagid' => $tagid, 'page' => 1, 'perpage' => $CFG->coursesperpage));
1768 $displayoptions['viewmoretext'] = new lang_string('findmorecourses');
1769 $chelper = new coursecat_helper();
1770 $searchcriteria = array('tagid' => $tagid);
1771 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1772 set_search_criteria(array('tagid' => $tagid))->
1773 set_courses_display_options($displayoptions)->
1774 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1775 // (we set the same css class as in search results by tagid)
1776 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1777 $totalcount = coursecat::search_courses_count($searchcriteria);
1778 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1779 if ($totalcount) {
1780 require_once $CFG->dirroot.'/tag/lib.php';
1781 $heading = get_string('courses') . ' ' . get_string('taggedwith', 'tag', tag_get_name($tagid)) .': '. $totalcount;
1782 return $this->heading($heading, 3). $content;
1784 return '';
1788 * Returns HTML to display one remote course
1790 * @param stdClass $course remote course information, contains properties:
1791 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1792 * @return string
1794 protected function frontpage_remote_course(stdClass $course) {
1795 $url = new moodle_url('/auth/mnet/jump.php', array(
1796 'hostid' => $course->hostid,
1797 'wantsurl' => '/course/view.php?id='. $course->remoteid
1800 $output = '';
1801 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1802 $output .= html_writer::start_tag('div', array('class' => 'info'));
1803 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1804 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1805 $output .= html_writer::end_tag('h3'); // .name
1806 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1807 $output .= html_writer::end_tag('div'); // .info
1808 $output .= html_writer::start_tag('div', array('class' => 'content'));
1809 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1810 $options = new stdClass();
1811 $options->noclean = true;
1812 $options->para = false;
1813 $options->overflowdiv = true;
1814 $output .= format_text($course->summary, $course->summaryformat, $options);
1815 $output .= html_writer::end_tag('div'); // .summary
1816 $addinfo = format_string($course->hostname) . ' : '
1817 . format_string($course->cat_name) . ' : '
1818 . format_string($course->shortname);
1819 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1820 $output .= html_writer::end_tag('div'); // .content
1821 $output .= html_writer::end_tag('div'); // .coursebox
1822 return $output;
1826 * Returns HTML to display one remote host
1828 * @param array $host host information, contains properties: name, url, count
1829 * @return string
1831 protected function frontpage_remote_host($host) {
1832 $output = '';
1833 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1834 $output .= html_writer::start_tag('div', array('class' => 'info'));
1835 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1836 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1837 $output .= html_writer::end_tag('h3'); // .name
1838 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1839 $output .= html_writer::end_tag('div'); // .info
1840 $output .= html_writer::start_tag('div', array('class' => 'content'));
1841 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1842 $output .= $host['count'] . ' ' . get_string('courses');
1843 $output .= html_writer::end_tag('div'); // .content
1844 $output .= html_writer::end_tag('div'); // .coursebox
1845 return $output;
1849 * Returns HTML to print list of courses user is enrolled to for the frontpage
1851 * Also lists remote courses or remote hosts if MNET authorisation is used
1853 * @return string
1855 public function frontpage_my_courses() {
1856 global $USER, $CFG, $DB;
1858 if (!isloggedin() or isguestuser()) {
1859 return '';
1862 $output = '';
1863 if (!empty($CFG->navsortmycoursessort)) {
1864 // sort courses the same as in navigation menu
1865 $sortorder = 'visible DESC,'. $CFG->navsortmycoursessort.' ASC';
1866 } else {
1867 $sortorder = 'visible DESC,sortorder ASC';
1869 $courses = enrol_get_my_courses('summary, summaryformat', $sortorder);
1870 $rhosts = array();
1871 $rcourses = array();
1872 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1873 $rcourses = get_my_remotecourses($USER->id);
1874 $rhosts = get_my_remotehosts();
1877 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1879 $chelper = new coursecat_helper();
1880 if (count($courses) > $CFG->frontpagecourselimit) {
1881 // There are more enrolled courses than we can display, display link to 'My courses'.
1882 $totalcount = count($courses);
1883 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
1884 $chelper->set_courses_display_options(array(
1885 'viewmoreurl' => new moodle_url('/my/'),
1886 'viewmoretext' => new lang_string('mycourses')
1888 } else {
1889 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
1890 $chelper->set_courses_display_options(array(
1891 'viewmoreurl' => new moodle_url('/course/index.php'),
1892 'viewmoretext' => new lang_string('fulllistofcourses')
1894 $totalcount = $DB->count_records('course') - 1;
1896 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
1897 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
1898 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
1900 // MNET
1901 if (!empty($rcourses)) {
1902 // at the IDP, we know of all the remote courses
1903 $output .= html_writer::start_tag('div', array('class' => 'courses'));
1904 foreach ($rcourses as $course) {
1905 $output .= $this->frontpage_remote_course($course);
1907 $output .= html_writer::end_tag('div'); // .courses
1908 } elseif (!empty($rhosts)) {
1909 // non-IDP, we know of all the remote servers, but not courses
1910 $output .= html_writer::start_tag('div', array('class' => 'courses'));
1911 foreach ($rhosts as $host) {
1912 $output .= $this->frontpage_remote_host($host);
1914 $output .= html_writer::end_tag('div'); // .courses
1917 return $output;
1921 * Returns HTML to print list of available courses for the frontpage
1923 * @return string
1925 public function frontpage_available_courses() {
1926 global $CFG;
1927 require_once($CFG->libdir. '/coursecatlib.php');
1929 $chelper = new coursecat_helper();
1930 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
1931 set_courses_display_options(array(
1932 'recursive' => true,
1933 'limit' => $CFG->frontpagecourselimit,
1934 'viewmoreurl' => new moodle_url('/course/index.php'),
1935 'viewmoretext' => new lang_string('fulllistofcourses')));
1937 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
1938 $courses = coursecat::get(0)->get_courses($chelper->get_courses_display_options());
1939 $totalcount = coursecat::get(0)->get_courses_count($chelper->get_courses_display_options());
1940 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
1941 // Print link to create a new course, for the 1st available category.
1942 return $this->add_new_course_button();
1944 return $this->coursecat_courses($chelper, $courses, $totalcount);
1948 * Returns HTML to the "add new course" button for the page
1950 * @return string
1952 public function add_new_course_button() {
1953 global $CFG;
1954 // Print link to create a new course, for the 1st available category.
1955 $output = $this->container_start('buttons');
1956 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1957 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1958 $output .= $this->container_end('buttons');
1959 return $output;
1963 * Returns HTML to print tree with course categories and courses for the frontpage
1965 * @return string
1967 public function frontpage_combo_list() {
1968 global $CFG;
1969 require_once($CFG->libdir. '/coursecatlib.php');
1970 $chelper = new coursecat_helper();
1971 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
1972 set_categories_display_options(array(
1973 'limit' => $CFG->coursesperpage,
1974 'viewmoreurl' => new moodle_url('/course/index.php',
1975 array('browse' => 'categories', 'page' => 1))
1976 ))->
1977 set_courses_display_options(array(
1978 'limit' => $CFG->coursesperpage,
1979 'viewmoreurl' => new moodle_url('/course/index.php',
1980 array('browse' => 'courses', 'page' => 1))
1981 ))->
1982 set_attributes(array('class' => 'frontpage-category-combo'));
1983 return $this->coursecat_tree($chelper, coursecat::get(0));
1987 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
1989 * @return string
1991 public function frontpage_categories_list() {
1992 global $CFG;
1993 require_once($CFG->libdir. '/coursecatlib.php');
1994 $chelper = new coursecat_helper();
1995 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
1996 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
1997 set_categories_display_options(array(
1998 'limit' => $CFG->coursesperpage,
1999 'viewmoreurl' => new moodle_url('/course/index.php',
2000 array('browse' => 'categories', 'page' => 1))
2001 ))->
2002 set_attributes(array('class' => 'frontpage-category-names'));
2003 return $this->coursecat_tree($chelper, coursecat::get(0));
2008 * Class storing display options and functions to help display course category and/or courses lists
2010 * This is a wrapper for coursecat objects that also stores display options
2011 * and functions to retrieve sorted and paginated lists of categories/courses.
2013 * If theme overrides methods in core_course_renderers that access this class
2014 * it may as well not use this class at all or extend it.
2016 * @package core
2017 * @copyright 2013 Marina Glancy
2018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2020 class coursecat_helper {
2021 /** @var string [none, collapsed, expanded] how (if) display courses list */
2022 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2023 /** @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) */
2024 protected $subcatdepth = 1;
2025 /** @var array options to display courses list */
2026 protected $coursesdisplayoptions = array();
2027 /** @var array options to display subcategories list */
2028 protected $categoriesdisplayoptions = array();
2029 /** @var array additional HTML attributes */
2030 protected $attributes = array();
2031 /** @var array search criteria if the list is a search result */
2032 protected $searchcriteria = null;
2035 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2037 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2038 * @return coursecat_helper
2040 public function set_show_courses($showcourses) {
2041 $this->showcourses = $showcourses;
2042 // Automatically set the options to preload summary and coursecontacts for coursecat::get_courses() and coursecat::search_courses()
2043 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2044 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2045 return $this;
2049 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2051 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2053 public function get_show_courses() {
2054 return $this->showcourses;
2058 * Sets the maximum depth to expand subcategories in the tree
2060 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2062 * @param int $subcatdepth
2063 * @return coursecat_helper
2065 public function set_subcat_depth($subcatdepth) {
2066 $this->subcatdepth = $subcatdepth;
2067 return $this;
2071 * Returns the maximum depth to expand subcategories in the tree
2073 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2075 * @return int
2077 public function get_subcat_depth() {
2078 return $this->subcatdepth;
2082 * Sets options to display list of courses
2084 * Options are later submitted as argument to coursecat::get_courses() and/or coursecat::search_courses()
2086 * Options that coursecat::get_courses() accept:
2087 * - recursive - return courses from subcategories as well. Use with care,
2088 * this may be a huge list!
2089 * - summary - preloads fields 'summary' and 'summaryformat'
2090 * - coursecontacts - preloads course contacts
2091 * - isenrolled - preloads indication whether this user is enrolled in the course
2092 * - sort - list of fields to sort. Example
2093 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2094 * will sort by idnumber asc, shortname asc and id desc.
2095 * Default: array('sortorder' => 1)
2096 * Only cached fields may be used for sorting!
2097 * - offset
2098 * - limit - maximum number of children to return, 0 or null for no limit
2100 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2102 * Also renderer can set here any additional options it wants to pass between renderer functions.
2104 * @param array $options
2105 * @return coursecat_helper
2107 public function set_courses_display_options($options) {
2108 $this->coursesdisplayoptions = $options;
2109 $this->set_show_courses($this->showcourses); // this will calculate special display options
2110 return $this;
2114 * Sets one option to display list of courses
2116 * @see coursecat_helper::set_courses_display_options()
2118 * @param string $key
2119 * @param mixed $value
2120 * @return coursecat_helper
2122 public function set_courses_display_option($key, $value) {
2123 $this->coursesdisplayoptions[$key] = $value;
2124 return $this;
2128 * Return the specified option to display list of courses
2130 * @param string $optionname option name
2131 * @param mixed $defaultvalue default value for option if it is not specified
2132 * @return mixed
2134 public function get_courses_display_option($optionname, $defaultvalue = null) {
2135 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2136 return $this->coursesdisplayoptions[$optionname];
2137 } else {
2138 return $defaultvalue;
2143 * Returns all options to display the courses
2145 * This array is usually passed to {@link coursecat::get_courses()} or
2146 * {@link coursecat::search_courses()}
2148 * @return array
2150 public function get_courses_display_options() {
2151 return $this->coursesdisplayoptions;
2155 * Sets options to display list of subcategories
2157 * Options 'sort', 'offset' and 'limit' are passed to coursecat::get_children().
2158 * Any other options may be used by renderer functions
2160 * @param array $options
2161 * @return coursecat_helper
2163 public function set_categories_display_options($options) {
2164 $this->categoriesdisplayoptions = $options;
2165 return $this;
2169 * Return the specified option to display list of subcategories
2171 * @param string $optionname option name
2172 * @param mixed $defaultvalue default value for option if it is not specified
2173 * @return mixed
2175 public function get_categories_display_option($optionname, $defaultvalue = null) {
2176 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2177 return $this->categoriesdisplayoptions[$optionname];
2178 } else {
2179 return $defaultvalue;
2184 * Returns all options to display list of subcategories
2186 * This array is usually passed to {@link coursecat::get_children()}
2188 * @return array
2190 public function get_categories_display_options() {
2191 return $this->categoriesdisplayoptions;
2195 * Sets additional general options to pass between renderer functions, usually HTML attributes
2197 * @param array $attributes
2198 * @return coursecat_helper
2200 public function set_attributes($attributes) {
2201 $this->attributes = $attributes;
2202 return $this;
2206 * Return all attributes and erases them so they are not applied again
2208 * @param string $classname adds additional class name to the beginning of $attributes['class']
2209 * @return array
2211 public function get_and_erase_attributes($classname) {
2212 $attributes = $this->attributes;
2213 $this->attributes = array();
2214 if (empty($attributes['class'])) {
2215 $attributes['class'] = '';
2217 $attributes['class'] = $classname . ' '. $attributes['class'];
2218 return $attributes;
2222 * Sets the search criteria if the course is a search result
2224 * Search string will be used to highlight terms in course name and description
2226 * @param array $searchcriteria
2227 * @return coursecat_helper
2229 public function set_search_criteria($searchcriteria) {
2230 $this->searchcriteria = $searchcriteria;
2231 return $this;
2235 * Returns formatted and filtered description of the given category
2237 * @param coursecat $coursecat category
2238 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2239 * if context is not specified it will be added automatically
2240 * @return string|null
2242 public function get_category_formatted_description($coursecat, $options = null) {
2243 if ($coursecat->id && !empty($coursecat->description)) {
2244 if (!isset($coursecat->descriptionformat)) {
2245 $descriptionformat = FORMAT_MOODLE;
2246 } else {
2247 $descriptionformat = $coursecat->descriptionformat;
2249 if ($options === null) {
2250 $options = array('noclean' => true, 'overflowdiv' => true);
2251 } else {
2252 $options = (array)$options;
2254 $context = context_coursecat::instance($coursecat->id);
2255 if (!isset($options['context'])) {
2256 $options['context'] = $context;
2258 $text = file_rewrite_pluginfile_urls($coursecat->description,
2259 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2260 return format_text($text, $descriptionformat, $options);
2262 return null;
2266 * Returns given course's summary with proper embedded files urls and formatted
2268 * @param course_in_list $course
2269 * @param array|stdClass $options additional formatting options
2270 * @return string
2272 public function get_course_formatted_summary($course, $options = array()) {
2273 global $CFG;
2274 require_once($CFG->libdir. '/filelib.php');
2275 if (!$course->has_summary()) {
2276 return '';
2278 $options = (array)$options;
2279 $context = context_course::instance($course->id);
2280 if (!isset($options['context'])) {
2281 // TODO see MDL-38521
2282 // option 1 (current), page context - no code required
2283 // option 2, system context
2284 // $options['context'] = context_system::instance();
2285 // option 3, course context:
2286 // $options['context'] = $context;
2287 // option 4, course category context:
2288 // $options['context'] = $context->get_parent_context();
2290 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2291 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2292 if (!empty($this->searchcriteria['search'])) {
2293 $summary = highlight($this->searchcriteria['search'], $summary);
2295 return $summary;
2299 * Returns course name as it is configured to appear in courses lists formatted to course context
2301 * @param course_in_list $course
2302 * @param array|stdClass $options additional formatting options
2303 * @return string
2305 public function get_course_formatted_name($course, $options = array()) {
2306 $options = (array)$options;
2307 if (!isset($options['context'])) {
2308 $options['context'] = context_course::instance($course->id);
2310 $name = format_string(get_course_display_name_for_list($course), true, $options);
2311 if (!empty($this->searchcriteria['search'])) {
2312 $name = highlight($this->searchcriteria['search'], $name);
2314 return $name;