MDL-58188 mod_assign: added missing require_once and updated docs
[moodle.git] / course / renderer.php
blobbee3fe78f70105320666649e6a68dbcd0978932e
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);
63 /**
64 * Adds the item in course settings navigation to toggle modchooser
66 * Theme can overwrite as an empty function to exclude it (for example if theme does not
67 * use modchooser at all)
69 * @deprecated since 3.2
71 protected function add_modchoosertoggle() {
72 debugging('core_course_renderer::add_modchoosertoggle() is deprecated.', DEBUG_DEVELOPER);
74 global $CFG;
76 // Only needs to be done once per page.
77 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchoosertoggle')) {
78 return;
81 if ($this->page->state > moodle_page::STATE_PRINTING_HEADER ||
82 $this->page->course->id == SITEID ||
83 !$this->page->user_is_editing() ||
84 !($context = context_course::instance($this->page->course->id)) ||
85 !has_capability('moodle/course:manageactivities', $context) ||
86 !course_ajax_enabled($this->page->course) ||
87 !($coursenode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE)) ||
88 !($turneditingnode = $coursenode->get('turneditingonoff'))) {
89 // Too late, or we are on site page, or we could not find the
90 // adjacent nodes in course settings menu, or we are not allowed to edit.
91 return;
94 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
95 // We are on the course page, retain the current page params e.g. section.
96 $modchoosertoggleurl = clone($this->page->url);
97 } else {
98 // Edit on the main course page.
99 $modchoosertoggleurl = new moodle_url('/course/view.php', array('id' => $this->page->course->id,
100 'return' => $this->page->url->out_as_local_url(false)));
102 $modchoosertoggleurl->param('sesskey', sesskey());
103 if ($usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault)) {
104 $modchoosertogglestring = get_string('modchooserdisable', 'moodle');
105 $modchoosertoggleurl->param('modchooser', 'off');
106 } else {
107 $modchoosertogglestring = get_string('modchooserenable', 'moodle');
108 $modchoosertoggleurl->param('modchooser', 'on');
110 $modchoosertoggle = navigation_node::create($modchoosertogglestring, $modchoosertoggleurl, navigation_node::TYPE_SETTING, null, 'modchoosertoggle');
112 // Insert the modchoosertoggle after the settings node 'turneditingonoff' (navigation_node only has function to insert before, so we insert before and then swap).
113 $coursenode->add_node($modchoosertoggle, 'turneditingonoff');
114 $turneditingnode->remove();
115 $coursenode->add_node($turneditingnode, 'modchoosertoggle');
117 $modchoosertoggle->add_class('modchoosertoggle');
118 $modchoosertoggle->add_class('visibleifjs');
119 user_preference_allow_ajax_update('usemodchooser', PARAM_BOOL);
123 * Renders course info box.
125 * @param stdClass|course_in_list $course
126 * @return string
128 public function course_info_box(stdClass $course) {
129 $content = '';
130 $content .= $this->output->box_start('generalbox info');
131 $chelper = new coursecat_helper();
132 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
133 $content .= $this->coursecat_coursebox($chelper, $course);
134 $content .= $this->output->box_end();
135 return $content;
139 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
141 * @deprecated since 2.5
143 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
145 * @param array $ignored argument ignored
146 * @return string
148 public final function course_category_tree(array $ignored) {
149 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
150 return $this->frontpage_combo_list();
154 * Renderers a category for use with course_category_tree
156 * @deprecated since 2.5
158 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
160 * @param array $category
161 * @param int $depth
162 * @return string
164 protected final function course_category_tree_category(stdClass $category, $depth=1) {
165 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
166 return '';
170 * Render a modchooser.
172 * @param renderable $modchooser The chooser.
173 * @return string
175 public function render_modchooser(renderable $modchooser) {
176 return $this->render_from_template('core_course/modchooser', $modchooser->export_for_template($this));
180 * Build the HTML for the module chooser javascript popup
182 * @param array $modules A set of modules as returned form @see
183 * get_module_metadata
184 * @param object $course The course that will be displayed
185 * @return string The composed HTML for the module
187 public function course_modchooser($modules, $course) {
188 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchooser')) {
189 return '';
191 $modchooser = new \core_course\output\modchooser($course, $modules);
192 return $this->render($modchooser);
196 * Build the HTML for a specified set of modules
198 * @param array $modules A set of modules as used by the
199 * course_modchooser_module function
200 * @return string The composed HTML for the module
202 protected function course_modchooser_module_types($modules) {
203 debugging('Method core_course_renderer::course_modchooser_module_types() is deprecated, ' .
204 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
205 return '';
209 * Return the HTML for the specified module adding any required classes
211 * @param object $module An object containing the title, and link. An
212 * icon, and help text may optionally be specified. If the module
213 * contains subtypes in the types option, then these will also be
214 * displayed.
215 * @param array $classes Additional classes to add to the encompassing
216 * div element
217 * @return string The composed HTML for the module
219 protected function course_modchooser_module($module, $classes = array('option')) {
220 debugging('Method core_course_renderer::course_modchooser_module() is deprecated, ' .
221 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
222 return '';
225 protected function course_modchooser_title($title, $identifier = null) {
226 debugging('Method core_course_renderer::course_modchooser_title() is deprecated, ' .
227 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
228 return '';
232 * Renders HTML for displaying the sequence of course module editing buttons
234 * @see course_get_cm_edit_actions()
236 * @param action_link[] $actions Array of action_link objects
237 * @param cm_info $mod The module we are displaying actions for.
238 * @param array $displayoptions additional display options:
239 * ownerselector => A JS/CSS selector that can be used to find an cm node.
240 * If specified the owning node will be given the class 'action-menu-shown' when the action
241 * menu is being displayed.
242 * constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
243 * the action menu to when it is being displayed.
244 * donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
245 * @return string
247 public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
248 global $CFG;
250 if (empty($actions)) {
251 return '';
254 if (isset($displayoptions['ownerselector'])) {
255 $ownerselector = $displayoptions['ownerselector'];
256 } else if ($mod) {
257 $ownerselector = '#module-'.$mod->id;
258 } else {
259 debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
260 $ownerselector = 'li.activity';
263 if (isset($displayoptions['constraintselector'])) {
264 $constraint = $displayoptions['constraintselector'];
265 } else {
266 $constraint = '.course-content';
269 $menu = new action_menu();
270 $menu->set_owner_selector($ownerselector);
271 $menu->set_constraint($constraint);
272 $menu->set_alignment(action_menu::TR, action_menu::BR);
273 $menu->set_menu_trigger(get_string('edit'));
275 foreach ($actions as $action) {
276 if ($action instanceof action_menu_link) {
277 $action->add_class('cm-edit-action');
279 $menu->add($action);
281 $menu->attributes['class'] .= ' section-cm-edit-actions commands';
283 // Prioritise the menu ahead of all other actions.
284 $menu->prioritise = true;
286 return $this->render($menu);
290 * Renders HTML for the menus to add activities and resources to the current course
292 * @param stdClass $course
293 * @param int $section relative section number (field course_sections.section)
294 * @param int $sectionreturn The section to link back to
295 * @param array $displayoptions additional display options, for example blocks add
296 * option 'inblock' => true, suggesting to display controls vertically
297 * @return string
299 function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
300 global $CFG;
302 $vertical = !empty($displayoptions['inblock']);
304 // check to see if user can add menus and there are modules to add
305 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
306 || !$this->page->user_is_editing()
307 || !($modnames = get_module_types_names()) || empty($modnames)) {
308 return '';
311 // Retrieve all modules with associated metadata
312 $modules = get_module_metadata($course, $modnames, $sectionreturn);
313 $urlparams = array('section' => $section);
315 // We'll sort resources and activities into two lists
316 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
318 foreach ($modules as $module) {
319 $activityclass = MOD_CLASS_ACTIVITY;
320 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
321 $activityclass = MOD_CLASS_RESOURCE;
322 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
323 // System modules cannot be added by user, do not add to dropdown.
324 continue;
326 $link = $module->link->out(true, $urlparams);
327 $activities[$activityclass][$link] = $module->title;
330 $straddactivity = get_string('addactivity');
331 $straddresource = get_string('addresource');
332 $sectionname = get_section_name($course, $section);
333 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
334 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
336 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
338 if (!$vertical) {
339 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
342 if (!empty($activities[MOD_CLASS_RESOURCE])) {
343 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array(''=>$straddresource), "ressection$section");
344 $select->set_help_icon('resources');
345 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
346 $output .= $this->output->render($select);
349 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
350 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array(''=>$straddactivity), "section$section");
351 $select->set_help_icon('activities');
352 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
353 $output .= $this->output->render($select);
356 if (!$vertical) {
357 $output .= html_writer::end_tag('div');
360 $output .= html_writer::end_tag('div');
362 if (course_ajax_enabled($course) && $course->id == $this->page->course->id) {
363 // modchooser can be added only for the current course set on the page!
364 $straddeither = get_string('addresourceoractivity');
365 // The module chooser link
366 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
367 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
368 $icon = $this->output->pix_icon('t/add', '');
369 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
370 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
371 $modchooser.= html_writer::end_tag('div');
372 $modchooser.= html_writer::end_tag('div');
374 // Wrap the normal output in a noscript div
375 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
376 if ($usemodchooser) {
377 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
378 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
379 } else {
380 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
381 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
382 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
384 $output = $this->course_modchooser($modules, $course) . $modchooser . $output;
387 return $output;
391 * Renders html to display a course search form
393 * @param string $value default value to populate the search field
394 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
395 * @return string
397 function course_search_form($value = '', $format = 'plain') {
398 static $count = 0;
399 $formid = 'coursesearch';
400 if ((++$count) > 1) {
401 $formid .= $count;
404 switch ($format) {
405 case 'navbar' :
406 $formid = 'coursesearchnavbar';
407 $inputid = 'navsearchbox';
408 $inputsize = 20;
409 break;
410 case 'short' :
411 $inputid = 'shortsearchbox';
412 $inputsize = 12;
413 break;
414 default :
415 $inputid = 'coursesearchbox';
416 $inputsize = 30;
419 $strsearchcourses= get_string("searchcourses");
420 $searchurl = new moodle_url('/course/search.php');
422 $output = html_writer::start_tag('form', array('id' => $formid, 'action' => $searchurl, 'method' => 'get'));
423 $output .= html_writer::start_tag('fieldset', array('class' => 'coursesearchbox invisiblefieldset'));
424 $output .= html_writer::tag('label', $strsearchcourses.': ', array('for' => $inputid));
425 $output .= html_writer::empty_tag('input', array('type' => 'text', 'id' => $inputid,
426 'size' => $inputsize, 'name' => 'search', 'value' => s($value)));
427 $output .= html_writer::empty_tag('input', array('type' => 'submit',
428 'value' => get_string('go')));
429 $output .= html_writer::end_tag('fieldset');
430 $output .= html_writer::end_tag('form');
432 return $output;
436 * Renders html for completion box on course page
438 * If completion is disabled, returns empty string
439 * If completion is automatic, returns an icon of the current completion state
440 * If completion is manual, returns a form (with an icon inside) that allows user to
441 * toggle completion
443 * @param stdClass $course course object
444 * @param completion_info $completioninfo completion info for the course, it is recommended
445 * to fetch once for all modules in course/section for performance
446 * @param cm_info $mod module to show completion for
447 * @param array $displayoptions display options, not used in core
448 * @return string
450 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
451 global $CFG;
452 $output = '';
453 if (!$mod->is_visible_on_course_page()) {
454 return $output;
456 if ($completioninfo === null) {
457 $completioninfo = new completion_info($course);
459 $completion = $completioninfo->is_enabled($mod);
460 if ($completion == COMPLETION_TRACKING_NONE) {
461 if ($this->page->user_is_editing()) {
462 $output .= html_writer::span('&nbsp;', 'filler');
464 return $output;
467 $completiondata = $completioninfo->get_data($mod, true);
468 $completionicon = '';
470 if ($this->page->user_is_editing()) {
471 switch ($completion) {
472 case COMPLETION_TRACKING_MANUAL :
473 $completionicon = 'manual-enabled'; break;
474 case COMPLETION_TRACKING_AUTOMATIC :
475 $completionicon = 'auto-enabled'; break;
477 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
478 switch($completiondata->completionstate) {
479 case COMPLETION_INCOMPLETE:
480 $completionicon = 'manual-n'; break;
481 case COMPLETION_COMPLETE:
482 $completionicon = 'manual-y'; break;
484 } else { // Automatic
485 switch($completiondata->completionstate) {
486 case COMPLETION_INCOMPLETE:
487 $completionicon = 'auto-n'; break;
488 case COMPLETION_COMPLETE:
489 $completionicon = 'auto-y'; break;
490 case COMPLETION_COMPLETE_PASS:
491 $completionicon = 'auto-pass'; break;
492 case COMPLETION_COMPLETE_FAIL:
493 $completionicon = 'auto-fail'; break;
496 if ($completionicon) {
497 $formattedname = $mod->get_formatted_name();
498 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
500 if ($this->page->user_is_editing()) {
501 // When editing, the icon is just an image.
502 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
503 array('title' => $imgalt, 'class' => 'iconsmall'));
504 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
505 array('class' => 'autocompletion'));
506 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
507 $imgtitle = get_string('completion-title-' . $completionicon, 'completion', $formattedname);
508 $newstate =
509 $completiondata->completionstate == COMPLETION_COMPLETE
510 ? COMPLETION_INCOMPLETE
511 : COMPLETION_COMPLETE;
512 // In manual mode the icon is a toggle form...
514 // If this completion state is used by the
515 // conditional activities system, we need to turn
516 // off the JS.
517 $extraclass = '';
518 if (!empty($CFG->enableavailability) &&
519 core_availability\info::completion_value_used($course, $mod->id)) {
520 $extraclass = ' preventjs';
522 $output .= html_writer::start_tag('form', array('method' => 'post',
523 'action' => new moodle_url('/course/togglecompletion.php'),
524 'class' => 'togglecompletion'. $extraclass));
525 $output .= html_writer::start_tag('div');
526 $output .= html_writer::empty_tag('input', array(
527 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
528 $output .= html_writer::empty_tag('input', array(
529 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
530 $output .= html_writer::empty_tag('input', array(
531 'type' => 'hidden', 'name' => 'modulename', 'value' => $mod->name));
532 $output .= html_writer::empty_tag('input', array(
533 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
534 $output .= html_writer::tag('button',
535 $this->output->pix_icon('i/completion-' . $completionicon, $imgalt), array('class' => 'btn btn-link'));
536 $output .= html_writer::end_tag('div');
537 $output .= html_writer::end_tag('form');
538 } else {
539 // In auto mode, the icon is just an image.
540 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
541 array('title' => $imgalt));
542 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
543 array('class' => 'autocompletion'));
546 return $output;
550 * Checks if course module has any conditions that may make it unavailable for
551 * all or some of the students
553 * This function is internal and is only used to create CSS classes for the module name/text
555 * @param cm_info $mod
556 * @return bool
558 protected function is_cm_conditionally_hidden(cm_info $mod) {
559 global $CFG;
560 $conditionalhidden = false;
561 if (!empty($CFG->enableavailability)) {
562 $info = new \core_availability\info_module($mod);
563 $conditionalhidden = !$info->is_available_for_all();
565 return $conditionalhidden;
569 * Renders html to display a name with the link to the course module on a course page
571 * If module is unavailable for user but still needs to be displayed
572 * in the list, just the name is returned without a link
574 * Note, that for course modules that never have separate pages (i.e. labels)
575 * this function return an empty string
577 * @param cm_info $mod
578 * @param array $displayoptions
579 * @return string
581 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
582 if (!$mod->is_visible_on_course_page() || !$mod->url) {
583 // Nothing to be displayed to the user.
584 return '';
587 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
588 $groupinglabel = $mod->get_grouping_label($textclasses);
590 // Render element that allows to edit activity name inline. It calls {@link course_section_cm_name_title()}
591 // to get the display title of the activity.
592 $tmpl = new \core_course\output\course_module_name($mod, $this->page->user_is_editing(), $displayoptions);
593 return $this->output->render_from_template('core/inplace_editable', $tmpl->export_for_template($this->output)) .
594 $groupinglabel;
598 * Returns the CSS classes for the activity name/content
600 * For items which are hidden, unavailable or stealth but should be displayed
601 * to current user ($mod->is_visible_on_course_page()), we show those as dimmed.
602 * Students will also see as dimmed activities names that are not yet available
603 * but should still be displayed (without link) with availability info.
605 * @param cm_info $mod
606 * @return array array of two elements ($linkclasses, $textclasses)
608 protected function course_section_cm_classes(cm_info $mod) {
609 $linkclasses = '';
610 $textclasses = '';
611 if ($mod->uservisible) {
612 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
613 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
614 has_capability('moodle/course:viewhiddenactivities', $mod->context);
615 if ($accessiblebutdim) {
616 $linkclasses .= ' dimmed';
617 $textclasses .= ' dimmed_text';
618 if ($conditionalhidden) {
619 $linkclasses .= ' conditionalhidden';
620 $textclasses .= ' conditionalhidden';
623 if ($mod->is_stealth()) {
624 // Stealth activity is the one that is not visible on course page.
625 // It still may be displayed to the users who can manage it.
626 $linkclasses .= ' stealth';
627 $textclasses .= ' stealth';
629 } else {
630 $linkclasses .= ' dimmed';
631 $textclasses .= ' dimmed_text';
633 return array($linkclasses, $textclasses);
637 * Renders html to display a name with the link to the course module on a course page
639 * If module is unavailable for user but still needs to be displayed
640 * in the list, just the name is returned without a link
642 * Note, that for course modules that never have separate pages (i.e. labels)
643 * this function return an empty string
645 * @param cm_info $mod
646 * @param array $displayoptions
647 * @return string
649 public function course_section_cm_name_title(cm_info $mod, $displayoptions = array()) {
650 $output = '';
651 $url = $mod->url;
652 if (!$mod->is_visible_on_course_page() || !$url) {
653 // Nothing to be displayed to the user.
654 return $output;
657 //Accessibility: for files get description via icon, this is very ugly hack!
658 $instancename = $mod->get_formatted_name();
659 $altname = $mod->modfullname;
660 // Avoid unnecessary duplication: if e.g. a forum name already
661 // includes the word forum (or Forum, etc) then it is unhelpful
662 // to include that in the accessible description that is added.
663 if (false !== strpos(core_text::strtolower($instancename),
664 core_text::strtolower($altname))) {
665 $altname = '';
667 // File type after name, for alphabetic lists (screen reader).
668 if ($altname) {
669 $altname = get_accesshide(' '.$altname);
672 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
674 // Get on-click attribute value if specified and decode the onclick - it
675 // has already been encoded for display (puke).
676 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
678 // Display link itself.
679 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
680 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
681 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
682 if ($mod->uservisible) {
683 $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick));
684 } else {
685 // We may be displaying this just in order to show information
686 // about visibility, without the actual link ($mod->is_visible_on_course_page()).
687 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses));
689 return $output;
693 * Renders html to display the module content on the course page (i.e. text of the labels)
695 * @param cm_info $mod
696 * @param array $displayoptions
697 * @return string
699 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
700 $output = '';
701 if (!$mod->is_visible_on_course_page()) {
702 // nothing to be displayed to the user
703 return $output;
705 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
706 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
707 if ($mod->url && $mod->uservisible) {
708 if ($content) {
709 // If specified, display extra content after link.
710 $output = html_writer::tag('div', $content, array('class' =>
711 trim('contentafterlink ' . $textclasses)));
713 } else {
714 $groupinglabel = $mod->get_grouping_label($textclasses);
716 // No link, so display only content.
717 $output = html_writer::tag('div', $content . $groupinglabel,
718 array('class' => 'contentwithoutlink ' . $textclasses));
720 return $output;
724 * Displays availability info for a course section or course module
726 * @param string $text
727 * @param string $additionalclasses
728 * @return string
730 public function availability_info($text, $additionalclasses = '') {
731 $data = ['text' => $text, 'classes' => $additionalclasses];
732 return $this->render_from_template('core/availability_info', $data);
736 * Renders HTML to show course module availability information (for someone who isn't allowed
737 * to see the activity itself, or for staff)
739 * @param cm_info $mod
740 * @param array $displayoptions
741 * @return string
743 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
744 global $CFG;
745 $output = '';
746 if (!$mod->is_visible_on_course_page()) {
747 return $output;
749 if (!$mod->uservisible) {
750 // this is a student who is not allowed to see the module but might be allowed
751 // to see availability info (i.e. "Available from ...")
752 if (!empty($mod->availableinfo)) {
753 $formattedinfo = \core_availability\info::format_info(
754 $mod->availableinfo, $mod->get_course());
755 $output = $this->availability_info($formattedinfo);
757 return $output;
759 // this is a teacher who is allowed to see module but still should see the
760 // information that module is not available to all/some students
761 $modcontext = context_module::instance($mod->id);
762 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
763 if ($canviewhidden && !$mod->visible) {
764 // This module is hidden but current user has capability to see it.
765 // Do not display the availability info if the whole section is hidden.
766 if ($mod->get_section_info()->visible) {
767 $output .= $this->availability_info(get_string('hiddenfromstudents'), 'ishidden');
769 } else if ($mod->is_stealth()) {
770 // This module is available but is normally not displayed on the course page
771 // (this user can see it because they can manage it).
772 $output .= $this->availability_info(get_string('hiddenoncoursepage'), 'isstealth');
774 if ($canviewhidden && !empty($CFG->enableavailability)) {
775 // Display information about conditional availability.
776 // Don't add availability information if user is not editing and activity is hidden.
777 if ($mod->visible || $this->page->user_is_editing()) {
778 $hidinfoclass = '';
779 if (!$mod->visible) {
780 $hidinfoclass = 'hide';
782 $ci = new \core_availability\info_module($mod);
783 $fullinfo = $ci->get_full_information();
784 if ($fullinfo) {
785 $formattedinfo = \core_availability\info::format_info(
786 $fullinfo, $mod->get_course());
787 $output .= $this->availability_info($formattedinfo, $hidinfoclass);
791 return $output;
795 * Renders HTML to display one course module for display within a section.
797 * This function calls:
798 * {@link core_course_renderer::course_section_cm()}
800 * @param stdClass $course
801 * @param completion_info $completioninfo
802 * @param cm_info $mod
803 * @param int|null $sectionreturn
804 * @param array $displayoptions
805 * @return String
807 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
808 $output = '';
809 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
810 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
811 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
813 return $output;
817 * Renders HTML to display one course module in a course section
819 * This includes link, content, availability, completion info and additional information
820 * that module type wants to display (i.e. number of unread forum posts)
822 * This function calls:
823 * {@link core_course_renderer::course_section_cm_name()}
824 * {@link core_course_renderer::course_section_cm_text()}
825 * {@link core_course_renderer::course_section_cm_availability()}
826 * {@link core_course_renderer::course_section_cm_completion()}
827 * {@link course_get_cm_edit_actions()}
828 * {@link core_course_renderer::course_section_cm_edit_actions()}
830 * @param stdClass $course
831 * @param completion_info $completioninfo
832 * @param cm_info $mod
833 * @param int|null $sectionreturn
834 * @param array $displayoptions
835 * @return string
837 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
838 $output = '';
839 // We return empty string (because course module will not be displayed at all)
840 // if:
841 // 1) The activity is not visible to users
842 // and
843 // 2) The 'availableinfo' is empty, i.e. the activity was
844 // hidden in a way that leaves no info, such as using the
845 // eye icon.
846 if (!$mod->is_visible_on_course_page()) {
847 return $output;
850 $indentclasses = 'mod-indent';
851 if (!empty($mod->indent)) {
852 $indentclasses .= ' mod-indent-'.$mod->indent;
853 if ($mod->indent > 15) {
854 $indentclasses .= ' mod-indent-huge';
858 $output .= html_writer::start_tag('div');
860 if ($this->page->user_is_editing()) {
861 $output .= course_get_cm_move($mod, $sectionreturn);
864 $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer'));
866 // This div is used to indent the content.
867 $output .= html_writer::div('', $indentclasses);
869 // Start a wrapper for the actual content to keep the indentation consistent
870 $output .= html_writer::start_tag('div');
872 // Display the link to the module (or do nothing if module has no url)
873 $cmname = $this->course_section_cm_name($mod, $displayoptions);
875 if (!empty($cmname)) {
876 // Start the div for the activity title, excluding the edit icons.
877 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
878 $output .= $cmname;
881 // Module can put text after the link (e.g. forum unread)
882 $output .= $mod->afterlink;
884 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
885 $output .= html_writer::end_tag('div'); // .activityinstance
888 // If there is content but NO link (eg label), then display the
889 // content here (BEFORE any icons). In this case cons must be
890 // displayed after the content so that it makes more sense visually
891 // and for accessibility reasons, e.g. if you have a one-line label
892 // it should work similarly (at least in terms of ordering) to an
893 // activity.
894 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
895 $url = $mod->url;
896 if (empty($url)) {
897 $output .= $contentpart;
900 $modicons = '';
901 if ($this->page->user_is_editing()) {
902 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
903 $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
904 $modicons .= $mod->afterediticons;
907 $modicons .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
909 if (!empty($modicons)) {
910 $output .= html_writer::span($modicons, 'actions');
913 // Show availability info (if module is not available).
914 $output .= $this->course_section_cm_availability($mod, $displayoptions);
916 // If there is content AND a link, then display the content here
917 // (AFTER any icons). Otherwise it was displayed before
918 if (!empty($url)) {
919 $output .= $contentpart;
922 $output .= html_writer::end_tag('div'); // $indentclasses
924 // End of indentation div.
925 $output .= html_writer::end_tag('div');
927 $output .= html_writer::end_tag('div');
928 return $output;
932 * Renders HTML to display a list of course modules in a course section
933 * Also displays "move here" controls in Javascript-disabled mode
935 * This function calls {@link core_course_renderer::course_section_cm()}
937 * @param stdClass $course course object
938 * @param int|stdClass|section_info $section relative section number or section object
939 * @param int $sectionreturn section number to return to
940 * @param int $displayoptions
941 * @return void
943 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
944 global $USER;
946 $output = '';
947 $modinfo = get_fast_modinfo($course);
948 if (is_object($section)) {
949 $section = $modinfo->get_section_info($section->section);
950 } else {
951 $section = $modinfo->get_section_info($section);
953 $completioninfo = new completion_info($course);
955 // check if we are currently in the process of moving a module with JavaScript disabled
956 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
957 if ($ismoving) {
958 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
959 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
962 // Get the list of modules visible to user (excluding the module being moved if there is one)
963 $moduleshtml = array();
964 if (!empty($modinfo->sections[$section->section])) {
965 foreach ($modinfo->sections[$section->section] as $modnumber) {
966 $mod = $modinfo->cms[$modnumber];
968 if ($ismoving and $mod->id == $USER->activitycopy) {
969 // do not display moving mod
970 continue;
973 if ($modulehtml = $this->course_section_cm_list_item($course,
974 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
975 $moduleshtml[$modnumber] = $modulehtml;
980 $sectionoutput = '';
981 if (!empty($moduleshtml) || $ismoving) {
982 foreach ($moduleshtml as $modnumber => $modulehtml) {
983 if ($ismoving) {
984 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
985 $sectionoutput .= html_writer::tag('li',
986 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
987 array('class' => 'movehere'));
990 $sectionoutput .= $modulehtml;
993 if ($ismoving) {
994 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
995 $sectionoutput .= html_writer::tag('li',
996 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
997 array('class' => 'movehere'));
1001 // Always output the section module list.
1002 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1004 return $output;
1008 * Displays a custom list of courses with paging bar if necessary
1010 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1011 * appears under the list.
1013 * If both $paginationurl and $totalcount are specified, and $totalcount is
1014 * bigger than count($courses), a paging bar is displayed above and under the
1015 * courses list.
1017 * @param array $courses array of course records (or instances of course_in_list) to show on this page
1018 * @param bool $showcategoryname whether to add category name to the course description
1019 * @param string $additionalclasses additional CSS classes to add to the div.courses
1020 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1021 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1022 * @param int $page current page number (defaults to 0 referring to the first page)
1023 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1024 * @return string
1026 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1027 global $CFG;
1028 // create instance of coursecat_helper to pass display options to function rendering courses list
1029 $chelper = new coursecat_helper();
1030 if ($showcategoryname) {
1031 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1032 } else {
1033 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1035 if ($totalcount !== null && $paginationurl !== null) {
1036 // add options to display pagination
1037 if ($perpage === null) {
1038 $perpage = $CFG->coursesperpage;
1040 $chelper->set_courses_display_options(array(
1041 'limit' => $perpage,
1042 'offset' => ((int)$page) * $perpage,
1043 'paginationurl' => $paginationurl,
1045 } else if ($paginationurl !== null) {
1046 // add options to display 'View more' link
1047 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1048 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1050 $chelper->set_attributes(array('class' => $additionalclasses));
1051 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1052 return $content;
1056 * Displays one course in the list of courses.
1058 * This is an internal function, to display an information about just one course
1059 * please use {@link core_course_renderer::course_info_box()}
1061 * @param coursecat_helper $chelper various display options
1062 * @param course_in_list|stdClass $course
1063 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1064 * depend on the course position in list - first/last/even/odd)
1065 * @return string
1067 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1068 global $CFG;
1069 if (!isset($this->strings->summary)) {
1070 $this->strings->summary = get_string('summary');
1072 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1073 return '';
1075 if ($course instanceof stdClass) {
1076 require_once($CFG->libdir. '/coursecatlib.php');
1077 $course = new course_in_list($course);
1079 $content = '';
1080 $classes = trim('coursebox clearfix '. $additionalclasses);
1081 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1082 $nametag = 'h3';
1083 } else {
1084 $classes .= ' collapsed';
1085 $nametag = 'div';
1088 // .coursebox
1089 $content .= html_writer::start_tag('div', array(
1090 'class' => $classes,
1091 'data-courseid' => $course->id,
1092 'data-type' => self::COURSECAT_TYPE_COURSE,
1095 $content .= html_writer::start_tag('div', array('class' => 'info'));
1097 // course name
1098 $coursename = $chelper->get_course_formatted_name($course);
1099 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', array('id' => $course->id)),
1100 $coursename, array('class' => $course->visible ? '' : 'dimmed'));
1101 $content .= html_writer::tag($nametag, $coursenamelink, array('class' => 'coursename'));
1102 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1103 $content .= html_writer::start_tag('div', array('class' => 'moreinfo'));
1104 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1105 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()) {
1106 $url = new moodle_url('/course/info.php', array('id' => $course->id));
1107 $image = $this->output->pix_icon('i/info', $this->strings->summary);
1108 $content .= html_writer::link($url, $image, array('title' => $this->strings->summary));
1109 // Make sure JS file to expand course content is included.
1110 $this->coursecat_include_js();
1113 $content .= html_writer::end_tag('div'); // .moreinfo
1115 // print enrolmenticons
1116 if ($icons = enrol_get_course_info_icons($course)) {
1117 $content .= html_writer::start_tag('div', array('class' => 'enrolmenticons'));
1118 foreach ($icons as $pix_icon) {
1119 $content .= $this->render($pix_icon);
1121 $content .= html_writer::end_tag('div'); // .enrolmenticons
1124 $content .= html_writer::end_tag('div'); // .info
1126 $content .= html_writer::start_tag('div', array('class' => 'content'));
1127 $content .= $this->coursecat_coursebox_content($chelper, $course);
1128 $content .= html_writer::end_tag('div'); // .content
1130 $content .= html_writer::end_tag('div'); // .coursebox
1131 return $content;
1135 * Returns HTML to display course content (summary, course contacts and optionally category name)
1137 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1139 * @param coursecat_helper $chelper various display options
1140 * @param stdClass|course_in_list $course
1141 * @return string
1143 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1144 global $CFG;
1145 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1146 return '';
1148 if ($course instanceof stdClass) {
1149 require_once($CFG->libdir. '/coursecatlib.php');
1150 $course = new course_in_list($course);
1152 $content = '';
1154 // display course summary
1155 if ($course->has_summary()) {
1156 $content .= html_writer::start_tag('div', array('class' => 'summary'));
1157 $content .= $chelper->get_course_formatted_summary($course,
1158 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1159 $content .= html_writer::end_tag('div'); // .summary
1162 // display course overview files
1163 $contentimages = $contentfiles = '';
1164 foreach ($course->get_course_overviewfiles() as $file) {
1165 $isimage = $file->is_valid_image();
1166 $url = file_encode_url("$CFG->wwwroot/pluginfile.php",
1167 '/'. $file->get_contextid(). '/'. $file->get_component(). '/'.
1168 $file->get_filearea(). $file->get_filepath(). $file->get_filename(), !$isimage);
1169 if ($isimage) {
1170 $contentimages .= html_writer::tag('div',
1171 html_writer::empty_tag('img', array('src' => $url)),
1172 array('class' => 'courseimage'));
1173 } else {
1174 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1175 $filename = html_writer::tag('span', $image, array('class' => 'fp-icon')).
1176 html_writer::tag('span', $file->get_filename(), array('class' => 'fp-filename'));
1177 $contentfiles .= html_writer::tag('span',
1178 html_writer::link($url, $filename),
1179 array('class' => 'coursefile fp-filename-icon'));
1182 $content .= $contentimages. $contentfiles;
1184 // display course contacts. See course_in_list::get_course_contacts()
1185 if ($course->has_course_contacts()) {
1186 $content .= html_writer::start_tag('ul', array('class' => 'teachers'));
1187 foreach ($course->get_course_contacts() as $userid => $coursecontact) {
1188 $name = $coursecontact['rolename'].': '.
1189 html_writer::link(new moodle_url('/user/view.php',
1190 array('id' => $userid, 'course' => SITEID)),
1191 $coursecontact['username']);
1192 $content .= html_writer::tag('li', $name);
1194 $content .= html_writer::end_tag('ul'); // .teachers
1197 // display course category if necessary (for example in search results)
1198 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1199 require_once($CFG->libdir. '/coursecatlib.php');
1200 if ($cat = coursecat::get($course->category, IGNORE_MISSING)) {
1201 $content .= html_writer::start_tag('div', array('class' => 'coursecat'));
1202 $content .= get_string('category').': '.
1203 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1204 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1205 $content .= html_writer::end_tag('div'); // .coursecat
1209 return $content;
1213 * Renders the list of courses
1215 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1216 * method from outside of the class
1218 * If list of courses is specified in $courses; the argument $chelper is only used
1219 * to retrieve display options and attributes, only methods get_show_courses(),
1220 * get_courses_display_option() and get_and_erase_attributes() are called.
1222 * @param coursecat_helper $chelper various display options
1223 * @param array $courses the list of courses to display
1224 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1225 * defaulted to count($courses)
1226 * @return string
1228 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1229 global $CFG;
1230 if ($totalcount === null) {
1231 $totalcount = count($courses);
1233 if (!$totalcount) {
1234 // Courses count is cached during courses retrieval.
1235 return '';
1238 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1239 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1240 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1241 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1242 } else {
1243 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1247 // prepare content of paging bar if it is needed
1248 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1249 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1250 if ($totalcount > count($courses)) {
1251 // there are more results that can fit on one page
1252 if ($paginationurl) {
1253 // the option paginationurl was specified, display pagingbar
1254 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1255 $page = $chelper->get_courses_display_option('offset') / $perpage;
1256 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1257 $paginationurl->out(false, array('perpage' => $perpage)));
1258 if ($paginationallowall) {
1259 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1260 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1262 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1263 // the option for 'View more' link was specified, display more link
1264 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1265 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1266 array('class' => 'paging paging-morelink'));
1268 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1269 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1270 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1271 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1274 // display list of courses
1275 $attributes = $chelper->get_and_erase_attributes('courses');
1276 $content = html_writer::start_tag('div', $attributes);
1278 if (!empty($pagingbar)) {
1279 $content .= $pagingbar;
1282 $coursecount = 0;
1283 foreach ($courses as $course) {
1284 $coursecount ++;
1285 $classes = ($coursecount%2) ? 'odd' : 'even';
1286 if ($coursecount == 1) {
1287 $classes .= ' first';
1289 if ($coursecount >= count($courses)) {
1290 $classes .= ' last';
1292 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1295 if (!empty($pagingbar)) {
1296 $content .= $pagingbar;
1298 if (!empty($morelink)) {
1299 $content .= $morelink;
1302 $content .= html_writer::end_tag('div'); // .courses
1303 return $content;
1307 * Renders the list of subcategories in a category
1309 * @param coursecat_helper $chelper various display options
1310 * @param coursecat $coursecat
1311 * @param int $depth depth of the category in the current tree
1312 * @return string
1314 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1315 global $CFG;
1316 $subcategories = array();
1317 if (!$chelper->get_categories_display_option('nodisplay')) {
1318 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1320 $totalcount = $coursecat->get_children_count();
1321 if (!$totalcount) {
1322 // Note that we call coursecat::get_children_count() AFTER coursecat::get_children() to avoid extra DB requests.
1323 // Categories count is cached during children categories retrieval.
1324 return '';
1327 // prepare content of paging bar or more link if it is needed
1328 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1329 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1330 if ($totalcount > count($subcategories)) {
1331 if ($paginationurl) {
1332 // the option 'paginationurl was specified, display pagingbar
1333 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1334 $page = $chelper->get_categories_display_option('offset') / $perpage;
1335 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1336 $paginationurl->out(false, array('perpage' => $perpage)));
1337 if ($paginationallowall) {
1338 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1339 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1341 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1342 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1343 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1344 $viewmoreurl->param('categoryid', $coursecat->id);
1346 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1347 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1348 array('class' => 'paging paging-morelink'));
1350 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1351 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1352 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1353 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1356 // display list of subcategories
1357 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1359 if (!empty($pagingbar)) {
1360 $content .= $pagingbar;
1363 foreach ($subcategories as $subcategory) {
1364 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1367 if (!empty($pagingbar)) {
1368 $content .= $pagingbar;
1370 if (!empty($morelink)) {
1371 $content .= $morelink;
1374 $content .= html_writer::end_tag('div');
1375 return $content;
1379 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1381 protected function coursecat_include_js() {
1382 if (!$this->page->requires->should_create_one_time_item_now('core_course_categoryexpanderjsinit')) {
1383 return;
1386 // We must only load this module once.
1387 $this->page->requires->yui_module('moodle-course-categoryexpander',
1388 'Y.Moodle.course.categoryexpander.init');
1392 * Returns HTML to display the subcategories and courses in the given category
1394 * This method is re-used by AJAX to expand content of not loaded category
1396 * @param coursecat_helper $chelper various display options
1397 * @param coursecat $coursecat
1398 * @param int $depth depth of the category in the current tree
1399 * @return string
1401 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1402 $content = '';
1403 // Subcategories
1404 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1406 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1407 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1408 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1409 if ($showcoursesauto && $depth) {
1410 // this is definitely collapsed mode
1411 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1414 // Courses
1415 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1416 $courses = array();
1417 if (!$chelper->get_courses_display_option('nodisplay')) {
1418 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1420 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1421 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1422 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1423 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1426 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1429 if ($showcoursesauto) {
1430 // restore the show_courses back to AUTO
1431 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1434 return $content;
1438 * Returns HTML to display a course category as a part of a tree
1440 * This is an internal function, to display a particular category and all its contents
1441 * use {@link core_course_renderer::course_category()}
1443 * @param coursecat_helper $chelper various display options
1444 * @param coursecat $coursecat
1445 * @param int $depth depth of this category in the current tree
1446 * @return string
1448 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1449 // open category tag
1450 $classes = array('category');
1451 if (empty($coursecat->visible)) {
1452 $classes[] = 'dimmed_category';
1454 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1455 // do not load content
1456 $categorycontent = '';
1457 $classes[] = 'notloaded';
1458 if ($coursecat->get_children_count() ||
1459 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1460 $classes[] = 'with_children';
1461 $classes[] = 'collapsed';
1463 } else {
1464 // load category content
1465 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1466 $classes[] = 'loaded';
1467 if (!empty($categorycontent)) {
1468 $classes[] = 'with_children';
1472 // Make sure JS file to expand category content is included.
1473 $this->coursecat_include_js();
1475 $content = html_writer::start_tag('div', array(
1476 'class' => join(' ', $classes),
1477 'data-categoryid' => $coursecat->id,
1478 'data-depth' => $depth,
1479 'data-showcourses' => $chelper->get_show_courses(),
1480 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1483 // category name
1484 $categoryname = $coursecat->get_formatted_name();
1485 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1486 array('categoryid' => $coursecat->id)),
1487 $categoryname);
1488 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1489 && ($coursescount = $coursecat->get_courses_count())) {
1490 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1491 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1493 $content .= html_writer::start_tag('div', array('class' => 'info'));
1495 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname'));
1496 $content .= html_writer::end_tag('div'); // .info
1498 // add category content to the output
1499 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1501 $content .= html_writer::end_tag('div'); // .category
1503 // Return the course category tree HTML
1504 return $content;
1508 * Returns HTML to display a tree of subcategories and courses in the given category
1510 * @param coursecat_helper $chelper various display options
1511 * @param coursecat $coursecat top category (this category's name and description will NOT be added to the tree)
1512 * @return string
1514 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1515 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1516 if (empty($categorycontent)) {
1517 return '';
1520 // Start content generation
1521 $content = '';
1522 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1523 $content .= html_writer::start_tag('div', $attributes);
1525 if ($coursecat->get_children_count()) {
1526 $classes = array(
1527 'collapseexpand',
1530 // Only show the collapse/expand if there are children to expand.
1531 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1532 $content .= html_writer::link('#', get_string('expandall'),
1533 array('class' => implode(' ', $classes)));
1534 $content .= html_writer::end_tag('div');
1535 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1538 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1540 $content .= html_writer::end_tag('div'); // .course_category_tree
1542 return $content;
1546 * Renders HTML to display particular course category - list of it's subcategories and courses
1548 * Invoked from /course/index.php
1550 * @param int|stdClass|coursecat $category
1552 public function course_category($category) {
1553 global $CFG;
1554 require_once($CFG->libdir. '/coursecatlib.php');
1555 $coursecat = coursecat::get(is_object($category) ? $category->id : $category);
1556 $site = get_site();
1557 $output = '';
1559 if (can_edit_in_category($coursecat->id)) {
1560 // Add 'Manage' button if user has permissions to edit this category.
1561 $managebutton = $this->single_button(new moodle_url('/course/management.php',
1562 array('categoryid' => $coursecat->id)), get_string('managecourses'), 'get');
1563 $this->page->set_button($managebutton);
1565 if (!$coursecat->id) {
1566 if (coursecat::count_all() == 1) {
1567 // There exists only one category in the system, do not display link to it
1568 $coursecat = coursecat::get_default();
1569 $strfulllistofcourses = get_string('fulllistofcourses');
1570 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1571 } else {
1572 $strcategories = get_string('categories');
1573 $this->page->set_title("$site->shortname: $strcategories");
1575 } else {
1576 $title = $site->shortname;
1577 if (coursecat::count_all() > 1) {
1578 $title .= ": ". $coursecat->get_formatted_name();
1580 $this->page->set_title($title);
1582 // Print the category selector
1583 if (coursecat::count_all() > 1) {
1584 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1585 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1586 coursecat::make_categories_list(), $coursecat->id, null, 'switchcategory');
1587 $select->set_label(get_string('categories').':');
1588 $output .= $this->render($select);
1589 $output .= html_writer::end_tag('div'); // .categorypicker
1593 // Print current category description
1594 $chelper = new coursecat_helper();
1595 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1596 $output .= $this->box($description, array('class' => 'generalbox info'));
1599 // Prepare parameters for courses and categories lists in the tree
1600 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1601 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1603 $coursedisplayoptions = array();
1604 $catdisplayoptions = array();
1605 $browse = optional_param('browse', null, PARAM_ALPHA);
1606 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1607 $page = optional_param('page', 0, PARAM_INT);
1608 $baseurl = new moodle_url('/course/index.php');
1609 if ($coursecat->id) {
1610 $baseurl->param('categoryid', $coursecat->id);
1612 if ($perpage != $CFG->coursesperpage) {
1613 $baseurl->param('perpage', $perpage);
1615 $coursedisplayoptions['limit'] = $perpage;
1616 $catdisplayoptions['limit'] = $perpage;
1617 if ($browse === 'courses' || !$coursecat->has_children()) {
1618 $coursedisplayoptions['offset'] = $page * $perpage;
1619 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1620 $catdisplayoptions['nodisplay'] = true;
1621 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1622 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1623 } else if ($browse === 'categories' || !$coursecat->has_courses()) {
1624 $coursedisplayoptions['nodisplay'] = true;
1625 $catdisplayoptions['offset'] = $page * $perpage;
1626 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1627 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1628 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1629 } else {
1630 // we have a category that has both subcategories and courses, display pagination separately
1631 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1632 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1634 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1635 // Add course search form.
1636 $output .= $this->course_search_form();
1638 // Display course category tree.
1639 $output .= $this->coursecat_tree($chelper, $coursecat);
1641 // Add action buttons
1642 $output .= $this->container_start('buttons');
1643 $context = get_category_or_system_context($coursecat->id);
1644 if (has_capability('moodle/course:create', $context)) {
1645 // Print link to create a new course, for the 1st available category.
1646 if ($coursecat->id) {
1647 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1648 } else {
1649 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1651 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1653 ob_start();
1654 if (coursecat::count_all() == 1) {
1655 print_course_request_buttons(context_system::instance());
1656 } else {
1657 print_course_request_buttons($context);
1659 $output .= ob_get_contents();
1660 ob_end_clean();
1661 $output .= $this->container_end();
1663 return $output;
1667 * Serves requests to /course/category.ajax.php
1669 * In this renderer implementation it may expand the category content or
1670 * course content.
1672 * @return string
1673 * @throws coding_exception
1675 public function coursecat_ajax() {
1676 global $DB, $CFG;
1677 require_once($CFG->libdir. '/coursecatlib.php');
1679 $type = required_param('type', PARAM_INT);
1681 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1682 // This is a request for a category list of some kind.
1683 $categoryid = required_param('categoryid', PARAM_INT);
1684 $showcourses = required_param('showcourses', PARAM_INT);
1685 $depth = required_param('depth', PARAM_INT);
1687 $category = coursecat::get($categoryid);
1689 $chelper = new coursecat_helper();
1690 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1691 $coursedisplayoptions = array(
1692 'limit' => $CFG->coursesperpage,
1693 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1695 $catdisplayoptions = array(
1696 'limit' => $CFG->coursesperpage,
1697 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1699 $chelper->set_show_courses($showcourses)->
1700 set_courses_display_options($coursedisplayoptions)->
1701 set_categories_display_options($catdisplayoptions);
1703 return $this->coursecat_category_content($chelper, $category, $depth);
1704 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1705 // This is a request for the course information.
1706 $courseid = required_param('courseid', PARAM_INT);
1708 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1710 $chelper = new coursecat_helper();
1711 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1712 return $this->coursecat_coursebox_content($chelper, $course);
1713 } else {
1714 throw new coding_exception('Invalid request type');
1719 * Renders html to display search result page
1721 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1722 * @return string
1724 public function search_courses($searchcriteria) {
1725 global $CFG;
1726 $content = '';
1727 if (!empty($searchcriteria)) {
1728 // print search results
1729 require_once($CFG->libdir. '/coursecatlib.php');
1731 $displayoptions = array('sort' => array('displayname' => 1));
1732 // take the current page and number of results per page from query
1733 $perpage = optional_param('perpage', 0, PARAM_RAW);
1734 if ($perpage !== 'all') {
1735 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1736 $page = optional_param('page', 0, PARAM_INT);
1737 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1739 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1740 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1741 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1743 $class = 'course-search-result';
1744 foreach ($searchcriteria as $key => $value) {
1745 if (!empty($value)) {
1746 $class .= ' course-search-result-'. $key;
1749 $chelper = new coursecat_helper();
1750 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1751 set_courses_display_options($displayoptions)->
1752 set_search_criteria($searchcriteria)->
1753 set_attributes(array('class' => $class));
1755 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1756 $totalcount = coursecat::search_courses_count($searchcriteria);
1757 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1759 if (!$totalcount) {
1760 if (!empty($searchcriteria['search'])) {
1761 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1762 } else {
1763 $content .= $this->heading(get_string('novalidcourses'));
1765 } else {
1766 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1767 $content .= $courseslist;
1770 if (!empty($searchcriteria['search'])) {
1771 // print search form only if there was a search by search string, otherwise it is confusing
1772 $content .= $this->box_start('generalbox mdl-align');
1773 $content .= $this->course_search_form($searchcriteria['search']);
1774 $content .= $this->box_end();
1776 } else {
1777 // just print search form
1778 $content .= $this->box_start('generalbox mdl-align');
1779 $content .= $this->course_search_form();
1780 $content .= html_writer::tag('div', get_string("searchhelp"), array('class' => 'searchhelp'));
1781 $content .= $this->box_end();
1783 return $content;
1787 * Renders html to print list of courses tagged with particular tag
1789 * @param int $tagid id of the tag
1790 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1791 * are displayed on the page and the per-page limit may be bigger
1792 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1793 * to display items in the same context first
1794 * @param int $ctx context id where to search for records
1795 * @param bool $rec search in subcontexts as well
1796 * @param array $displayoptions
1797 * @return string empty string if no courses are marked with this tag or rendered list of courses
1799 public function tagged_courses($tagid, $exclusivemode = true, $ctx = 0, $rec = true, $displayoptions = null) {
1800 global $CFG;
1801 require_once($CFG->libdir . '/coursecatlib.php');
1802 if (empty($displayoptions)) {
1803 $displayoptions = array();
1805 $showcategories = coursecat::count_all() > 1;
1806 $displayoptions += array('limit' => $CFG->coursesperpage, 'offset' => 0);
1807 $chelper = new coursecat_helper();
1808 $searchcriteria = array('tagid' => $tagid, 'ctx' => $ctx, 'rec' => $rec);
1809 $chelper->set_show_courses($showcategories ? self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT :
1810 self::COURSECAT_SHOW_COURSES_EXPANDED)->
1811 set_search_criteria($searchcriteria)->
1812 set_courses_display_options($displayoptions)->
1813 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1814 // (we set the same css class as in search results by tagid)
1815 if ($totalcount = coursecat::search_courses_count($searchcriteria)) {
1816 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1817 if ($exclusivemode) {
1818 return $this->coursecat_courses($chelper, $courses, $totalcount);
1819 } else {
1820 $tagfeed = new core_tag\output\tagfeed();
1821 $img = $this->output->pix_icon('i/course', '');
1822 foreach ($courses as $course) {
1823 $url = course_get_url($course);
1824 $imgwithlink = html_writer::link($url, $img);
1825 $coursename = html_writer::link($url, $course->get_formatted_name());
1826 $details = '';
1827 if ($showcategories && ($cat = coursecat::get($course->category, IGNORE_MISSING))) {
1828 $details = get_string('category').': '.
1829 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1830 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1832 $tagfeed->add($imgwithlink, $coursename, $details);
1834 return $this->output->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($this->output));
1837 return '';
1841 * Returns HTML to display one remote course
1843 * @param stdClass $course remote course information, contains properties:
1844 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1845 * @return string
1847 protected function frontpage_remote_course(stdClass $course) {
1848 $url = new moodle_url('/auth/mnet/jump.php', array(
1849 'hostid' => $course->hostid,
1850 'wantsurl' => '/course/view.php?id='. $course->remoteid
1853 $output = '';
1854 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1855 $output .= html_writer::start_tag('div', array('class' => 'info'));
1856 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1857 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1858 $output .= html_writer::end_tag('h3'); // .name
1859 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1860 $output .= html_writer::end_tag('div'); // .info
1861 $output .= html_writer::start_tag('div', array('class' => 'content'));
1862 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1863 $options = new stdClass();
1864 $options->noclean = true;
1865 $options->para = false;
1866 $options->overflowdiv = true;
1867 $output .= format_text($course->summary, $course->summaryformat, $options);
1868 $output .= html_writer::end_tag('div'); // .summary
1869 $addinfo = format_string($course->hostname) . ' : '
1870 . format_string($course->cat_name) . ' : '
1871 . format_string($course->shortname);
1872 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1873 $output .= html_writer::end_tag('div'); // .content
1874 $output .= html_writer::end_tag('div'); // .coursebox
1875 return $output;
1879 * Returns HTML to display one remote host
1881 * @param array $host host information, contains properties: name, url, count
1882 * @return string
1884 protected function frontpage_remote_host($host) {
1885 $output = '';
1886 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1887 $output .= html_writer::start_tag('div', array('class' => 'info'));
1888 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1889 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1890 $output .= html_writer::end_tag('h3'); // .name
1891 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1892 $output .= html_writer::end_tag('div'); // .info
1893 $output .= html_writer::start_tag('div', array('class' => 'content'));
1894 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1895 $output .= $host['count'] . ' ' . get_string('courses');
1896 $output .= html_writer::end_tag('div'); // .content
1897 $output .= html_writer::end_tag('div'); // .coursebox
1898 return $output;
1902 * Returns HTML to print list of courses user is enrolled to for the frontpage
1904 * Also lists remote courses or remote hosts if MNET authorisation is used
1906 * @return string
1908 public function frontpage_my_courses() {
1909 global $USER, $CFG, $DB;
1911 if (!isloggedin() or isguestuser()) {
1912 return '';
1915 $output = '';
1916 if (!empty($CFG->navsortmycoursessort)) {
1917 // sort courses the same as in navigation menu
1918 $sortorder = 'visible DESC,'. $CFG->navsortmycoursessort.' ASC';
1919 } else {
1920 $sortorder = 'visible DESC,sortorder ASC';
1922 $courses = enrol_get_my_courses('summary, summaryformat', $sortorder);
1923 $rhosts = array();
1924 $rcourses = array();
1925 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1926 $rcourses = get_my_remotecourses($USER->id);
1927 $rhosts = get_my_remotehosts();
1930 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
1932 $chelper = new coursecat_helper();
1933 if (count($courses) > $CFG->frontpagecourselimit) {
1934 // There are more enrolled courses than we can display, display link to 'My courses'.
1935 $totalcount = count($courses);
1936 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
1937 $chelper->set_courses_display_options(array(
1938 'viewmoreurl' => new moodle_url('/my/'),
1939 'viewmoretext' => new lang_string('mycourses')
1941 } else {
1942 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
1943 $chelper->set_courses_display_options(array(
1944 'viewmoreurl' => new moodle_url('/course/index.php'),
1945 'viewmoretext' => new lang_string('fulllistofcourses')
1947 $totalcount = $DB->count_records('course') - 1;
1949 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
1950 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
1951 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
1953 // MNET
1954 if (!empty($rcourses)) {
1955 // at the IDP, we know of all the remote courses
1956 $output .= html_writer::start_tag('div', array('class' => 'courses'));
1957 foreach ($rcourses as $course) {
1958 $output .= $this->frontpage_remote_course($course);
1960 $output .= html_writer::end_tag('div'); // .courses
1961 } elseif (!empty($rhosts)) {
1962 // non-IDP, we know of all the remote servers, but not courses
1963 $output .= html_writer::start_tag('div', array('class' => 'courses'));
1964 foreach ($rhosts as $host) {
1965 $output .= $this->frontpage_remote_host($host);
1967 $output .= html_writer::end_tag('div'); // .courses
1970 return $output;
1974 * Returns HTML to print list of available courses for the frontpage
1976 * @return string
1978 public function frontpage_available_courses() {
1979 global $CFG;
1980 require_once($CFG->libdir. '/coursecatlib.php');
1982 $chelper = new coursecat_helper();
1983 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
1984 set_courses_display_options(array(
1985 'recursive' => true,
1986 'limit' => $CFG->frontpagecourselimit,
1987 'viewmoreurl' => new moodle_url('/course/index.php'),
1988 'viewmoretext' => new lang_string('fulllistofcourses')));
1990 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
1991 $courses = coursecat::get(0)->get_courses($chelper->get_courses_display_options());
1992 $totalcount = coursecat::get(0)->get_courses_count($chelper->get_courses_display_options());
1993 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
1994 // Print link to create a new course, for the 1st available category.
1995 return $this->add_new_course_button();
1997 return $this->coursecat_courses($chelper, $courses, $totalcount);
2001 * Returns HTML to the "add new course" button for the page
2003 * @return string
2005 public function add_new_course_button() {
2006 global $CFG;
2007 // Print link to create a new course, for the 1st available category.
2008 $output = $this->container_start('buttons');
2009 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2010 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2011 $output .= $this->container_end('buttons');
2012 return $output;
2016 * Returns HTML to print tree with course categories and courses for the frontpage
2018 * @return string
2020 public function frontpage_combo_list() {
2021 global $CFG;
2022 require_once($CFG->libdir. '/coursecatlib.php');
2023 $chelper = new coursecat_helper();
2024 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2025 set_categories_display_options(array(
2026 'limit' => $CFG->coursesperpage,
2027 'viewmoreurl' => new moodle_url('/course/index.php',
2028 array('browse' => 'categories', 'page' => 1))
2029 ))->
2030 set_courses_display_options(array(
2031 'limit' => $CFG->coursesperpage,
2032 'viewmoreurl' => new moodle_url('/course/index.php',
2033 array('browse' => 'courses', 'page' => 1))
2034 ))->
2035 set_attributes(array('class' => 'frontpage-category-combo'));
2036 return $this->coursecat_tree($chelper, coursecat::get(0));
2040 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2042 * @return string
2044 public function frontpage_categories_list() {
2045 global $CFG;
2046 require_once($CFG->libdir. '/coursecatlib.php');
2047 $chelper = new coursecat_helper();
2048 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2049 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2050 set_categories_display_options(array(
2051 'limit' => $CFG->coursesperpage,
2052 'viewmoreurl' => new moodle_url('/course/index.php',
2053 array('browse' => 'categories', 'page' => 1))
2054 ))->
2055 set_attributes(array('class' => 'frontpage-category-names'));
2056 return $this->coursecat_tree($chelper, coursecat::get(0));
2062 * Class storing display options and functions to help display course category and/or courses lists
2064 * This is a wrapper for coursecat objects that also stores display options
2065 * and functions to retrieve sorted and paginated lists of categories/courses.
2067 * If theme overrides methods in core_course_renderers that access this class
2068 * it may as well not use this class at all or extend it.
2070 * @package core
2071 * @copyright 2013 Marina Glancy
2072 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2074 class coursecat_helper {
2075 /** @var string [none, collapsed, expanded] how (if) display courses list */
2076 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2077 /** @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) */
2078 protected $subcatdepth = 1;
2079 /** @var array options to display courses list */
2080 protected $coursesdisplayoptions = array();
2081 /** @var array options to display subcategories list */
2082 protected $categoriesdisplayoptions = array();
2083 /** @var array additional HTML attributes */
2084 protected $attributes = array();
2085 /** @var array search criteria if the list is a search result */
2086 protected $searchcriteria = null;
2089 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2091 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2092 * @return coursecat_helper
2094 public function set_show_courses($showcourses) {
2095 $this->showcourses = $showcourses;
2096 // Automatically set the options to preload summary and coursecontacts for coursecat::get_courses() and coursecat::search_courses()
2097 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2098 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2099 return $this;
2103 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2105 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2107 public function get_show_courses() {
2108 return $this->showcourses;
2112 * Sets the maximum depth to expand subcategories in the tree
2114 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2116 * @param int $subcatdepth
2117 * @return coursecat_helper
2119 public function set_subcat_depth($subcatdepth) {
2120 $this->subcatdepth = $subcatdepth;
2121 return $this;
2125 * Returns the maximum depth to expand subcategories in the tree
2127 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2129 * @return int
2131 public function get_subcat_depth() {
2132 return $this->subcatdepth;
2136 * Sets options to display list of courses
2138 * Options are later submitted as argument to coursecat::get_courses() and/or coursecat::search_courses()
2140 * Options that coursecat::get_courses() accept:
2141 * - recursive - return courses from subcategories as well. Use with care,
2142 * this may be a huge list!
2143 * - summary - preloads fields 'summary' and 'summaryformat'
2144 * - coursecontacts - preloads course contacts
2145 * - isenrolled - preloads indication whether this user is enrolled in the course
2146 * - sort - list of fields to sort. Example
2147 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2148 * will sort by idnumber asc, shortname asc and id desc.
2149 * Default: array('sortorder' => 1)
2150 * Only cached fields may be used for sorting!
2151 * - offset
2152 * - limit - maximum number of children to return, 0 or null for no limit
2154 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2156 * Also renderer can set here any additional options it wants to pass between renderer functions.
2158 * @param array $options
2159 * @return coursecat_helper
2161 public function set_courses_display_options($options) {
2162 $this->coursesdisplayoptions = $options;
2163 $this->set_show_courses($this->showcourses); // this will calculate special display options
2164 return $this;
2168 * Sets one option to display list of courses
2170 * @see coursecat_helper::set_courses_display_options()
2172 * @param string $key
2173 * @param mixed $value
2174 * @return coursecat_helper
2176 public function set_courses_display_option($key, $value) {
2177 $this->coursesdisplayoptions[$key] = $value;
2178 return $this;
2182 * Return the specified option to display list of courses
2184 * @param string $optionname option name
2185 * @param mixed $defaultvalue default value for option if it is not specified
2186 * @return mixed
2188 public function get_courses_display_option($optionname, $defaultvalue = null) {
2189 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2190 return $this->coursesdisplayoptions[$optionname];
2191 } else {
2192 return $defaultvalue;
2197 * Returns all options to display the courses
2199 * This array is usually passed to {@link coursecat::get_courses()} or
2200 * {@link coursecat::search_courses()}
2202 * @return array
2204 public function get_courses_display_options() {
2205 return $this->coursesdisplayoptions;
2209 * Sets options to display list of subcategories
2211 * Options 'sort', 'offset' and 'limit' are passed to coursecat::get_children().
2212 * Any other options may be used by renderer functions
2214 * @param array $options
2215 * @return coursecat_helper
2217 public function set_categories_display_options($options) {
2218 $this->categoriesdisplayoptions = $options;
2219 return $this;
2223 * Return the specified option to display list of subcategories
2225 * @param string $optionname option name
2226 * @param mixed $defaultvalue default value for option if it is not specified
2227 * @return mixed
2229 public function get_categories_display_option($optionname, $defaultvalue = null) {
2230 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2231 return $this->categoriesdisplayoptions[$optionname];
2232 } else {
2233 return $defaultvalue;
2238 * Returns all options to display list of subcategories
2240 * This array is usually passed to {@link coursecat::get_children()}
2242 * @return array
2244 public function get_categories_display_options() {
2245 return $this->categoriesdisplayoptions;
2249 * Sets additional general options to pass between renderer functions, usually HTML attributes
2251 * @param array $attributes
2252 * @return coursecat_helper
2254 public function set_attributes($attributes) {
2255 $this->attributes = $attributes;
2256 return $this;
2260 * Return all attributes and erases them so they are not applied again
2262 * @param string $classname adds additional class name to the beginning of $attributes['class']
2263 * @return array
2265 public function get_and_erase_attributes($classname) {
2266 $attributes = $this->attributes;
2267 $this->attributes = array();
2268 if (empty($attributes['class'])) {
2269 $attributes['class'] = '';
2271 $attributes['class'] = $classname . ' '. $attributes['class'];
2272 return $attributes;
2276 * Sets the search criteria if the course is a search result
2278 * Search string will be used to highlight terms in course name and description
2280 * @param array $searchcriteria
2281 * @return coursecat_helper
2283 public function set_search_criteria($searchcriteria) {
2284 $this->searchcriteria = $searchcriteria;
2285 return $this;
2289 * Returns formatted and filtered description of the given category
2291 * @param coursecat $coursecat category
2292 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2293 * if context is not specified it will be added automatically
2294 * @return string|null
2296 public function get_category_formatted_description($coursecat, $options = null) {
2297 if ($coursecat->id && !empty($coursecat->description)) {
2298 if (!isset($coursecat->descriptionformat)) {
2299 $descriptionformat = FORMAT_MOODLE;
2300 } else {
2301 $descriptionformat = $coursecat->descriptionformat;
2303 if ($options === null) {
2304 $options = array('noclean' => true, 'overflowdiv' => true);
2305 } else {
2306 $options = (array)$options;
2308 $context = context_coursecat::instance($coursecat->id);
2309 if (!isset($options['context'])) {
2310 $options['context'] = $context;
2312 $text = file_rewrite_pluginfile_urls($coursecat->description,
2313 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2314 return format_text($text, $descriptionformat, $options);
2316 return null;
2320 * Returns given course's summary with proper embedded files urls and formatted
2322 * @param course_in_list $course
2323 * @param array|stdClass $options additional formatting options
2324 * @return string
2326 public function get_course_formatted_summary($course, $options = array()) {
2327 global $CFG;
2328 require_once($CFG->libdir. '/filelib.php');
2329 if (!$course->has_summary()) {
2330 return '';
2332 $options = (array)$options;
2333 $context = context_course::instance($course->id);
2334 if (!isset($options['context'])) {
2335 // TODO see MDL-38521
2336 // option 1 (current), page context - no code required
2337 // option 2, system context
2338 // $options['context'] = context_system::instance();
2339 // option 3, course context:
2340 // $options['context'] = $context;
2341 // option 4, course category context:
2342 // $options['context'] = $context->get_parent_context();
2344 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2345 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2346 if (!empty($this->searchcriteria['search'])) {
2347 $summary = highlight($this->searchcriteria['search'], $summary);
2349 return $summary;
2353 * Returns course name as it is configured to appear in courses lists formatted to course context
2355 * @param course_in_list $course
2356 * @param array|stdClass $options additional formatting options
2357 * @return string
2359 public function get_course_formatted_name($course, $options = array()) {
2360 $options = (array)$options;
2361 if (!isset($options['context'])) {
2362 $options['context'] = context_course::instance($course->id);
2364 $name = format_string(get_course_display_name_for_list($course), true, $options);
2365 if (!empty($this->searchcriteria['search'])) {
2366 $name = highlight($this->searchcriteria['search'], $name);
2368 return $name;