Merge branch 'MDL-61296-master' of git://github.com/cescobedo/moodle
[moodle.git] / course / renderer.php
blobb78acb6d38c08d70bab580e98935f1096465cefe
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 * Whether a category content is being initially rendered with children. This is mainly used by the
54 * core_course_renderer::corsecat_tree() to render the appropriate action for the Expand/Collapse all link on
55 * page load.
56 * @var bool
58 protected $categoryexpandedonload = false;
60 /**
61 * Override the constructor so that we can initialise the string cache
63 * @param moodle_page $page
64 * @param string $target
66 public function __construct(moodle_page $page, $target) {
67 $this->strings = new stdClass;
68 parent::__construct($page, $target);
71 /**
72 * Adds the item in course settings navigation to toggle modchooser
74 * Theme can overwrite as an empty function to exclude it (for example if theme does not
75 * use modchooser at all)
77 * @deprecated since 3.2
79 protected function add_modchoosertoggle() {
80 debugging('core_course_renderer::add_modchoosertoggle() is deprecated.', DEBUG_DEVELOPER);
82 global $CFG;
84 // Only needs to be done once per page.
85 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchoosertoggle')) {
86 return;
89 if ($this->page->state > moodle_page::STATE_PRINTING_HEADER ||
90 $this->page->course->id == SITEID ||
91 !$this->page->user_is_editing() ||
92 !($context = context_course::instance($this->page->course->id)) ||
93 !has_capability('moodle/course:manageactivities', $context) ||
94 !course_ajax_enabled($this->page->course) ||
95 !($coursenode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE)) ||
96 !($turneditingnode = $coursenode->get('turneditingonoff'))) {
97 // Too late, or we are on site page, or we could not find the
98 // adjacent nodes in course settings menu, or we are not allowed to edit.
99 return;
102 if ($this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
103 // We are on the course page, retain the current page params e.g. section.
104 $modchoosertoggleurl = clone($this->page->url);
105 } else {
106 // Edit on the main course page.
107 $modchoosertoggleurl = new moodle_url('/course/view.php', array('id' => $this->page->course->id,
108 'return' => $this->page->url->out_as_local_url(false)));
110 $modchoosertoggleurl->param('sesskey', sesskey());
111 if ($usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault)) {
112 $modchoosertogglestring = get_string('modchooserdisable', 'moodle');
113 $modchoosertoggleurl->param('modchooser', 'off');
114 } else {
115 $modchoosertogglestring = get_string('modchooserenable', 'moodle');
116 $modchoosertoggleurl->param('modchooser', 'on');
118 $modchoosertoggle = navigation_node::create($modchoosertogglestring, $modchoosertoggleurl, navigation_node::TYPE_SETTING, null, 'modchoosertoggle');
120 // Insert the modchoosertoggle after the settings node 'turneditingonoff' (navigation_node only has function to insert before, so we insert before and then swap).
121 $coursenode->add_node($modchoosertoggle, 'turneditingonoff');
122 $turneditingnode->remove();
123 $coursenode->add_node($turneditingnode, 'modchoosertoggle');
125 $modchoosertoggle->add_class('modchoosertoggle');
126 $modchoosertoggle->add_class('visibleifjs');
127 user_preference_allow_ajax_update('usemodchooser', PARAM_BOOL);
131 * Renders course info box.
133 * @param stdClass|course_in_list $course
134 * @return string
136 public function course_info_box(stdClass $course) {
137 $content = '';
138 $content .= $this->output->box_start('generalbox info');
139 $chelper = new coursecat_helper();
140 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
141 $content .= $this->coursecat_coursebox($chelper, $course);
142 $content .= $this->output->box_end();
143 return $content;
147 * Renderers a structured array of courses and categories into a nice XHTML tree structure.
149 * @deprecated since 2.5
151 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
153 * @param array $ignored argument ignored
154 * @return string
156 public final function course_category_tree(array $ignored) {
157 debugging('Function core_course_renderer::course_category_tree() is deprecated, please use frontpage_combo_list()', DEBUG_DEVELOPER);
158 return $this->frontpage_combo_list();
162 * Renderers a category for use with course_category_tree
164 * @deprecated since 2.5
166 * Please see http://docs.moodle.org/dev/Courses_lists_upgrade_to_2.5
168 * @param array $category
169 * @param int $depth
170 * @return string
172 protected final function course_category_tree_category(stdClass $category, $depth=1) {
173 debugging('Function core_course_renderer::course_category_tree_category() is deprecated', DEBUG_DEVELOPER);
174 return '';
178 * Render a modchooser.
180 * @param renderable $modchooser The chooser.
181 * @return string
183 public function render_modchooser(renderable $modchooser) {
184 return $this->render_from_template('core_course/modchooser', $modchooser->export_for_template($this));
188 * Build the HTML for the module chooser javascript popup
190 * @param array $modules A set of modules as returned form @see
191 * get_module_metadata
192 * @param object $course The course that will be displayed
193 * @return string The composed HTML for the module
195 public function course_modchooser($modules, $course) {
196 if (!$this->page->requires->should_create_one_time_item_now('core_course_modchooser')) {
197 return '';
199 $modchooser = new \core_course\output\modchooser($course, $modules);
200 return $this->render($modchooser);
204 * Build the HTML for a specified set of modules
206 * @param array $modules A set of modules as used by the
207 * course_modchooser_module function
208 * @return string The composed HTML for the module
210 protected function course_modchooser_module_types($modules) {
211 debugging('Method core_course_renderer::course_modchooser_module_types() is deprecated, ' .
212 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
213 return '';
217 * Return the HTML for the specified module adding any required classes
219 * @param object $module An object containing the title, and link. An
220 * icon, and help text may optionally be specified. If the module
221 * contains subtypes in the types option, then these will also be
222 * displayed.
223 * @param array $classes Additional classes to add to the encompassing
224 * div element
225 * @return string The composed HTML for the module
227 protected function course_modchooser_module($module, $classes = array('option')) {
228 debugging('Method core_course_renderer::course_modchooser_module() is deprecated, ' .
229 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
230 return '';
233 protected function course_modchooser_title($title, $identifier = null) {
234 debugging('Method core_course_renderer::course_modchooser_title() is deprecated, ' .
235 'see core_course_renderer::render_modchooser().', DEBUG_DEVELOPER);
236 return '';
240 * Renders HTML for displaying the sequence of course module editing buttons
242 * @see course_get_cm_edit_actions()
244 * @param action_link[] $actions Array of action_link objects
245 * @param cm_info $mod The module we are displaying actions for.
246 * @param array $displayoptions additional display options:
247 * ownerselector => A JS/CSS selector that can be used to find an cm node.
248 * If specified the owning node will be given the class 'action-menu-shown' when the action
249 * menu is being displayed.
250 * constraintselector => A JS/CSS selector that can be used to find the parent node for which to constrain
251 * the action menu to when it is being displayed.
252 * donotenhance => If set to true the action menu that gets displayed won't be enhanced by JS.
253 * @return string
255 public function course_section_cm_edit_actions($actions, cm_info $mod = null, $displayoptions = array()) {
256 global $CFG;
258 if (empty($actions)) {
259 return '';
262 if (isset($displayoptions['ownerselector'])) {
263 $ownerselector = $displayoptions['ownerselector'];
264 } else if ($mod) {
265 $ownerselector = '#module-'.$mod->id;
266 } else {
267 debugging('You should upgrade your call to '.__FUNCTION__.' and provide $mod', DEBUG_DEVELOPER);
268 $ownerselector = 'li.activity';
271 if (isset($displayoptions['constraintselector'])) {
272 $constraint = $displayoptions['constraintselector'];
273 } else {
274 $constraint = '.course-content';
277 $menu = new action_menu();
278 $menu->set_owner_selector($ownerselector);
279 $menu->set_constraint($constraint);
280 $menu->set_alignment(action_menu::TR, action_menu::BR);
281 $menu->set_menu_trigger(get_string('edit'));
283 foreach ($actions as $action) {
284 if ($action instanceof action_menu_link) {
285 $action->add_class('cm-edit-action');
287 $menu->add($action);
289 $menu->attributes['class'] .= ' section-cm-edit-actions commands';
291 // Prioritise the menu ahead of all other actions.
292 $menu->prioritise = true;
294 return $this->render($menu);
298 * Renders HTML for the menus to add activities and resources to the current course
300 * @param stdClass $course
301 * @param int $section relative section number (field course_sections.section)
302 * @param int $sectionreturn The section to link back to
303 * @param array $displayoptions additional display options, for example blocks add
304 * option 'inblock' => true, suggesting to display controls vertically
305 * @return string
307 function course_section_add_cm_control($course, $section, $sectionreturn = null, $displayoptions = array()) {
308 global $CFG;
310 $vertical = !empty($displayoptions['inblock']);
312 // check to see if user can add menus and there are modules to add
313 if (!has_capability('moodle/course:manageactivities', context_course::instance($course->id))
314 || !$this->page->user_is_editing()
315 || !($modnames = get_module_types_names()) || empty($modnames)) {
316 return '';
319 // Retrieve all modules with associated metadata
320 $modules = get_module_metadata($course, $modnames, $sectionreturn);
321 $urlparams = array('section' => $section);
323 // We'll sort resources and activities into two lists
324 $activities = array(MOD_CLASS_ACTIVITY => array(), MOD_CLASS_RESOURCE => array());
326 foreach ($modules as $module) {
327 $activityclass = MOD_CLASS_ACTIVITY;
328 if ($module->archetype == MOD_ARCHETYPE_RESOURCE) {
329 $activityclass = MOD_CLASS_RESOURCE;
330 } else if ($module->archetype === MOD_ARCHETYPE_SYSTEM) {
331 // System modules cannot be added by user, do not add to dropdown.
332 continue;
334 $link = $module->link->out(true, $urlparams);
335 $activities[$activityclass][$link] = $module->title;
338 $straddactivity = get_string('addactivity');
339 $straddresource = get_string('addresource');
340 $sectionname = get_section_name($course, $section);
341 $strresourcelabel = get_string('addresourcetosection', null, $sectionname);
342 $stractivitylabel = get_string('addactivitytosection', null, $sectionname);
344 $output = html_writer::start_tag('div', array('class' => 'section_add_menus', 'id' => 'add_menus-section-' . $section));
346 if (!$vertical) {
347 $output .= html_writer::start_tag('div', array('class' => 'horizontal'));
350 if (!empty($activities[MOD_CLASS_RESOURCE])) {
351 $select = new url_select($activities[MOD_CLASS_RESOURCE], '', array(''=>$straddresource), "ressection$section");
352 $select->set_help_icon('resources');
353 $select->set_label($strresourcelabel, array('class' => 'accesshide'));
354 $output .= $this->output->render($select);
357 if (!empty($activities[MOD_CLASS_ACTIVITY])) {
358 $select = new url_select($activities[MOD_CLASS_ACTIVITY], '', array(''=>$straddactivity), "section$section");
359 $select->set_help_icon('activities');
360 $select->set_label($stractivitylabel, array('class' => 'accesshide'));
361 $output .= $this->output->render($select);
364 if (!$vertical) {
365 $output .= html_writer::end_tag('div');
368 $output .= html_writer::end_tag('div');
370 if (course_ajax_enabled($course) && $course->id == $this->page->course->id) {
371 // modchooser can be added only for the current course set on the page!
372 $straddeither = get_string('addresourceoractivity');
373 // The module chooser link
374 $modchooser = html_writer::start_tag('div', array('class' => 'mdl-right'));
375 $modchooser.= html_writer::start_tag('div', array('class' => 'section-modchooser'));
376 $icon = $this->output->pix_icon('t/add', '');
377 $span = html_writer::tag('span', $straddeither, array('class' => 'section-modchooser-text'));
378 $modchooser .= html_writer::tag('span', $icon . $span, array('class' => 'section-modchooser-link'));
379 $modchooser.= html_writer::end_tag('div');
380 $modchooser.= html_writer::end_tag('div');
382 // Wrap the normal output in a noscript div
383 $usemodchooser = get_user_preferences('usemodchooser', $CFG->modchooserdefault);
384 if ($usemodchooser) {
385 $output = html_writer::tag('div', $output, array('class' => 'hiddenifjs addresourcedropdown'));
386 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'visibleifjs addresourcemodchooser'));
387 } else {
388 // If the module chooser is disabled, we need to ensure that the dropdowns are shown even if javascript is disabled
389 $output = html_writer::tag('div', $output, array('class' => 'show addresourcedropdown'));
390 $modchooser = html_writer::tag('div', $modchooser, array('class' => 'hide addresourcemodchooser'));
392 $output = $this->course_modchooser($modules, $course) . $modchooser . $output;
395 return $output;
399 * Renders html to display a course search form
401 * @param string $value default value to populate the search field
402 * @param string $format display format - 'plain' (default), 'short' or 'navbar'
403 * @return string
405 function course_search_form($value = '', $format = 'plain') {
406 static $count = 0;
407 $formid = 'coursesearch';
408 if ((++$count) > 1) {
409 $formid .= $count;
412 switch ($format) {
413 case 'navbar' :
414 $formid = 'coursesearchnavbar';
415 $inputid = 'navsearchbox';
416 $inputsize = 20;
417 break;
418 case 'short' :
419 $inputid = 'shortsearchbox';
420 $inputsize = 12;
421 break;
422 default :
423 $inputid = 'coursesearchbox';
424 $inputsize = 30;
427 $strsearchcourses= get_string("searchcourses");
428 $searchurl = new moodle_url('/course/search.php');
430 $output = html_writer::start_tag('form', array('id' => $formid, 'action' => $searchurl, 'method' => 'get'));
431 $output .= html_writer::start_tag('fieldset', array('class' => 'coursesearchbox invisiblefieldset'));
432 $output .= html_writer::tag('label', $strsearchcourses.': ', array('for' => $inputid));
433 $output .= html_writer::empty_tag('input', array('type' => 'text', 'id' => $inputid,
434 'size' => $inputsize, 'name' => 'search', 'value' => s($value)));
435 $output .= html_writer::empty_tag('input', array('type' => 'submit',
436 'value' => get_string('go')));
437 $output .= html_writer::end_tag('fieldset');
438 $output .= html_writer::end_tag('form');
440 return $output;
444 * Renders html for completion box on course page
446 * If completion is disabled, returns empty string
447 * If completion is automatic, returns an icon of the current completion state
448 * If completion is manual, returns a form (with an icon inside) that allows user to
449 * toggle completion
451 * @param stdClass $course course object
452 * @param completion_info $completioninfo completion info for the course, it is recommended
453 * to fetch once for all modules in course/section for performance
454 * @param cm_info $mod module to show completion for
455 * @param array $displayoptions display options, not used in core
456 * @return string
458 public function course_section_cm_completion($course, &$completioninfo, cm_info $mod, $displayoptions = array()) {
459 global $CFG, $DB;
460 $output = '';
461 if (!empty($displayoptions['hidecompletion']) || !isloggedin() || isguestuser() || !$mod->uservisible) {
462 return $output;
464 if ($completioninfo === null) {
465 $completioninfo = new completion_info($course);
467 $completion = $completioninfo->is_enabled($mod);
468 if ($completion == COMPLETION_TRACKING_NONE) {
469 if ($this->page->user_is_editing()) {
470 $output .= html_writer::span('&nbsp;', 'filler');
472 return $output;
475 $completiondata = $completioninfo->get_data($mod, true);
476 $completionicon = '';
478 if ($this->page->user_is_editing()) {
479 switch ($completion) {
480 case COMPLETION_TRACKING_MANUAL :
481 $completionicon = 'manual-enabled'; break;
482 case COMPLETION_TRACKING_AUTOMATIC :
483 $completionicon = 'auto-enabled'; break;
485 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
486 switch($completiondata->completionstate) {
487 case COMPLETION_INCOMPLETE:
488 $completionicon = 'manual-n' . ($completiondata->overrideby ? '-override' : '');
489 break;
490 case COMPLETION_COMPLETE:
491 $completionicon = 'manual-y' . ($completiondata->overrideby ? '-override' : '');
492 break;
494 } else { // Automatic
495 switch($completiondata->completionstate) {
496 case COMPLETION_INCOMPLETE:
497 $completionicon = 'auto-n' . ($completiondata->overrideby ? '-override' : '');
498 break;
499 case COMPLETION_COMPLETE:
500 $completionicon = 'auto-y' . ($completiondata->overrideby ? '-override' : '');
501 break;
502 case COMPLETION_COMPLETE_PASS:
503 $completionicon = 'auto-pass'; break;
504 case COMPLETION_COMPLETE_FAIL:
505 $completionicon = 'auto-fail'; break;
508 if ($completionicon) {
509 $formattedname = $mod->get_formatted_name();
510 if ($completiondata->overrideby) {
511 $args = new stdClass();
512 $args->modname = $formattedname;
513 $overridebyuser = \core_user::get_user($completiondata->overrideby, '*', MUST_EXIST);
514 $args->overrideuser = fullname($overridebyuser);
515 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $args);
516 } else {
517 $imgalt = get_string('completion-alt-' . $completionicon, 'completion', $formattedname);
520 if ($this->page->user_is_editing()) {
521 // When editing, the icon is just an image.
522 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
523 array('title' => $imgalt, 'class' => 'iconsmall'));
524 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
525 array('class' => 'autocompletion'));
526 } else if ($completion == COMPLETION_TRACKING_MANUAL) {
527 $newstate =
528 $completiondata->completionstate == COMPLETION_COMPLETE
529 ? COMPLETION_INCOMPLETE
530 : COMPLETION_COMPLETE;
531 // In manual mode the icon is a toggle form...
533 // If this completion state is used by the
534 // conditional activities system, we need to turn
535 // off the JS.
536 $extraclass = '';
537 if (!empty($CFG->enableavailability) &&
538 core_availability\info::completion_value_used($course, $mod->id)) {
539 $extraclass = ' preventjs';
541 $output .= html_writer::start_tag('form', array('method' => 'post',
542 'action' => new moodle_url('/course/togglecompletion.php'),
543 'class' => 'togglecompletion'. $extraclass));
544 $output .= html_writer::start_tag('div');
545 $output .= html_writer::empty_tag('input', array(
546 'type' => 'hidden', 'name' => 'id', 'value' => $mod->id));
547 $output .= html_writer::empty_tag('input', array(
548 'type' => 'hidden', 'name' => 'sesskey', 'value' => sesskey()));
549 $output .= html_writer::empty_tag('input', array(
550 'type' => 'hidden', 'name' => 'modulename', 'value' => $mod->name));
551 $output .= html_writer::empty_tag('input', array(
552 'type' => 'hidden', 'name' => 'completionstate', 'value' => $newstate));
553 $output .= html_writer::tag('button',
554 $this->output->pix_icon('i/completion-' . $completionicon, $imgalt),
555 array('class' => 'btn btn-link', 'title' => $imgalt));
556 $output .= html_writer::end_tag('div');
557 $output .= html_writer::end_tag('form');
558 } else {
559 // In auto mode, the icon is just an image.
560 $completionpixicon = new pix_icon('i/completion-'.$completionicon, $imgalt, '',
561 array('title' => $imgalt));
562 $output .= html_writer::tag('span', $this->output->render($completionpixicon),
563 array('class' => 'autocompletion'));
566 return $output;
570 * Checks if course module has any conditions that may make it unavailable for
571 * all or some of the students
573 * This function is internal and is only used to create CSS classes for the module name/text
575 * @param cm_info $mod
576 * @return bool
578 protected function is_cm_conditionally_hidden(cm_info $mod) {
579 global $CFG;
580 $conditionalhidden = false;
581 if (!empty($CFG->enableavailability)) {
582 $info = new \core_availability\info_module($mod);
583 $conditionalhidden = !$info->is_available_for_all();
585 return $conditionalhidden;
589 * Renders html to display a name with the link to the course module on a course page
591 * If module is unavailable for user but still needs to be displayed
592 * in the list, just the name is returned without a link
594 * Note, that for course modules that never have separate pages (i.e. labels)
595 * this function return an empty string
597 * @param cm_info $mod
598 * @param array $displayoptions
599 * @return string
601 public function course_section_cm_name(cm_info $mod, $displayoptions = array()) {
602 if (!$mod->is_visible_on_course_page() || !$mod->url) {
603 // Nothing to be displayed to the user.
604 return '';
607 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
608 $groupinglabel = $mod->get_grouping_label($textclasses);
610 // Render element that allows to edit activity name inline. It calls {@link course_section_cm_name_title()}
611 // to get the display title of the activity.
612 $tmpl = new \core_course\output\course_module_name($mod, $this->page->user_is_editing(), $displayoptions);
613 return $this->output->render_from_template('core/inplace_editable', $tmpl->export_for_template($this->output)) .
614 $groupinglabel;
618 * Returns the CSS classes for the activity name/content
620 * For items which are hidden, unavailable or stealth but should be displayed
621 * to current user ($mod->is_visible_on_course_page()), we show those as dimmed.
622 * Students will also see as dimmed activities names that are not yet available
623 * but should still be displayed (without link) with availability info.
625 * @param cm_info $mod
626 * @return array array of two elements ($linkclasses, $textclasses)
628 protected function course_section_cm_classes(cm_info $mod) {
629 $linkclasses = '';
630 $textclasses = '';
631 if ($mod->uservisible) {
632 $conditionalhidden = $this->is_cm_conditionally_hidden($mod);
633 $accessiblebutdim = (!$mod->visible || $conditionalhidden) &&
634 has_capability('moodle/course:viewhiddenactivities', $mod->context);
635 if ($accessiblebutdim) {
636 $linkclasses .= ' dimmed';
637 $textclasses .= ' dimmed_text';
638 if ($conditionalhidden) {
639 $linkclasses .= ' conditionalhidden';
640 $textclasses .= ' conditionalhidden';
643 if ($mod->is_stealth()) {
644 // Stealth activity is the one that is not visible on course page.
645 // It still may be displayed to the users who can manage it.
646 $linkclasses .= ' stealth';
647 $textclasses .= ' stealth';
649 } else {
650 $linkclasses .= ' dimmed';
651 $textclasses .= ' dimmed dimmed_text';
653 return array($linkclasses, $textclasses);
657 * Renders html to display a name with the link to the course module on a course page
659 * If module is unavailable for user but still needs to be displayed
660 * in the list, just the name is returned without a link
662 * Note, that for course modules that never have separate pages (i.e. labels)
663 * this function return an empty string
665 * @param cm_info $mod
666 * @param array $displayoptions
667 * @return string
669 public function course_section_cm_name_title(cm_info $mod, $displayoptions = array()) {
670 $output = '';
671 $url = $mod->url;
672 if (!$mod->is_visible_on_course_page() || !$url) {
673 // Nothing to be displayed to the user.
674 return $output;
677 //Accessibility: for files get description via icon, this is very ugly hack!
678 $instancename = $mod->get_formatted_name();
679 $altname = $mod->modfullname;
680 // Avoid unnecessary duplication: if e.g. a forum name already
681 // includes the word forum (or Forum, etc) then it is unhelpful
682 // to include that in the accessible description that is added.
683 if (false !== strpos(core_text::strtolower($instancename),
684 core_text::strtolower($altname))) {
685 $altname = '';
687 // File type after name, for alphabetic lists (screen reader).
688 if ($altname) {
689 $altname = get_accesshide(' '.$altname);
692 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
694 // Get on-click attribute value if specified and decode the onclick - it
695 // has already been encoded for display (puke).
696 $onclick = htmlspecialchars_decode($mod->onclick, ENT_QUOTES);
698 // Display link itself.
699 $activitylink = html_writer::empty_tag('img', array('src' => $mod->get_icon_url(),
700 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
701 html_writer::tag('span', $instancename . $altname, array('class' => 'instancename'));
702 if ($mod->uservisible) {
703 $output .= html_writer::link($url, $activitylink, array('class' => $linkclasses, 'onclick' => $onclick));
704 } else {
705 // We may be displaying this just in order to show information
706 // about visibility, without the actual link ($mod->is_visible_on_course_page()).
707 $output .= html_writer::tag('div', $activitylink, array('class' => $textclasses));
709 return $output;
713 * Renders html to display the module content on the course page (i.e. text of the labels)
715 * @param cm_info $mod
716 * @param array $displayoptions
717 * @return string
719 public function course_section_cm_text(cm_info $mod, $displayoptions = array()) {
720 $output = '';
721 if (!$mod->is_visible_on_course_page()) {
722 // nothing to be displayed to the user
723 return $output;
725 $content = $mod->get_formatted_content(array('overflowdiv' => true, 'noclean' => true));
726 list($linkclasses, $textclasses) = $this->course_section_cm_classes($mod);
727 if ($mod->url && $mod->uservisible) {
728 if ($content) {
729 // If specified, display extra content after link.
730 $output = html_writer::tag('div', $content, array('class' =>
731 trim('contentafterlink ' . $textclasses)));
733 } else {
734 $groupinglabel = $mod->get_grouping_label($textclasses);
736 // No link, so display only content.
737 $output = html_writer::tag('div', $content . $groupinglabel,
738 array('class' => 'contentwithoutlink ' . $textclasses));
740 return $output;
744 * Displays availability info for a course section or course module
746 * @param string $text
747 * @param string $additionalclasses
748 * @return string
750 public function availability_info($text, $additionalclasses = '') {
752 $data = ['text' => $text, 'classes' => $additionalclasses];
753 $additionalclasses = array_filter(explode(' ', $additionalclasses));
755 if (in_array('ishidden', $additionalclasses)) {
756 $data['ishidden'] = 1;
758 } else if (in_array('isstealth', $additionalclasses)) {
759 $data['isstealth'] = 1;
761 } else if (in_array('isrestricted', $additionalclasses)) {
762 $data['isrestricted'] = 1;
764 if (in_array('isfullinfo', $additionalclasses)) {
765 $data['isfullinfo'] = 1;
769 return $this->render_from_template('core/availability_info', $data);
773 * Renders HTML to show course module availability information (for someone who isn't allowed
774 * to see the activity itself, or for staff)
776 * @param cm_info $mod
777 * @param array $displayoptions
778 * @return string
780 public function course_section_cm_availability(cm_info $mod, $displayoptions = array()) {
781 global $CFG;
782 $output = '';
783 if (!$mod->is_visible_on_course_page()) {
784 return $output;
786 if (!$mod->uservisible) {
787 // this is a student who is not allowed to see the module but might be allowed
788 // to see availability info (i.e. "Available from ...")
789 if (!empty($mod->availableinfo)) {
790 $formattedinfo = \core_availability\info::format_info(
791 $mod->availableinfo, $mod->get_course());
792 $output = $this->availability_info($formattedinfo, 'isrestricted');
794 return $output;
796 // this is a teacher who is allowed to see module but still should see the
797 // information that module is not available to all/some students
798 $modcontext = context_module::instance($mod->id);
799 $canviewhidden = has_capability('moodle/course:viewhiddenactivities', $modcontext);
800 if ($canviewhidden && !$mod->visible) {
801 // This module is hidden but current user has capability to see it.
802 // Do not display the availability info if the whole section is hidden.
803 if ($mod->get_section_info()->visible) {
804 $output .= $this->availability_info(get_string('hiddenfromstudents'), 'ishidden');
806 } else if ($mod->is_stealth()) {
807 // This module is available but is normally not displayed on the course page
808 // (this user can see it because they can manage it).
809 $output .= $this->availability_info(get_string('hiddenoncoursepage'), 'isstealth');
811 if ($canviewhidden && !empty($CFG->enableavailability)) {
812 // Display information about conditional availability.
813 // Don't add availability information if user is not editing and activity is hidden.
814 if ($mod->visible || $this->page->user_is_editing()) {
815 $hidinfoclass = 'isrestricted isfullinfo';
816 if (!$mod->visible) {
817 $hidinfoclass .= ' hide';
819 $ci = new \core_availability\info_module($mod);
820 $fullinfo = $ci->get_full_information();
821 if ($fullinfo) {
822 $formattedinfo = \core_availability\info::format_info(
823 $fullinfo, $mod->get_course());
824 $output .= $this->availability_info($formattedinfo, $hidinfoclass);
828 return $output;
832 * Renders HTML to display one course module for display within a section.
834 * This function calls:
835 * {@link core_course_renderer::course_section_cm()}
837 * @param stdClass $course
838 * @param completion_info $completioninfo
839 * @param cm_info $mod
840 * @param int|null $sectionreturn
841 * @param array $displayoptions
842 * @return String
844 public function course_section_cm_list_item($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
845 $output = '';
846 if ($modulehtml = $this->course_section_cm($course, $completioninfo, $mod, $sectionreturn, $displayoptions)) {
847 $modclasses = 'activity ' . $mod->modname . ' modtype_' . $mod->modname . ' ' . $mod->extraclasses;
848 $output .= html_writer::tag('li', $modulehtml, array('class' => $modclasses, 'id' => 'module-' . $mod->id));
850 return $output;
854 * Renders HTML to display one course module in a course section
856 * This includes link, content, availability, completion info and additional information
857 * that module type wants to display (i.e. number of unread forum posts)
859 * This function calls:
860 * {@link core_course_renderer::course_section_cm_name()}
861 * {@link core_course_renderer::course_section_cm_text()}
862 * {@link core_course_renderer::course_section_cm_availability()}
863 * {@link core_course_renderer::course_section_cm_completion()}
864 * {@link course_get_cm_edit_actions()}
865 * {@link core_course_renderer::course_section_cm_edit_actions()}
867 * @param stdClass $course
868 * @param completion_info $completioninfo
869 * @param cm_info $mod
870 * @param int|null $sectionreturn
871 * @param array $displayoptions
872 * @return string
874 public function course_section_cm($course, &$completioninfo, cm_info $mod, $sectionreturn, $displayoptions = array()) {
875 $output = '';
876 // We return empty string (because course module will not be displayed at all)
877 // if:
878 // 1) The activity is not visible to users
879 // and
880 // 2) The 'availableinfo' is empty, i.e. the activity was
881 // hidden in a way that leaves no info, such as using the
882 // eye icon.
883 if (!$mod->is_visible_on_course_page()) {
884 return $output;
887 $indentclasses = 'mod-indent';
888 if (!empty($mod->indent)) {
889 $indentclasses .= ' mod-indent-'.$mod->indent;
890 if ($mod->indent > 15) {
891 $indentclasses .= ' mod-indent-huge';
895 $output .= html_writer::start_tag('div');
897 if ($this->page->user_is_editing()) {
898 $output .= course_get_cm_move($mod, $sectionreturn);
901 $output .= html_writer::start_tag('div', array('class' => 'mod-indent-outer'));
903 // This div is used to indent the content.
904 $output .= html_writer::div('', $indentclasses);
906 // Start a wrapper for the actual content to keep the indentation consistent
907 $output .= html_writer::start_tag('div');
909 // Display the link to the module (or do nothing if module has no url)
910 $cmname = $this->course_section_cm_name($mod, $displayoptions);
912 if (!empty($cmname)) {
913 // Start the div for the activity title, excluding the edit icons.
914 $output .= html_writer::start_tag('div', array('class' => 'activityinstance'));
915 $output .= $cmname;
918 // Module can put text after the link (e.g. forum unread)
919 $output .= $mod->afterlink;
921 // Closing the tag which contains everything but edit icons. Content part of the module should not be part of this.
922 $output .= html_writer::end_tag('div'); // .activityinstance
925 // If there is content but NO link (eg label), then display the
926 // content here (BEFORE any icons). In this case cons must be
927 // displayed after the content so that it makes more sense visually
928 // and for accessibility reasons, e.g. if you have a one-line label
929 // it should work similarly (at least in terms of ordering) to an
930 // activity.
931 $contentpart = $this->course_section_cm_text($mod, $displayoptions);
932 $url = $mod->url;
933 if (empty($url)) {
934 $output .= $contentpart;
937 $modicons = '';
938 if ($this->page->user_is_editing()) {
939 $editactions = course_get_cm_edit_actions($mod, $mod->indent, $sectionreturn);
940 $modicons .= ' '. $this->course_section_cm_edit_actions($editactions, $mod, $displayoptions);
941 $modicons .= $mod->afterediticons;
944 $modicons .= $this->course_section_cm_completion($course, $completioninfo, $mod, $displayoptions);
946 if (!empty($modicons)) {
947 $output .= html_writer::span($modicons, 'actions');
950 // Show availability info (if module is not available).
951 $output .= $this->course_section_cm_availability($mod, $displayoptions);
953 // If there is content AND a link, then display the content here
954 // (AFTER any icons). Otherwise it was displayed before
955 if (!empty($url)) {
956 $output .= $contentpart;
959 $output .= html_writer::end_tag('div'); // $indentclasses
961 // End of indentation div.
962 $output .= html_writer::end_tag('div');
964 $output .= html_writer::end_tag('div');
965 return $output;
969 * Message displayed to the user when they try to access unavailable activity following URL
971 * This method is a very simplified version of {@link course_section_cm()} to be part of the error
972 * notification only. It also does not check if module is visible on course page or not.
974 * The message will be displayed inside notification!
976 * @param cm_info $cm
977 * @return string
979 public function course_section_cm_unavailable_error_message(cm_info $cm) {
980 if ($cm->uservisible) {
981 return null;
983 if (!$cm->availableinfo) {
984 return get_string('activityiscurrentlyhidden');
987 $altname = get_accesshide(' ' . $cm->modfullname);
988 $name = html_writer::empty_tag('img', array('src' => $cm->get_icon_url(),
989 'class' => 'iconlarge activityicon', 'alt' => ' ', 'role' => 'presentation')) .
990 html_writer::tag('span', ' '.$cm->get_formatted_name() . $altname, array('class' => 'instancename'));
991 $formattedinfo = \core_availability\info::format_info($cm->availableinfo, $cm->get_course());
992 return html_writer::div($name, 'activityinstance-error') .
993 html_writer::div($formattedinfo, 'availabilityinfo-error');
997 * Renders HTML to display a list of course modules in a course section
998 * Also displays "move here" controls in Javascript-disabled mode
1000 * This function calls {@link core_course_renderer::course_section_cm()}
1002 * @param stdClass $course course object
1003 * @param int|stdClass|section_info $section relative section number or section object
1004 * @param int $sectionreturn section number to return to
1005 * @param int $displayoptions
1006 * @return void
1008 public function course_section_cm_list($course, $section, $sectionreturn = null, $displayoptions = array()) {
1009 global $USER;
1011 $output = '';
1012 $modinfo = get_fast_modinfo($course);
1013 if (is_object($section)) {
1014 $section = $modinfo->get_section_info($section->section);
1015 } else {
1016 $section = $modinfo->get_section_info($section);
1018 $completioninfo = new completion_info($course);
1020 // check if we are currently in the process of moving a module with JavaScript disabled
1021 $ismoving = $this->page->user_is_editing() && ismoving($course->id);
1022 if ($ismoving) {
1023 $movingpix = new pix_icon('movehere', get_string('movehere'), 'moodle', array('class' => 'movetarget'));
1024 $strmovefull = strip_tags(get_string("movefull", "", "'$USER->activitycopyname'"));
1027 // Get the list of modules visible to user (excluding the module being moved if there is one)
1028 $moduleshtml = array();
1029 if (!empty($modinfo->sections[$section->section])) {
1030 foreach ($modinfo->sections[$section->section] as $modnumber) {
1031 $mod = $modinfo->cms[$modnumber];
1033 if ($ismoving and $mod->id == $USER->activitycopy) {
1034 // do not display moving mod
1035 continue;
1038 if ($modulehtml = $this->course_section_cm_list_item($course,
1039 $completioninfo, $mod, $sectionreturn, $displayoptions)) {
1040 $moduleshtml[$modnumber] = $modulehtml;
1045 $sectionoutput = '';
1046 if (!empty($moduleshtml) || $ismoving) {
1047 foreach ($moduleshtml as $modnumber => $modulehtml) {
1048 if ($ismoving) {
1049 $movingurl = new moodle_url('/course/mod.php', array('moveto' => $modnumber, 'sesskey' => sesskey()));
1050 $sectionoutput .= html_writer::tag('li',
1051 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1052 array('class' => 'movehere'));
1055 $sectionoutput .= $modulehtml;
1058 if ($ismoving) {
1059 $movingurl = new moodle_url('/course/mod.php', array('movetosection' => $section->id, 'sesskey' => sesskey()));
1060 $sectionoutput .= html_writer::tag('li',
1061 html_writer::link($movingurl, $this->output->render($movingpix), array('title' => $strmovefull)),
1062 array('class' => 'movehere'));
1066 // Always output the section module list.
1067 $output .= html_writer::tag('ul', $sectionoutput, array('class' => 'section img-text'));
1069 return $output;
1073 * Displays a custom list of courses with paging bar if necessary
1075 * If $paginationurl is specified but $totalcount is not, the link 'View more'
1076 * appears under the list.
1078 * If both $paginationurl and $totalcount are specified, and $totalcount is
1079 * bigger than count($courses), a paging bar is displayed above and under the
1080 * courses list.
1082 * @param array $courses array of course records (or instances of course_in_list) to show on this page
1083 * @param bool $showcategoryname whether to add category name to the course description
1084 * @param string $additionalclasses additional CSS classes to add to the div.courses
1085 * @param moodle_url $paginationurl url to view more or url to form links to the other pages in paging bar
1086 * @param int $totalcount total number of courses on all pages, if omitted $paginationurl will be displayed as 'View more' link
1087 * @param int $page current page number (defaults to 0 referring to the first page)
1088 * @param int $perpage number of records per page (defaults to $CFG->coursesperpage)
1089 * @return string
1091 public function courses_list($courses, $showcategoryname = false, $additionalclasses = null, $paginationurl = null, $totalcount = null, $page = 0, $perpage = null) {
1092 global $CFG;
1093 // create instance of coursecat_helper to pass display options to function rendering courses list
1094 $chelper = new coursecat_helper();
1095 if ($showcategoryname) {
1096 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT);
1097 } else {
1098 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1100 if ($totalcount !== null && $paginationurl !== null) {
1101 // add options to display pagination
1102 if ($perpage === null) {
1103 $perpage = $CFG->coursesperpage;
1105 $chelper->set_courses_display_options(array(
1106 'limit' => $perpage,
1107 'offset' => ((int)$page) * $perpage,
1108 'paginationurl' => $paginationurl,
1110 } else if ($paginationurl !== null) {
1111 // add options to display 'View more' link
1112 $chelper->set_courses_display_options(array('viewmoreurl' => $paginationurl));
1113 $totalcount = count($courses) + 1; // has to be bigger than count($courses) otherwise link will not be displayed
1115 $chelper->set_attributes(array('class' => $additionalclasses));
1116 $content = $this->coursecat_courses($chelper, $courses, $totalcount);
1117 return $content;
1121 * Displays one course in the list of courses.
1123 * This is an internal function, to display an information about just one course
1124 * please use {@link core_course_renderer::course_info_box()}
1126 * @param coursecat_helper $chelper various display options
1127 * @param course_in_list|stdClass $course
1128 * @param string $additionalclasses additional classes to add to the main <div> tag (usually
1129 * depend on the course position in list - first/last/even/odd)
1130 * @return string
1132 protected function coursecat_coursebox(coursecat_helper $chelper, $course, $additionalclasses = '') {
1133 global $CFG;
1134 if (!isset($this->strings->summary)) {
1135 $this->strings->summary = get_string('summary');
1137 if ($chelper->get_show_courses() <= self::COURSECAT_SHOW_COURSES_COUNT) {
1138 return '';
1140 if ($course instanceof stdClass) {
1141 require_once($CFG->libdir. '/coursecatlib.php');
1142 $course = new course_in_list($course);
1144 $content = '';
1145 $classes = trim('coursebox clearfix '. $additionalclasses);
1146 if ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_EXPANDED) {
1147 $nametag = 'h3';
1148 } else {
1149 $classes .= ' collapsed';
1150 $nametag = 'div';
1153 // .coursebox
1154 $content .= html_writer::start_tag('div', array(
1155 'class' => $classes,
1156 'data-courseid' => $course->id,
1157 'data-type' => self::COURSECAT_TYPE_COURSE,
1160 $content .= html_writer::start_tag('div', array('class' => 'info'));
1162 // course name
1163 $coursename = $chelper->get_course_formatted_name($course);
1164 $coursenamelink = html_writer::link(new moodle_url('/course/view.php', array('id' => $course->id)),
1165 $coursename, array('class' => $course->visible ? '' : 'dimmed'));
1166 $content .= html_writer::tag($nametag, $coursenamelink, array('class' => 'coursename'));
1167 // If we display course in collapsed form but the course has summary or course contacts, display the link to the info page.
1168 $content .= html_writer::start_tag('div', array('class' => 'moreinfo'));
1169 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1170 if ($course->has_summary() || $course->has_course_contacts() || $course->has_course_overviewfiles()) {
1171 $url = new moodle_url('/course/info.php', array('id' => $course->id));
1172 $image = $this->output->pix_icon('i/info', $this->strings->summary);
1173 $content .= html_writer::link($url, $image, array('title' => $this->strings->summary));
1174 // Make sure JS file to expand course content is included.
1175 $this->coursecat_include_js();
1178 $content .= html_writer::end_tag('div'); // .moreinfo
1180 // print enrolmenticons
1181 if ($icons = enrol_get_course_info_icons($course)) {
1182 $content .= html_writer::start_tag('div', array('class' => 'enrolmenticons'));
1183 foreach ($icons as $pix_icon) {
1184 $content .= $this->render($pix_icon);
1186 $content .= html_writer::end_tag('div'); // .enrolmenticons
1189 $content .= html_writer::end_tag('div'); // .info
1191 $content .= html_writer::start_tag('div', array('class' => 'content'));
1192 $content .= $this->coursecat_coursebox_content($chelper, $course);
1193 $content .= html_writer::end_tag('div'); // .content
1195 $content .= html_writer::end_tag('div'); // .coursebox
1196 return $content;
1200 * Returns HTML to display course content (summary, course contacts and optionally category name)
1202 * This method is called from coursecat_coursebox() and may be re-used in AJAX
1204 * @param coursecat_helper $chelper various display options
1205 * @param stdClass|course_in_list $course
1206 * @return string
1208 protected function coursecat_coursebox_content(coursecat_helper $chelper, $course) {
1209 global $CFG;
1210 if ($chelper->get_show_courses() < self::COURSECAT_SHOW_COURSES_EXPANDED) {
1211 return '';
1213 if ($course instanceof stdClass) {
1214 require_once($CFG->libdir. '/coursecatlib.php');
1215 $course = new course_in_list($course);
1217 $content = '';
1219 // display course summary
1220 if ($course->has_summary()) {
1221 $content .= html_writer::start_tag('div', array('class' => 'summary'));
1222 $content .= $chelper->get_course_formatted_summary($course,
1223 array('overflowdiv' => true, 'noclean' => true, 'para' => false));
1224 $content .= html_writer::end_tag('div'); // .summary
1227 // display course overview files
1228 $contentimages = $contentfiles = '';
1229 foreach ($course->get_course_overviewfiles() as $file) {
1230 $isimage = $file->is_valid_image();
1231 $url = file_encode_url("$CFG->wwwroot/pluginfile.php",
1232 '/'. $file->get_contextid(). '/'. $file->get_component(). '/'.
1233 $file->get_filearea(). $file->get_filepath(). $file->get_filename(), !$isimage);
1234 if ($isimage) {
1235 $contentimages .= html_writer::tag('div',
1236 html_writer::empty_tag('img', array('src' => $url)),
1237 array('class' => 'courseimage'));
1238 } else {
1239 $image = $this->output->pix_icon(file_file_icon($file, 24), $file->get_filename(), 'moodle');
1240 $filename = html_writer::tag('span', $image, array('class' => 'fp-icon')).
1241 html_writer::tag('span', $file->get_filename(), array('class' => 'fp-filename'));
1242 $contentfiles .= html_writer::tag('span',
1243 html_writer::link($url, $filename),
1244 array('class' => 'coursefile fp-filename-icon'));
1247 $content .= $contentimages. $contentfiles;
1249 // display course contacts. See course_in_list::get_course_contacts()
1250 if ($course->has_course_contacts()) {
1251 $content .= html_writer::start_tag('ul', array('class' => 'teachers'));
1252 foreach ($course->get_course_contacts() as $userid => $coursecontact) {
1253 $name = $coursecontact['rolename'].': '.
1254 html_writer::link(new moodle_url('/user/view.php',
1255 array('id' => $userid, 'course' => SITEID)),
1256 $coursecontact['username']);
1257 $content .= html_writer::tag('li', $name);
1259 $content .= html_writer::end_tag('ul'); // .teachers
1262 // display course category if necessary (for example in search results)
1263 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT) {
1264 require_once($CFG->libdir. '/coursecatlib.php');
1265 if ($cat = coursecat::get($course->category, IGNORE_MISSING)) {
1266 $content .= html_writer::start_tag('div', array('class' => 'coursecat'));
1267 $content .= get_string('category').': '.
1268 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1269 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1270 $content .= html_writer::end_tag('div'); // .coursecat
1274 return $content;
1278 * Renders the list of courses
1280 * This is internal function, please use {@link core_course_renderer::courses_list()} or another public
1281 * method from outside of the class
1283 * If list of courses is specified in $courses; the argument $chelper is only used
1284 * to retrieve display options and attributes, only methods get_show_courses(),
1285 * get_courses_display_option() and get_and_erase_attributes() are called.
1287 * @param coursecat_helper $chelper various display options
1288 * @param array $courses the list of courses to display
1289 * @param int|null $totalcount total number of courses (affects display mode if it is AUTO or pagination if applicable),
1290 * defaulted to count($courses)
1291 * @return string
1293 protected function coursecat_courses(coursecat_helper $chelper, $courses, $totalcount = null) {
1294 global $CFG;
1295 if ($totalcount === null) {
1296 $totalcount = count($courses);
1298 if (!$totalcount) {
1299 // Courses count is cached during courses retrieval.
1300 return '';
1303 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO) {
1304 // In 'auto' course display mode we analyse if number of courses is more or less than $CFG->courseswithsummarieslimit
1305 if ($totalcount <= $CFG->courseswithsummarieslimit) {
1306 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1307 } else {
1308 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1312 // prepare content of paging bar if it is needed
1313 $paginationurl = $chelper->get_courses_display_option('paginationurl');
1314 $paginationallowall = $chelper->get_courses_display_option('paginationallowall');
1315 if ($totalcount > count($courses)) {
1316 // there are more results that can fit on one page
1317 if ($paginationurl) {
1318 // the option paginationurl was specified, display pagingbar
1319 $perpage = $chelper->get_courses_display_option('limit', $CFG->coursesperpage);
1320 $page = $chelper->get_courses_display_option('offset') / $perpage;
1321 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1322 $paginationurl->out(false, array('perpage' => $perpage)));
1323 if ($paginationallowall) {
1324 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1325 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1327 } else if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1328 // the option for 'View more' link was specified, display more link
1329 $viewmoretext = $chelper->get_courses_display_option('viewmoretext', new lang_string('viewmore'));
1330 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1331 array('class' => 'paging paging-morelink'));
1333 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1334 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1335 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1336 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1339 // display list of courses
1340 $attributes = $chelper->get_and_erase_attributes('courses');
1341 $content = html_writer::start_tag('div', $attributes);
1343 if (!empty($pagingbar)) {
1344 $content .= $pagingbar;
1347 $coursecount = 0;
1348 foreach ($courses as $course) {
1349 $coursecount ++;
1350 $classes = ($coursecount%2) ? 'odd' : 'even';
1351 if ($coursecount == 1) {
1352 $classes .= ' first';
1354 if ($coursecount >= count($courses)) {
1355 $classes .= ' last';
1357 $content .= $this->coursecat_coursebox($chelper, $course, $classes);
1360 if (!empty($pagingbar)) {
1361 $content .= $pagingbar;
1363 if (!empty($morelink)) {
1364 $content .= $morelink;
1367 $content .= html_writer::end_tag('div'); // .courses
1368 return $content;
1372 * Renders the list of subcategories in a category
1374 * @param coursecat_helper $chelper various display options
1375 * @param coursecat $coursecat
1376 * @param int $depth depth of the category in the current tree
1377 * @return string
1379 protected function coursecat_subcategories(coursecat_helper $chelper, $coursecat, $depth) {
1380 global $CFG;
1381 $subcategories = array();
1382 if (!$chelper->get_categories_display_option('nodisplay')) {
1383 $subcategories = $coursecat->get_children($chelper->get_categories_display_options());
1385 $totalcount = $coursecat->get_children_count();
1386 if (!$totalcount) {
1387 // Note that we call coursecat::get_children_count() AFTER coursecat::get_children() to avoid extra DB requests.
1388 // Categories count is cached during children categories retrieval.
1389 return '';
1392 // prepare content of paging bar or more link if it is needed
1393 $paginationurl = $chelper->get_categories_display_option('paginationurl');
1394 $paginationallowall = $chelper->get_categories_display_option('paginationallowall');
1395 if ($totalcount > count($subcategories)) {
1396 if ($paginationurl) {
1397 // the option 'paginationurl was specified, display pagingbar
1398 $perpage = $chelper->get_categories_display_option('limit', $CFG->coursesperpage);
1399 $page = $chelper->get_categories_display_option('offset') / $perpage;
1400 $pagingbar = $this->paging_bar($totalcount, $page, $perpage,
1401 $paginationurl->out(false, array('perpage' => $perpage)));
1402 if ($paginationallowall) {
1403 $pagingbar .= html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => 'all')),
1404 get_string('showall', '', $totalcount)), array('class' => 'paging paging-showall'));
1406 } else if ($viewmoreurl = $chelper->get_categories_display_option('viewmoreurl')) {
1407 // the option 'viewmoreurl' was specified, display more link (if it is link to category view page, add category id)
1408 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1409 $viewmoreurl->param('categoryid', $coursecat->id);
1411 $viewmoretext = $chelper->get_categories_display_option('viewmoretext', new lang_string('viewmore'));
1412 $morelink = html_writer::tag('div', html_writer::link($viewmoreurl, $viewmoretext),
1413 array('class' => 'paging paging-morelink'));
1415 } else if (($totalcount > $CFG->coursesperpage) && $paginationurl && $paginationallowall) {
1416 // there are more than one page of results and we are in 'view all' mode, suggest to go back to paginated view mode
1417 $pagingbar = html_writer::tag('div', html_writer::link($paginationurl->out(false, array('perpage' => $CFG->coursesperpage)),
1418 get_string('showperpage', '', $CFG->coursesperpage)), array('class' => 'paging paging-showperpage'));
1421 // display list of subcategories
1422 $content = html_writer::start_tag('div', array('class' => 'subcategories'));
1424 if (!empty($pagingbar)) {
1425 $content .= $pagingbar;
1428 foreach ($subcategories as $subcategory) {
1429 $content .= $this->coursecat_category($chelper, $subcategory, $depth + 1);
1432 if (!empty($pagingbar)) {
1433 $content .= $pagingbar;
1435 if (!empty($morelink)) {
1436 $content .= $morelink;
1439 $content .= html_writer::end_tag('div');
1440 return $content;
1444 * Make sure that javascript file for AJAX expanding of courses and categories content is included
1446 protected function coursecat_include_js() {
1447 if (!$this->page->requires->should_create_one_time_item_now('core_course_categoryexpanderjsinit')) {
1448 return;
1451 // We must only load this module once.
1452 $this->page->requires->yui_module('moodle-course-categoryexpander',
1453 'Y.Moodle.course.categoryexpander.init');
1457 * Returns HTML to display the subcategories and courses in the given category
1459 * This method is re-used by AJAX to expand content of not loaded category
1461 * @param coursecat_helper $chelper various display options
1462 * @param coursecat $coursecat
1463 * @param int $depth depth of the category in the current tree
1464 * @return string
1466 protected function coursecat_category_content(coursecat_helper $chelper, $coursecat, $depth) {
1467 $content = '';
1468 // Subcategories
1469 $content .= $this->coursecat_subcategories($chelper, $coursecat, $depth);
1471 // AUTO show courses: Courses will be shown expanded if this is not nested category,
1472 // and number of courses no bigger than $CFG->courseswithsummarieslimit.
1473 $showcoursesauto = $chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_AUTO;
1474 if ($showcoursesauto && $depth) {
1475 // this is definitely collapsed mode
1476 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_COLLAPSED);
1479 // Courses
1480 if ($chelper->get_show_courses() > core_course_renderer::COURSECAT_SHOW_COURSES_COUNT) {
1481 $courses = array();
1482 if (!$chelper->get_courses_display_option('nodisplay')) {
1483 $courses = $coursecat->get_courses($chelper->get_courses_display_options());
1485 if ($viewmoreurl = $chelper->get_courses_display_option('viewmoreurl')) {
1486 // the option for 'View more' link was specified, display more link (if it is link to category view page, add category id)
1487 if ($viewmoreurl->compare(new moodle_url('/course/index.php'), URL_MATCH_BASE)) {
1488 $chelper->set_courses_display_option('viewmoreurl', new moodle_url($viewmoreurl, array('categoryid' => $coursecat->id)));
1491 $content .= $this->coursecat_courses($chelper, $courses, $coursecat->get_courses_count());
1494 if ($showcoursesauto) {
1495 // restore the show_courses back to AUTO
1496 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO);
1499 return $content;
1503 * Returns HTML to display a course category as a part of a tree
1505 * This is an internal function, to display a particular category and all its contents
1506 * use {@link core_course_renderer::course_category()}
1508 * @param coursecat_helper $chelper various display options
1509 * @param coursecat $coursecat
1510 * @param int $depth depth of this category in the current tree
1511 * @return string
1513 protected function coursecat_category(coursecat_helper $chelper, $coursecat, $depth) {
1514 // open category tag
1515 $classes = array('category');
1516 if (empty($coursecat->visible)) {
1517 $classes[] = 'dimmed_category';
1519 if ($chelper->get_subcat_depth() > 0 && $depth >= $chelper->get_subcat_depth()) {
1520 // do not load content
1521 $categorycontent = '';
1522 $classes[] = 'notloaded';
1523 if ($coursecat->get_children_count() ||
1524 ($chelper->get_show_courses() >= self::COURSECAT_SHOW_COURSES_COLLAPSED && $coursecat->get_courses_count())) {
1525 $classes[] = 'with_children';
1526 $classes[] = 'collapsed';
1528 } else {
1529 // load category content
1530 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, $depth);
1531 $classes[] = 'loaded';
1532 if (!empty($categorycontent)) {
1533 $classes[] = 'with_children';
1534 // Category content loaded with children.
1535 $this->categoryexpandedonload = true;
1539 // Make sure JS file to expand category content is included.
1540 $this->coursecat_include_js();
1542 $content = html_writer::start_tag('div', array(
1543 'class' => join(' ', $classes),
1544 'data-categoryid' => $coursecat->id,
1545 'data-depth' => $depth,
1546 'data-showcourses' => $chelper->get_show_courses(),
1547 'data-type' => self::COURSECAT_TYPE_CATEGORY,
1550 // category name
1551 $categoryname = $coursecat->get_formatted_name();
1552 $categoryname = html_writer::link(new moodle_url('/course/index.php',
1553 array('categoryid' => $coursecat->id)),
1554 $categoryname);
1555 if ($chelper->get_show_courses() == self::COURSECAT_SHOW_COURSES_COUNT
1556 && ($coursescount = $coursecat->get_courses_count())) {
1557 $categoryname .= html_writer::tag('span', ' ('. $coursescount.')',
1558 array('title' => get_string('numberofcourses'), 'class' => 'numberofcourse'));
1560 $content .= html_writer::start_tag('div', array('class' => 'info'));
1562 $content .= html_writer::tag(($depth > 1) ? 'h4' : 'h3', $categoryname, array('class' => 'categoryname'));
1563 $content .= html_writer::end_tag('div'); // .info
1565 // add category content to the output
1566 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1568 $content .= html_writer::end_tag('div'); // .category
1570 // Return the course category tree HTML
1571 return $content;
1575 * Returns HTML to display a tree of subcategories and courses in the given category
1577 * @param coursecat_helper $chelper various display options
1578 * @param coursecat $coursecat top category (this category's name and description will NOT be added to the tree)
1579 * @return string
1581 protected function coursecat_tree(coursecat_helper $chelper, $coursecat) {
1582 // Reset the category expanded flag for this course category tree first.
1583 $this->categoryexpandedonload = false;
1584 $categorycontent = $this->coursecat_category_content($chelper, $coursecat, 0);
1585 if (empty($categorycontent)) {
1586 return '';
1589 // Start content generation
1590 $content = '';
1591 $attributes = $chelper->get_and_erase_attributes('course_category_tree clearfix');
1592 $content .= html_writer::start_tag('div', $attributes);
1594 if ($coursecat->get_children_count()) {
1595 $classes = array(
1596 'collapseexpand',
1599 // Check if the category content contains subcategories with children's content loaded.
1600 if ($this->categoryexpandedonload) {
1601 $classes[] = 'collapse-all';
1602 $linkname = get_string('collapseall');
1603 } else {
1604 $linkname = get_string('expandall');
1607 // Only show the collapse/expand if there are children to expand.
1608 $content .= html_writer::start_tag('div', array('class' => 'collapsible-actions'));
1609 $content .= html_writer::link('#', $linkname, array('class' => implode(' ', $classes)));
1610 $content .= html_writer::end_tag('div');
1611 $this->page->requires->strings_for_js(array('collapseall', 'expandall'), 'moodle');
1614 $content .= html_writer::tag('div', $categorycontent, array('class' => 'content'));
1616 $content .= html_writer::end_tag('div'); // .course_category_tree
1618 return $content;
1622 * Renders HTML to display particular course category - list of it's subcategories and courses
1624 * Invoked from /course/index.php
1626 * @param int|stdClass|coursecat $category
1628 public function course_category($category) {
1629 global $CFG;
1630 require_once($CFG->libdir. '/coursecatlib.php');
1631 $coursecat = coursecat::get(is_object($category) ? $category->id : $category);
1632 $site = get_site();
1633 $output = '';
1635 if (can_edit_in_category($coursecat->id)) {
1636 // Add 'Manage' button if user has permissions to edit this category.
1637 $managebutton = $this->single_button(new moodle_url('/course/management.php',
1638 array('categoryid' => $coursecat->id)), get_string('managecourses'), 'get');
1639 $this->page->set_button($managebutton);
1641 if (!$coursecat->id) {
1642 if (coursecat::count_all() == 1) {
1643 // There exists only one category in the system, do not display link to it
1644 $coursecat = coursecat::get_default();
1645 $strfulllistofcourses = get_string('fulllistofcourses');
1646 $this->page->set_title("$site->shortname: $strfulllistofcourses");
1647 } else {
1648 $strcategories = get_string('categories');
1649 $this->page->set_title("$site->shortname: $strcategories");
1651 } else {
1652 $title = $site->shortname;
1653 if (coursecat::count_all() > 1) {
1654 $title .= ": ". $coursecat->get_formatted_name();
1656 $this->page->set_title($title);
1658 // Print the category selector
1659 if (coursecat::count_all() > 1) {
1660 $output .= html_writer::start_tag('div', array('class' => 'categorypicker'));
1661 $select = new single_select(new moodle_url('/course/index.php'), 'categoryid',
1662 coursecat::make_categories_list(), $coursecat->id, null, 'switchcategory');
1663 $select->set_label(get_string('categories').':');
1664 $output .= $this->render($select);
1665 $output .= html_writer::end_tag('div'); // .categorypicker
1669 // Print current category description
1670 $chelper = new coursecat_helper();
1671 if ($description = $chelper->get_category_formatted_description($coursecat)) {
1672 $output .= $this->box($description, array('class' => 'generalbox info'));
1675 // Prepare parameters for courses and categories lists in the tree
1676 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_AUTO)
1677 ->set_attributes(array('class' => 'category-browse category-browse-'.$coursecat->id));
1679 $coursedisplayoptions = array();
1680 $catdisplayoptions = array();
1681 $browse = optional_param('browse', null, PARAM_ALPHA);
1682 $perpage = optional_param('perpage', $CFG->coursesperpage, PARAM_INT);
1683 $page = optional_param('page', 0, PARAM_INT);
1684 $baseurl = new moodle_url('/course/index.php');
1685 if ($coursecat->id) {
1686 $baseurl->param('categoryid', $coursecat->id);
1688 if ($perpage != $CFG->coursesperpage) {
1689 $baseurl->param('perpage', $perpage);
1691 $coursedisplayoptions['limit'] = $perpage;
1692 $catdisplayoptions['limit'] = $perpage;
1693 if ($browse === 'courses' || !$coursecat->has_children()) {
1694 $coursedisplayoptions['offset'] = $page * $perpage;
1695 $coursedisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1696 $catdisplayoptions['nodisplay'] = true;
1697 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1698 $catdisplayoptions['viewmoretext'] = new lang_string('viewallsubcategories');
1699 } else if ($browse === 'categories' || !$coursecat->has_courses()) {
1700 $coursedisplayoptions['nodisplay'] = true;
1701 $catdisplayoptions['offset'] = $page * $perpage;
1702 $catdisplayoptions['paginationurl'] = new moodle_url($baseurl, array('browse' => 'categories'));
1703 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses'));
1704 $coursedisplayoptions['viewmoretext'] = new lang_string('viewallcourses');
1705 } else {
1706 // we have a category that has both subcategories and courses, display pagination separately
1707 $coursedisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1));
1708 $catdisplayoptions['viewmoreurl'] = new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1));
1710 $chelper->set_courses_display_options($coursedisplayoptions)->set_categories_display_options($catdisplayoptions);
1711 // Add course search form.
1712 $output .= $this->course_search_form();
1714 // Display course category tree.
1715 $output .= $this->coursecat_tree($chelper, $coursecat);
1717 // Add action buttons
1718 $output .= $this->container_start('buttons');
1719 $context = get_category_or_system_context($coursecat->id);
1720 if (has_capability('moodle/course:create', $context)) {
1721 // Print link to create a new course, for the 1st available category.
1722 if ($coursecat->id) {
1723 $url = new moodle_url('/course/edit.php', array('category' => $coursecat->id, 'returnto' => 'category'));
1724 } else {
1725 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
1727 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
1729 ob_start();
1730 if (coursecat::count_all() == 1) {
1731 print_course_request_buttons(context_system::instance());
1732 } else {
1733 print_course_request_buttons($context);
1735 $output .= ob_get_contents();
1736 ob_end_clean();
1737 $output .= $this->container_end();
1739 return $output;
1743 * Serves requests to /course/category.ajax.php
1745 * In this renderer implementation it may expand the category content or
1746 * course content.
1748 * @return string
1749 * @throws coding_exception
1751 public function coursecat_ajax() {
1752 global $DB, $CFG;
1753 require_once($CFG->libdir. '/coursecatlib.php');
1755 $type = required_param('type', PARAM_INT);
1757 if ($type === self::COURSECAT_TYPE_CATEGORY) {
1758 // This is a request for a category list of some kind.
1759 $categoryid = required_param('categoryid', PARAM_INT);
1760 $showcourses = required_param('showcourses', PARAM_INT);
1761 $depth = required_param('depth', PARAM_INT);
1763 $category = coursecat::get($categoryid);
1765 $chelper = new coursecat_helper();
1766 $baseurl = new moodle_url('/course/index.php', array('categoryid' => $categoryid));
1767 $coursedisplayoptions = array(
1768 'limit' => $CFG->coursesperpage,
1769 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'courses', 'page' => 1))
1771 $catdisplayoptions = array(
1772 'limit' => $CFG->coursesperpage,
1773 'viewmoreurl' => new moodle_url($baseurl, array('browse' => 'categories', 'page' => 1))
1775 $chelper->set_show_courses($showcourses)->
1776 set_courses_display_options($coursedisplayoptions)->
1777 set_categories_display_options($catdisplayoptions);
1779 return $this->coursecat_category_content($chelper, $category, $depth);
1780 } else if ($type === self::COURSECAT_TYPE_COURSE) {
1781 // This is a request for the course information.
1782 $courseid = required_param('courseid', PARAM_INT);
1784 $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
1786 $chelper = new coursecat_helper();
1787 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED);
1788 return $this->coursecat_coursebox_content($chelper, $course);
1789 } else {
1790 throw new coding_exception('Invalid request type');
1795 * Renders html to display search result page
1797 * @param array $searchcriteria may contain elements: search, blocklist, modulelist, tagid
1798 * @return string
1800 public function search_courses($searchcriteria) {
1801 global $CFG;
1802 $content = '';
1803 if (!empty($searchcriteria)) {
1804 // print search results
1805 require_once($CFG->libdir. '/coursecatlib.php');
1807 $displayoptions = array('sort' => array('displayname' => 1));
1808 // take the current page and number of results per page from query
1809 $perpage = optional_param('perpage', 0, PARAM_RAW);
1810 if ($perpage !== 'all') {
1811 $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
1812 $page = optional_param('page', 0, PARAM_INT);
1813 $displayoptions['offset'] = $displayoptions['limit'] * $page;
1815 // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
1816 $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
1817 $displayoptions['paginationallowall'] = true; // allow adding link 'View all'
1819 $class = 'course-search-result';
1820 foreach ($searchcriteria as $key => $value) {
1821 if (!empty($value)) {
1822 $class .= ' course-search-result-'. $key;
1825 $chelper = new coursecat_helper();
1826 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
1827 set_courses_display_options($displayoptions)->
1828 set_search_criteria($searchcriteria)->
1829 set_attributes(array('class' => $class));
1831 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1832 $totalcount = coursecat::search_courses_count($searchcriteria);
1833 $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);
1835 if (!$totalcount) {
1836 if (!empty($searchcriteria['search'])) {
1837 $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
1838 } else {
1839 $content .= $this->heading(get_string('novalidcourses'));
1841 } else {
1842 $content .= $this->heading(get_string('searchresults'). ": $totalcount");
1843 $content .= $courseslist;
1846 if (!empty($searchcriteria['search'])) {
1847 // print search form only if there was a search by search string, otherwise it is confusing
1848 $content .= $this->box_start('generalbox mdl-align');
1849 $content .= $this->course_search_form($searchcriteria['search']);
1850 $content .= $this->box_end();
1852 } else {
1853 // just print search form
1854 $content .= $this->box_start('generalbox mdl-align');
1855 $content .= $this->course_search_form();
1856 $content .= html_writer::tag('div', get_string("searchhelp"), array('class' => 'searchhelp'));
1857 $content .= $this->box_end();
1859 return $content;
1863 * Renders html to print list of courses tagged with particular tag
1865 * @param int $tagid id of the tag
1866 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1867 * are displayed on the page and the per-page limit may be bigger
1868 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1869 * to display items in the same context first
1870 * @param int $ctx context id where to search for records
1871 * @param bool $rec search in subcontexts as well
1872 * @param array $displayoptions
1873 * @return string empty string if no courses are marked with this tag or rendered list of courses
1875 public function tagged_courses($tagid, $exclusivemode = true, $ctx = 0, $rec = true, $displayoptions = null) {
1876 global $CFG;
1877 require_once($CFG->libdir . '/coursecatlib.php');
1878 if (empty($displayoptions)) {
1879 $displayoptions = array();
1881 $showcategories = coursecat::count_all() > 1;
1882 $displayoptions += array('limit' => $CFG->coursesperpage, 'offset' => 0);
1883 $chelper = new coursecat_helper();
1884 $searchcriteria = array('tagid' => $tagid, 'ctx' => $ctx, 'rec' => $rec);
1885 $chelper->set_show_courses($showcategories ? self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT :
1886 self::COURSECAT_SHOW_COURSES_EXPANDED)->
1887 set_search_criteria($searchcriteria)->
1888 set_courses_display_options($displayoptions)->
1889 set_attributes(array('class' => 'course-search-result course-search-result-tagid'));
1890 // (we set the same css class as in search results by tagid)
1891 if ($totalcount = coursecat::search_courses_count($searchcriteria)) {
1892 $courses = coursecat::search_courses($searchcriteria, $chelper->get_courses_display_options());
1893 if ($exclusivemode) {
1894 return $this->coursecat_courses($chelper, $courses, $totalcount);
1895 } else {
1896 $tagfeed = new core_tag\output\tagfeed();
1897 $img = $this->output->pix_icon('i/course', '');
1898 foreach ($courses as $course) {
1899 $url = course_get_url($course);
1900 $imgwithlink = html_writer::link($url, $img);
1901 $coursename = html_writer::link($url, $course->get_formatted_name());
1902 $details = '';
1903 if ($showcategories && ($cat = coursecat::get($course->category, IGNORE_MISSING))) {
1904 $details = get_string('category').': '.
1905 html_writer::link(new moodle_url('/course/index.php', array('categoryid' => $cat->id)),
1906 $cat->get_formatted_name(), array('class' => $cat->visible ? '' : 'dimmed'));
1908 $tagfeed->add($imgwithlink, $coursename, $details);
1910 return $this->output->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($this->output));
1913 return '';
1917 * Returns HTML to display one remote course
1919 * @param stdClass $course remote course information, contains properties:
1920 id, remoteid, shortname, fullname, hostid, summary, summaryformat, cat_name, hostname
1921 * @return string
1923 protected function frontpage_remote_course(stdClass $course) {
1924 $url = new moodle_url('/auth/mnet/jump.php', array(
1925 'hostid' => $course->hostid,
1926 'wantsurl' => '/course/view.php?id='. $course->remoteid
1929 $output = '';
1930 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotecoursebox clearfix'));
1931 $output .= html_writer::start_tag('div', array('class' => 'info'));
1932 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1933 $output .= html_writer::link($url, format_string($course->fullname), array('title' => get_string('entercourse')));
1934 $output .= html_writer::end_tag('h3'); // .name
1935 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1936 $output .= html_writer::end_tag('div'); // .info
1937 $output .= html_writer::start_tag('div', array('class' => 'content'));
1938 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1939 $options = new stdClass();
1940 $options->noclean = true;
1941 $options->para = false;
1942 $options->overflowdiv = true;
1943 $output .= format_text($course->summary, $course->summaryformat, $options);
1944 $output .= html_writer::end_tag('div'); // .summary
1945 $addinfo = format_string($course->hostname) . ' : '
1946 . format_string($course->cat_name) . ' : '
1947 . format_string($course->shortname);
1948 $output .= html_writer::tag('div', $addinfo, array('class' => 'remotecourseinfo'));
1949 $output .= html_writer::end_tag('div'); // .content
1950 $output .= html_writer::end_tag('div'); // .coursebox
1951 return $output;
1955 * Returns HTML to display one remote host
1957 * @param array $host host information, contains properties: name, url, count
1958 * @return string
1960 protected function frontpage_remote_host($host) {
1961 $output = '';
1962 $output .= html_writer::start_tag('div', array('class' => 'coursebox remotehost clearfix'));
1963 $output .= html_writer::start_tag('div', array('class' => 'info'));
1964 $output .= html_writer::start_tag('h3', array('class' => 'name'));
1965 $output .= html_writer::link($host['url'], s($host['name']), array('title' => s($host['name'])));
1966 $output .= html_writer::end_tag('h3'); // .name
1967 $output .= html_writer::tag('div', '', array('class' => 'moreinfo'));
1968 $output .= html_writer::end_tag('div'); // .info
1969 $output .= html_writer::start_tag('div', array('class' => 'content'));
1970 $output .= html_writer::start_tag('div', array('class' => 'summary'));
1971 $output .= $host['count'] . ' ' . get_string('courses');
1972 $output .= html_writer::end_tag('div'); // .content
1973 $output .= html_writer::end_tag('div'); // .coursebox
1974 return $output;
1978 * Returns HTML to print list of courses user is enrolled to for the frontpage
1980 * Also lists remote courses or remote hosts if MNET authorisation is used
1982 * @return string
1984 public function frontpage_my_courses() {
1985 global $USER, $CFG, $DB;
1987 if (!isloggedin() or isguestuser()) {
1988 return '';
1991 $output = '';
1992 $courses = enrol_get_my_courses('summary, summaryformat');
1993 $rhosts = array();
1994 $rcourses = array();
1995 if (!empty($CFG->mnet_dispatcher_mode) && $CFG->mnet_dispatcher_mode==='strict') {
1996 $rcourses = get_my_remotecourses($USER->id);
1997 $rhosts = get_my_remotehosts();
2000 if (!empty($courses) || !empty($rcourses) || !empty($rhosts)) {
2002 $chelper = new coursecat_helper();
2003 if (count($courses) > $CFG->frontpagecourselimit) {
2004 // There are more enrolled courses than we can display, display link to 'My courses'.
2005 $totalcount = count($courses);
2006 $courses = array_slice($courses, 0, $CFG->frontpagecourselimit, true);
2007 $chelper->set_courses_display_options(array(
2008 'viewmoreurl' => new moodle_url('/my/'),
2009 'viewmoretext' => new lang_string('mycourses')
2011 } else {
2012 // All enrolled courses are displayed, display link to 'All courses' if there are more courses in system.
2013 $chelper->set_courses_display_options(array(
2014 'viewmoreurl' => new moodle_url('/course/index.php'),
2015 'viewmoretext' => new lang_string('fulllistofcourses')
2017 $totalcount = $DB->count_records('course') - 1;
2019 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2020 set_attributes(array('class' => 'frontpage-course-list-enrolled'));
2021 $output .= $this->coursecat_courses($chelper, $courses, $totalcount);
2023 // MNET
2024 if (!empty($rcourses)) {
2025 // at the IDP, we know of all the remote courses
2026 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2027 foreach ($rcourses as $course) {
2028 $output .= $this->frontpage_remote_course($course);
2030 $output .= html_writer::end_tag('div'); // .courses
2031 } elseif (!empty($rhosts)) {
2032 // non-IDP, we know of all the remote servers, but not courses
2033 $output .= html_writer::start_tag('div', array('class' => 'courses'));
2034 foreach ($rhosts as $host) {
2035 $output .= $this->frontpage_remote_host($host);
2037 $output .= html_writer::end_tag('div'); // .courses
2040 return $output;
2044 * Returns HTML to print list of available courses for the frontpage
2046 * @return string
2048 public function frontpage_available_courses() {
2049 global $CFG;
2050 require_once($CFG->libdir. '/coursecatlib.php');
2052 $chelper = new coursecat_helper();
2053 $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED)->
2054 set_courses_display_options(array(
2055 'recursive' => true,
2056 'limit' => $CFG->frontpagecourselimit,
2057 'viewmoreurl' => new moodle_url('/course/index.php'),
2058 'viewmoretext' => new lang_string('fulllistofcourses')));
2060 $chelper->set_attributes(array('class' => 'frontpage-course-list-all'));
2061 $courses = coursecat::get(0)->get_courses($chelper->get_courses_display_options());
2062 $totalcount = coursecat::get(0)->get_courses_count($chelper->get_courses_display_options());
2063 if (!$totalcount && !$this->page->user_is_editing() && has_capability('moodle/course:create', context_system::instance())) {
2064 // Print link to create a new course, for the 1st available category.
2065 return $this->add_new_course_button();
2067 return $this->coursecat_courses($chelper, $courses, $totalcount);
2071 * Returns HTML to the "add new course" button for the page
2073 * @return string
2075 public function add_new_course_button() {
2076 global $CFG;
2077 // Print link to create a new course, for the 1st available category.
2078 $output = $this->container_start('buttons');
2079 $url = new moodle_url('/course/edit.php', array('category' => $CFG->defaultrequestcategory, 'returnto' => 'topcat'));
2080 $output .= $this->single_button($url, get_string('addnewcourse'), 'get');
2081 $output .= $this->container_end('buttons');
2082 return $output;
2086 * Returns HTML to print tree with course categories and courses for the frontpage
2088 * @return string
2090 public function frontpage_combo_list() {
2091 global $CFG;
2092 require_once($CFG->libdir. '/coursecatlib.php');
2093 $chelper = new coursecat_helper();
2094 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2095 set_categories_display_options(array(
2096 'limit' => $CFG->coursesperpage,
2097 'viewmoreurl' => new moodle_url('/course/index.php',
2098 array('browse' => 'categories', 'page' => 1))
2099 ))->
2100 set_courses_display_options(array(
2101 'limit' => $CFG->coursesperpage,
2102 'viewmoreurl' => new moodle_url('/course/index.php',
2103 array('browse' => 'courses', 'page' => 1))
2104 ))->
2105 set_attributes(array('class' => 'frontpage-category-combo'));
2106 return $this->coursecat_tree($chelper, coursecat::get(0));
2110 * Returns HTML to print tree of course categories (with number of courses) for the frontpage
2112 * @return string
2114 public function frontpage_categories_list() {
2115 global $CFG;
2116 require_once($CFG->libdir. '/coursecatlib.php');
2117 $chelper = new coursecat_helper();
2118 $chelper->set_subcat_depth($CFG->maxcategorydepth)->
2119 set_show_courses(self::COURSECAT_SHOW_COURSES_COUNT)->
2120 set_categories_display_options(array(
2121 'limit' => $CFG->coursesperpage,
2122 'viewmoreurl' => new moodle_url('/course/index.php',
2123 array('browse' => 'categories', 'page' => 1))
2124 ))->
2125 set_attributes(array('class' => 'frontpage-category-names'));
2126 return $this->coursecat_tree($chelper, coursecat::get(0));
2130 * Renders the activity navigation.
2132 * Defer to template.
2134 * @param \core_course\output\activity_navigation $page
2135 * @return string html for the page
2137 public function render_activity_navigation(\core_course\output\activity_navigation $page) {
2138 $data = $page->export_for_template($this->output);
2139 return $this->output->render_from_template('core_course/activity_navigation', $data);
2143 * Display the selector to advertise or publish a course
2144 * @param int $courseid
2146 public function publicationselector($courseid) {
2147 $text = '';
2149 $advertiseurl = new moodle_url("/course/publish/metadata.php",
2150 array('sesskey' => sesskey(), 'id' => $courseid, 'advertise' => true));
2151 $advertisebutton = new single_button($advertiseurl, get_string('advertise', 'hub'));
2152 $text .= $this->output->render($advertisebutton);
2153 $text .= html_writer::tag('div', get_string('advertisepublication_help', 'hub'),
2154 array('class' => 'publishhelp'));
2156 $text .= html_writer::empty_tag('br'); // TODO Delete.
2158 $uploadurl = new moodle_url("/course/publish/metadata.php",
2159 array('sesskey' => sesskey(), 'id' => $courseid, 'share' => true));
2160 $uploadbutton = new single_button($uploadurl, get_string('share', 'hub'));
2161 $text .= $this->output->render($uploadbutton);
2162 $text .= html_writer::tag('div', get_string('sharepublication_help', 'hub'),
2163 array('class' => 'publishhelp'));
2165 return $text;
2169 * Display the listing of hub where a course is registered on
2170 * @param int $courseid
2171 * @param array $publications
2173 public function registeredonhublisting($courseid, $publications) {
2174 global $CFG;
2175 $table = new html_table();
2176 $table->head = array(get_string('type', 'hub'),
2177 get_string('date'), get_string('status', 'hub'), get_string('operation', 'hub'));
2178 $table->size = array('20%', '30%', '%20', '%25');
2180 $brtag = html_writer::empty_tag('br');
2182 foreach ($publications as $publication) {
2184 $params = array('id' => $publication->courseid, 'publicationid' => $publication->id);
2185 $cancelurl = new moodle_url("/course/publish/index.php", $params);
2186 $cancelbutton = new single_button($cancelurl, get_string('removefromhub', 'hub'));
2187 $cancelbutton->class = 'centeredbutton';
2188 $cancelbuttonhtml = $this->output->render($cancelbutton);
2190 if ($publication->enrollable) {
2191 $params = array('sesskey' => sesskey(), 'id' => $publication->courseid, 'publicationid' => $publication->id);
2192 $updateurl = new moodle_url("/course/publish/metadata.php", $params);
2193 $updatebutton = new single_button($updateurl, get_string('update', 'hub'));
2194 $updatebutton->class = 'centeredbutton';
2195 $updatebuttonhtml = $this->output->render($updatebutton);
2197 $operations = $updatebuttonhtml . $brtag . $cancelbuttonhtml;
2198 } else {
2199 $operations = $cancelbuttonhtml;
2202 // If the publication check time if bigger than May 2010, it has been checked.
2203 if ($publication->timechecked > 1273127954) {
2204 if ($publication->status == 0) {
2205 $status = get_string('statusunpublished', 'hub');
2206 } else {
2207 $status = get_string('statuspublished', 'hub');
2208 if (!empty($publication->link)) {
2209 $status = html_writer::link($publication->link, $status);
2213 $status .= $brtag . html_writer::tag('a', get_string('updatestatus', 'hub'),
2214 array('href' => $CFG->wwwroot . '/course/publish/index.php?id='
2215 . $courseid . "&updatestatusid=" . $publication->id
2216 . "&sesskey=" . sesskey())) .
2217 $brtag . get_string('lasttimechecked', 'hub') . ": "
2218 . format_time(time() - $publication->timechecked);
2219 } else {
2220 $status = get_string('neverchecked', 'hub') . $brtag
2221 . html_writer::tag('a', get_string('updatestatus', 'hub'),
2222 array('href' => $CFG->wwwroot . '/course/publish/index.php?id='
2223 . $courseid . "&updatestatusid=" . $publication->id
2224 . "&sesskey=" . sesskey()));
2226 // Add button cells.
2227 $cells = array($publication->enrollable ?
2228 get_string('advertised', 'hub') : get_string('shared', 'hub'),
2229 userdate($publication->timepublished,
2230 get_string('strftimedatetimeshort')), $status, $operations);
2231 $row = new html_table_row($cells);
2232 $table->data[] = $row;
2235 $contenthtml = html_writer::table($table);
2237 return $contenthtml;
2241 * Display unpublishing confirmation page
2242 * @param stdClass $publication
2243 * $publication->courseshortname
2244 * $publication->courseid
2245 * $publication->hubname
2246 * $publication->huburl
2247 * $publication->id
2249 public function confirmunpublishing($publication) {
2250 $optionsyes = array('sesskey' => sesskey(), 'id' => $publication->courseid,
2251 'hubcourseid' => $publication->hubcourseid,
2252 'cancel' => true, 'publicationid' => $publication->id, 'confirm' => true);
2253 $optionsno = array('sesskey' => sesskey(), 'id' => $publication->courseid);
2254 $publication->hubname = html_writer::tag('a', 'Moodle.net',
2255 array('href' => HUB_MOODLEORGHUBURL));
2256 $formcontinue = new single_button(new moodle_url("/course/publish/index.php",
2257 $optionsyes), get_string('unpublish', 'hub'), 'post');
2258 $formcancel = new single_button(new moodle_url("/course/publish/index.php",
2259 $optionsno), get_string('cancel'), 'get');
2260 return $this->output->confirm(get_string('unpublishconfirmation', 'hub', $publication),
2261 $formcontinue, $formcancel);
2265 * Display waiting information about backup size during uploading backup process
2266 * @param object $backupfile the backup stored_file
2267 * @return $html string
2269 public function sendingbackupinfo($backupfile) {
2270 $sizeinfo = new stdClass();
2271 $sizeinfo->total = number_format($backupfile->get_filesize() / 1000000, 2);
2272 $html = html_writer::tag('div', get_string('sendingsize', 'hub', $sizeinfo),
2273 array('class' => 'courseuploadtextinfo'));
2274 return $html;
2278 * Display upload successfull message and a button to the publish index page
2279 * @param int $id the course id
2280 * @return $html string
2282 public function sentbackupinfo($id) {
2283 $html = html_writer::tag('div', get_string('sent', 'hub'),
2284 array('class' => 'courseuploadtextinfo'));
2285 $publishindexurl = new moodle_url('/course/publish/index.php',
2286 array('sesskey' => sesskey(), 'id' => $id,
2287 'published' => true));
2288 $continue = $this->output->render(
2289 new single_button($publishindexurl, get_string('continue')));
2290 $html .= html_writer::tag('div', $continue, array('class' => 'sharecoursecontinue'));
2291 return $html;
2295 * Hub information (logo - name - description - link)
2296 * @param object $hubinfo
2297 * @return string html code
2299 public function hubinfo($hubinfo) {
2300 $screenshothtml = html_writer::empty_tag('img',
2301 array('src' => $hubinfo['imgurl'], 'alt' => $hubinfo['name']));
2302 $hubdescription = html_writer::tag('div', $screenshothtml,
2303 array('class' => 'hubscreenshot'));
2305 $hubdescription .= html_writer::tag('a', $hubinfo['name'],
2306 array('class' => 'hublink', 'href' => $hubinfo['url'],
2307 'onclick' => 'this.target="_blank"'));
2309 $hubdescription .= html_writer::tag('div', format_text($hubinfo['description'], FORMAT_PLAIN),
2310 array('class' => 'hubdescription'));
2311 $hubdescription = html_writer::tag('div', $hubdescription, array('class' => 'hubinfo clearfix'));
2313 return $hubdescription;
2317 * Output frontpage summary text and frontpage modules (stored as section 1 in site course)
2319 * This may be disabled in settings
2321 * @return string
2323 public function frontpage_section1() {
2324 global $SITE, $USER;
2326 $output = '';
2327 $editing = $this->page->user_is_editing();
2329 if ($editing) {
2330 // Make sure section with number 1 exists.
2331 course_create_sections_if_missing($SITE, 1);
2334 $modinfo = get_fast_modinfo($SITE);
2335 $section = $modinfo->get_section_info(1);
2336 if (($section && (!empty($modinfo->sections[1]) or !empty($section->summary))) or $editing) {
2337 $output .= $this->box_start('generalbox sitetopic');
2339 // If currently moving a file then show the current clipboard.
2340 if (ismoving($SITE->id)) {
2341 $stractivityclipboard = strip_tags(get_string('activityclipboard', '', $USER->activitycopyname));
2342 $output .= '<p><font size="2">';
2343 $cancelcopyurl = new moodle_url('/course/mod.php', ['cancelcopy' => 'true', 'sesskey' => sesskey()]);
2344 $output .= "$stractivityclipboard&nbsp;&nbsp;(" . html_writer::link($cancelcopyurl, get_string('cancel')) .')';
2345 $output .= '</font></p>';
2348 $context = context_course::instance(SITEID);
2350 // If the section name is set we show it.
2351 if (trim($section->name) !== '') {
2352 $output .= $this->heading(
2353 format_string($section->name, true, array('context' => $context)),
2355 'sectionname'
2359 $summarytext = file_rewrite_pluginfile_urls($section->summary,
2360 'pluginfile.php',
2361 $context->id,
2362 'course',
2363 'section',
2364 $section->id);
2365 $summaryformatoptions = new stdClass();
2366 $summaryformatoptions->noclean = true;
2367 $summaryformatoptions->overflowdiv = true;
2369 $output .= format_text($summarytext, $section->summaryformat, $summaryformatoptions);
2371 if ($editing && has_capability('moodle/course:update', $context)) {
2372 $streditsummary = get_string('editsummary');
2373 $editsectionurl = new moodle_url('/course/editsection.php', ['id' => $section->id]);
2374 $output .= html_writer::link($editsectionurl, $this->pix_icon('t/edit', $streditsummary)) .
2375 "<br /><br />";
2378 $output .= $this->course_section_cm_list($SITE, $section);
2380 $output .= $this->course_section_add_cm_control($SITE, $section->section);
2381 $output .= $this->box_end();
2384 return $output;
2388 * Output news for the frontpage (extract from site-wide news forum)
2390 * @param stdClass $newsforum record from db table 'forum' that represents the site news forum
2391 * @return string
2393 protected function frontpage_news($newsforum) {
2394 global $CFG, $SITE, $SESSION, $USER;
2395 require_once($CFG->dirroot .'/mod/forum/lib.php');
2397 $output = '';
2399 if (isloggedin()) {
2400 $SESSION->fromdiscussion = $CFG->wwwroot;
2401 $subtext = '';
2402 if (\mod_forum\subscriptions::is_subscribed($USER->id, $newsforum)) {
2403 if (!\mod_forum\subscriptions::is_forcesubscribed($newsforum)) {
2404 $subtext = get_string('unsubscribe', 'forum');
2406 } else {
2407 $subtext = get_string('subscribe', 'forum');
2409 $suburl = new moodle_url('/mod/forum/subscribe.php', array('id' => $newsforum->id, 'sesskey' => sesskey()));
2410 $output .= html_writer::tag('div', html_writer::link($suburl, $subtext), array('class' => 'subscribelink'));
2413 ob_start();
2414 forum_print_latest_discussions($SITE, $newsforum, $SITE->newsitems, 'plain', 'p.modified DESC');
2415 $output .= ob_get_contents();
2416 ob_end_clean();
2418 return $output;
2422 * Renders part of frontpage with a skip link (i.e. "My courses", "Site news", etc.)
2424 * @param string $skipdivid
2425 * @param string $contentsdivid
2426 * @param string $header Header of the part
2427 * @param string $contents Contents of the part
2428 * @return string
2430 protected function frontpage_part($skipdivid, $contentsdivid, $header, $contents) {
2431 $output = html_writer::link('#' . $skipdivid,
2432 get_string('skipa', 'access', core_text::strtolower(strip_tags($header))),
2433 array('class' => 'skip-block skip'));
2435 // Wrap frontpage part in div container.
2436 $output .= html_writer::start_tag('div', array('id' => $contentsdivid));
2437 $output .= $this->heading($header);
2439 $output .= $contents;
2441 // End frontpage part div container.
2442 $output .= html_writer::end_tag('div');
2444 $output .= html_writer::tag('span', '', array('class' => 'skip-block-to', 'id' => $skipdivid));
2445 return $output;
2449 * Outputs contents for frontpage as configured in $CFG->frontpage or $CFG->frontpageloggedin
2451 * @return string
2453 public function frontpage() {
2454 global $CFG, $SITE;
2456 $output = '';
2458 if (isloggedin() and !isguestuser() and isset($CFG->frontpageloggedin)) {
2459 $frontpagelayout = $CFG->frontpageloggedin;
2460 } else {
2461 $frontpagelayout = $CFG->frontpage;
2464 foreach (explode(',', $frontpagelayout) as $v) {
2465 switch ($v) {
2466 // Display the main part of the front page.
2467 case FRONTPAGENEWS:
2468 if ($SITE->newsitems) {
2469 // Print forums only when needed.
2470 require_once($CFG->dirroot .'/mod/forum/lib.php');
2471 if (($newsforum = forum_get_course_forum($SITE->id, 'news')) &&
2472 ($forumcontents = $this->frontpage_news($newsforum))) {
2473 $newsforumcm = get_fast_modinfo($SITE)->instances['forum'][$newsforum->id];
2474 $output .= $this->frontpage_part('skipsitenews', 'site-news-forum',
2475 $newsforumcm->get_formatted_name(), $forumcontents);
2478 break;
2480 case FRONTPAGEENROLLEDCOURSELIST:
2481 $mycourseshtml = $this->frontpage_my_courses();
2482 if (!empty($mycourseshtml)) {
2483 $output .= $this->frontpage_part('skipmycourses', 'frontpage-course-list',
2484 get_string('mycourses'), $mycourseshtml);
2485 break;
2487 // No "break" here. If there are no enrolled courses - continue to 'Available courses'.
2489 case FRONTPAGEALLCOURSELIST:
2490 $availablecourseshtml = $this->frontpage_available_courses();
2491 if (!empty($availablecourseshtml)) {
2492 $output .= $this->frontpage_part('skipavailablecourses', 'frontpage-available-course-list',
2493 get_string('availablecourses'), $availablecourseshtml);
2495 break;
2497 case FRONTPAGECATEGORYNAMES:
2498 $output .= $this->frontpage_part('skipcategories', 'frontpage-category-names',
2499 get_string('categories'), $this->frontpage_categories_list());
2500 break;
2502 case FRONTPAGECATEGORYCOMBO:
2503 $output .= $this->frontpage_part('skipcourses', 'frontpage-category-combo',
2504 get_string('courses'), $this->frontpage_combo_list());
2505 break;
2507 case FRONTPAGECOURSESEARCH:
2508 $output .= $this->box($this->course_search_form('', 'short'), 'mdl-align');
2509 break;
2512 $output .= '<br />';
2515 return $output;
2520 * Class storing display options and functions to help display course category and/or courses lists
2522 * This is a wrapper for coursecat objects that also stores display options
2523 * and functions to retrieve sorted and paginated lists of categories/courses.
2525 * If theme overrides methods in core_course_renderers that access this class
2526 * it may as well not use this class at all or extend it.
2528 * @package core
2529 * @copyright 2013 Marina Glancy
2530 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2532 class coursecat_helper {
2533 /** @var string [none, collapsed, expanded] how (if) display courses list */
2534 protected $showcourses = 10; /* core_course_renderer::COURSECAT_SHOW_COURSES_COLLAPSED */
2535 /** @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) */
2536 protected $subcatdepth = 1;
2537 /** @var array options to display courses list */
2538 protected $coursesdisplayoptions = array();
2539 /** @var array options to display subcategories list */
2540 protected $categoriesdisplayoptions = array();
2541 /** @var array additional HTML attributes */
2542 protected $attributes = array();
2543 /** @var array search criteria if the list is a search result */
2544 protected $searchcriteria = null;
2547 * Sets how (if) to show the courses - none, collapsed, expanded, etc.
2549 * @param int $showcourses SHOW_COURSES_NONE, SHOW_COURSES_COLLAPSED, SHOW_COURSES_EXPANDED, etc.
2550 * @return coursecat_helper
2552 public function set_show_courses($showcourses) {
2553 $this->showcourses = $showcourses;
2554 // Automatically set the options to preload summary and coursecontacts for coursecat::get_courses() and coursecat::search_courses()
2555 $this->coursesdisplayoptions['summary'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_AUTO;
2556 $this->coursesdisplayoptions['coursecontacts'] = $showcourses >= core_course_renderer::COURSECAT_SHOW_COURSES_EXPANDED;
2557 return $this;
2561 * Returns how (if) to show the courses - none, collapsed, expanded, etc.
2563 * @return int - COURSECAT_SHOW_COURSES_NONE, COURSECAT_SHOW_COURSES_COLLAPSED, COURSECAT_SHOW_COURSES_EXPANDED, etc.
2565 public function get_show_courses() {
2566 return $this->showcourses;
2570 * Sets the maximum depth to expand subcategories in the tree
2572 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2574 * @param int $subcatdepth
2575 * @return coursecat_helper
2577 public function set_subcat_depth($subcatdepth) {
2578 $this->subcatdepth = $subcatdepth;
2579 return $this;
2583 * Returns the maximum depth to expand subcategories in the tree
2585 * deeper subcategories may be loaded by AJAX or proceed to category page by clicking on category name
2587 * @return int
2589 public function get_subcat_depth() {
2590 return $this->subcatdepth;
2594 * Sets options to display list of courses
2596 * Options are later submitted as argument to coursecat::get_courses() and/or coursecat::search_courses()
2598 * Options that coursecat::get_courses() accept:
2599 * - recursive - return courses from subcategories as well. Use with care,
2600 * this may be a huge list!
2601 * - summary - preloads fields 'summary' and 'summaryformat'
2602 * - coursecontacts - preloads course contacts
2603 * - isenrolled - preloads indication whether this user is enrolled in the course
2604 * - sort - list of fields to sort. Example
2605 * array('idnumber' => 1, 'shortname' => 1, 'id' => -1)
2606 * will sort by idnumber asc, shortname asc and id desc.
2607 * Default: array('sortorder' => 1)
2608 * Only cached fields may be used for sorting!
2609 * - offset
2610 * - limit - maximum number of children to return, 0 or null for no limit
2612 * Options summary and coursecontacts are filled automatically in the set_show_courses()
2614 * Also renderer can set here any additional options it wants to pass between renderer functions.
2616 * @param array $options
2617 * @return coursecat_helper
2619 public function set_courses_display_options($options) {
2620 $this->coursesdisplayoptions = $options;
2621 $this->set_show_courses($this->showcourses); // this will calculate special display options
2622 return $this;
2626 * Sets one option to display list of courses
2628 * @see coursecat_helper::set_courses_display_options()
2630 * @param string $key
2631 * @param mixed $value
2632 * @return coursecat_helper
2634 public function set_courses_display_option($key, $value) {
2635 $this->coursesdisplayoptions[$key] = $value;
2636 return $this;
2640 * Return the specified option to display list of courses
2642 * @param string $optionname option name
2643 * @param mixed $defaultvalue default value for option if it is not specified
2644 * @return mixed
2646 public function get_courses_display_option($optionname, $defaultvalue = null) {
2647 if (array_key_exists($optionname, $this->coursesdisplayoptions)) {
2648 return $this->coursesdisplayoptions[$optionname];
2649 } else {
2650 return $defaultvalue;
2655 * Returns all options to display the courses
2657 * This array is usually passed to {@link coursecat::get_courses()} or
2658 * {@link coursecat::search_courses()}
2660 * @return array
2662 public function get_courses_display_options() {
2663 return $this->coursesdisplayoptions;
2667 * Sets options to display list of subcategories
2669 * Options 'sort', 'offset' and 'limit' are passed to coursecat::get_children().
2670 * Any other options may be used by renderer functions
2672 * @param array $options
2673 * @return coursecat_helper
2675 public function set_categories_display_options($options) {
2676 $this->categoriesdisplayoptions = $options;
2677 return $this;
2681 * Return the specified option to display list of subcategories
2683 * @param string $optionname option name
2684 * @param mixed $defaultvalue default value for option if it is not specified
2685 * @return mixed
2687 public function get_categories_display_option($optionname, $defaultvalue = null) {
2688 if (array_key_exists($optionname, $this->categoriesdisplayoptions)) {
2689 return $this->categoriesdisplayoptions[$optionname];
2690 } else {
2691 return $defaultvalue;
2696 * Returns all options to display list of subcategories
2698 * This array is usually passed to {@link coursecat::get_children()}
2700 * @return array
2702 public function get_categories_display_options() {
2703 return $this->categoriesdisplayoptions;
2707 * Sets additional general options to pass between renderer functions, usually HTML attributes
2709 * @param array $attributes
2710 * @return coursecat_helper
2712 public function set_attributes($attributes) {
2713 $this->attributes = $attributes;
2714 return $this;
2718 * Return all attributes and erases them so they are not applied again
2720 * @param string $classname adds additional class name to the beginning of $attributes['class']
2721 * @return array
2723 public function get_and_erase_attributes($classname) {
2724 $attributes = $this->attributes;
2725 $this->attributes = array();
2726 if (empty($attributes['class'])) {
2727 $attributes['class'] = '';
2729 $attributes['class'] = $classname . ' '. $attributes['class'];
2730 return $attributes;
2734 * Sets the search criteria if the course is a search result
2736 * Search string will be used to highlight terms in course name and description
2738 * @param array $searchcriteria
2739 * @return coursecat_helper
2741 public function set_search_criteria($searchcriteria) {
2742 $this->searchcriteria = $searchcriteria;
2743 return $this;
2747 * Returns formatted and filtered description of the given category
2749 * @param coursecat $coursecat category
2750 * @param stdClass|array $options format options, by default [noclean,overflowdiv],
2751 * if context is not specified it will be added automatically
2752 * @return string|null
2754 public function get_category_formatted_description($coursecat, $options = null) {
2755 if ($coursecat->id && !empty($coursecat->description)) {
2756 if (!isset($coursecat->descriptionformat)) {
2757 $descriptionformat = FORMAT_MOODLE;
2758 } else {
2759 $descriptionformat = $coursecat->descriptionformat;
2761 if ($options === null) {
2762 $options = array('noclean' => true, 'overflowdiv' => true);
2763 } else {
2764 $options = (array)$options;
2766 $context = context_coursecat::instance($coursecat->id);
2767 if (!isset($options['context'])) {
2768 $options['context'] = $context;
2770 $text = file_rewrite_pluginfile_urls($coursecat->description,
2771 'pluginfile.php', $context->id, 'coursecat', 'description', null);
2772 return format_text($text, $descriptionformat, $options);
2774 return null;
2778 * Returns given course's summary with proper embedded files urls and formatted
2780 * @param course_in_list $course
2781 * @param array|stdClass $options additional formatting options
2782 * @return string
2784 public function get_course_formatted_summary($course, $options = array()) {
2785 global $CFG;
2786 require_once($CFG->libdir. '/filelib.php');
2787 if (!$course->has_summary()) {
2788 return '';
2790 $options = (array)$options;
2791 $context = context_course::instance($course->id);
2792 if (!isset($options['context'])) {
2793 // TODO see MDL-38521
2794 // option 1 (current), page context - no code required
2795 // option 2, system context
2796 // $options['context'] = context_system::instance();
2797 // option 3, course context:
2798 // $options['context'] = $context;
2799 // option 4, course category context:
2800 // $options['context'] = $context->get_parent_context();
2802 $summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', null);
2803 $summary = format_text($summary, $course->summaryformat, $options, $course->id);
2804 if (!empty($this->searchcriteria['search'])) {
2805 $summary = highlight($this->searchcriteria['search'], $summary);
2807 return $summary;
2811 * Returns course name as it is configured to appear in courses lists formatted to course context
2813 * @param course_in_list $course
2814 * @param array|stdClass $options additional formatting options
2815 * @return string
2817 public function get_course_formatted_name($course, $options = array()) {
2818 $options = (array)$options;
2819 if (!isset($options['context'])) {
2820 $options['context'] = context_course::instance($course->id);
2822 $name = format_string(get_course_display_name_for_list($course), true, $options);
2823 if (!empty($this->searchcriteria['search'])) {
2824 $name = highlight($this->searchcriteria['search'], $name);
2826 return $name;