MDL-42016 repository: Implement new sync method in repositories
[moodle.git] / course / renderer.php
blob7f7d78950ecdb702033799a64d8d22a2ecd44f91
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Renderer for use with the course section and all the goodness that falls
20 * within it.
22 * This renderer should contain methods useful to courses, and categories.
24 * @package moodlecore
25 * @copyright 2010 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 /**
30 * The core course renderer
32 * Can be retrieved with the following:
33 * $renderer = $PAGE->get_renderer('core','course');
35 class core_course_renderer extends plugin_renderer_base {
36 const COURSECAT_SHOW_COURSES_NONE = 0; /* do not show courses at all */
37 const COURSECAT_SHOW_COURSES_COUNT = 5; /* do not show courses but show number of courses next to category name */
38 const COURSECAT_SHOW_COURSES_COLLAPSED = 10;
39 const COURSECAT_SHOW_COURSES_AUTO = 15; /* will choose between collapsed and expanded automatically */
40 const COURSECAT_SHOW_COURSES_EXPANDED = 20;
41 const COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT = 30;
43 const COURSECAT_TYPE_CATEGORY = 0;
44 const COURSECAT_TYPE_COURSE = 1;
46 /**
47 * A cache of strings
48 * @var stdClass
50 protected $strings;
52 /**
53 * Override the constructor so that we can initialise the string cache
55 * @param moodle_page $page
56 * @param string $target
58 public function __construct(moodle_page $page, $target) {
59 $this->strings = new stdClass;
60 parent::__construct($page, $target);
61 $this->add_modchoosertoggle();
64 /**
65 * Adds the item in course settings navigation to toggle modchooser
67 * Theme can overwrite as an empty function to exclude it (for example if theme does not
68 * use modchooser at all)
70 protected function add_modchoosertoggle() {
71 global $CFG;
72 static $modchoosertoggleadded = false;
73 // Add the module chooser toggle to the course page
74 if ($modchoosertoggleadded || $this->page->state > moodle_page::STATE_PRINTING_HEADER ||
75 $this->page->course->id == SITEID ||
76 !$this->page->user_is_editing() ||
77 !($context = context_course::instance($this->page->course->id)) ||
78 !has_capability('moodle/course:manageactivities', $context) ||
79 !course_ajax_enabled($this->page->course) ||
80 !($coursenode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE)) ||
81 !($turneditingnode = $coursenode->get('turneditingonoff'))) {
82 // too late or we are on site page or we could not find the adjacent nodes in course settings menu
83 // or we are not allowed to edit
84 return;
86 $modchoosertoggleadded = true;
87 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
88 // We are on the course page, retain the current page params e.g. section.
89 $modchoosertoggleurl = clone($this->page->url);
90 } else {
91 // Edit on the main course page.
92 $modchoosertoggleurl = new moodle_url('/course/view.php', array('id' => $this->page->course->id,
93 'return' => $this->page->url->out_as_local_url(false)));
95 $modchoosertoggleurl->param('sesskey', sesskey());
96 if ($usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault)) {
97 $modchoosertogglestring = get_string('modchooserdisable', 'moodle');
98 $modchoosertoggleurl->param('modchooser', 'off');
99 } else {
100 $modchoosertogglestring = get_string('modchooserenable', 'moodle');
101 $modchoosertoggleurl->param('modchooser', 'on');
103 $modchoosertoggle = navigation_node::create($modchoosertogglestring, $modchoosertoggleurl, navigation_node::TYPE_SETTING, null, 'modchoosertoggle');
105 // Insert the modchoosertoggle after the settings node 'turneditingonoff' (navigation_node only has function to insert before, so we insert before and then swap).
106 $coursenode->add_node($modchoosertoggle, 'turneditingonoff');
107 $turneditingnode->remove();
108 $coursenode->add_node($turneditingnode, 'modchoosertoggle');
110 $modchoosertoggle->add_class('modchoosertoggle');
111 $modchoosertoggle->add_class('visibleifjs');
112 user_preference_allow_ajax_update('usemodchooser', PARAM_BOOL);
116 * Renders course info box.
118 * @param stdClass|course_in_list $course
119 * @return string
121 public function course_info_box(stdClass $course) {
122 $content = '';
123 $content .= $this->output->box_start('generalbox info');
124 $chelper = new coursecat_helper();
125 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
126 $content .= $this->coursecat_coursebox($chelper, $course);
127 $content .= $this->output->box_end();
128 return $content;
132 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
134 * @deprecated since 2.5
136 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
138 * @param array $ignored argument ignored
139 * @return string
141 public final function course_category_tree(array $ignored) {
142 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
143 return $this->frontpage_combo_list();
147 * Renderers a category for use with course_category_tree
149 * @deprecated since 2.5
151 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
153 * @param array $category
154 * @param int $depth
155 * @return string
157 protected final function course_category_tree_category(stdClass $category, $depth=1) {
158 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
159 return '';
163 * Build the HTML for the module chooser javascript popup
165 * @param array $modules A set of modules as returned form @see
166 * get_module_metadata
167 * @param object $course The course that will be displayed
168 * @return string The composed HTML for the module
170 public function course_modchooser($modules, $course) {
171 static $isdisplayed = false;
172 if ($isdisplayed) {
173 return '';
175 $isdisplayed = true;
177 // Add the module chooser
178 $this->page->requires->yui_module('moodle-course-modchooser',
179 'M.course.init_chooser',
180 array(array('courseid' => $course->id, 'closeButtonTitle' => get_string('close', 'editor')))
182 $this->page->requires->strings_for_js(array(
183 'addresourceoractivity',
184 'modchooserenable',
185 'modchooserdisable',
186 ), 'moodle');
188 // Add the header
189 $header = html_writer::tag('div', get_string('addresourceoractivity', 'moodle'),
190 array('class' => 'hd choosertitle'));
192 $formcontent = html_writer::start_tag('form', array('action' => new moodle_url('/course/jumpto.php'),
193 'id' => 'chooserform', 'method' => 'post'));
194 $formcontent .= html_writer::start_tag('div', array('id' => 'typeformdiv'));
195 $formcontent .= html_writer::tag('input', '', array('type' => 'hidden', 'id' => 'course',
196 'name' => 'course', 'value' => $course->id));
197 $formcontent .= html_writer::tag('input', '',
198 array('type' => 'hidden', 'class' => 'jump', 'name' => 'jump', 'value' => ''));
199 $formcontent .= html_writer::tag('input', '', array('type' => 'hidden', 'name' => 'sesskey',
200 'value' => sesskey()));
201 $formcontent .= html_writer::end_tag('div');
203 // Put everything into one tag 'options'
204 $formcontent .= html_writer::start_tag('div', array('class' => 'options'));
205 $formcontent .= html_writer::tag('div', get_string('selectmoduletoviewhelp', 'moodle'),
206 array('class' => 'instruction'));
207 // Put all options into one tag 'alloptions' to allow us to handle scrolling
208 $formcontent .= html_writer::start_tag('div', array('class' => 'alloptions'));
210 // Activities
211 $activities = array_filter($modules, create_function('$mod', 'return ($mod->archetype !== MOD_ARCHETYPE_RESOURCE && $mod->archetype !== MOD_ARCHETYPE_SYSTEM);'));
212 if (count($activities)) {
213 $formcontent .= $this->course_modchooser_title('activities');
214 $formcontent .= $this->course_modchooser_module_types($activities);
217 // Resources
218 $resources = array_filter($modules, create_function('$mod', 'return ($mod->archetype === MOD_ARCHETYPE_RESOURCE);'));
219 if (count($resources)) {
220 $formcontent .= $this->course_modchooser_title('resources');
221 $formcontent .= $this->course_modchooser_module_types($resources);
224 $formcontent .= html_writer::end_tag('div'); // modoptions
225 $formcontent .= html_writer::end_tag('div'); // types
227 $formcontent .= html_writer::start_tag('div', array('class' => 'submitbuttons'));
228 $formcontent .= html_writer::tag('input', '',
229 array('type' => 'submit', 'name' => 'submitbutton', 'class' => 'submitbutton', 'value' => get_string('add')));
230 $formcontent .= html_writer::tag('input', '',
231 array('type' => 'submit', 'name' => 'addcancel', 'class' => 'addcancel', 'value' => get_string('cancel')));
232 $formcontent .= html_writer::end_tag('div');
233 $formcontent .= html_writer::end_tag('form');
235 // Wrap the whole form in a div
236 $formcontent = html_writer::tag('div', $formcontent, array('id' => 'chooseform'));
238 // Put all of the content together
239 $content = $formcontent;
241 $content = html_writer::tag('div', $content, array('class' => 'choosercontainer'));
242 return $header . html_writer::tag('div', $content, array('class' => 'chooserdialoguebody'));
246 * Build the HTML for a specified set of modules
248 * @param array $modules A set of modules as used by the
249 * course_modchooser_module function
250 * @return string The composed HTML for the module
252 protected function course_modchooser_module_types($modules) {
253 $return = '';
254 foreach ($modules as $module) {
255 if (!isset($module->types)) {
256 $return .= $this->course_modchooser_module($module);
257 } else {
258 $return .= $this->course_modchooser_module($module, array('nonoption'));
259 foreach ($module->types as $type) {
260 $return .= $this->course_modchooser_module($type, array('option', 'subtype'));
264 return $return;
268 * Return the HTML for the specified module adding any required classes
270 * @param object $module An object containing the title, and link. An
271 * icon, and help text may optionally be specified. If the module
272 * contains subtypes in the types option, then these will also be
273 * displayed.
274 * @param array $classes Additional classes to add to the encompassing
275 * div element
276 * @return string The composed HTML for the module
278 protected function course_modchooser_module($module, $classes = array('option')) {
279 $output = '';
280 $output .= html_writer::start_tag('div', array('class' => implode(' ', $classes)));
281 $output .= html_writer::start_tag('label', array('for' => 'module_' . $module->name));
282 if (!isset($module->types)) {
283 $output .= html_writer::tag('input', '', array('type' => 'radio',
284 'name' => 'jumplink', 'id' => 'module_' . $module->name, 'value' => $module->link));
287 $output .= html_writer::start_tag('span', array('class' => 'modicon'));
288 if (isset($module->icon)) {
289 // Add an icon if we have one
290 $output .= $module->icon;
292 $output .= html_writer::end_tag('span');
294 $output .= html_writer::tag('span', $module->title, array('class' => 'typename'));
295 if (!isset($module->help)) {
296 // Add help if found
297 $module->help = get_string('nohelpforactivityorresource', 'moodle');
300 // Format the help text using markdown with the following options
301 $options = new stdClass();
302 $options->trusted = false;
303 $options->noclean = false;
304 $options->smiley = false;
305 $options->filter = false;
306 $options->para = true;
307 $options->newlines = false;
308 $options->overflowdiv = false;
309 $module->help = format_text($module->help, FORMAT_MARKDOWN, $options);
310 $output .= html_writer::tag('span', $module->help, array('class' => 'typesummary'));
311 $output .= html_writer::end_tag('label');
312 $output .= html_writer::end_tag('div');
314 return $output;
317 protected function course_modchooser_title($title, $identifier = null) {
318 $module = new stdClass();
319 $module->name = $title;
320 $module->types = array();
321 $module->title = get_string($title, $identifier);
322 $module->help = '';
323 return $this->course_modchooser_module($module, array('moduletypetitle'));
327 * Renders HTML for displaying the sequence of course module editing buttons
329 * @see course_get_cm_edit_actions()
331 * @param action_link[] $actions Array of action_link objects
332 * @param cm_info $mod The module we are displaying actions for.
333 * @param array $displayoptions additional display options:
334 * ownerselector => A JS/CSS selector that can be used to find an cm node.
335 * If specified the owning node will be given the class 'action-menu-shown' when the action
336 * menu is being displayed.
337 * constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
338 * the action menu to when it is being displayed.
339 * donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
340 * @return string
342 public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
343 global $CFG;
345 if (empty($actions)) {
346 return '';
349 if (isset($displayoptions['ownerselector'])) {
350 $ownerselector = $displayoptions['ownerselector'];
351 } else if ($mod) {
352 $ownerselector = '#module-'.$mod->id;
353 } else {
354 debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
355 $ownerselector = 'li.activity';
358 if (isset($displayoptions['constraintselector'])) {
359 $constraint = $displayoptions['constraintselector'];
360 } else {
361 $constraint = '.course-content';
364 $menu = new action_menu();
365 $menu->set_owner_selector($ownerselector);
366 $menu->set_contraint($constraint);
367 $menu->set_alignment(action_menu::TL, action_menu::TR);
368 if (isset($CFG->modeditingmenu) && !$CFG->modeditingmenu || !empty($displayoptions['donotenhance'])) {
369 $menu->do_not_enhance();
371 foreach ($actions as $action) {
372 if ($action instanceof action_menu_link) {
373 $action->add_class('cm-edit-action');
375 $menu->add($action);
377 $menu->attributes['class'] .= ' section-cm-edit-actions commands';
378 return $this->render($menu);
382 * Renders HTML for the menus to add activities and resources to the current course
384 * Note, if theme overwrites this function and it does not use modchooser,
385 * see also {@link core_course_renderer::add_modchoosertoggle()}
387 * @param stdClass $course
388 * @param int $section relative section number (field course_sections.section)
389 * @param int $sectionreturn The section to link back to
390 * @param array $displayoptions additional display options, for example blocks add
391 * option 'inblock' => true, suggesting to display controls vertically
392 * @return string
394 function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
395 global $CFG;
397 $vertical = !empty($displayoptions['inblock']);
399 // check to see if user can add menus and there are modules to add
400 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
401 || !$this->page->user_is_editing()
402 || !($modnames = get_module_types_names()) || empty($modnames)) {
403 return '';
406 // Retrieve all modules with associated metadata
407 $modules = get_module_metadata($course, $modnames, $sectionreturn);
408 $urlparams = array('section' => $section);
410 // We'll sort resources and activities into two lists
411 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
413 foreach ($modules as $module) {
414 if (isset($module->types)) {
415 // This module has a subtype
416 // NOTE: this is legacy stuff, module subtypes are very strongly discouraged!!
417 $subtypes = array();
418 foreach ($module->types as $subtype) {
419 $link = $subtype->link->out(true, $urlparams);
420 $subtypes[$link] = $subtype->title;
423 // Sort module subtypes into the list
424 $activityclass = MOD_CLASS_ACTIVITY;
425 if ($module->archetype == MOD_CLASS_RESOURCE) {
426 $activityclass = MOD_CLASS_RESOURCE;
428 if (!empty($module->title)) {
429 // This grouping has a name
430 $activities[$activityclass][] = array($module->title => $subtypes);
431 } else {
432 // This grouping does not have a name
433 $activities[$activityclass] = array_merge($activities[$activityclass], $subtypes);
435 } else {
436 // This module has no subtypes
437 $activityclass = MOD_CLASS_ACTIVITY;
438 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
439 $activityclass = MOD_CLASS_RESOURCE;
440 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
441 // System modules cannot be added by user, do not add to dropdown
442 continue;
444 $link = $module->link->out(true, $urlparams);
445 $activities[$activityclass][$link] = $module->title;
449 $straddactivity = get_string('addactivity');
450 $straddresource = get_string('addresource');
451 $sectionname = get_section_name($course, $section);
452 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
453 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
455 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
457 if (!$vertical) {
458 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
461 if (!empty($activities[MOD_CLASS_RESOURCE])) {
462 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array(''=>$straddresource), "ressection$section");
463 $select->set_help_icon('resources');
464 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
465 $output .= $this->output->render($select);
468 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
469 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array(''=>$straddactivity), "section$section");
470 $select->set_help_icon('activities');
471 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
472 $output .= $this->output->render($select);
475 if (!$vertical) {
476 $output .= html_writer::end_tag('div');
479 $output .= html_writer::end_tag('div');
481 if (course_ajax_enabled($course) && $course->id == $this->page->course->id) {
482 // modchooser can be added only for the current course set on the page!
483 $straddeither = get_string('addresourceoractivity');
484 // The module chooser link
485 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
486 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
487 $icon = $this->output->pix_icon('t/add', '');
488 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
489 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
490 $modchooser.= html_writer::end_tag('div');
491 $modchooser.= html_writer::end_tag('div');
493 // Wrap the normal output in a noscript div
494 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
495 if ($usemodchooser) {
496 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
497 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
498 } else {
499 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
500 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
501 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
503 $output = $this->course_modchooser($modules, $course) . $modchooser . $output;
506 return $output;
510 * Renders html to display a course search form
512 * @param string $value default value to populate the search field
513 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
514 * @return string
516 function course_search_form($value = '', $format = 'plain') {
517 static $count = 0;
518 $formid = 'coursesearch';
519 if ((++$count) > 1) {
520 $formid .= $count;
523 switch ($format) {
524 case 'navbar' :
525 $formid = 'coursesearchnavbar';
526 $inputid = 'navsearchbox';
527 $inputsize = 20;
528 break;
529 case 'short' :
530 $inputid = 'shortsearchbox';
531 $inputsize = 12;
532 break;
533 default :
534 $inputid = 'coursesearchbox';
535 $inputsize = 30;
538 $strsearchcourses= get_string("searchcourses");
539 $searchurl = new moodle_url('/course/search.php');
541 $output = html_writer::start_tag('form', array('id' => $formid, 'action' => $searchurl, 'method' => 'get'));
542 $output .= html_writer::start_tag('fieldset', array('class' => 'coursesearchbox invisiblefieldset'));
543 $output .= html_writer::tag('label', $strsearchcourses.': ', array('for' => $inputid));
544 $output .= html_writer::empty_tag('input', array('type' => 'text', 'id' => $inputid,
545 'size' => $inputsize, 'name' => 'search', 'value' => s($value)));
546 $output .= html_writer::empty_tag('input', array('type' => 'submit',
547 'value' => get_string('go')));
548 $output .= html_writer::end_tag('fieldset');
549 $output .= html_writer::end_tag('form');
551 return $output;
555 * Renders html for completion box on course page
557 * If completion is disabled, returns empty string
558 * If completion is automatic, returns an icon of the current completion state
559 * If completion is manual, returns a form (with an icon inside) that allows user to
560 * toggle completion
562 * @param stdClass $course course object
563 * @param completion_info $completioninfo completion info for the course, it is recommended
564 * to fetch once for all modules in course/section for performance
565 * @param cm_info $mod module to show completion for
566 * @param array $displayoptions display options, not used in core
567 * @return string
569 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
570 global $CFG;
571 $output = '';
572 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
573 return $output;
575 if ($completioninfo === null) {
576 $completioninfo = new completion_info($course);
578 $completion = $completioninfo->is_enabled($mod);
579 if ($completion == COMPLETION_TRACKING_NONE) {
580 return $output;
583 $completiondata = $completioninfo->get_data($mod, true);
584 $completionicon = '';
586 if ($this->page->user_is_editing()) {
587 switch ($completion) {
588 case COMPLETION_TRACKING_MANUAL :
589 $completionicon = 'manual-enabled'; break;
590 case COMPLETION_TRACKING_AUTOMATIC :
591 $completionicon = 'auto-enabled'; break;
593 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
594 switch($completiondata->completionstate) {
595 case COMPLETION_INCOMPLETE:
596 $completionicon = 'manual-n'; break;
597 case COMPLETION_COMPLETE:
598 $completionicon = 'manual-y'; break;
600 } else { // Automatic
601 switch($completiondata->completionstate) {
602 case COMPLETION_INCOMPLETE:
603 $completionicon = 'auto-n'; break;
604 case COMPLETION_COMPLETE:
605 $completionicon = 'auto-y'; break;
606 case COMPLETION_COMPLETE_PASS:
607 $completionicon = 'auto-pass'; break;
608 case COMPLETION_COMPLETE_FAIL:
609 $completionicon = 'auto-fail'; break;
612 if ($completionicon) {
613 $formattedname = $mod->get_formatted_name();
614 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
615 if ($completion == COMPLETION_TRACKING_MANUAL && !$this->page->user_is_editing()) {
616 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
617 $newstate =
618 $completiondata->completionstate == COMPLETION_COMPLETE
619 ? COMPLETION_INCOMPLETE
620 : COMPLETION_COMPLETE;
621 // In manual mode the icon is a toggle form...
623 // If this completion state is used by the
624 // conditional activities system, we need to turn
625 // off the JS.
626 $extraclass = '';
627 if (!empty($CFG->enableavailability) &&
628 condition_info::completion_value_used_as_condition($course, $mod)) {
629 $extraclass = ' preventjs';
631 $output .= html_writer::start_tag('form', array('method' => 'post',
632 'action' => new moodle_url('/course/togglecompletion.php'),
633 'class' => 'togglecompletion'. $extraclass));
634 $output .= html_writer::start_tag('div');
635 $output .= html_writer::empty_tag('input', array(
636 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
637 $output .= html_writer::empty_tag('input', array(
638 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
639 $output .= html_writer::empty_tag('input', array(
640 'type' => 'hidden', 'name' => 'modulename', 'value' => $mod->name));
641 $output .= html_writer::empty_tag('input', array(
642 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
643 $output .= html_writer::empty_tag('input', array(
644 'type' => 'image',
645 'src' => $this->output->pix_url('i/completion-'.$completionicon),
646 'alt' => $imgalt, 'title' => $imgtitle,
647 'aria-live' => 'polite'));
648 $output .= html_writer::end_tag('div');
649 $output .= html_writer::end_tag('form');
650 } else {
651 // In auto mode, or when editing, the icon is just an image
652 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
653 array('title' => $imgalt));
654 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
655 array('class' => 'autocompletion'));
658 return $output;
662 * Checks if course module has any conditions that may make it unavailable for
663 * all or some of the students
665 * This function is internal and is only used to create CSS classes for the module name/text
667 * @param cm_info $mod
668 * @return bool
670 protected function is_cm_conditionally_hidden(cm_info $mod) {
671 global $CFG;
672 $conditionalhidden = false;
673 if (!empty($CFG->enableavailability)) {
674 $conditionalhidden = $mod->availablefrom > time() ||
675 ($mod->availableuntil && $mod->availableuntil < time()) ||
676 count($mod->conditionsgrade) > 0 ||
677 count($mod->conditionscompletion) > 0 ||
678 count($mod->conditionsfield);
680 return $conditionalhidden;
684 * Renders html to display a name with the link to the course module on a course page
686 * If module is unavailable for user but still needs to be displayed
687 * in the list, just the name is returned without a link
689 * Note, that for course modules that never have separate pages (i.e. labels)
690 * this function return an empty string
692 * @param cm_info $mod
693 * @param array $displayoptions
694 * @return string
696 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
697 global $CFG;
698 $output = '';
699 if (!$mod->uservisible &&
700 (empty($mod->showavailability) || empty($mod->availableinfo))) {
701 // nothing to be displayed to the user
702 return $output;
704 $url = $mod->get_url();
705 if (!$url) {
706 return $output;
709 //Accessibility: for files get description via icon, this is very ugly hack!
710 $instancename = $mod->get_formatted_name();
711 $altname = $mod->modfullname;
712 // Avoid unnecessary duplication: if e.g. a forum name already
713 // includes the word forum (or Forum, etc) then it is unhelpful
714 // to include that in the accessible description that is added.
715 if (false !== strpos(core_text::strtolower($instancename),
716 core_text::strtolower($altname))) {
717 $altname = '';
719 // File type after name, for alphabetic lists (screen reader).
720 if ($altname) {
721 $altname = get_accesshide(' '.$altname);
724 // For items which are hidden but available to current user
725 // ($mod->uservisible), we show those as dimmed only if the user has
726 // viewhiddenactivities, so that teachers see 'items which might not
727 // be available to some students' dimmed but students do not see 'item
728 // which is actually available to current student' dimmed.
729 $linkclasses = '';
730 $accesstext = '';
731 $textclasses = '';
732 if ($mod->uservisible) {
733 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
734 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
735 has_capability('moodle/course:viewhiddenactivities',
736 context_course::instance($mod->course));
737 if ($accessiblebutdim) {
738 $linkclasses .= ' dimmed';
739 $textclasses .= ' dimmed_text';
740 if ($conditionalhidden) {
741 $linkclasses .= ' conditionalhidden';
742 $textclasses .= ' conditionalhidden';
744 // Show accessibility note only if user can access the module himself.
745 $accesstext = get_accesshide(get_string('hiddenfromstudents').':'. $mod->modfullname);
747 } else {
748 $linkclasses .= ' dimmed';
749 $textclasses .= ' dimmed_text';
752 // Get on-click attribute value if specified and decode the onclick - it
753 // has already been encoded for display (puke).
754 $onclick = htmlspecialchars_decode($mod->get_on_click(), ENT_QUOTES);
756 $groupinglabel = '';
757 if (!empty($mod->groupingid) && has_capability('moodle/course:managegroups', context_course::instance($mod->course))) {
758 $groupings = groups_get_all_groupings($mod->course);
759 $groupinglabel = html_writer::tag('span', '('.format_string($groupings[$mod->groupingid]->name).')',
760 array('class' => 'groupinglabel '.$textclasses));
763 // Display link itself.
764 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
765 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) . $accesstext .
766 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
767 if ($mod->uservisible) {
768 $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick)) .
769 $groupinglabel;
770 } else {
771 // We may be displaying this just in order to show information
772 // about visibility, without the actual link ($mod->uservisible)
773 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses)) .
774 $groupinglabel;
776 return $output;
780 * Renders html to display the module content on the course page (i.e. text of the labels)
782 * @param cm_info $mod
783 * @param array $displayoptions
784 * @return string
786 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
787 $output = '';
788 if (!$mod->uservisible &&
789 (empty($mod->showavailability) || empty($mod->availableinfo))) {
790 // nothing to be displayed to the user
791 return $output;
793 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
794 $accesstext = '';
795 $textclasses = '';
796 if ($mod->uservisible) {
797 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
798 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
799 has_capability('moodle/course:viewhiddenactivities',
800 context_course::instance($mod->course));
801 if ($accessiblebutdim) {
802 $textclasses .= ' dimmed_text';
803 if ($conditionalhidden) {
804 $textclasses .= ' conditionalhidden';
806 // Show accessibility note only if user can access the module himself.
807 $accesstext = get_accesshide(get_string('hiddenfromstudents').':'. $mod->modfullname);
809 } else {
810 $textclasses .= ' dimmed_text';
812 if ($mod->get_url()) {
813 if ($content) {
814 // If specified, display extra content after link.
815 $output = html_writer::tag('div', $content, array('class' =>
816 trim('contentafterlink ' . $textclasses)));
818 } else {
819 // No link, so display only content.
820 $output = html_writer::tag('div', $accesstext . $content, array('class' => $textclasses));
822 return $output;
826 * Renders HTML to show course module availability information (for someone who isn't allowed
827 * to see the activity itself, or for staff)
829 * @param cm_info $mod
830 * @param array $displayoptions
831 * @return string
833 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
834 global $CFG;
835 if (!$mod->uservisible) {
836 // this is a student who is not allowed to see the module but might be allowed
837 // to see availability info (i.e. "Available from ...")
838 if (!empty($mod->showavailability) && !empty($mod->availableinfo)) {
839 $output = html_writer::tag('div', $mod->availableinfo, array('class' => 'availabilityinfo'));
841 return $output;
843 // this is a teacher who is allowed to see module but still should see the
844 // information that module is not available to all/some students
845 $modcontext = context_module::instance($mod->id);
846 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
847 if ($canviewhidden && !empty($CFG->enableavailability)) {
848 // Don't add availability information if user is not editing and activity is hidden.
849 if ($mod->visible || $this->page->user_is_editing()) {
850 $hidinfoclass = '';
851 if (!$mod->visible) {
852 $hidinfoclass = 'hide';
854 $ci = new condition_info($mod);
855 $fullinfo = $ci->get_full_information();
856 if($fullinfo) {
857 return '<div class="availabilityinfo '.$hidinfoclass.'">'.get_string($mod->showavailability
858 ? 'userrestriction_visible'
859 : 'userrestriction_hidden','condition',
860 $fullinfo).'</div>';
864 return '';
868 * Renders HTML to display one course module for display within a section.
870 * This function calls:
871 * {@link core_course_renderer::course_section_cm()}
873 * @param stdClass $course
874 * @param completion_info $completioninfo
875 * @param cm_info $mod
876 * @param int|null $sectionreturn
877 * @param array $displayoptions
878 * @return String
880 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
881 $output = '';
882 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
883 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->get_extra_classes();
884 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
886 return $output;
890 * Renders HTML to display one course module in a course section
892 * This includes link, content, availability, completion info and additional information
893 * that module type wants to display (i.e. number of unread forum posts)
895 * This function calls:
896 * {@link core_course_renderer::course_section_cm_name()}
897 * {@link cm_info::get_after_link()}
898 * {@link core_course_renderer::course_section_cm_text()}
899 * {@link core_course_renderer::course_section_cm_availability()}
900 * {@link core_course_renderer::course_section_cm_completion()}
901 * {@link course_get_cm_edit_actions()}
902 * {@link core_course_renderer::course_section_cm_edit_actions()}
904 * @param stdClass $course
905 * @param completion_info $completioninfo
906 * @param cm_info $mod
907 * @param int|null $sectionreturn
908 * @param array $displayoptions
909 * @return string
911 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
912 $output = '';
913 // We return empty string (because course module will not be displayed at all)
914 // if:
915 // 1) The activity is not visible to users
916 // and
917 // 2a) The 'showavailability' option is not set (if that is set,
918 // we need to display the activity so we can show
919 // availability info)
920 // or
921 // 2b) The 'availableinfo' is empty, i.e. the activity was
922 // hidden in a way that leaves no info, such as using the
923 // eye icon.
924 if (!$mod->uservisible &&
925 (empty($mod->showavailability) || empty($mod->availableinfo))) {
926 return $output;
929 $indentclasses = 'mod-indent';
930 if (!empty($mod->indent)) {
931 $indentclasses .= ' mod-indent-'.$mod->indent;
932 if ($mod->indent > 15) {
933 $indentclasses .= ' mod-indent-huge';
936 $output .= html_writer::start_tag('div', array('class' => $indentclasses));
938 // Start the div for the activity title, excluding the edit icons.
939 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
941 // Display the link to the module (or do nothing if module has no url)
942 $output .= $this->course_section_cm_name($mod, $displayoptions);
944 // Module can put text after the link (e.g. forum unread)
945 $output .= $mod->get_after_link();
947 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
948 $output .= html_writer::end_tag('div'); // .activityinstance
950 // If there is content but NO link (eg label), then display the
951 // content here (BEFORE any icons). In this case cons must be
952 // displayed after the content so that it makes more sense visually
953 // and for accessibility reasons, e.g. if you have a one-line label
954 // it should work similarly (at least in terms of ordering) to an
955 // activity.
956 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
957 $url = $mod->get_url();
958 if (empty($url)) {
959 $output .= $contentpart;
962 if ($this->page->user_is_editing()) {
963 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
964 $output .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
965 $output .= $mod->get_after_edit_icons();
968 $output .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
970 // If there is content AND a link, then display the content here
971 // (AFTER any icons). Otherwise it was displayed before
972 if (!empty($url)) {
973 $output .= $contentpart;
976 // show availability info (if module is not available)
977 $output .= $this->course_section_cm_availability($mod, $displayoptions);
979 $output .= html_writer::end_tag('div'); // $indentclasses
980 return $output;
984 * Renders HTML to display a list of course modules in a course section
985 * Also displays "move here" controls in Javascript-disabled mode
987 * This function calls {@link core_course_renderer::course_section_cm()}
989 * @param stdClass $course course object
990 * @param int|stdClass|section_info $section relative section number or section object
991 * @param int $sectionreturn section number to return to
992 * @param int $displayoptions
993 * @return void
995 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
996 global $USER;
998 $output = '';
999 $modinfo = get_fast_modinfo($course);
1000 if (is_object($section)) {
1001 $section = $modinfo->get_section_info($section->section);
1002 } else {
1003 $section = $modinfo->get_section_info($section);
1005 $completioninfo = new completion_info($course);
1007 // check if we are currently in the process of moving a module with JavaScript disabled
1008 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
1009 if ($ismoving) {
1010 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
1011 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1014 // Get the list of modules visible to user (excluding the module being moved if there is one)
1015 $moduleshtml = array();
1016 if (!empty($modinfo->sections[$section->section])) {
1017 foreach ($modinfo->sections[$section->section] as $modnumber) {
1018 $mod = $modinfo->cms[$modnumber];
1020 if ($ismoving and $mod->id == $USER->activitycopy) {
1021 // do not display moving mod
1022 continue;
1025 if ($modulehtml = $this->course_section_cm_list_item($course,
1026 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
1027 $moduleshtml[$modnumber] = $modulehtml;
1032 $sectionoutput = '';
1033 if (!empty($moduleshtml) || $ismoving) {
1034 foreach ($moduleshtml as $modnumber => $modulehtml) {
1035 if ($ismoving) {
1036 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
1037 $sectionoutput .= html_writer::tag('li', html_writer::link($movingurl, $this->output->render($movingpix)),
1038 array('class' => 'movehere', 'title' => $strmovefull));
1041 $sectionoutput .= $modulehtml;
1044 if ($ismoving) {
1045 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1046 $sectionoutput .= html_writer::tag('li', html_writer::link($movingurl, $this->output->render($movingpix)),
1047 array('class' => 'movehere', 'title' => $strmovefull));
1051 // Always output the section module list.
1052 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1054 return $output;
1058 * Displays a custom list of courses with paging bar if necessary
1060 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1061 * appears under the list.
1063 * If both $paginationurl and $totalcount are specified, and $totalcount is
1064 * bigger than count($courses), a paging bar is displayed above and under the
1065 * courses list.
1067 * @param array $courses array of course records (or instances of course_in_list) to show on this page
1068 * @param bool $showcategoryname whether to add category name to the course description
1069 * @param string $additionalclasses additional CSS classes to add to the div.courses
1070 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1071 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1072 * @param int $page current page number (defaults to 0 referring to the first page)
1073 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1074 * @return string
1076 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1077 global $CFG;
1078 // create instance of coursecat_helper to pass display options to function rendering courses list
1079 $chelper = new coursecat_helper();
1080 if ($showcategoryname) {
1081 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1082 } else {
1083 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1085 if ($totalcount !== null && $paginationurl !== null) {
1086 // add options to display pagination
1087 if ($perpage === null) {
1088 $perpage = $CFG->coursesperpage;
1090 $chelper->set_courses_display_options(array(
1091 'limit' => $perpage,
1092 'offset' => ((int)$page) * $perpage,
1093 'paginationurl' => $paginationurl,
1095 } else if ($paginationurl !== null) {
1096 // add options to display 'View more' link
1097 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1098 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1100 $chelper->set_attributes(array('class' => $additionalclasses));
1101 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1102 return $content;
1106 * Displays one course in the list of courses.
1108 * This is an internal function, to display an information about just one course
1109 * please use {@link core_course_renderer::course_info_box()}
1111 * @param coursecat_helper $chelper various display options
1112 * @param course_in_list|stdClass $course
1113 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1114 * depend on the course position in list - first/last/even/odd)
1115 * @return string
1117 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1118 global $CFG;
1119 if (!isset($this->strings->summary)) {
1120 $this->strings->summary = get_string('summary');
1122 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1123 return '';
1125 if ($course instanceof stdClass) {
1126 require_once($CFG->libdir. '/coursecatlib.php');
1127 $course = new course_in_list($course);
1129 $content = '';
1130 $classes = trim('coursebox clearfix '. $additionalclasses);
1131 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1132 $nametag = 'h3';
1133 } else {
1134 $classes .= ' collapsed';
1135 $nametag = 'div';
1138 // .coursebox
1139 $content .= html_writer::start_tag('div', array(
1140 'class' => $classes,
1141 'data-courseid' => $course->id,
1142 'data-type' => self::COURSECAT_TYPE_COURSE,
1145 $content .= html_writer::start_tag('div', array('class' => 'info'));
1147 // course name
1148 $coursename = $chelper->get_course_formatted_name($course);
1149 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', array('id' => $course->id)),
1150 $coursename, array('class' => $course->visible ? '' : 'dimmed'));
1151 $content .= html_writer::tag($nametag, $coursenamelink, array('class' => 'coursename'));
1152 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1153 $content .= html_writer::start_tag('div', array('class' => 'moreinfo'));
1154 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1155 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()) {
1156 $url = new moodle_url('/course/info.php', array('id' => $course->id));
1157 $image = html_writer::empty_tag('img', array('src' => $this->output->pix_url('i/info'),
1158 'alt' => $this->strings->summary));
1159 $content .= html_writer::link($url, $image, array('title' => $this->strings->summary));
1160 // Make sure JS file to expand course content is included.
1161 $this->coursecat_include_js();
1164 $content .= html_writer::end_tag('div'); // .moreinfo
1166 // print enrolmenticons
1167 if ($icons = enrol_get_course_info_icons($course)) {
1168 $content .= html_writer::start_tag('div', array('class' => 'enrolmenticons'));
1169 foreach ($icons as $pix_icon) {
1170 $content .= $this->render($pix_icon);
1172 $content .= html_writer::end_tag('div'); // .enrolmenticons
1175 $content .= html_writer::end_tag('div'); // .info
1177 $content .= html_writer::start_tag('div', array('class' => 'content'));
1178 $content .= $this->coursecat_coursebox_content($chelper, $course);
1179 $content .= html_writer::end_tag('div'); // .content
1181 $content .= html_writer::end_tag('div'); // .coursebox
1182 return $content;
1186 * Returns HTML to display course content (summary, course contacts and optionally category name)
1188 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1190 * @param coursecat_helper $chelper various display options
1191 * @param stdClass|course_in_list $course
1192 * @return string
1194 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1195 global $CFG;
1196 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1197 return '';
1199 if ($course instanceof stdClass) {
1200 require_once($CFG->libdir. '/coursecatlib.php');
1201 $course = new course_in_list($course);
1203 $content = '';
1205 // display course summary
1206 if ($course->has_summary()) {
1207 $content .= html_writer::start_tag('div', array('class' => 'summary'));
1208 $content .= $chelper->get_course_formatted_summary($course,
1209 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1210 $content .= html_writer::end_tag('div'); // .summary
1213 // display course overview files
1214 $contentimages = $contentfiles = '';
1215 foreach ($course->get_course_overviewfiles() as $file) {
1216 $isimage = $file->is_valid_image();
1217 $url = file_encode_url("$CFG->wwwroot/pluginfile.php",
1218 '/'. $file->get_contextid(). '/'. $file->get_component(). '/'.
1219 $file->get_filearea(). $file->get_filepath(). $file->get_filename(), !$isimage);
1220 if ($isimage) {
1221 $contentimages .= html_writer::tag('div',
1222 html_writer::empty_tag('img', array('src' => $url)),
1223 array('class' => 'courseimage'));
1224 } else {
1225 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1226 $filename = html_writer::tag('span', $image, array('class' => 'fp-icon')).
1227 html_writer::tag('span', $file->get_filename(), array('class' => 'fp-filename'));
1228 $contentfiles .= html_writer::tag('span',
1229 html_writer::link($url, $filename),
1230 array('class' => 'coursefile fp-filename-icon'));
1233 $content .= $contentimages. $contentfiles;
1235 // display course contacts. See course_in_list::get_course_contacts()
1236 if ($course->has_course_contacts()) {
1237 $content .= html_writer::start_tag('ul', array('class' => 'teachers'));
1238 foreach ($course->get_course_contacts() as $userid => $coursecontact) {
1239 $name = $coursecontact['rolename'].': '.
1240 html_writer::link(new moodle_url('/user/view.php',
1241 array('id' => $userid, 'course' => SITEID)),
1242 $coursecontact['username']);
1243 $content .= html_writer::tag('li', $name);
1245 $content .= html_writer::end_tag('ul'); // .teachers
1248 // display course category if necessary (for example in search results)
1249 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1250 require_once($CFG->libdir. '/coursecatlib.php');
1251 if ($cat = coursecat::get($course->category, IGNORE_MISSING)) {
1252 $content .= html_writer::start_tag('div', array('class' => 'coursecat'));
1253 $content .= get_string('category').': '.
1254 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1255 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1256 $content .= html_writer::end_tag('div'); // .coursecat
1260 return $content;
1264 * Renders the list of courses
1266 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1267 * method from outside of the class
1269 * If list of courses is specified in $courses; the argument $chelper is only used
1270 * to retrieve display options and attributes, only methods get_show_courses(),
1271 * get_courses_display_option() and get_and_erase_attributes() are called.
1273 * @param coursecat_helper $chelper various display options
1274 * @param array $courses the list of courses to display
1275 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1276 * defaulted to count($courses)
1277 * @return string
1279 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1280 global $CFG;
1281 if ($totalcount === null) {
1282 $totalcount = count($courses);
1284 if (!$totalcount) {
1285 // Courses count is cached during courses retrieval.
1286 return '';
1289 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1290 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1291 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1292 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1293 } else {
1294 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1298 // prepare content of paging bar if it is needed
1299 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1300 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1301 if ($totalcount > count($courses)) {
1302 // there are more results that can fit on one page
1303 if ($paginationurl) {
1304 // the option paginationurl was specified, display pagingbar
1305 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1306 $page = $chelper->get_courses_display_option('offset') / $perpage;
1307 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1308 $paginationurl->out(false, array('perpage' => $perpage)));
1309 if ($paginationallowall) {
1310 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1311 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1313 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1314 // the option for 'View more' link was specified, display more link
1315 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1316 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1317 array('class' => 'paging paging-morelink'));
1319 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1320 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1321 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1322 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1325 // display list of courses
1326 $attributes = $chelper->get_and_erase_attributes('courses');
1327 $content = html_writer::start_tag('div', $attributes);
1329 if (!empty($pagingbar)) {
1330 $content .= $pagingbar;
1333 $coursecount = 0;
1334 foreach ($courses as $course) {
1335 $coursecount ++;
1336 $classes = ($coursecount%2) ? 'odd' : 'even';
1337 if ($coursecount == 1) {
1338 $classes .= ' first';
1340 if ($coursecount >= count($courses)) {
1341 $classes .= ' last';
1343 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1346 if (!empty($pagingbar)) {
1347 $content .= $pagingbar;
1349 if (!empty($morelink)) {
1350 $content .= $morelink;
1353 $content .= html_writer::end_tag('div'); // .courses
1354 return $content;
1358 * Renders the list of subcategories in a category
1360 * @param coursecat_helper $chelper various display options
1361 * @param coursecat $coursecat
1362 * @param int $depth depth of the category in the current tree
1363 * @return string
1365 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1366 global $CFG;
1367 $subcategories = array();
1368 if (!$chelper->get_categories_display_option('nodisplay')) {
1369 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1371 $totalcount = $coursecat->get_children_count();
1372 if (!$totalcount) {
1373 // Note that we call get_child_categories_count() AFTER get_child_categories() to avoid extra DB requests.
1374 // Categories count is cached during children categories retrieval.
1375 return '';
1378 // prepare content of paging bar or more link if it is needed
1379 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1380 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1381 if ($totalcount > count($subcategories)) {
1382 if ($paginationurl) {
1383 // the option 'paginationurl was specified, display pagingbar
1384 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1385 $page = $chelper->get_categories_display_option('offset') / $perpage;
1386 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1387 $paginationurl->out(false, array('perpage' => $perpage)));
1388 if ($paginationallowall) {
1389 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1390 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1392 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1393 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1394 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1395 $viewmoreurl->param('categoryid', $coursecat->id);
1397 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1398 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1399 array('class' => 'paging paging-morelink'));
1401 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1402 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1403 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1404 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1407 // display list of subcategories
1408 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1410 if (!empty($pagingbar)) {
1411 $content .= $pagingbar;
1414 foreach ($subcategories as $subcategory) {
1415 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1418 if (!empty($pagingbar)) {
1419 $content .= $pagingbar;
1421 if (!empty($morelink)) {
1422 $content .= $morelink;
1425 $content .= html_writer::end_tag('div');
1426 return $content;
1430 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1432 protected function coursecat_include_js() {
1433 global $CFG;
1434 static $jsloaded = false;
1435 if (!$jsloaded && $CFG->enableajax) {
1436 // We must only load this module once.
1437 $this->page->requires->yui_module('moodle-course-categoryexpander',
1438 'Y.Moodle.course.categoryexpander.init');
1439 $jsloaded = true;
1444 * Returns HTML to display the subcategories and courses in the given category
1446 * This method is re-used by AJAX to expand content of not loaded category
1448 * @param coursecat_helper $chelper various display options
1449 * @param coursecat $coursecat
1450 * @param int $depth depth of the category in the current tree
1451 * @return string
1453 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1454 $content = '';
1455 // Subcategories
1456 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1458 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1459 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1460 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1461 if ($showcoursesauto && $depth) {
1462 // this is definitely collapsed mode
1463 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1466 // Courses
1467 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1468 $courses = array();
1469 if (!$chelper->get_courses_display_option('nodisplay')) {
1470 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1472 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1473 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1474 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1475 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1478 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1481 if ($showcoursesauto) {
1482 // restore the show_courses back to AUTO
1483 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1486 return $content;
1490 * Returns HTML to display a course category as a part of a tree
1492 * This is an internal function, to display a particular category and all its contents
1493 * use {@link core_course_renderer::course_category()}
1495 * @param coursecat_helper $chelper various display options
1496 * @param coursecat $coursecat
1497 * @param int $depth depth of this category in the current tree
1498 * @return string
1500 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1501 // open category tag
1502 $classes = array('category');
1503 if (empty($coursecat->visible)) {
1504 $classes[] = 'dimmed_category';
1506 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1507 // do not load content
1508 $categorycontent = '';
1509 $classes[] = 'notloaded';
1510 if ($coursecat->get_children_count() ||
1511 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1512 $classes[] = 'with_children';
1513 $classes[] = 'collapsed';
1515 // Make sure JS file to expand category content is included.
1516 $this->coursecat_include_js();
1517 } else {
1518 // load category content
1519 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1520 $classes[] = 'loaded';
1521 if (!empty($categorycontent)) {
1522 $classes[] = 'with_children';
1525 $content = html_writer::start_tag('div', array(
1526 'class' => join(' ', $classes),
1527 'data-categoryid' => $coursecat->id,
1528 'data-depth' => $depth,
1529 'data-showcourses' => $chelper->get_show_courses(),
1530 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1533 // category name
1534 $categoryname = $coursecat->get_formatted_name();
1535 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1536 array('categoryid' => $coursecat->id)),
1537 $categoryname);
1538 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1539 && ($coursescount = $coursecat->get_courses_count())) {
1540 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1541 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1543 $content .= html_writer::start_tag('div', array('class' => 'info'));
1545 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname'));
1546 $content .= html_writer::end_tag('div'); // .info
1548 // add category content to the output
1549 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1551 $content .= html_writer::end_tag('div'); // .category
1553 // Return the course category tree HTML
1554 return $content;
1558 * Returns HTML to display a tree of subcategories and courses in the given category
1560 * @param coursecat_helper $chelper various display options
1561 * @param coursecat $coursecat top category (this category's name and description will NOT be added to the tree)
1562 * @return string
1564 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1565 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1566 if (empty($categorycontent)) {
1567 return '';
1570 // Start content generation
1571 $content = '';
1572 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1573 $content .= html_writer::start_tag('div', $attributes);
1575 if ($coursecat->get_children_count()) {
1576 $classes = array(
1577 'collapseexpand',
1578 'collapse-all',
1580 if ($chelper->get_subcat_depth() == 1) {
1581 $classes[] = 'disabled';
1583 // Only show the collapse/expand if there are children to expand.
1584 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1585 $content .= html_writer::link('#', get_string('collapseall'),
1586 array('class' => implode(' ', $classes)));
1587 $content .= html_writer::end_tag('div');
1588 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1591 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1593 $content .= html_writer::end_tag('div'); // .course_category_tree
1595 return $content;
1599 * Renders HTML to display particular course category - list of it's subcategories and courses
1601 * Invoked from /course/index.php
1603 * @param int|stdClass|coursecat $category
1605 public function course_category($category) {
1606 global $CFG;
1607 require_once($CFG->libdir. '/coursecatlib.php');
1608 $coursecat = coursecat::get(is_object($category) ? $category->id : $category);
1609 $site = get_site();
1610 $output = '';
1612 $this->page->set_button($this->course_search_form('', 'navbar'));
1613 if (!$coursecat->id) {
1614 if (can_edit_in_category()) {
1615 // add 'Manage' button instead of course search form
1616 $managebutton = $this->single_button(new moodle_url('/course/manage.php'),
1617 get_string('managecourses'), 'get');
1618 $this->page->set_button($managebutton);
1620 if (coursecat::count_all() == 1) {
1621 // There exists only one category in the system, do not display link to it
1622 $coursecat = coursecat::get_default();
1623 $strfulllistofcourses = get_string('fulllistofcourses');
1624 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1625 } else {
1626 $strcategories = get_string('categories');
1627 $this->page->set_title("$site->shortname: $strcategories");
1629 } else {
1630 $this->page->set_title("$site->shortname: ". $coursecat->get_formatted_name());
1632 // Print the category selector
1633 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1634 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1635 coursecat::make_categories_list(), $coursecat->id, null, 'switchcategory');
1636 $select->set_label(get_string('categories').':');
1637 $output .= $this->render($select);
1638 $output .= html_writer::end_tag('div'); // .categorypicker
1641 // Print current category description
1642 $chelper = new coursecat_helper();
1643 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1644 $output .= $this->box($description, array('class' => 'generalbox info'));
1647 // Prepare parameters for courses and categories lists in the tree
1648 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1649 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1651 $coursedisplayoptions = array();
1652 $catdisplayoptions = array();
1653 $browse = optional_param('browse', null, PARAM_ALPHA);
1654 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1655 $page = optional_param('page', 0, PARAM_INT);
1656 $baseurl = new moodle_url('/course/index.php');
1657 if ($coursecat->id) {
1658 $baseurl->param('categoryid', $coursecat->id);
1660 if ($perpage != $CFG->coursesperpage) {
1661 $baseurl->param('perpage', $perpage);
1663 $coursedisplayoptions['limit'] = $perpage;
1664 $catdisplayoptions['limit'] = $perpage;
1665 if ($browse === 'courses' || !$coursecat->has_children()) {
1666 $coursedisplayoptions['offset'] = $page * $perpage;
1667 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1668 $catdisplayoptions['nodisplay'] = true;
1669 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1670 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1671 } else if ($browse === 'categories' || !$coursecat->has_courses()) {
1672 $coursedisplayoptions['nodisplay'] = true;
1673 $catdisplayoptions['offset'] = $page * $perpage;
1674 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1675 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1676 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1677 } else {
1678 // we have a category that has both subcategories and courses, display pagination separately
1679 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1680 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1682 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1684 // Display course category tree
1685 $output .= $this->coursecat_tree($chelper, $coursecat);
1687 // Add course search form (if we are inside category it was already added to the navbar)
1688 if (!$coursecat->id) {
1689 $output .= $this->course_search_form();
1692 // Add action buttons
1693 $output .= $this->container_start('buttons');
1694 $context = get_category_or_system_context($coursecat->id);
1695 if (has_capability('moodle/course:create', $context)) {
1696 // Print link to create a new course, for the 1st available category.
1697 if ($coursecat->id) {
1698 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1699 } else {
1700 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1702 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1704 ob_start();
1705 if (coursecat::count_all() == 1) {
1706 print_course_request_buttons(context_system::instance());
1707 } else {
1708 print_course_request_buttons($context);
1710 $output .= ob_get_contents();
1711 ob_end_clean();
1712 $output .= $this->container_end();
1714 return $output;
1718 * Serves requests to /course/category.ajax.php
1720 * In this renderer implementation it may expand the category content or
1721 * course content.
1723 * @return string
1724 * @throws coding_exception
1726 public function coursecat_ajax() {
1727 global $DB, $CFG;
1728 require_once($CFG->libdir. '/coursecatlib.php');
1730 $type = required_param('type', PARAM_INT);
1732 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1733 // This is a request for a category list of some kind.
1734 $categoryid = required_param('categoryid', PARAM_INT);
1735 $showcourses = required_param('showcourses', PARAM_INT);
1736 $depth = required_param('depth', PARAM_INT);
1738 $category = coursecat::get($categoryid);
1740 $chelper = new coursecat_helper();
1741 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1742 $coursedisplayoptions = array(
1743 'limit' => $CFG->coursesperpage,
1744 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1746 $catdisplayoptions = array(
1747 'limit' => $CFG->coursesperpage,
1748 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1750 $chelper->set_show_courses($showcourses)->
1751 set_courses_display_options($coursedisplayoptions)->
1752 set_categories_display_options($catdisplayoptions);
1754 return $this->coursecat_category_content($chelper, $category, $depth);
1755 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1756 // This is a request for the course information.
1757 $courseid = required_param('courseid', PARAM_INT);
1759 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1761 $chelper = new coursecat_helper();
1762 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1763 return $this->coursecat_coursebox_content($chelper, $course);
1764 } else {
1765 throw new coding_exception('Invalid request type');
1770 * Renders html to display search result page
1772 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1773 * @return string
1775 public function search_courses($searchcriteria) {
1776 global $CFG;
1777 $content = '';
1778 if (!empty($searchcriteria)) {
1779 // print search results
1780 require_once($CFG->libdir. '/coursecatlib.php');
1782 $displayoptions = array('sort' => array('displayname' => 1));
1783 // take the current page and number of results per page from query
1784 $perpage = optional_param('perpage', 0, PARAM_RAW);
1785 if ($perpage !== 'all') {
1786 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1787 $page = optional_param('page', 0, PARAM_INT);
1788 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1790 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1791 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1792 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1794 $class = 'course-search-result';
1795 foreach ($searchcriteria as $key => $value) {
1796 if (!empty($value)) {
1797 $class .= ' course-search-result-'. $key;
1800 $chelper = new coursecat_helper();
1801 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1802 set_courses_display_options($displayoptions)->
1803 set_search_criteria($searchcriteria)->
1804 set_attributes(array('class' => $class));
1806 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1807 $totalcount = coursecat::search_courses_count($searchcriteria);
1808 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1810 if (!$totalcount) {
1811 if (!empty($searchcriteria['search'])) {
1812 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1813 } else {
1814 $content .= $this->heading(get_string('novalidcourses'));
1816 } else {
1817 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1818 $content .= $courseslist;
1821 if (!empty($searchcriteria['search'])) {
1822 // print search form only if there was a search by search string, otherwise it is confusing
1823 $content .= $this->box_start('generalbox mdl-align');
1824 $content .= $this->course_search_form($searchcriteria['search']);
1825 $content .= $this->box_end();
1827 } else {
1828 // just print search form
1829 $content .= $this->box_start('generalbox mdl-align');
1830 $content .= $this->course_search_form();
1831 $content .= html_writer::tag('div', get_string("searchhelp"), array('class' => 'searchhelp'));
1832 $content .= $this->box_end();
1834 return $content;
1838 * Renders html to print list of courses tagged with particular tag
1840 * @param int $tagid id of the tag
1841 * @return string empty string if no courses are marked with this tag or rendered list of courses
1843 public function tagged_courses($tagid) {
1844 global $CFG;
1845 require_once($CFG->libdir. '/coursecatlib.php');
1846 $displayoptions = array('limit' => $CFG->coursesperpage);
1847 $displayoptions['viewmoreurl'] = new moodle_url('/course/search.php',
1848 array('tagid' => $tagid, 'page' => 1, 'perpage' => $CFG->coursesperpage));
1849 $displayoptions['viewmoretext'] = new lang_string('findmorecourses');
1850 $chelper = new coursecat_helper();
1851 $searchcriteria = array('tagid' => $tagid);
1852 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1853 set_search_criteria(array('tagid' => $tagid))->
1854 set_courses_display_options($displayoptions)->
1855 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1856 // (we set the same css class as in search results by tagid)
1857 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1858 $totalcount = coursecat::search_courses_count($searchcriteria);
1859 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1860 if ($totalcount) {
1861 require_once $CFG->dirroot.'/tag/lib.php';
1862 $heading = get_string('courses') . ' ' . get_string('taggedwith', 'tag', tag_get_name($tagid)) .': '. $totalcount;
1863 return $this->heading($heading, 3). $content;
1865 return '';
1869 * Returns HTML to display one remote course
1871 * @param stdClass $course remote course information, contains properties:
1872 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1873 * @return string
1875 protected function frontpage_remote_course(stdClass $course) {
1876 $url = new moodle_url('/auth/mnet/jump.php', array(
1877 'hostid' => $course->hostid,
1878 'wantsurl' => '/course/view.php?id='. $course->remoteid
1881 $output = '';
1882 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1883 $output .= html_writer::start_tag('div', array('class' => 'info'));
1884 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1885 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1886 $output .= html_writer::end_tag('h3'); // .name
1887 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1888 $output .= html_writer::end_tag('div'); // .info
1889 $output .= html_writer::start_tag('div', array('class' => 'content'));
1890 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1891 $options = new stdClass();
1892 $options->noclean = true;
1893 $options->para = false;
1894 $options->overflowdiv = true;
1895 $output .= format_text($course->summary, $course->summaryformat, $options);
1896 $output .= html_writer::end_tag('div'); // .summary
1897 $addinfo = format_string($course->hostname) . ' : '
1898 . format_string($course->cat_name) . ' : '
1899 . format_string($course->shortname);
1900 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1901 $output .= html_writer::end_tag('div'); // .content
1902 $output .= html_writer::end_tag('div'); // .coursebox
1903 return $output;
1907 * Returns HTML to display one remote host
1909 * @param array $host host information, contains properties: name, url, count
1910 * @return string
1912 protected function frontpage_remote_host($host) {
1913 $output = '';
1914 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1915 $output .= html_writer::start_tag('div', array('class' => 'info'));
1916 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1917 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1918 $output .= html_writer::end_tag('h3'); // .name
1919 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1920 $output .= html_writer::end_tag('div'); // .info
1921 $output .= html_writer::start_tag('div', array('class' => 'content'));
1922 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1923 $output .= $host['count'] . ' ' . get_string('courses');
1924 $output .= html_writer::end_tag('div'); // .content
1925 $output .= html_writer::end_tag('div'); // .coursebox
1926 return $output;
1930 * Returns HTML to print list of courses user is enrolled to for the frontpage
1932 * Also lists remote courses or remote hosts if MNET authorisation is used
1934 * @return string
1936 public function frontpage_my_courses() {
1937 global $USER, $CFG, $DB;
1939 if (!isloggedin() or isguestuser()) {
1940 return '';
1943 $output = '';
1944 if (!empty($CFG->navsortmycoursessort)) {
1945 // sort courses the same as in navigation menu
1946 $sortorder = 'visible DESC,'. $CFG->navsortmycoursessort.' ASC';
1947 } else {
1948 $sortorder = 'visible DESC,sortorder ASC';
1950 $courses = enrol_get_my_courses('summary, summaryformat', $sortorder);
1951 $rhosts = array();
1952 $rcourses = array();
1953 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1954 $rcourses = get_my_remotecourses($USER->id);
1955 $rhosts = get_my_remotehosts();
1958 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1960 $chelper = new coursecat_helper();
1961 if (count($courses) > $CFG->frontpagecourselimit) {
1962 // There are more enrolled courses than we can display, display link to 'My courses'.
1963 $totalcount = count($courses);
1964 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
1965 $chelper->set_courses_display_options(array(
1966 'viewmoreurl' => new moodle_url('/my/'),
1967 'viewmoretext' => new lang_string('mycourses')
1969 } else {
1970 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
1971 $chelper->set_courses_display_options(array(
1972 'viewmoreurl' => new moodle_url('/course/index.php'),
1973 'viewmoretext' => new lang_string('fulllistofcourses')
1975 $totalcount = $DB->count_records('course') - 1;
1977 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
1978 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
1979 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
1981 // MNET
1982 if (!empty($rcourses)) {
1983 // at the IDP, we know of all the remote courses
1984 $output .= html_writer::start_tag('div', array('class' => 'courses'));
1985 foreach ($rcourses as $course) {
1986 $output .= $this->frontpage_remote_course($course);
1988 $output .= html_writer::end_tag('div'); // .courses
1989 } elseif (!empty($rhosts)) {
1990 // non-IDP, we know of all the remote servers, but not courses
1991 $output .= html_writer::start_tag('div', array('class' => 'courses'));
1992 foreach ($rhosts as $host) {
1993 $output .= $this->frontpage_remote_host($host);
1995 $output .= html_writer::end_tag('div'); // .courses
1998 return $output;
2002 * Returns HTML to print list of available courses for the frontpage
2004 * @return string
2006 public function frontpage_available_courses() {
2007 global $CFG;
2008 require_once($CFG->libdir. '/coursecatlib.php');
2010 $chelper = new coursecat_helper();
2011 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2012 set_courses_display_options(array(
2013 'recursive' => true,
2014 'limit' => $CFG->frontpagecourselimit,
2015 'viewmoreurl' => new moodle_url('/course/index.php'),
2016 'viewmoretext' => new lang_string('fulllistofcourses')));
2018 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
2019 $courses = coursecat::get(0)->get_courses($chelper->get_courses_display_options());
2020 $totalcount = coursecat::get(0)->get_courses_count($chelper->get_courses_display_options());
2021 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
2022 // Print link to create a new course, for the 1st available category.
2023 return $this->add_new_course_button();
2025 return $this->coursecat_courses($chelper, $courses, $totalcount);
2029 * Returns HTML to the "add new course" button for the page
2031 * @return string
2033 public function add_new_course_button() {
2034 global $CFG;
2035 // Print link to create a new course, for the 1st available category.
2036 $output = $this->container_start('buttons');
2037 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2038 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2039 $output .= $this->container_end('buttons');
2040 return $output;
2044 * Returns HTML to print tree with course categories and courses for the frontpage
2046 * @return string
2048 public function frontpage_combo_list() {
2049 global $CFG;
2050 require_once($CFG->libdir. '/coursecatlib.php');
2051 $chelper = new coursecat_helper();
2052 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2053 set_categories_display_options(array(
2054 'limit' => $CFG->coursesperpage,
2055 'viewmoreurl' => new moodle_url('/course/index.php',
2056 array('browse' => 'categories', 'page' => 1))
2057 ))->
2058 set_courses_display_options(array(
2059 'limit' => $CFG->coursesperpage,
2060 'viewmoreurl' => new moodle_url('/course/index.php',
2061 array('browse' => 'courses', 'page' => 1))
2062 ))->
2063 set_attributes(array('class' => 'frontpage-category-combo'));
2064 return $this->coursecat_tree($chelper, coursecat::get(0));
2068 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2070 * @return string
2072 public function frontpage_categories_list() {
2073 global $CFG;
2074 require_once($CFG->libdir. '/coursecatlib.php');
2075 $chelper = new coursecat_helper();
2076 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2077 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2078 set_categories_display_options(array(
2079 'limit' => $CFG->coursesperpage,
2080 'viewmoreurl' => new moodle_url('/course/index.php',
2081 array('browse' => 'categories', 'page' => 1))
2082 ))->
2083 set_attributes(array('class' => 'frontpage-category-names'));
2084 return $this->coursecat_tree($chelper, coursecat::get(0));
2089 * Class storing display options and functions to help display course category and/or courses lists
2091 * This is a wrapper for coursecat objects that also stores display options
2092 * and functions to retrieve sorted and paginated lists of categories/courses.
2094 * If theme overrides methods in core_course_renderers that access this class
2095 * it may as well not use this class at all or extend it.
2097 * @package core
2098 * @copyright 2013 Marina Glancy
2099 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2101 class coursecat_helper {
2102 /** @var string [none, collapsed, expanded] how (if) display courses list */
2103 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2104 /** @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) */
2105 protected $subcatdepth = 1;
2106 /** @var array options to display courses list */
2107 protected $coursesdisplayoptions = array();
2108 /** @var array options to display subcategories list */
2109 protected $categoriesdisplayoptions = array();
2110 /** @var array additional HTML attributes */
2111 protected $attributes = array();
2112 /** @var array search criteria if the list is a search result */
2113 protected $searchcriteria = null;
2116 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2118 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2119 * @return coursecat_helper
2121 public function set_show_courses($showcourses) {
2122 $this->showcourses = $showcourses;
2123 // Automatically set the options to preload summary and coursecontacts for coursecat::get_courses() and coursecat::search_courses()
2124 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2125 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2126 return $this;
2130 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2132 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2134 public function get_show_courses() {
2135 return $this->showcourses;
2139 * Sets the maximum depth to expand subcategories in the tree
2141 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2143 * @param int $subcatdepth
2144 * @return coursecat_helper
2146 public function set_subcat_depth($subcatdepth) {
2147 $this->subcatdepth = $subcatdepth;
2148 return $this;
2152 * Returns the maximum depth to expand subcategories in the tree
2154 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2156 * @return int
2158 public function get_subcat_depth() {
2159 return $this->subcatdepth;
2163 * Sets options to display list of courses
2165 * Options are later submitted as argument to coursecat::get_courses() and/or coursecat::search_courses()
2167 * Options that coursecat::get_courses() accept:
2168 * - recursive - return courses from subcategories as well. Use with care,
2169 * this may be a huge list!
2170 * - summary - preloads fields 'summary' and 'summaryformat'
2171 * - coursecontacts - preloads course contacts
2172 * - isenrolled - preloads indication whether this user is enrolled in the course
2173 * - sort - list of fields to sort. Example
2174 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2175 * will sort by idnumber asc, shortname asc and id desc.
2176 * Default: array('sortorder' => 1)
2177 * Only cached fields may be used for sorting!
2178 * - offset
2179 * - limit - maximum number of children to return, 0 or null for no limit
2181 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2183 * Also renderer can set here any additional options it wants to pass between renderer functions.
2185 * @param array $options
2186 * @return coursecat_helper
2188 public function set_courses_display_options($options) {
2189 $this->coursesdisplayoptions = $options;
2190 $this->set_show_courses($this->showcourses); // this will calculate special display options
2191 return $this;
2195 * Sets one option to display list of courses
2197 * @see coursecat_helper::set_courses_display_options()
2199 * @param string $key
2200 * @param mixed $value
2201 * @return coursecat_helper
2203 public function set_courses_display_option($key, $value) {
2204 $this->coursesdisplayoptions[$key] = $value;
2205 return $this;
2209 * Return the specified option to display list of courses
2211 * @param string $optionname option name
2212 * @param mixed $defaultvalue default value for option if it is not specified
2213 * @return mixed
2215 public function get_courses_display_option($optionname, $defaultvalue = null) {
2216 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2217 return $this->coursesdisplayoptions[$optionname];
2218 } else {
2219 return $defaultvalue;
2224 * Returns all options to display the courses
2226 * This array is usually passed to {@link coursecat::get_courses()} or
2227 * {@link coursecat::search_courses()}
2229 * @return array
2231 public function get_courses_display_options() {
2232 return $this->coursesdisplayoptions;
2236 * Sets options to display list of subcategories
2238 * Options 'sort', 'offset' and 'limit' are passed to coursecat::get_children().
2239 * Any other options may be used by renderer functions
2241 * @param array $options
2242 * @return coursecat_helper
2244 public function set_categories_display_options($options) {
2245 $this->categoriesdisplayoptions = $options;
2246 return $this;
2250 * Return the specified option to display list of subcategories
2252 * @param string $optionname option name
2253 * @param mixed $defaultvalue default value for option if it is not specified
2254 * @return mixed
2256 public function get_categories_display_option($optionname, $defaultvalue = null) {
2257 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2258 return $this->categoriesdisplayoptions[$optionname];
2259 } else {
2260 return $defaultvalue;
2265 * Returns all options to display list of subcategories
2267 * This array is usually passed to {@link coursecat::get_children()}
2269 * @return array
2271 public function get_categories_display_options() {
2272 return $this->categoriesdisplayoptions;
2276 * Sets additional general options to pass between renderer functions, usually HTML attributes
2278 * @param array $attributes
2279 * @return coursecat_helper
2281 public function set_attributes($attributes) {
2282 $this->attributes = $attributes;
2283 return $this;
2287 * Return all attributes and erases them so they are not applied again
2289 * @param string $classname adds additional class name to the beginning of $attributes['class']
2290 * @return array
2292 public function get_and_erase_attributes($classname) {
2293 $attributes = $this->attributes;
2294 $this->attributes = array();
2295 if (empty($attributes['class'])) {
2296 $attributes['class'] = '';
2298 $attributes['class'] = $classname . ' '. $attributes['class'];
2299 return $attributes;
2303 * Sets the search criteria if the course is a search result
2305 * Search string will be used to highlight terms in course name and description
2307 * @param array $searchcriteria
2308 * @return coursecat_helper
2310 public function set_search_criteria($searchcriteria) {
2311 $this->searchcriteria = $searchcriteria;
2312 return $this;
2316 * Returns formatted and filtered description of the given category
2318 * @param coursecat $coursecat category
2319 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2320 * if context is not specified it will be added automatically
2321 * @return string|null
2323 public function get_category_formatted_description($coursecat, $options = null) {
2324 if ($coursecat->id && !empty($coursecat->description)) {
2325 if (!isset($coursecat->descriptionformat)) {
2326 $descriptionformat = FORMAT_MOODLE;
2327 } else {
2328 $descriptionformat = $coursecat->descriptionformat;
2330 if ($options === null) {
2331 $options = array('noclean' => true, 'overflowdiv' => true);
2332 } else {
2333 $options = (array)$options;
2335 $context = context_coursecat::instance($coursecat->id);
2336 if (!isset($options['context'])) {
2337 $options['context'] = $context;
2339 $text = file_rewrite_pluginfile_urls($coursecat->description,
2340 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2341 return format_text($text, $descriptionformat, $options);
2343 return null;
2347 * Returns given course's summary with proper embedded files urls and formatted
2349 * @param course_in_list $course
2350 * @param array|stdClass $options additional formatting options
2351 * @return string
2353 public function get_course_formatted_summary($course, $options = array()) {
2354 global $CFG;
2355 require_once($CFG->libdir. '/filelib.php');
2356 if (!$course->has_summary()) {
2357 return '';
2359 $options = (array)$options;
2360 $context = context_course::instance($course->id);
2361 if (!isset($options['context'])) {
2362 // TODO see MDL-38521
2363 // option 1 (current), page context - no code required
2364 // option 2, system context
2365 // $options['context'] = context_system::instance();
2366 // option 3, course context:
2367 // $options['context'] = $context;
2368 // option 4, course category context:
2369 // $options['context'] = $context->get_parent_context();
2371 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2372 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2373 if (!empty($this->searchcriteria['search'])) {
2374 $summary = highlight($this->searchcriteria['search'], $summary);
2376 return $summary;
2380 * Returns course name as it is configured to appear in courses lists formatted to course context
2382 * @param course_in_list $course
2383 * @param array|stdClass $options additional formatting options
2384 * @return string
2386 public function get_course_formatted_name($course, $options = array()) {
2387 $options = (array)$options;
2388 if (!isset($options['context'])) {
2389 $options['context'] = context_course::instance($course->id);
2391 $name = format_string(get_course_display_name_for_list($course), true, $options);
2392 if (!empty($this->searchcriteria['search'])) {
2393 $name = highlight($this->searchcriteria['search'], $name);
2395 return $name;